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
c556eef23ae7ebfac5dc91919fafa2264bef9368
0
cstamas/orientdb,jdillon/orientdb,joansmith/orientdb,sanyaade-g2g-repos/orientdb,alonsod86/orientdb,wyzssw/orientdb,intfrr/orientdb,wouterv/orientdb,mmacfadden/orientdb,tempbottle/orientdb,allanmoso/orientdb,joansmith/orientdb,orientechnologies/orientdb,orientechnologies/orientdb,mbhulin/orientdb,intfrr/orientdb,cstamas/orientdb,giastfader/orientdb,allanmoso/orientdb,rprabhat/orientdb,orientechnologies/orientdb,allanmoso/orientdb,sanyaade-g2g-repos/orientdb,rprabhat/orientdb,alonsod86/orientdb,sanyaade-g2g-repos/orientdb,orientechnologies/orientdb,allanmoso/orientdb,giastfader/orientdb,giastfader/orientdb,tempbottle/orientdb,mbhulin/orientdb,rprabhat/orientdb,joansmith/orientdb,sanyaade-g2g-repos/orientdb,tempbottle/orientdb,mbhulin/orientdb,wouterv/orientdb,wyzssw/orientdb,mmacfadden/orientdb,rprabhat/orientdb,giastfader/orientdb,mbhulin/orientdb,alonsod86/orientdb,intfrr/orientdb,jdillon/orientdb,intfrr/orientdb,joansmith/orientdb,cstamas/orientdb,wouterv/orientdb,alonsod86/orientdb,mmacfadden/orientdb,wouterv/orientdb,wyzssw/orientdb,cstamas/orientdb,wyzssw/orientdb,jdillon/orientdb,tempbottle/orientdb,mmacfadden/orientdb
/* * Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.core.tx; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map.Entry; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.db.ODatabaseComplex.OPERATION_MODE; import com.orientechnologies.orient.core.db.record.ODatabaseRecordTx; import com.orientechnologies.orient.core.db.record.ORecordOperation; import com.orientechnologies.orient.core.hook.ORecordHook.TYPE; import com.orientechnologies.orient.core.id.OClusterPositionFactory; import com.orientechnologies.orient.core.id.ORID; import com.orientechnologies.orient.core.id.ORecordId; import com.orientechnologies.orient.core.index.OIndex; import com.orientechnologies.orient.core.index.OIndexMVRBTreeAbstract; import com.orientechnologies.orient.core.record.ORecord; import com.orientechnologies.orient.core.record.ORecordInternal; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.storage.ORecordCallback; import com.orientechnologies.orient.core.storage.OStorageEmbedded; import com.orientechnologies.orient.core.storage.OStorageProxy; import com.orientechnologies.orient.core.version.ORecordVersion; public class OTransactionOptimistic extends OTransactionRealAbstract { private boolean usingLog; private static AtomicInteger txSerial = new AtomicInteger(); public OTransactionOptimistic(final ODatabaseRecordTx iDatabase) { super(iDatabase, txSerial.incrementAndGet()); usingLog = OGlobalConfiguration.TX_USE_LOG.getValueAsBoolean(); } public void begin() { status = TXSTATUS.BEGUN; } public void commit() { checkTransaction(); status = TXSTATUS.COMMITTING; if (database.getStorage() instanceof OStorageProxy) database.getStorage().commit(this); else { final List<String> involvedIndexes = getInvolvedIndexes(); if (involvedIndexes != null) Collections.sort(involvedIndexes); // LOCK INVOLVED INDEXES List<OIndexMVRBTreeAbstract<?>> lockedIndexes = null; try { if (involvedIndexes != null) for (String indexName : involvedIndexes) { final OIndexMVRBTreeAbstract<?> index = (OIndexMVRBTreeAbstract<?>) database.getMetadata().getIndexManager() .getIndexInternal(indexName); if (lockedIndexes == null) lockedIndexes = new ArrayList<OIndexMVRBTreeAbstract<?>>(); index.acquireModificationLock(); lockedIndexes.add(index); } // SEARCH FOR INDEX BASED ON DOCUMENT TOUCHED final Collection<? extends OIndex<?>> indexes = database.getMetadata().getIndexManager().getIndexes(); List<? extends OIndex<?>> indexesToLock = null; if (indexes != null) { indexesToLock = new ArrayList<OIndex<?>>(indexes); Collections.sort(indexesToLock, new Comparator<OIndex<?>>() { public int compare(final OIndex<?> indexOne, final OIndex<?> indexTwo) { return indexOne.getName().compareTo(indexTwo.getName()); } }); } if (indexesToLock != null && !indexesToLock.isEmpty()) { if (lockedIndexes == null) lockedIndexes = new ArrayList<OIndexMVRBTreeAbstract<?>>(); for (OIndex<?> index : indexesToLock) { for (Entry<ORID, ORecordOperation> entry : recordEntries.entrySet()) { final ORecord<?> record = entry.getValue().record.getRecord(); if (record instanceof ODocument) { ODocument doc = (ODocument) record; if (!lockedIndexes.contains(index.getInternal()) && doc.getSchemaClass() != null && index.getDefinition() != null && doc.getSchemaClass().isSubClassOf(index.getDefinition().getClassName())) { index.getInternal().acquireModificationLock(); lockedIndexes.add((OIndexMVRBTreeAbstract<?>) index.getInternal()); } } } } for (OIndexMVRBTreeAbstract<?> index : lockedIndexes) index.acquireExclusiveLock(); } database.getStorage().callInLock(new Callable<Void>() { public Void call() throws Exception { database.getStorage().commit(OTransactionOptimistic.this); // COMMIT INDEX CHANGES final ODocument indexEntries = getIndexChanges(); if (indexEntries != null) { for (Entry<String, Object> indexEntry : indexEntries) { final OIndex<?> index = database.getMetadata().getIndexManager().getIndexInternal(indexEntry.getKey()); index.commit((ODocument) indexEntry.getValue()); } } return null; } }, true); } finally { // RELEASE INDEX LOCKS IF ANY if (lockedIndexes != null) { for (OIndexMVRBTreeAbstract<?> index : lockedIndexes) index.releaseExclusiveLock(); for (OIndexMVRBTreeAbstract<?> index : lockedIndexes) index.releaseModificationLock(); } } } } public void rollback() { checkTransaction(); status = TXSTATUS.ROLLBACKING; // CLEAR THE CACHE MOVING GOOD RECORDS TO LEVEL-2 CACHE database.getLevel1Cache().clear(); // REMOVE ALL THE ENTRIES AND INVALIDATE THE DOCUMENTS TO AVOID TO BE RE-USED DIRTY AT USER-LEVEL. IN THIS WAY RE-LOADING MUST // EXECUTED for (ORecordOperation v : recordEntries.values()) v.getRecord().unload(); for (ORecordOperation v : allEntries.values()) v.getRecord().unload(); indexEntries.clear(); } public ORecordInternal<?> loadRecord(final ORID iRid, final ORecordInternal<?> iRecord, final String iFetchPlan, boolean ignoreCache, boolean loadTombstone) { checkTransaction(); final ORecordInternal<?> txRecord = getRecord(iRid); if (txRecord == OTransactionRealAbstract.DELETED_RECORD) // DELETED IN TX return null; if (txRecord != null) return txRecord; // DELEGATE TO THE STORAGE, NO TOMBSTONES SUPPORT IN TX MODE return database.executeReadRecord((ORecordId) iRid, iRecord, iFetchPlan, ignoreCache, false); } public void deleteRecord(final ORecordInternal<?> iRecord, final OPERATION_MODE iMode) { if (!iRecord.getIdentity().isValid()) return; addRecord(iRecord, ORecordOperation.DELETED, null); } public void saveRecord(final ORecordInternal<?> iRecord, final String iClusterName, final OPERATION_MODE iMode, boolean iForceCreate, final ORecordCallback<? extends Number> iRecordCreatedCallback, ORecordCallback<ORecordVersion> iRecordUpdatedCallback) { if (iRecord == null) return; addRecord(iRecord, iRecord.getIdentity().isValid() ? ORecordOperation.UPDATED : ORecordOperation.CREATED, iClusterName); } protected void addRecord(final ORecordInternal<?> iRecord, final byte iStatus, final String iClusterName) { checkTransaction(); switch (iStatus) { case ORecordOperation.CREATED: database.callbackHooks(TYPE.BEFORE_CREATE, iRecord); break; case ORecordOperation.LOADED: database.callbackHooks(TYPE.BEFORE_READ, iRecord); break; case ORecordOperation.UPDATED: database.callbackHooks(TYPE.BEFORE_UPDATE, iRecord); break; case ORecordOperation.DELETED: database.callbackHooks(TYPE.BEFORE_DELETE, iRecord); break; } try { if (iRecord.getIdentity().isTemporary()) temp2persistent.put(iRecord.getIdentity().copy(), iRecord); if ((status == OTransaction.TXSTATUS.COMMITTING) && database.getStorage() instanceof OStorageEmbedded) { // I'M COMMITTING: BYPASS LOCAL BUFFER switch (iStatus) { case ORecordOperation.CREATED: case ORecordOperation.UPDATED: database.executeSaveRecord(iRecord, iClusterName, iRecord.getRecordVersion(), iRecord.getRecordType(), false, OPERATION_MODE.SYNCHRONOUS, false, null, null); break; case ORecordOperation.DELETED: database.executeDeleteRecord(iRecord, iRecord.getRecordVersion(), false, false, OPERATION_MODE.SYNCHRONOUS, false); break; } final ORecordOperation txRecord = getRecordEntry(iRecord.getIdentity()); if (txRecord != null && txRecord.record != iRecord) { // UPDATE LOCAL RECORDS TO AVOID MISMATCH OF VERSION/CONTENT OLogManager.instance().debug(this, "Update record in transaction: " + txRecord + ", rid=" + (txRecord != null ? txRecord.record : "NULL")); txRecord.record = iRecord; } } else { final ORecordId rid = (ORecordId) iRecord.getIdentity(); if (!rid.isValid()) { iRecord.onBeforeIdentityChanged(rid); // ASSIGN A UNIQUE SERIAL TEMPORARY ID if (rid.clusterId == ORID.CLUSTER_ID_INVALID) rid.clusterId = iClusterName != null ? database.getClusterIdByName(iClusterName) : database.getDefaultClusterId(); rid.clusterPosition = OClusterPositionFactory.INSTANCE.valueOf(newObjectCounter--); iRecord.onAfterIdentityChanged(iRecord); } else // REMOVE FROM THE DB'S CACHE database.getLevel1Cache().freeRecord(rid); ORecordOperation txEntry = getRecordEntry(rid); if (txEntry == null) { if (!(rid.isTemporary() && iStatus != ORecordOperation.CREATED)) { // NEW ENTRY: JUST REGISTER IT txEntry = new ORecordOperation(iRecord, iStatus); recordEntries.put(rid, txEntry); } } else { // UPDATE PREVIOUS STATUS txEntry.record = iRecord; switch (txEntry.type) { case ORecordOperation.LOADED: switch (iStatus) { case ORecordOperation.UPDATED: txEntry.type = ORecordOperation.UPDATED; break; case ORecordOperation.DELETED: txEntry.type = ORecordOperation.DELETED; break; } break; case ORecordOperation.UPDATED: switch (iStatus) { case ORecordOperation.DELETED: txEntry.type = ORecordOperation.DELETED; break; } break; case ORecordOperation.DELETED: break; case ORecordOperation.CREATED: switch (iStatus) { case ORecordOperation.DELETED: recordEntries.remove(rid); break; } break; } } } switch (iStatus) { case ORecordOperation.CREATED: database.callbackHooks(TYPE.AFTER_CREATE, iRecord); break; case ORecordOperation.LOADED: database.callbackHooks(TYPE.AFTER_READ, iRecord); break; case ORecordOperation.UPDATED: database.callbackHooks(TYPE.AFTER_UPDATE, iRecord); break; case ORecordOperation.DELETED: database.callbackHooks(TYPE.AFTER_DELETE, iRecord); break; } } catch (Throwable t) { switch (iStatus) { case ORecordOperation.CREATED: database.callbackHooks(TYPE.CREATE_FAILED, iRecord); break; case ORecordOperation.UPDATED: database.callbackHooks(TYPE.UPDATE_FAILED, iRecord); break; case ORecordOperation.DELETED: database.callbackHooks(TYPE.DELETE_FAILED, iRecord); break; } } } @Override public boolean updateReplica(ORecordInternal<?> iRecord) { throw new UnsupportedOperationException("updateReplica()"); } @Override public String toString() { return "OTransactionOptimistic [id=" + id + ", status=" + status + ", recEntries=" + recordEntries.size() + ", idxEntries=" + indexEntries.size() + ']'; } public boolean isUsingLog() { return usingLog; } public void setUsingLog(final boolean useLog) { this.usingLog = useLog; } }
core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java
/* * Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.core.tx; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map.Entry; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.db.ODatabaseComplex.OPERATION_MODE; import com.orientechnologies.orient.core.db.record.ODatabaseRecordTx; import com.orientechnologies.orient.core.db.record.ORecordOperation; import com.orientechnologies.orient.core.hook.ORecordHook.TYPE; import com.orientechnologies.orient.core.id.OClusterPositionFactory; import com.orientechnologies.orient.core.id.ORID; import com.orientechnologies.orient.core.id.ORecordId; import com.orientechnologies.orient.core.index.OIndex; import com.orientechnologies.orient.core.index.OIndexMVRBTreeAbstract; import com.orientechnologies.orient.core.record.ORecord; import com.orientechnologies.orient.core.record.ORecordInternal; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.storage.ORecordCallback; import com.orientechnologies.orient.core.storage.OStorageEmbedded; import com.orientechnologies.orient.core.storage.OStorageProxy; import com.orientechnologies.orient.core.version.ORecordVersion; public class OTransactionOptimistic extends OTransactionRealAbstract { private boolean usingLog; private static AtomicInteger txSerial = new AtomicInteger(); public OTransactionOptimistic(final ODatabaseRecordTx iDatabase) { super(iDatabase, txSerial.incrementAndGet()); usingLog = OGlobalConfiguration.TX_USE_LOG.getValueAsBoolean(); } public void begin() { status = TXSTATUS.BEGUN; } public void commit() { checkTransaction(); status = TXSTATUS.COMMITTING; if (database.getStorage() instanceof OStorageProxy) database.getStorage().commit(this); else { final List<String> involvedIndexes = getInvolvedIndexes(); if (involvedIndexes != null) Collections.sort(involvedIndexes); // LOCK INVOLVED INDEXES List<OIndexMVRBTreeAbstract<?>> lockedIndexes = null; try { if (involvedIndexes != null) for (String indexName : involvedIndexes) { final OIndexMVRBTreeAbstract<?> index = (OIndexMVRBTreeAbstract<?>) database.getMetadata().getIndexManager() .getIndexInternal(indexName); if (lockedIndexes == null) lockedIndexes = new ArrayList<OIndexMVRBTreeAbstract<?>>(); index.acquireModificationLock(); lockedIndexes.add(index); } // SEARCH FOR INDEX BASED ON DOCUMENT TOUCHED final Collection<? extends OIndex<?>> indexes = database.getMetadata().getIndexManager().getIndexes(); List<? extends OIndex<?>> indexesToLock = null; if (indexes != null) { indexesToLock = new ArrayList<OIndex<?>>(indexes); Collections.sort(indexesToLock, new Comparator<OIndex<?>>() { public int compare(final OIndex<?> indexOne, final OIndex<?> indexTwo) { return indexOne.getName().compareTo(indexTwo.getName()); } }); } if (indexesToLock != null && !indexesToLock.isEmpty()) if (lockedIndexes == null) lockedIndexes = new ArrayList<OIndexMVRBTreeAbstract<?>>(); for (OIndex<?> index : indexesToLock) { for (Entry<ORID, ORecordOperation> entry : recordEntries.entrySet()) { final ORecord<?> record = entry.getValue().record.getRecord(); if (record instanceof ODocument) { ODocument doc = (ODocument) record; if (!lockedIndexes.contains(index.getInternal()) && doc.getSchemaClass() != null && index.getDefinition() != null && doc.getSchemaClass().isSubClassOf(index.getDefinition().getClassName())) { index.getInternal().acquireModificationLock(); lockedIndexes.add((OIndexMVRBTreeAbstract<?>) index.getInternal()); } } } } for (OIndexMVRBTreeAbstract<?> index : lockedIndexes) index.acquireExclusiveLock(); database.getStorage().callInLock(new Callable<Void>() { public Void call() throws Exception { database.getStorage().commit(OTransactionOptimistic.this); // COMMIT INDEX CHANGES final ODocument indexEntries = getIndexChanges(); if (indexEntries != null) { for (Entry<String, Object> indexEntry : indexEntries) { final OIndex<?> index = database.getMetadata().getIndexManager().getIndexInternal(indexEntry.getKey()); index.commit((ODocument) indexEntry.getValue()); } } return null; } }, true); } finally { // RELEASE INDEX LOCKS IF ANY if (lockedIndexes != null) { for (OIndexMVRBTreeAbstract<?> index : lockedIndexes) index.releaseExclusiveLock(); for (OIndexMVRBTreeAbstract<?> index : lockedIndexes) index.releaseModificationLock(); } } } } public void rollback() { checkTransaction(); status = TXSTATUS.ROLLBACKING; // CLEAR THE CACHE MOVING GOOD RECORDS TO LEVEL-2 CACHE database.getLevel1Cache().clear(); // REMOVE ALL THE ENTRIES AND INVALIDATE THE DOCUMENTS TO AVOID TO BE RE-USED DIRTY AT USER-LEVEL. IN THIS WAY RE-LOADING MUST // EXECUTED for (ORecordOperation v : recordEntries.values()) v.getRecord().unload(); for (ORecordOperation v : allEntries.values()) v.getRecord().unload(); indexEntries.clear(); } public ORecordInternal<?> loadRecord(final ORID iRid, final ORecordInternal<?> iRecord, final String iFetchPlan, boolean ignoreCache, boolean loadTombstone) { checkTransaction(); final ORecordInternal<?> txRecord = getRecord(iRid); if (txRecord == OTransactionRealAbstract.DELETED_RECORD) // DELETED IN TX return null; if (txRecord != null) return txRecord; // DELEGATE TO THE STORAGE, NO TOMBSTONES SUPPORT IN TX MODE return database.executeReadRecord((ORecordId) iRid, iRecord, iFetchPlan, ignoreCache, false); } public void deleteRecord(final ORecordInternal<?> iRecord, final OPERATION_MODE iMode) { if (!iRecord.getIdentity().isValid()) return; addRecord(iRecord, ORecordOperation.DELETED, null); } public void saveRecord(final ORecordInternal<?> iRecord, final String iClusterName, final OPERATION_MODE iMode, boolean iForceCreate, final ORecordCallback<? extends Number> iRecordCreatedCallback, ORecordCallback<ORecordVersion> iRecordUpdatedCallback) { if (iRecord == null) return; addRecord(iRecord, iRecord.getIdentity().isValid() ? ORecordOperation.UPDATED : ORecordOperation.CREATED, iClusterName); } protected void addRecord(final ORecordInternal<?> iRecord, final byte iStatus, final String iClusterName) { checkTransaction(); switch (iStatus) { case ORecordOperation.CREATED: database.callbackHooks(TYPE.BEFORE_CREATE, iRecord); break; case ORecordOperation.LOADED: database.callbackHooks(TYPE.BEFORE_READ, iRecord); break; case ORecordOperation.UPDATED: database.callbackHooks(TYPE.BEFORE_UPDATE, iRecord); break; case ORecordOperation.DELETED: database.callbackHooks(TYPE.BEFORE_DELETE, iRecord); break; } try { if (iRecord.getIdentity().isTemporary()) temp2persistent.put(iRecord.getIdentity().copy(), iRecord); if ((status == OTransaction.TXSTATUS.COMMITTING) && database.getStorage() instanceof OStorageEmbedded) { // I'M COMMITTING: BYPASS LOCAL BUFFER switch (iStatus) { case ORecordOperation.CREATED: case ORecordOperation.UPDATED: database.executeSaveRecord(iRecord, iClusterName, iRecord.getRecordVersion(), iRecord.getRecordType(), false, OPERATION_MODE.SYNCHRONOUS, false, null, null); break; case ORecordOperation.DELETED: database.executeDeleteRecord(iRecord, iRecord.getRecordVersion(), false, false, OPERATION_MODE.SYNCHRONOUS, false); break; } final ORecordOperation txRecord = getRecordEntry(iRecord.getIdentity()); if (txRecord != null && txRecord.record != iRecord) { // UPDATE LOCAL RECORDS TO AVOID MISMATCH OF VERSION/CONTENT OLogManager.instance().debug(this, "Update record in transaction: " + txRecord + ", rid=" + (txRecord != null ? txRecord.record : "NULL")); txRecord.record = iRecord; } } else { final ORecordId rid = (ORecordId) iRecord.getIdentity(); if (!rid.isValid()) { iRecord.onBeforeIdentityChanged(rid); // ASSIGN A UNIQUE SERIAL TEMPORARY ID if (rid.clusterId == ORID.CLUSTER_ID_INVALID) rid.clusterId = iClusterName != null ? database.getClusterIdByName(iClusterName) : database.getDefaultClusterId(); rid.clusterPosition = OClusterPositionFactory.INSTANCE.valueOf(newObjectCounter--); iRecord.onAfterIdentityChanged(iRecord); } else // REMOVE FROM THE DB'S CACHE database.getLevel1Cache().freeRecord(rid); ORecordOperation txEntry = getRecordEntry(rid); if (txEntry == null) { if (!(rid.isTemporary() && iStatus != ORecordOperation.CREATED)) { // NEW ENTRY: JUST REGISTER IT txEntry = new ORecordOperation(iRecord, iStatus); recordEntries.put(rid, txEntry); } } else { // UPDATE PREVIOUS STATUS txEntry.record = iRecord; switch (txEntry.type) { case ORecordOperation.LOADED: switch (iStatus) { case ORecordOperation.UPDATED: txEntry.type = ORecordOperation.UPDATED; break; case ORecordOperation.DELETED: txEntry.type = ORecordOperation.DELETED; break; } break; case ORecordOperation.UPDATED: switch (iStatus) { case ORecordOperation.DELETED: txEntry.type = ORecordOperation.DELETED; break; } break; case ORecordOperation.DELETED: break; case ORecordOperation.CREATED: switch (iStatus) { case ORecordOperation.DELETED: recordEntries.remove(rid); break; } break; } } } switch (iStatus) { case ORecordOperation.CREATED: database.callbackHooks(TYPE.AFTER_CREATE, iRecord); break; case ORecordOperation.LOADED: database.callbackHooks(TYPE.AFTER_READ, iRecord); break; case ORecordOperation.UPDATED: database.callbackHooks(TYPE.AFTER_UPDATE, iRecord); break; case ORecordOperation.DELETED: database.callbackHooks(TYPE.AFTER_DELETE, iRecord); break; } } catch (Throwable t) { switch (iStatus) { case ORecordOperation.CREATED: database.callbackHooks(TYPE.CREATE_FAILED, iRecord); break; case ORecordOperation.UPDATED: database.callbackHooks(TYPE.UPDATE_FAILED, iRecord); break; case ORecordOperation.DELETED: database.callbackHooks(TYPE.DELETE_FAILED, iRecord); break; } } } @Override public boolean updateReplica(ORecordInternal<?> iRecord) { throw new UnsupportedOperationException("updateReplica()"); } @Override public String toString() { return "OTransactionOptimistic [id=" + id + ", status=" + status + ", recEntries=" + recordEntries.size() + ", idxEntries=" + indexEntries.size() + ']'; } public boolean isUsingLog() { return usingLog; } public void setUsingLog(final boolean useLog) { this.usingLog = useLog; } }
Index: fixed problem on index locking
core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java
Index: fixed problem on index locking
<ide><path>ore/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java <ide> }); <ide> } <ide> <del> if (indexesToLock != null && !indexesToLock.isEmpty()) <add> if (indexesToLock != null && !indexesToLock.isEmpty()) { <ide> if (lockedIndexes == null) <ide> lockedIndexes = new ArrayList<OIndexMVRBTreeAbstract<?>>(); <ide> <del> for (OIndex<?> index : indexesToLock) { <del> for (Entry<ORID, ORecordOperation> entry : recordEntries.entrySet()) { <del> final ORecord<?> record = entry.getValue().record.getRecord(); <del> if (record instanceof ODocument) { <del> ODocument doc = (ODocument) record; <del> if (!lockedIndexes.contains(index.getInternal()) && doc.getSchemaClass() != null && index.getDefinition() != null <del> && doc.getSchemaClass().isSubClassOf(index.getDefinition().getClassName())) { <del> index.getInternal().acquireModificationLock(); <del> lockedIndexes.add((OIndexMVRBTreeAbstract<?>) index.getInternal()); <add> for (OIndex<?> index : indexesToLock) { <add> for (Entry<ORID, ORecordOperation> entry : recordEntries.entrySet()) { <add> final ORecord<?> record = entry.getValue().record.getRecord(); <add> if (record instanceof ODocument) { <add> ODocument doc = (ODocument) record; <add> if (!lockedIndexes.contains(index.getInternal()) && doc.getSchemaClass() != null && index.getDefinition() != null <add> && doc.getSchemaClass().isSubClassOf(index.getDefinition().getClassName())) { <add> index.getInternal().acquireModificationLock(); <add> lockedIndexes.add((OIndexMVRBTreeAbstract<?>) index.getInternal()); <add> } <ide> } <ide> } <ide> } <del> } <del> <del> for (OIndexMVRBTreeAbstract<?> index : lockedIndexes) <del> index.acquireExclusiveLock(); <add> <add> for (OIndexMVRBTreeAbstract<?> index : lockedIndexes) <add> index.acquireExclusiveLock(); <add> } <ide> <ide> database.getStorage().callInLock(new Callable<Void>() { <ide>
Java
mit
e01367f1e52e8510f97843da56ee06651fbdc2c2
0
thaliproject/Thali_CordovaPlugin,thaliproject/Thali_CordovaPlugin,thaliproject/Thali_CordovaPlugin,thaliproject/Thali_CordovaPlugin,thaliproject/Thali_CordovaPlugin
/* Copyright (c) 2015-2016 Microsoft Corporation. This software is licensed under the MIT License. * See the license file delivered with this project for further information. */ package io.jxcore.node; import android.content.Context; import android.net.wifi.WifiManager; import android.os.Build; import android.util.Log; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.thaliproject.p2p.btconnectorlib.DiscoveryManager; import org.thaliproject.p2p.btconnectorlib.PeerProperties; import org.thaliproject.p2p.btconnectorlib.internal.bluetooth.BluetoothManager; import org.thaliproject.p2p.btconnectorlib.internal.bluetooth.BluetoothUtils; import org.thaliproject.p2p.btconnectorlib.utils.CommonUtils; import java.util.ArrayList; import java.util.Date; import io.jxcore.node.jxcore.JXcoreCallback; /** * Implements Thali native interface. * For the documentation, please see * https://github.com/thaliproject/Thali_CordovaPlugin/blob/vNext/thali/NextGeneration/thaliMobileNative.js */ public class JXcoreExtension { // Common Thali methods and events public static final String CALLBACK_VALUE_LISTENING_ON_PORT_NUMBER = "listeningPort"; public static final String CALLBACK_VALUE_CLIENT_PORT_NUMBER = "clientPort"; public static final String CALLBACK_VALUE_SERVER_PORT_NUMBER = "serverPort"; private static final String METHOD_NAME_START_LISTENING_FOR_ADVERTISEMENTS = "startListeningForAdvertisements"; private static final String METHOD_NAME_STOP_LISTENING_FOR_ADVERTISEMENTS = "stopListeningForAdvertisements"; private static final String METHOD_NAME_START_UPDATE_ADVERTISING_AND_LISTENING = "startUpdateAdvertisingAndListening"; private static final String METHOD_NAME_STOP_ADVERTISING_AND_LISTENING = "stopAdvertisingAndListening"; private static final String METHOD_NAME_CONNECT = "connect"; private static final String METHOD_NAME_KILL_CONNECTIONS = "killConnections"; private static final String METHOD_NAME_DID_REGISTER_TO_NATIVE = "didRegisterToNative"; private static final String EVENT_NAME_PEER_AVAILABILITY_CHANGED = "peerAvailabilityChanged"; private static final String EVENT_NAME_DISCOVERY_ADVERTISING_STATE_UPDATE = "discoveryAdvertisingStateUpdateNonTCP"; private static final String EVENT_NAME_NETWORK_CHANGED = "networkChanged"; private static final String EVENT_NAME_INCOMING_CONNECTION_TO_PORT_NUMBER_FAILED = "incomingConnectionToPortNumberFailed"; private static final String METHOD_ARGUMENT_NETWORK_CHANGED = EVENT_NAME_NETWORK_CHANGED; private static final String EVENT_VALUE_PEER_ID = "peerIdentifier"; private static final String EVENT_VALUE_PEER_AVAILABLE = "peerAvailable"; private static final String EVENT_VALUE_PLEASE_CONNECT = "pleaseConnect"; private static final String EVENT_VALUE_DISCOVERY_ACTIVE = "discoveryActive"; private static final String EVENT_VALUE_ADVERTISING_ACTIVE = "advertisingActive"; private static final String EVENT_VALUE_BLUETOOTH_LOW_ENERGY = "bluetoothLowEnergy"; private static final String EVENT_VALUE_BLUETOOTH = "bluetooth"; private static final String EVENT_VALUE_WIFI = "wifi"; private static final String EVENT_VALUE_CELLULAR = "cellular"; private static final String EVENT_VALUE_BSSID_NAME = "bssidName"; private static final String EVENT_VALUE_SSID_NAME = "ssidName"; private static final String EVENT_VALUE_PORT_NUMBER = "portNumber"; // Android specific methods and events private static final String METHOD_NAME_IS_BLE_MULTIPLE_ADVERTISEMENT_SUPPORTED = "isBleMultipleAdvertisementSupported"; private static final String METHOD_NAME_GET_BLUETOOTH_ADDRESS = "getBluetoothAddress"; private static final String METHOD_NAME_GET_BLUETOOTH_NAME = "getBluetoothName"; private static final String METHOD_NAME_KILL_OUTGOING_CONNECTIONS = "killOutgoingConnections"; private static final String METHOD_NAME_GET_OS_VERSION = "getOSVersion"; private static final String METHOD_NAME_RECONNECT_WIFI_AP = "reconnectWifiAp"; private static final String METHOD_NAME_SHOW_TOAST = "showToast"; private static final String TAG = JXcoreExtension.class.getName(); private static final String BLUETOOTH_MAC_ADDRESS_AND_TOKEN_COUNTER_SEPARATOR = "-"; private static final long INCOMING_CONNECTION_FAILED_NOTIFICATION_MIN_INTERVAL_IN_MILLISECONDS = 100; private static ConnectionHelper mConnectionHelper = null; private static long mLastTimeIncomingConnectionFailedNotificationWasFired = 0; private static boolean mNetworkChangedRegistered = false; public static void LoadExtensions() { if (mConnectionHelper != null) { Log.e(TAG, "LoadExtensions: A connection helper instance already exists - this indicates that this method was called twice - disposing of the previous instance"); mConnectionHelper.dispose(); mConnectionHelper = null; } mConnectionHelper = new ConnectionHelper(); final LifeCycleMonitor lifeCycleMonitor = new LifeCycleMonitor(new LifeCycleMonitor.LifeCycleMonitorListener() { @Override public void onActivityLifeCycleEvent(LifeCycleMonitor.ActivityLifeCycleEvent activityLifeCycleEvent) { Log.d(TAG, "onActivityLifeCycleEvent: " + activityLifeCycleEvent); switch (activityLifeCycleEvent) { case DESTROYED: mConnectionHelper.dispose(); default: // No need to do anything } } }); lifeCycleMonitor.start(); /* This is the line where we are dynamically sticking execution of UT during build, so if you are editing this line, please check updateJXCoreExtensionWithUTMethod in androidBeforeCompile.js. */ jxcore.RegisterMethod(METHOD_NAME_START_LISTENING_FOR_ADVERTISEMENTS, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, String callbackId) { Log.d(TAG, METHOD_NAME_START_LISTENING_FOR_ADVERTISEMENTS); startConnectionHelper(ConnectionHelper.NO_PORT_NUMBER, false, callbackId); } }); jxcore.RegisterMethod(METHOD_NAME_STOP_LISTENING_FOR_ADVERTISEMENTS, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, final String callbackId) { Log.d(TAG, METHOD_NAME_STOP_LISTENING_FOR_ADVERTISEMENTS); mConnectionHelper.stop(true, new JXcoreThaliCallback() { @Override protected void onStartStopCallback(String errorMessage) { ArrayList<Object> args = new ArrayList<Object>(); args.add(errorMessage); jxcore.CallJSMethod(callbackId, args.toArray()); } }); } }); jxcore.RegisterMethod(METHOD_NAME_START_UPDATE_ADVERTISING_AND_LISTENING, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, String callbackId) { Log.d(TAG, METHOD_NAME_START_UPDATE_ADVERTISING_AND_LISTENING); ArrayList<Object> args = new ArrayList<Object>(); String errorString = null; if (params != null && params.size() > 0) { Object parameterObject = params.get(0); if (parameterObject instanceof Integer && ((Integer) parameterObject > 0)) { startConnectionHelper((Integer) parameterObject, true, callbackId); } else { errorString = "Required parameter, {number} portNumber, is invalid - must be a positive integer"; } } else { errorString = "Required parameter, {number} portNumber, missing"; } if (errorString != null) { // Failed straight away args.add(errorString); jxcore.CallJSMethod(callbackId, args.toArray()); } } }); jxcore.RegisterMethod(METHOD_NAME_STOP_ADVERTISING_AND_LISTENING, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, final String callbackId) { Log.d(TAG, METHOD_NAME_STOP_ADVERTISING_AND_LISTENING); mConnectionHelper.stop(false, new JXcoreThaliCallback() { @Override protected void onStartStopCallback(String errorMessage) { ArrayList<Object> args = new ArrayList<Object>(); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); } }); } }); jxcore.RegisterMethod(METHOD_NAME_CONNECT, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, final String callbackId) { if (params.size() == 0) { ArrayList<Object> args = new ArrayList<Object>(); args.add("Required parameter, {string} peerIdentifier, missing"); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); return; } if (mConnectionHelper.getConnectivityMonitor().isBleMultipleAdvertisementSupported() == BluetoothManager.FeatureSupportedStatus.NOT_SUPPORTED) { ArrayList<Object> args = new ArrayList<Object>(); args.add("No Native Non-TCP Support"); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); return; } if (mConnectionHelper.getDiscoveryManager().getState() == DiscoveryManager.DiscoveryManagerState.WAITING_FOR_SERVICES_TO_BE_ENABLED) { ArrayList<Object> args = new ArrayList<Object>(); args.add("Radio Turned Off"); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); return; } final DiscoveryManager discoveryManager = mConnectionHelper.getDiscoveryManager(); final DiscoveryManager.DiscoveryManagerState discoveryManagerState = discoveryManager.getState(); if (discoveryManagerState != DiscoveryManager.DiscoveryManagerState.RUNNING_BLE) { ArrayList<Object> args = new ArrayList<Object>(); args.add("startListeningForAdvertisements is not active"); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); return; } String peerId = params.get(0).toString(); String bluetoothMacAddress = null; if (peerId != null) { try { bluetoothMacAddress = peerId.split(BLUETOOTH_MAC_ADDRESS_AND_TOKEN_COUNTER_SEPARATOR)[0]; } catch (IndexOutOfBoundsException e) { Log.e(TAG, METHOD_NAME_CONNECT + ": Failed to extract the Bluetooth MAC address: " + e.getMessage(), e); } } if (!BluetoothUtils.isValidBluetoothMacAddress(bluetoothMacAddress)) { ArrayList<Object> args = new ArrayList<Object>(); args.add("Illegal peerID"); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); return; } Log.d(TAG, METHOD_NAME_CONNECT + ": " + bluetoothMacAddress); if (mConnectionHelper.getConnectionModel().getOutgoingConnectionCallbackByBluetoothMacAddress(bluetoothMacAddress) != null) { Log.e(TAG, METHOD_NAME_CONNECT + ": Already connecting"); ArrayList<Object> args = new ArrayList<Object>(); // In case you want to check, if we are already connected (instead of connecting), do: // mConnectionHelper.getConnectionModel().hasOutgoingConnection() args.add("Already connect(ing/ed)"); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); return; } if (mConnectionHelper.hasMaximumNumberOfConnections()) { ArrayList<Object> args = new ArrayList<Object>(); args.add("Max connections reached"); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); return; } final String errorMessage = mConnectionHelper.connect(bluetoothMacAddress, new JXcoreThaliCallback() { @Override public void onConnectCallback( String errorMessage, ListenerOrIncomingConnection listenerOrIncomingConnection) { ArrayList<Object> args = new ArrayList<Object>(); args.add(errorMessage); if (errorMessage == null) { if (listenerOrIncomingConnection != null) { args.add(listenerOrIncomingConnection.toString()); } else { throw new NullPointerException( "ListenerOrIncomingConnection is null even though there is no error message"); } } jxcore.CallJSMethod(callbackId, args.toArray()); } }); if (errorMessage != null) { // Failed to start connecting ArrayList<Object> args = new ArrayList<Object>(); args.add(errorMessage); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); } } }); /** * Not supported on Android. */ jxcore.RegisterMethod(METHOD_NAME_KILL_CONNECTIONS, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, String callbackId) { ArrayList<Object> args = new ArrayList<Object>(); args.add("Not Supported"); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); } }); jxcore.RegisterMethod(METHOD_NAME_DID_REGISTER_TO_NATIVE, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, String callbackId) { ArrayList<Object> args = new ArrayList<Object>(); String errorString = null; if (params != null && params.size() > 0) { Object parameterObject = params.get(0); if (parameterObject instanceof String && CommonUtils.isNonEmptyString((String) parameterObject)) { String methodName = (String) parameterObject; if (methodName.equals(METHOD_ARGUMENT_NETWORK_CHANGED)) { mNetworkChangedRegistered = true; mConnectionHelper.getConnectivityMonitor().updateConnectivityInfo(true); // Will call notifyNetworkChanged } else { errorString = "Unrecognized method name: " + methodName; } } else { errorString = "Required parameter, {string} methodName, is invalid - must be a non-null and non-empty string"; } } else { errorString = "Required parameter, {string} methodName, missing"; } args.add(errorString); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); } }); /* * Android specific methods start here */ /** * Method for checking whether or not the device supports Bluetooth LE multi advertisement. * * When successful, the method will return two arguments: The first will have null value and * the second will contain a string value: * * - "Not resolved" if not resolved (can happen when Bluetooth is disabled) * - "Not supported" if not supported * - "Supported" if supported * * In case of an error the first argument will contain an error message followed by a null * argument. More specifically the error message will be a string starting with * "Unrecognized status: " followed by the unrecognized status. */ jxcore.RegisterMethod(METHOD_NAME_IS_BLE_MULTIPLE_ADVERTISEMENT_SUPPORTED, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, String callbackId) { ArrayList<Object> args = new ArrayList<Object>(); BluetoothManager bluetoothManager = mConnectionHelper.getDiscoveryManager().getBluetoothManager(); BluetoothManager.FeatureSupportedStatus featureSupportedStatus = bluetoothManager.isBleMultipleAdvertisementSupported(); Log.v(TAG, METHOD_NAME_IS_BLE_MULTIPLE_ADVERTISEMENT_SUPPORTED + ": " + featureSupportedStatus); switch (featureSupportedStatus) { case NOT_RESOLVED: args.add(null); args.add("Not resolved"); break; case NOT_SUPPORTED: args.add(null); args.add("Not supported"); break; case SUPPORTED: args.add(null); args.add("Supported"); break; default: String errorMessage = "Unrecognized status: " + featureSupportedStatus; Log.e(TAG, METHOD_NAME_IS_BLE_MULTIPLE_ADVERTISEMENT_SUPPORTED + ": " + errorMessage); args.add(errorMessage); args.add(null); break; } jxcore.CallJSMethod(callbackId, args.toArray()); } }); jxcore.RegisterMethod(METHOD_NAME_GET_BLUETOOTH_ADDRESS, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, String callbackId) { ArrayList<Object> args = new ArrayList<Object>(); String bluetoothMacAddress = mConnectionHelper.getDiscoveryManager().getBluetoothMacAddress(); if (bluetoothMacAddress == null || bluetoothMacAddress.length() == 0) { args.add("Bluetooth MAC address unknown"); } else { args.add(null); args.add(bluetoothMacAddress); } jxcore.CallJSMethod(callbackId, args.toArray()); } }); jxcore.RegisterMethod(METHOD_NAME_GET_BLUETOOTH_NAME, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, String callbackId) { ArrayList<Object> args = new ArrayList<Object>(); String bluetoothNameString = mConnectionHelper.getBluetoothName(); if (bluetoothNameString == null) { args.add("Unable to get the Bluetooth name"); } else { args.add(null); args.add(bluetoothNameString); } jxcore.CallJSMethod(callbackId, args.toArray()); } }); jxcore.RegisterMethod(METHOD_NAME_KILL_OUTGOING_CONNECTIONS, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, String callbackId) { mConnectionHelper.killConnections(false); ArrayList<Object> args = new ArrayList<Object>(); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); } }); jxcore.RegisterMethod(METHOD_NAME_GET_OS_VERSION, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, String callbackId) { ArrayList<Object> args = new ArrayList<Object>(); args.add(Build.VERSION.RELEASE); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); } }); jxcore.RegisterMethod(METHOD_NAME_RECONNECT_WIFI_AP, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, String callbackId) { ArrayList<Object> args = new ArrayList<Object>(); WifiManager wifiManager = (WifiManager) jxcore.activity.getBaseContext().getSystemService(Context.WIFI_SERVICE); if (wifiManager.reconnect()) { wifiManager.disconnect(); if (!wifiManager.reconnect()) { args.add("WifiManager.reconnect returned false"); } } args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); } }); jxcore.RegisterMethod(METHOD_NAME_SHOW_TOAST, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, String callbackId) { ArrayList<Object> args = new ArrayList<Object>(); if (params.size() == 0) { args.add("Required parameter (toast message) missing"); } else { String message = params.get(0).toString(); int toastDuration = Toast.LENGTH_SHORT; if (params.size() == 2 && ((Boolean) params.get(1))) { toastDuration = Toast.LENGTH_LONG; } Toast.makeText(jxcore.activity.getApplicationContext(), message, toastDuration).show(); args.add(null); } jxcore.CallJSMethod(callbackId, args.toArray()); } }); } public static void notifyPeerAvailabilityChanged(PeerProperties peerProperties, boolean isAvailable) { String peerId = peerProperties.getId() + BLUETOOTH_MAC_ADDRESS_AND_TOKEN_COUNTER_SEPARATOR + peerProperties.getExtraInformation(); JSONObject jsonObject = new JSONObject(); boolean jsonObjectCreated = false; try { jsonObject.put(EVENT_VALUE_PEER_ID, peerId); jsonObject.put(EVENT_VALUE_PEER_AVAILABLE, isAvailable); jsonObject.put(EVENT_VALUE_PLEASE_CONNECT, false); jsonObjectCreated = true; } catch (JSONException e) { Log.e(TAG, "notifyPeerAvailabilityChanged: Failed to populate the JSON object: " + e.getMessage(), e); } if (jsonObjectCreated) { JSONArray jsonArray = new JSONArray(); jsonArray.put(jsonObject); final String jsonArrayAsString = jsonArray.toString(); jxcore.activity.runOnUiThread(new Runnable() { @Override public void run() { jxcore.CallJSMethod(EVENT_NAME_PEER_AVAILABILITY_CHANGED, jsonArrayAsString); } }); } } public static void notifyDiscoveryAdvertisingStateUpdateNonTcp( boolean isDiscoveryActive, boolean isAdvertisingActive) { JSONObject jsonObject = new JSONObject(); boolean jsonObjectCreated = false; try { jsonObject.put(EVENT_VALUE_DISCOVERY_ACTIVE, isDiscoveryActive); jsonObject.put(EVENT_VALUE_ADVERTISING_ACTIVE, isAdvertisingActive); jsonObjectCreated = true; } catch (JSONException e) { Log.e(TAG, "notifyDiscoveryAdvertisingStateUpdateNonTcp: Failed to populate the JSON object: " + e.getMessage(), e); } if (jsonObjectCreated) { final String jsonObjectAsString = jsonObject.toString(); try { jxcore.activity.runOnUiThread(new Runnable() { @Override public void run() { jxcore.CallJSMethod(EVENT_NAME_DISCOVERY_ADVERTISING_STATE_UPDATE, jsonObjectAsString); } }); } catch (NullPointerException e) { Log.e(TAG, "notifyDiscoveryAdvertisingStateUpdateNonTcp: Failed to notify: " + e.getMessage(), e); } } } /** * @param isBluetoothEnabled If true, Bluetooth is enabled. False otherwise. * @param isWifiEnabled If true, Wi-Fi is enabled. False otherwise. * @param bssidName If null this value indicates that either wifiRadioOn is not 'on' or * that the Wi-Fi isn't currently connected to an access point. * If non-null then this is the BSSID of the access point that Wi-Fi * is connected to. */ public static synchronized void notifyNetworkChanged( boolean isBluetoothEnabled, boolean isWifiEnabled, String bssidName, String ssidName) { if (!mNetworkChangedRegistered) { Log.d(TAG, "notifyNetworkChanged: Not registered for event \"" + EVENT_NAME_NETWORK_CHANGED + "\" and will not notify, in JS call method \"" + METHOD_NAME_DID_REGISTER_TO_NATIVE + "\" with argument \"" + METHOD_ARGUMENT_NETWORK_CHANGED + "\" to register"); return; } RadioState bluetoothLowEnergyRadioState; RadioState bluetoothRadioState; RadioState wifiRadioState; RadioState cellularRadioState = RadioState.DO_NOT_CARE; final ConnectivityMonitor connectivityMonitor = mConnectionHelper.getConnectivityMonitor(); if (connectivityMonitor.isBleMultipleAdvertisementSupported() != BluetoothManager.FeatureSupportedStatus.NOT_SUPPORTED) { if (isBluetoothEnabled) { bluetoothLowEnergyRadioState = RadioState.ON; } else { bluetoothLowEnergyRadioState = RadioState.OFF; } } else { bluetoothLowEnergyRadioState = RadioState.NOT_HERE; } if (connectivityMonitor.isBluetoothSupported()) { if (isBluetoothEnabled) { bluetoothRadioState = RadioState.ON; } else { bluetoothRadioState = RadioState.OFF; } } else { bluetoothRadioState = RadioState.NOT_HERE; } if (connectivityMonitor.isWifiDirectSupported()) { if (isWifiEnabled) { wifiRadioState = RadioState.ON; } else { wifiRadioState = RadioState.OFF; } } else { wifiRadioState = RadioState.NOT_HERE; } Log.d(TAG, "notifyNetworkChanged: BLE: " + bluetoothLowEnergyRadioState + ", Bluetooth: " + bluetoothRadioState + ", Wi-Fi: " + wifiRadioState + ", cellular: " + cellularRadioState + ", BSSID name: " + bssidName + ", SSID name: " + ssidName); JSONObject jsonObject = new JSONObject(); boolean jsonObjectCreated = false; try { jsonObject.put(EVENT_VALUE_BLUETOOTH_LOW_ENERGY, radioStateEnumValueToString(bluetoothLowEnergyRadioState)); jsonObject.put(EVENT_VALUE_BLUETOOTH, radioStateEnumValueToString(bluetoothRadioState)); jsonObject.put(EVENT_VALUE_WIFI, radioStateEnumValueToString(wifiRadioState)); jsonObject.put(EVENT_VALUE_CELLULAR, radioStateEnumValueToString(cellularRadioState)); jsonObject.put(EVENT_VALUE_BSSID_NAME, bssidName); jsonObject.put(EVENT_VALUE_SSID_NAME, ssidName); jsonObjectCreated = true; } catch (JSONException e) { Log.e(TAG, "notifyNetworkChanged: Failed to populate the JSON object: " + e.getMessage(), e); } if (jsonObjectCreated) { final String jsonObjectAsString = jsonObject.toString(); jxcore.activity.runOnUiThread(new Runnable() { @Override public void run() { jxcore.CallJSMethod(EVENT_NAME_NETWORK_CHANGED, jsonObjectAsString); } }); } } /** * This event is guaranteed to be not sent more often than every 100 ms. * * @param portNumber The 127.0.0.1 port that the TCP/IP bridge tried to connect to. */ public static void notifyIncomingConnectionToPortNumberFailed(int portNumber) { long currentTime = new Date().getTime(); if (currentTime > mLastTimeIncomingConnectionFailedNotificationWasFired + INCOMING_CONNECTION_FAILED_NOTIFICATION_MIN_INTERVAL_IN_MILLISECONDS) { JSONObject jsonObject = new JSONObject(); boolean jsonObjectCreated = false; try { jsonObject.put(EVENT_VALUE_PORT_NUMBER, portNumber); jsonObjectCreated = true; } catch (JSONException e) { Log.e(TAG, "notifyIncomingConnectionToPortNumberFailed: Failed to populate the JSON object: " + e.getMessage(), e); } if (jsonObjectCreated) { mLastTimeIncomingConnectionFailedNotificationWasFired = currentTime; final String jsonObjectAsString = jsonObject.toString(); jxcore.activity.runOnUiThread(new Runnable() { @Override public void run() { jxcore.CallJSMethod(EVENT_NAME_INCOMING_CONNECTION_TO_PORT_NUMBER_FAILED, jsonObjectAsString); } }); } } } /** * Tries to starts the connection helper. * * @param serverPortNumber The port on 127.0.0.1 that any incoming connections over the native * non-TCP/IP transport should be bridged to. * @param startAdvertisements If true, will start advertising our presence and scanning for other peers. * If false, will only scan for other peers. * @param callbackId The JXcore callback ID. */ private static void startConnectionHelper( int serverPortNumber, boolean startAdvertisements, final String callbackId) { final ArrayList<Object> args = new ArrayList<Object>(); String errorString = null; if (mConnectionHelper.getConnectivityMonitor().isBleMultipleAdvertisementSupported() != BluetoothManager.FeatureSupportedStatus.NOT_SUPPORTED) { boolean succeededToStartOrWasAlreadyRunning = mConnectionHelper.start(serverPortNumber, startAdvertisements, new JXcoreThaliCallback() { @Override protected void onStartStopCallback(final String errorMessage) { args.add(errorMessage); jxcore.CallJSMethod(callbackId, args.toArray()); } }); if (succeededToStartOrWasAlreadyRunning) { final DiscoveryManager discoveryManager = mConnectionHelper.getDiscoveryManager(); if (discoveryManager.getState() == DiscoveryManager.DiscoveryManagerState.WAITING_FOR_SERVICES_TO_BE_ENABLED) { errorString = "Radio Turned Off"; // If/when radios are turned on, the discovery is started automatically // unless stop is called } } else { errorString = "Unspecified Error with Radio infrastructure"; } } else { errorString = "No Native Non-TCP Support"; } if (errorString != null) { // Failed straight away args.add(errorString); jxcore.CallJSMethod(callbackId, args.toArray()); } } /** * Returns a string value matching the given RadioState enum value. * * @param radioState The RadioState enum value. * @return A string matching the given RadioState enum value. */ private static String radioStateEnumValueToString(RadioState radioState) { switch (radioState) { case ON: return "on"; case OFF: return "off"; case UNAVAILABLE: return "unavailable"; case NOT_HERE: return "notHere"; case DO_NOT_CARE: return "doNotCare"; } return null; } public enum RadioState { ON, // The radio is on and available for use. OFF, // The radio exists on the device but is turned off. UNAVAILABLE, // The radio exists on the device and is on but for some reason the system won't let us use it. NOT_HERE, // We depend on this radio type for this platform type but it doesn't appear to exist on this device. DO_NOT_CARE // Thali doesn't use this radio type on this platform and so makes no effort to determine its state. } }
src/android/java/io/jxcore/node/JXcoreExtension.java
/* Copyright (c) 2015-2016 Microsoft Corporation. This software is licensed under the MIT License. * See the license file delivered with this project for further information. */ package io.jxcore.node; import com.test.thalitest.RegisterExecuteUT; import android.content.Context; import android.net.wifi.WifiManager; import android.os.Build; import android.util.Log; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.thaliproject.p2p.btconnectorlib.DiscoveryManager; import org.thaliproject.p2p.btconnectorlib.PeerProperties; import org.thaliproject.p2p.btconnectorlib.internal.bluetooth.BluetoothManager; import org.thaliproject.p2p.btconnectorlib.internal.bluetooth.BluetoothUtils; import org.thaliproject.p2p.btconnectorlib.utils.CommonUtils; import java.util.ArrayList; import java.util.Date; import io.jxcore.node.jxcore.JXcoreCallback; /** * Implements Thali native interface. * For the documentation, please see * https://github.com/thaliproject/Thali_CordovaPlugin/blob/vNext/thali/NextGeneration/thaliMobileNative.js */ public class JXcoreExtension { // Common Thali methods and events public static final String CALLBACK_VALUE_LISTENING_ON_PORT_NUMBER = "listeningPort"; public static final String CALLBACK_VALUE_CLIENT_PORT_NUMBER = "clientPort"; public static final String CALLBACK_VALUE_SERVER_PORT_NUMBER = "serverPort"; private static final String METHOD_NAME_START_LISTENING_FOR_ADVERTISEMENTS = "startListeningForAdvertisements"; private static final String METHOD_NAME_STOP_LISTENING_FOR_ADVERTISEMENTS = "stopListeningForAdvertisements"; private static final String METHOD_NAME_START_UPDATE_ADVERTISING_AND_LISTENING = "startUpdateAdvertisingAndListening"; private static final String METHOD_NAME_STOP_ADVERTISING_AND_LISTENING = "stopAdvertisingAndListening"; private static final String METHOD_NAME_CONNECT = "connect"; private static final String METHOD_NAME_KILL_CONNECTIONS = "killConnections"; private static final String METHOD_NAME_DID_REGISTER_TO_NATIVE = "didRegisterToNative"; private static final String EVENT_NAME_PEER_AVAILABILITY_CHANGED = "peerAvailabilityChanged"; private static final String EVENT_NAME_DISCOVERY_ADVERTISING_STATE_UPDATE = "discoveryAdvertisingStateUpdateNonTCP"; private static final String EVENT_NAME_NETWORK_CHANGED = "networkChanged"; private static final String EVENT_NAME_INCOMING_CONNECTION_TO_PORT_NUMBER_FAILED = "incomingConnectionToPortNumberFailed"; private static final String METHOD_ARGUMENT_NETWORK_CHANGED = EVENT_NAME_NETWORK_CHANGED; private static final String EVENT_VALUE_PEER_ID = "peerIdentifier"; private static final String EVENT_VALUE_PEER_AVAILABLE = "peerAvailable"; private static final String EVENT_VALUE_PLEASE_CONNECT = "pleaseConnect"; private static final String EVENT_VALUE_DISCOVERY_ACTIVE = "discoveryActive"; private static final String EVENT_VALUE_ADVERTISING_ACTIVE = "advertisingActive"; private static final String EVENT_VALUE_BLUETOOTH_LOW_ENERGY = "bluetoothLowEnergy"; private static final String EVENT_VALUE_BLUETOOTH = "bluetooth"; private static final String EVENT_VALUE_WIFI = "wifi"; private static final String EVENT_VALUE_CELLULAR = "cellular"; private static final String EVENT_VALUE_BSSID_NAME = "bssidName"; private static final String EVENT_VALUE_SSID_NAME = "ssidName"; private static final String EVENT_VALUE_PORT_NUMBER = "portNumber"; // Android specific methods and events private static final String METHOD_NAME_IS_BLE_MULTIPLE_ADVERTISEMENT_SUPPORTED = "isBleMultipleAdvertisementSupported"; private static final String METHOD_NAME_GET_BLUETOOTH_ADDRESS = "getBluetoothAddress"; private static final String METHOD_NAME_GET_BLUETOOTH_NAME = "getBluetoothName"; private static final String METHOD_NAME_KILL_OUTGOING_CONNECTIONS = "killOutgoingConnections"; private static final String METHOD_NAME_GET_OS_VERSION = "getOSVersion"; private static final String METHOD_NAME_RECONNECT_WIFI_AP = "reconnectWifiAp"; private static final String METHOD_NAME_SHOW_TOAST = "showToast"; private static final String TAG = JXcoreExtension.class.getName(); private static final String BLUETOOTH_MAC_ADDRESS_AND_TOKEN_COUNTER_SEPARATOR = "-"; private static final long INCOMING_CONNECTION_FAILED_NOTIFICATION_MIN_INTERVAL_IN_MILLISECONDS = 100; private static ConnectionHelper mConnectionHelper = null; private static long mLastTimeIncomingConnectionFailedNotificationWasFired = 0; private static boolean mNetworkChangedRegistered = false; public static void LoadExtensions() { if (mConnectionHelper != null) { Log.e(TAG, "LoadExtensions: A connection helper instance already exists - this indicates that this method was called twice - disposing of the previous instance"); mConnectionHelper.dispose(); mConnectionHelper = null; } mConnectionHelper = new ConnectionHelper(); final LifeCycleMonitor lifeCycleMonitor = new LifeCycleMonitor(new LifeCycleMonitor.LifeCycleMonitorListener() { @Override public void onActivityLifeCycleEvent(LifeCycleMonitor.ActivityLifeCycleEvent activityLifeCycleEvent) { Log.d(TAG, "onActivityLifeCycleEvent: " + activityLifeCycleEvent); switch (activityLifeCycleEvent) { case DESTROYED: mConnectionHelper.dispose(); default: // No need to do anything } } }); lifeCycleMonitor.start(); RegisterExecuteUT.Register(); /* This is the line where we are dynamically sticking execution of UT during build, so if you are editing this line, please check updateJXCoreExtensionWithUTMethod in androidBeforeCompile.js. */ jxcore.RegisterMethod(METHOD_NAME_START_LISTENING_FOR_ADVERTISEMENTS, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, String callbackId) { Log.d(TAG, METHOD_NAME_START_LISTENING_FOR_ADVERTISEMENTS); startConnectionHelper(ConnectionHelper.NO_PORT_NUMBER, false, callbackId); } }); jxcore.RegisterMethod(METHOD_NAME_STOP_LISTENING_FOR_ADVERTISEMENTS, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, final String callbackId) { Log.d(TAG, METHOD_NAME_STOP_LISTENING_FOR_ADVERTISEMENTS); mConnectionHelper.stop(true, new JXcoreThaliCallback() { @Override protected void onStartStopCallback(String errorMessage) { ArrayList<Object> args = new ArrayList<Object>(); args.add(errorMessage); jxcore.CallJSMethod(callbackId, args.toArray()); } }); } }); jxcore.RegisterMethod(METHOD_NAME_START_UPDATE_ADVERTISING_AND_LISTENING, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, String callbackId) { Log.d(TAG, METHOD_NAME_START_UPDATE_ADVERTISING_AND_LISTENING); ArrayList<Object> args = new ArrayList<Object>(); String errorString = null; if (params != null && params.size() > 0) { Object parameterObject = params.get(0); if (parameterObject instanceof Integer && ((Integer) parameterObject > 0)) { startConnectionHelper((Integer) parameterObject, true, callbackId); } else { errorString = "Required parameter, {number} portNumber, is invalid - must be a positive integer"; } } else { errorString = "Required parameter, {number} portNumber, missing"; } if (errorString != null) { // Failed straight away args.add(errorString); jxcore.CallJSMethod(callbackId, args.toArray()); } } }); jxcore.RegisterMethod(METHOD_NAME_STOP_ADVERTISING_AND_LISTENING, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, final String callbackId) { Log.d(TAG, METHOD_NAME_STOP_ADVERTISING_AND_LISTENING); mConnectionHelper.stop(false, new JXcoreThaliCallback() { @Override protected void onStartStopCallback(String errorMessage) { ArrayList<Object> args = new ArrayList<Object>(); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); } }); } }); jxcore.RegisterMethod(METHOD_NAME_CONNECT, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, final String callbackId) { if (params.size() == 0) { ArrayList<Object> args = new ArrayList<Object>(); args.add("Required parameter, {string} peerIdentifier, missing"); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); return; } if (mConnectionHelper.getConnectivityMonitor().isBleMultipleAdvertisementSupported() == BluetoothManager.FeatureSupportedStatus.NOT_SUPPORTED) { ArrayList<Object> args = new ArrayList<Object>(); args.add("No Native Non-TCP Support"); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); return; } if (mConnectionHelper.getDiscoveryManager().getState() == DiscoveryManager.DiscoveryManagerState.WAITING_FOR_SERVICES_TO_BE_ENABLED) { ArrayList<Object> args = new ArrayList<Object>(); args.add("Radio Turned Off"); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); return; } final DiscoveryManager discoveryManager = mConnectionHelper.getDiscoveryManager(); final DiscoveryManager.DiscoveryManagerState discoveryManagerState = discoveryManager.getState(); if (discoveryManagerState != DiscoveryManager.DiscoveryManagerState.RUNNING_BLE) { ArrayList<Object> args = new ArrayList<Object>(); args.add("startListeningForAdvertisements is not active"); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); return; } String peerId = params.get(0).toString(); String bluetoothMacAddress = null; if (peerId != null) { try { bluetoothMacAddress = peerId.split(BLUETOOTH_MAC_ADDRESS_AND_TOKEN_COUNTER_SEPARATOR)[0]; } catch (IndexOutOfBoundsException e) { Log.e(TAG, METHOD_NAME_CONNECT + ": Failed to extract the Bluetooth MAC address: " + e.getMessage(), e); } } if (!BluetoothUtils.isValidBluetoothMacAddress(bluetoothMacAddress)) { ArrayList<Object> args = new ArrayList<Object>(); args.add("Illegal peerID"); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); return; } Log.d(TAG, METHOD_NAME_CONNECT + ": " + bluetoothMacAddress); if (mConnectionHelper.getConnectionModel().getOutgoingConnectionCallbackByBluetoothMacAddress(bluetoothMacAddress) != null) { Log.e(TAG, METHOD_NAME_CONNECT + ": Already connecting"); ArrayList<Object> args = new ArrayList<Object>(); // In case you want to check, if we are already connected (instead of connecting), do: // mConnectionHelper.getConnectionModel().hasOutgoingConnection() args.add("Already connect(ing/ed)"); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); return; } if (mConnectionHelper.hasMaximumNumberOfConnections()) { ArrayList<Object> args = new ArrayList<Object>(); args.add("Max connections reached"); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); return; } final String errorMessage = mConnectionHelper.connect(bluetoothMacAddress, new JXcoreThaliCallback() { @Override public void onConnectCallback( String errorMessage, ListenerOrIncomingConnection listenerOrIncomingConnection) { ArrayList<Object> args = new ArrayList<Object>(); args.add(errorMessage); if (errorMessage == null) { if (listenerOrIncomingConnection != null) { args.add(listenerOrIncomingConnection.toString()); } else { throw new NullPointerException( "ListenerOrIncomingConnection is null even though there is no error message"); } } jxcore.CallJSMethod(callbackId, args.toArray()); } }); if (errorMessage != null) { // Failed to start connecting ArrayList<Object> args = new ArrayList<Object>(); args.add(errorMessage); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); } } }); /** * Not supported on Android. */ jxcore.RegisterMethod(METHOD_NAME_KILL_CONNECTIONS, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, String callbackId) { ArrayList<Object> args = new ArrayList<Object>(); args.add("Not Supported"); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); } }); jxcore.RegisterMethod(METHOD_NAME_DID_REGISTER_TO_NATIVE, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, String callbackId) { ArrayList<Object> args = new ArrayList<Object>(); String errorString = null; if (params != null && params.size() > 0) { Object parameterObject = params.get(0); if (parameterObject instanceof String && CommonUtils.isNonEmptyString((String) parameterObject)) { String methodName = (String) parameterObject; if (methodName.equals(METHOD_ARGUMENT_NETWORK_CHANGED)) { mNetworkChangedRegistered = true; mConnectionHelper.getConnectivityMonitor().updateConnectivityInfo(true); // Will call notifyNetworkChanged } else { errorString = "Unrecognized method name: " + methodName; } } else { errorString = "Required parameter, {string} methodName, is invalid - must be a non-null and non-empty string"; } } else { errorString = "Required parameter, {string} methodName, missing"; } args.add(errorString); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); } }); /* * Android specific methods start here */ /** * Method for checking whether or not the device supports Bluetooth LE multi advertisement. * * When successful, the method will return two arguments: The first will have null value and * the second will contain a string value: * * - "Not resolved" if not resolved (can happen when Bluetooth is disabled) * - "Not supported" if not supported * - "Supported" if supported * * In case of an error the first argument will contain an error message followed by a null * argument. More specifically the error message will be a string starting with * "Unrecognized status: " followed by the unrecognized status. */ jxcore.RegisterMethod(METHOD_NAME_IS_BLE_MULTIPLE_ADVERTISEMENT_SUPPORTED, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, String callbackId) { ArrayList<Object> args = new ArrayList<Object>(); BluetoothManager bluetoothManager = mConnectionHelper.getDiscoveryManager().getBluetoothManager(); BluetoothManager.FeatureSupportedStatus featureSupportedStatus = bluetoothManager.isBleMultipleAdvertisementSupported(); Log.v(TAG, METHOD_NAME_IS_BLE_MULTIPLE_ADVERTISEMENT_SUPPORTED + ": " + featureSupportedStatus); switch (featureSupportedStatus) { case NOT_RESOLVED: args.add(null); args.add("Not resolved"); break; case NOT_SUPPORTED: args.add(null); args.add("Not supported"); break; case SUPPORTED: args.add(null); args.add("Supported"); break; default: String errorMessage = "Unrecognized status: " + featureSupportedStatus; Log.e(TAG, METHOD_NAME_IS_BLE_MULTIPLE_ADVERTISEMENT_SUPPORTED + ": " + errorMessage); args.add(errorMessage); args.add(null); break; } jxcore.CallJSMethod(callbackId, args.toArray()); } }); jxcore.RegisterMethod(METHOD_NAME_GET_BLUETOOTH_ADDRESS, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, String callbackId) { ArrayList<Object> args = new ArrayList<Object>(); String bluetoothMacAddress = mConnectionHelper.getDiscoveryManager().getBluetoothMacAddress(); if (bluetoothMacAddress == null || bluetoothMacAddress.length() == 0) { args.add("Bluetooth MAC address unknown"); } else { args.add(null); args.add(bluetoothMacAddress); } jxcore.CallJSMethod(callbackId, args.toArray()); } }); jxcore.RegisterMethod(METHOD_NAME_GET_BLUETOOTH_NAME, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, String callbackId) { ArrayList<Object> args = new ArrayList<Object>(); String bluetoothNameString = mConnectionHelper.getBluetoothName(); if (bluetoothNameString == null) { args.add("Unable to get the Bluetooth name"); } else { args.add(null); args.add(bluetoothNameString); } jxcore.CallJSMethod(callbackId, args.toArray()); } }); jxcore.RegisterMethod(METHOD_NAME_KILL_OUTGOING_CONNECTIONS, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, String callbackId) { mConnectionHelper.killConnections(false); ArrayList<Object> args = new ArrayList<Object>(); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); } }); jxcore.RegisterMethod(METHOD_NAME_GET_OS_VERSION, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, String callbackId) { ArrayList<Object> args = new ArrayList<Object>(); args.add(Build.VERSION.RELEASE); args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); } }); jxcore.RegisterMethod(METHOD_NAME_RECONNECT_WIFI_AP, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, String callbackId) { ArrayList<Object> args = new ArrayList<Object>(); WifiManager wifiManager = (WifiManager) jxcore.activity.getBaseContext().getSystemService(Context.WIFI_SERVICE); if (wifiManager.reconnect()) { wifiManager.disconnect(); if (!wifiManager.reconnect()) { args.add("WifiManager.reconnect returned false"); } } args.add(null); jxcore.CallJSMethod(callbackId, args.toArray()); } }); jxcore.RegisterMethod(METHOD_NAME_SHOW_TOAST, new JXcoreCallback() { @Override public void Receiver(ArrayList<Object> params, String callbackId) { ArrayList<Object> args = new ArrayList<Object>(); if (params.size() == 0) { args.add("Required parameter (toast message) missing"); } else { String message = params.get(0).toString(); int toastDuration = Toast.LENGTH_SHORT; if (params.size() == 2 && ((Boolean) params.get(1))) { toastDuration = Toast.LENGTH_LONG; } Toast.makeText(jxcore.activity.getApplicationContext(), message, toastDuration).show(); args.add(null); } jxcore.CallJSMethod(callbackId, args.toArray()); } }); } public static void notifyPeerAvailabilityChanged(PeerProperties peerProperties, boolean isAvailable) { String peerId = peerProperties.getId() + BLUETOOTH_MAC_ADDRESS_AND_TOKEN_COUNTER_SEPARATOR + peerProperties.getExtraInformation(); JSONObject jsonObject = new JSONObject(); boolean jsonObjectCreated = false; try { jsonObject.put(EVENT_VALUE_PEER_ID, peerId); jsonObject.put(EVENT_VALUE_PEER_AVAILABLE, isAvailable); jsonObject.put(EVENT_VALUE_PLEASE_CONNECT, false); jsonObjectCreated = true; } catch (JSONException e) { Log.e(TAG, "notifyPeerAvailabilityChanged: Failed to populate the JSON object: " + e.getMessage(), e); } if (jsonObjectCreated) { JSONArray jsonArray = new JSONArray(); jsonArray.put(jsonObject); final String jsonArrayAsString = jsonArray.toString(); jxcore.activity.runOnUiThread(new Runnable() { @Override public void run() { jxcore.CallJSMethod(EVENT_NAME_PEER_AVAILABILITY_CHANGED, jsonArrayAsString); } }); } } public static void notifyDiscoveryAdvertisingStateUpdateNonTcp( boolean isDiscoveryActive, boolean isAdvertisingActive) { JSONObject jsonObject = new JSONObject(); boolean jsonObjectCreated = false; try { jsonObject.put(EVENT_VALUE_DISCOVERY_ACTIVE, isDiscoveryActive); jsonObject.put(EVENT_VALUE_ADVERTISING_ACTIVE, isAdvertisingActive); jsonObjectCreated = true; } catch (JSONException e) { Log.e(TAG, "notifyDiscoveryAdvertisingStateUpdateNonTcp: Failed to populate the JSON object: " + e.getMessage(), e); } if (jsonObjectCreated) { final String jsonObjectAsString = jsonObject.toString(); try { jxcore.activity.runOnUiThread(new Runnable() { @Override public void run() { jxcore.CallJSMethod(EVENT_NAME_DISCOVERY_ADVERTISING_STATE_UPDATE, jsonObjectAsString); } }); } catch (NullPointerException e) { Log.e(TAG, "notifyDiscoveryAdvertisingStateUpdateNonTcp: Failed to notify: " + e.getMessage(), e); } } } /** * @param isBluetoothEnabled If true, Bluetooth is enabled. False otherwise. * @param isWifiEnabled If true, Wi-Fi is enabled. False otherwise. * @param bssidName If null this value indicates that either wifiRadioOn is not 'on' or * that the Wi-Fi isn't currently connected to an access point. * If non-null then this is the BSSID of the access point that Wi-Fi * is connected to. */ public static synchronized void notifyNetworkChanged( boolean isBluetoothEnabled, boolean isWifiEnabled, String bssidName, String ssidName) { if (!mNetworkChangedRegistered) { Log.d(TAG, "notifyNetworkChanged: Not registered for event \"" + EVENT_NAME_NETWORK_CHANGED + "\" and will not notify, in JS call method \"" + METHOD_NAME_DID_REGISTER_TO_NATIVE + "\" with argument \"" + METHOD_ARGUMENT_NETWORK_CHANGED + "\" to register"); return; } RadioState bluetoothLowEnergyRadioState; RadioState bluetoothRadioState; RadioState wifiRadioState; RadioState cellularRadioState = RadioState.DO_NOT_CARE; final ConnectivityMonitor connectivityMonitor = mConnectionHelper.getConnectivityMonitor(); if (connectivityMonitor.isBleMultipleAdvertisementSupported() != BluetoothManager.FeatureSupportedStatus.NOT_SUPPORTED) { if (isBluetoothEnabled) { bluetoothLowEnergyRadioState = RadioState.ON; } else { bluetoothLowEnergyRadioState = RadioState.OFF; } } else { bluetoothLowEnergyRadioState = RadioState.NOT_HERE; } if (connectivityMonitor.isBluetoothSupported()) { if (isBluetoothEnabled) { bluetoothRadioState = RadioState.ON; } else { bluetoothRadioState = RadioState.OFF; } } else { bluetoothRadioState = RadioState.NOT_HERE; } if (connectivityMonitor.isWifiDirectSupported()) { if (isWifiEnabled) { wifiRadioState = RadioState.ON; } else { wifiRadioState = RadioState.OFF; } } else { wifiRadioState = RadioState.NOT_HERE; } Log.d(TAG, "notifyNetworkChanged: BLE: " + bluetoothLowEnergyRadioState + ", Bluetooth: " + bluetoothRadioState + ", Wi-Fi: " + wifiRadioState + ", cellular: " + cellularRadioState + ", BSSID name: " + bssidName + ", SSID name: " + ssidName); JSONObject jsonObject = new JSONObject(); boolean jsonObjectCreated = false; try { jsonObject.put(EVENT_VALUE_BLUETOOTH_LOW_ENERGY, radioStateEnumValueToString(bluetoothLowEnergyRadioState)); jsonObject.put(EVENT_VALUE_BLUETOOTH, radioStateEnumValueToString(bluetoothRadioState)); jsonObject.put(EVENT_VALUE_WIFI, radioStateEnumValueToString(wifiRadioState)); jsonObject.put(EVENT_VALUE_CELLULAR, radioStateEnumValueToString(cellularRadioState)); jsonObject.put(EVENT_VALUE_BSSID_NAME, bssidName); jsonObject.put(EVENT_VALUE_SSID_NAME, ssidName); jsonObjectCreated = true; } catch (JSONException e) { Log.e(TAG, "notifyNetworkChanged: Failed to populate the JSON object: " + e.getMessage(), e); } if (jsonObjectCreated) { final String jsonObjectAsString = jsonObject.toString(); jxcore.activity.runOnUiThread(new Runnable() { @Override public void run() { jxcore.CallJSMethod(EVENT_NAME_NETWORK_CHANGED, jsonObjectAsString); } }); } } /** * This event is guaranteed to be not sent more often than every 100 ms. * * @param portNumber The 127.0.0.1 port that the TCP/IP bridge tried to connect to. */ public static void notifyIncomingConnectionToPortNumberFailed(int portNumber) { long currentTime = new Date().getTime(); if (currentTime > mLastTimeIncomingConnectionFailedNotificationWasFired + INCOMING_CONNECTION_FAILED_NOTIFICATION_MIN_INTERVAL_IN_MILLISECONDS) { JSONObject jsonObject = new JSONObject(); boolean jsonObjectCreated = false; try { jsonObject.put(EVENT_VALUE_PORT_NUMBER, portNumber); jsonObjectCreated = true; } catch (JSONException e) { Log.e(TAG, "notifyIncomingConnectionToPortNumberFailed: Failed to populate the JSON object: " + e.getMessage(), e); } if (jsonObjectCreated) { mLastTimeIncomingConnectionFailedNotificationWasFired = currentTime; final String jsonObjectAsString = jsonObject.toString(); jxcore.activity.runOnUiThread(new Runnable() { @Override public void run() { jxcore.CallJSMethod(EVENT_NAME_INCOMING_CONNECTION_TO_PORT_NUMBER_FAILED, jsonObjectAsString); } }); } } } /** * Tries to starts the connection helper. * * @param serverPortNumber The port on 127.0.0.1 that any incoming connections over the native * non-TCP/IP transport should be bridged to. * @param startAdvertisements If true, will start advertising our presence and scanning for other peers. * If false, will only scan for other peers. * @param callbackId The JXcore callback ID. */ private static void startConnectionHelper( int serverPortNumber, boolean startAdvertisements, final String callbackId) { final ArrayList<Object> args = new ArrayList<Object>(); String errorString = null; if (mConnectionHelper.getConnectivityMonitor().isBleMultipleAdvertisementSupported() != BluetoothManager.FeatureSupportedStatus.NOT_SUPPORTED) { boolean succeededToStartOrWasAlreadyRunning = mConnectionHelper.start(serverPortNumber, startAdvertisements, new JXcoreThaliCallback() { @Override protected void onStartStopCallback(final String errorMessage) { args.add(errorMessage); jxcore.CallJSMethod(callbackId, args.toArray()); } }); if (succeededToStartOrWasAlreadyRunning) { final DiscoveryManager discoveryManager = mConnectionHelper.getDiscoveryManager(); if (discoveryManager.getState() == DiscoveryManager.DiscoveryManagerState.WAITING_FOR_SERVICES_TO_BE_ENABLED) { errorString = "Radio Turned Off"; // If/when radios are turned on, the discovery is started automatically // unless stop is called } } else { errorString = "Unspecified Error with Radio infrastructure"; } } else { errorString = "No Native Non-TCP Support"; } if (errorString != null) { // Failed straight away args.add(errorString); jxcore.CallJSMethod(callbackId, args.toArray()); } } /** * Returns a string value matching the given RadioState enum value. * * @param radioState The RadioState enum value. * @return A string matching the given RadioState enum value. */ private static String radioStateEnumValueToString(RadioState radioState) { switch (radioState) { case ON: return "on"; case OFF: return "off"; case UNAVAILABLE: return "unavailable"; case NOT_HERE: return "notHere"; case DO_NOT_CARE: return "doNotCare"; } return null; } public enum RadioState { ON, // The radio is on and available for use. OFF, // The radio exists on the device but is turned off. UNAVAILABLE, // The radio exists on the device and is on but for some reason the system won't let us use it. NOT_HERE, // We depend on this radio type for this platform type but it doesn't appear to exist on this device. DO_NOT_CARE // Thali doesn't use this radio type on this platform and so makes no effort to determine its state. } }
deleted autocreated code
src/android/java/io/jxcore/node/JXcoreExtension.java
deleted autocreated code
<ide><path>rc/android/java/io/jxcore/node/JXcoreExtension.java <ide> * See the license file delivered with this project for further information. <ide> */ <ide> package io.jxcore.node; <del>import com.test.thalitest.RegisterExecuteUT; <ide> <ide> import android.content.Context; <ide> import android.net.wifi.WifiManager; <ide> }); <ide> <ide> lifeCycleMonitor.start(); <del> RegisterExecuteUT.Register(); <ide> /* <ide> This is the line where we are dynamically sticking execution of UT during build, so if you are <ide> editing this line, please check updateJXCoreExtensionWithUTMethod in androidBeforeCompile.js.
JavaScript
mit
73703fde12be1453b8a9316904815a96bd19cd74
0
JimiC/vscode-icons,vscode-icons/vscode-icons,JimiC/vscode-icons,robertohuertasm/vscode-icons,olzaragoza/vscode-icons,vscode-icons/vscode-icons,jens1o/vscode-icons
/* eslint-disable max-len */ exports.extensions = { supported: [ { icon: 'actionscript', extensions: ['as'] }, { icon: 'angular', extensions: [] }, { icon: 'apache', extensions: ['htaccess', 'htpasswd'] }, { icon: 'apib', extensions: ['apib'] }, { icon: 'applescript', extensions: ['app'] }, { icon: 'appveyor', extensions: ['appveyor.yml'], special: 'yml' }, { icon: 'asp', extensions: ['asp'] }, { icon: 'aspx', extensions: ['aspx'] }, { icon: 'assembly', extensions: ['s', 'asm'] }, { icon: 'autohotkey', extensions: ['ahk'] }, { icon: 'babel', extensions: ['babelrc'] }, { icon: 'binary', extensions: ['bin', 'o', 'a', 'exe', 'obj', 'lib', 'dll', 'so', 'pyc', 'pyd', 'pyo', 'n', 'ndll', 'pdb', 'cmo', 'cmx', 'cma', 'cmxa', 'cmi'] }, // http://www.file-extensions.org/filetype/extension/name/binary-files { icon: 'blade', extensions: ['.blade.php'], special: 'php' }, { icon: 'bower', extensions: ['bowerrc'] }, { icon: 'bower', extensions: ['bower'], special: 'json' }, { icon: 'c++', extensions: ['cpp', 'hpp', 'cc', 'cxx'] }, { icon: 'c', extensions: ['c'] }, { icon: 'cake', extensions: ['cake'] }, { icon: 'cfm', extensions: ['cfm', 'cfc', 'lucee'] }, { icon: 'cheader', extensions: ['h'] }, { icon: 'clojure', extensions: ['clojure', 'cjm', 'clj', 'cljs', 'cljc', 'edn'] }, { icon: 'codeclimate', extensions: ['codeclimate.yml'], special: 'yml' }, { icon: 'coffeescript', extensions: ['coffee'] }, { icon: 'config', extensions: ['env', 'ini', 'makefile', 'config'] }, { icon: 'compass', extensions: [] }, { icon: 'composer', extensions: ['composer.json'], special: 'json' }, { icon: 'composer', extensions: ['composer.lock'], special: 'lock' }, { icon: 'cs', extensions: ['cs'] }, { icon: 'cshtml', extensions: ['cshtml'] }, { icon: 'css', extensions: ['css'] }, { icon: 'csslint', extensions: ['csslintrc'] }, { icon: 'cucumber', extensions: ['feature'] }, { icon: 'dartlang', extensions: ['dart'] }, { icon: 'dlang', extensions: ['d'] }, { icon: 'docker', extensions: ['dockerfile'] }, { icon: 'editorconfig', extensions: ['editorconfig'] }, { icon: 'ejs', extensions: ['ejs'] }, { icon: 'elixir', extensions: ['ex', 'exs', 'eex'] }, { icon: 'elm', extensions: ['elm'] }, { icon: 'erb', extensions: ['rhtml', 'erb'] }, { icon: 'erlang', extensions: ['erl', 'hrl', 'emakefile', 'emakerfile'] }, { icon: 'eslint', extensions: ['eslintrc', 'eslintignore'] }, { icon: 'eslint', extensions: ['.eslintrc.js'], special: 'js' }, { icon: 'eslint', extensions: ['.eslintrc.json'], special: 'json' }, { icon: 'eslint', extensions: ['.eslintrc.yaml'], special: 'yaml' }, { icon: 'eslint', extensions: ['.eslintrc.yml'], special: 'yml' }, { icon: 'excel', extensions: ['xls', 'xlsx', 'csv', 'ods'] }, { icon: 'favicon', extensions: ['favicon'], special: 'ico' }, { icon: 'font', extensions: ['woff', 'woff2', 'ttf', 'otf', 'eot', 'pfa', 'pfb', 'sfd'] }, { icon: 'flash', extensions: ['swf', 'swc', 'sol'] }, { icon: 'fsharp', extensions: ['fs', 'fsx', 'fsi'] }, { icon: 'git', extensions: ['gitattributes', 'gitignore', 'gitmodules', 'gitkeep'] }, { icon: 'go', extensions: ['go'] }, { icon: 'gradle', extensions: ['gradle'] }, { icon: 'graphviz', extensions: [] }, { icon: 'groovy', extensions: ['groovy'] }, { icon: 'gruntfile', extensions: ['gruntfile'], special: 'js' }, { icon: 'gulpfile', extensions: ['gulpfile'], special: 'js' }, { icon: 'haml', extensions: ['haml'] }, { icon: 'handlebars', extensions: ['hbs', 'handlebars'] }, { icon: 'haskell', extensions: ['has', 'hs', 'lhs', 'lit', 'gf'] }, { icon: 'haxe', extensions: ['hx', 'hxml'] }, { icon: 'haxe', extensions: ['haxelib'], special: 'json' }, { icon: 'haxecheckstyle', extensions: ['checkstyle.json'], special: 'json' }, { icon: 'haxedevelop', extensions: ['hxproj'] }, { icon: 'html', extensions: ['htm', 'html'] }, { icon: 'image', extensions: ['jpeg', 'jpg', 'gif', 'png', 'bmp', 'ico'] }, { icon: 'ionic', extensions: ['ionic'], special: 'project' }, { icon: 'ionic', extensions: ['ionic.config'], special: 'json' }, { icon: 'jade', extensions: ['jade', 'pug', 'jade-lintrc', 'pug-lintrc'] }, { icon: 'jade', extensions: ['.jade-lint.json'], special: 'json' }, { icon: 'jade', extensions: ['.pug-lintrc.js'], special: 'js' }, { icon: 'jade', extensions: ['.pug-lintrc.json'], special: 'json' }, { icon: 'java', extensions: ['java'] }, { icon: 'js', extensions: ['js'] }, { icon: 'jshintrc', extensions: ['jshintrc'] }, { icon: 'jsmap', extensions: ['.js.map'], special: 'map' }, { icon: 'jsp', extensions: ['jsp'] }, { icon: 'julia', extensions: ['jl'] }, { icon: 'log', extensions: ['log'] }, { icon: 'less', extensions: ['less'] }, { icon: 'license', extensions: ['license', 'enc'] }, { icon: 'lisp', extensions: ['bil'] }, { icon: 'lime', extensions: ['hxp'] }, { icon: 'lime', extensions: ['include.xml'], special: 'xml' }, { icon: 'lsl', extensions: ['lsl'] }, { icon: 'lua', extensions: ['lua'] }, { icon: 'm', extensions: ['m'] }, { icon: 'markdown', extensions: ['md', 'markdown'] }, { icon: 'marko', extensions: ['marko'] }, { icon: 'markojs', extensions: ['.marko.js'], special: 'js' }, { icon: 'markup', extensions: [] }, { icon: 'matlab', extensions: ['fig', 'mat', 'mex', 'mexn', 'mexrs6', 'mn', 'mum', 'mx', 'mx3', 'rwd', 'slx', 'slddc', 'smv', 'tikz', 'xvc', 'xvc'] }, { icon: 'mustache', extensions: ['mustache', 'mst'] }, { icon: 'nim', extensions: ['nim', 'nims', 'cfg'] }, { icon: 'node', extensions: ['json'] }, { icon: 'node2', extensions: ['nvmrc'] }, { icon: 'npm', extensions: ['npmignore'] }, { icon: 'npm', extensions: ['package'], special: 'json' }, { icon: 'nsi', extensions: ['nsi', 'nsh'] }, { icon: 'nunjucks', extensions: ['njk', 'nunjucks', 'nunjs', 'nunj', 'njs', 'nj'] }, { icon: 'ocaml', extensions: ['ml', 'mll', 'mli', 'mly', 'ocamlmakefile', 'merlin'] }, { icon: 'paket', extensions: ['paket.dependencies'], special: 'dependencies' }, { icon: 'paket', extensions: ['paket.lock'], special: 'lock' }, { icon: 'paket', extensions: ['paket.references'], special: 'references' }, { icon: 'paket', extensions: ['paket.template'], special: 'template' }, { icon: 'paket', extensions: ['paket.local'], special: 'local' }, { icon: 'patch', extensions: ['patch'] }, { icon: 'perl', extensions: ['perl'] }, { icon: 'poedit', extensions: ['po', 'mo'] }, { icon: 'photoshop', extensions: ['psd'] }, { icon: 'php', extensions: ['php', 'php1', 'php2', 'php3', 'php4', 'php5', 'php6', 'phps', 'phpsa', 'phpt', 'phtml', 'phar'] }, { icon: 'phpunit', extensions: ['phpunit.xml'], special: 'xml' }, { icon: 'procfile', extensions: ['procfile'] }, { icon: 'postcss', extensions: ['pcss', 'postcss'] }, { icon: 'powershell', extensions: ['ps1', 'psm1', 'psd1'] }, { icon: 'puppet', extensions: ['epp'] }, { icon: 'python', extensions: ['py', 'pyw'] }, { icon: 'r', extensions: ['r'] }, { icon: 'rails', extensions: [] }, { icon: 'raml', extensions: ['raml'] }, { icon: 'reactjs', extensions: ['jsx'] }, { icon: 'reacttemplate', extensions: ['rt'] }, { icon: 'reactts', extensions: ['tsx'] }, { icon: 'riot', extensions: ['tag'] }, { icon: 'robotframework', extensions: ['robot'] }, { icon: 'ruby', extensions: ['rb', 'gemfile'] }, { icon: 'ruby', extensions: ['gemfile'], special: 'lock' }, { icon: 'rust', extensions: ['rs'] }, { icon: 'sass', extensions: ['sass'] }, { icon: 'scala', extensions: ['scala'] }, { icon: 'scss', extensions: ['scss'] }, { icon: 'settings', extensions: [] }, { icon: 'shell', extensions: ['bat', 'sh', 'cmd', 'bash', 'zsh', 'fish'] }, { icon: 'slim', extensions: [] }, { icon: 'source', extensions: [] }, { icon: 'sql', extensions: ['sql'] }, { icon: 'sqlite', extensions: ['sqlite', 'db3'] }, { icon: 'smarty', extensions: ['tpl', 'swig'] }, { icon: 'stylelint', extensions: ['stylelintrc'] }, { icon: 'stylelint', extensions: ['stylelint.config'], special: 'js' }, { icon: 'stylus', extensions: ['styl'] }, { icon: 'svg', extensions: ['svg'] }, { icon: 'swift', extensions: ['swift'] }, { icon: 'tcl', extensions: ['tcl'] }, { icon: 'tex', extensions: ['texi', 'tex'] }, { icon: 'text', extensions: ['txt'] }, { icon: 'textile', extensions: ['textile'] }, { icon: 'todo', extensions: ['todo'] }, { icon: 'travis', extensions: ['travis.yml'], special: 'yml' }, { icon: 'twig', extensions: ['twig'] }, { icon: 'typescript', extensions: ['ts'] }, { icon: 'typescriptdef', extensions: ['.d.ts'], special: 'ts' }, { icon: 'volt', extensions: ['volt'] }, { icon: 'vbhtml', extensions: ['vbhtml'] }, { icon: 'vue', extensions: ['vue'] }, { icon: 'vscode', extensions: ['vscodeignore', 'launch', 'jsconfig', 'tsconfig'], special: 'json' }, { icon: 'xml', extensions: ['xml', 'axml', 'xaml'] }, { icon: 'yaml', extensions: ['yml', 'yaml'] }, { icon: 'zip', extensions: ['zip', 'rar', '7z', 'tar', 'gz', 'bzip2', 'xz', 'bz2'] } ], parse: function () { var s = this.replace(/\./g, '_'); if ((/^\d/).test(s)) return 'n' + s; return s; } };
src/build/supportedExtensions.js
/* eslint-disable max-len */ exports.extensions = { supported: [ { icon: 'actionscript', extensions: ['as'] }, { icon: 'angular', extensions: [] }, { icon: 'apache', extensions: ['htaccess', 'htpasswd'] }, { icon: 'apib', extensions: ['apib'] }, { icon: 'applescript', extensions: ['app'] }, { icon: 'appveyor', extensions: ['appveyor.yml'], special: 'yml' }, { icon: 'asp', extensions: ['asp'] }, { icon: 'assembly', extensions: ['s', 'asm'] }, { icon: 'autohotkey', extensions: ['ahk'] }, { icon: 'babel', extensions: ['babelrc'] }, { icon: 'binary', extensions: ['bin', 'o', 'a', 'exe', 'obj', 'lib', 'dll', 'so', 'pyc', 'pyd', 'pyo', 'n', 'ndll', 'pdb', 'cmo', 'cmx', 'cma', 'cmxa', 'cmi'] }, // http://www.file-extensions.org/filetype/extension/name/binary-files { icon: 'blade', extensions: ['.blade.php'], special: 'php' }, { icon: 'bower', extensions: ['bowerrc'] }, { icon: 'bower', extensions: ['bower'], special: 'json' }, { icon: 'c++', extensions: ['cpp', 'hpp', 'cc', 'cxx'] }, { icon: 'c', extensions: ['c'] }, { icon: 'cake', extensions: ['cake'] }, { icon: 'cfm', extensions: ['cfm', 'cfc', 'lucee'] }, { icon: 'cheader', extensions: ['h'] }, { icon: 'clojure', extensions: ['clojure', 'cjm', 'clj', 'cljs', 'cljc', 'edn'] }, { icon: 'codeclimate', extensions: ['codeclimate.yml'], special: 'yml' }, { icon: 'coffeescript', extensions: ['coffee'] }, { icon: 'config', extensions: ['env', 'ini', 'makefile', 'config'] }, { icon: 'compass', extensions: [] }, { icon: 'composer', extensions: ['composer.json'], special: 'json' }, { icon: 'composer', extensions: ['composer.lock'], special: 'lock' }, { icon: 'cs', extensions: ['cs'] }, { icon: 'cshtml', extensions: ['cshtml'] }, { icon: 'css', extensions: ['css'] }, { icon: 'csslint', extensions: ['csslintrc'] }, { icon: 'cucumber', extensions: ['feature'] }, { icon: 'dartlang', extensions: ['dart'] }, { icon: 'dlang', extensions: ['d'] }, { icon: 'docker', extensions: ['dockerfile'] }, { icon: 'editorconfig', extensions: ['editorconfig'] }, { icon: 'ejs', extensions: ['ejs'] }, { icon: 'elixir', extensions: ['ex', 'exs', 'eex'] }, { icon: 'elm', extensions: ['elm'] }, { icon: 'erb', extensions: ['rhtml', 'erb'] }, { icon: 'erlang', extensions: ['erl', 'hrl', 'emakefile', 'emakerfile'] }, { icon: 'eslint', extensions: ['eslintrc', 'eslintignore'] }, { icon: 'eslint', extensions: ['.eslintrc.js'], special: 'js' }, { icon: 'eslint', extensions: ['.eslintrc.json'], special: 'json' }, { icon: 'eslint', extensions: ['.eslintrc.yaml'], special: 'yaml' }, { icon: 'eslint', extensions: ['.eslintrc.yml'], special: 'yml' }, { icon: 'excel', extensions: ['xls', 'xlsx', 'csv', 'ods'] }, { icon: 'favicon', extensions: ['favicon'], special: 'ico' }, { icon: 'font', extensions: ['woff', 'woff2', 'ttf', 'otf', 'eot', 'pfa', 'pfb', 'sfd'] }, { icon: 'flash', extensions: ['swf', 'swc', 'sol'] }, { icon: 'fsharp', extensions: ['fs', 'fsx', 'fsi'] }, { icon: 'git', extensions: ['gitattributes', 'gitignore', 'gitmodules', 'gitkeep'] }, { icon: 'go', extensions: ['go'] }, { icon: 'gradle', extensions: ['gradle'] }, { icon: 'graphviz', extensions: [] }, { icon: 'groovy', extensions: ['groovy'] }, { icon: 'gruntfile', extensions: ['gruntfile'], special: 'js' }, { icon: 'gulpfile', extensions: ['gulpfile'], special: 'js' }, { icon: 'haml', extensions: ['haml'] }, { icon: 'handlebars', extensions: ['hbs', 'handlebars'] }, { icon: 'haskell', extensions: ['has', 'hs', 'lhs', 'lit', 'gf'] }, { icon: 'haxe', extensions: ['hx', 'hxml'] }, { icon: 'haxe', extensions: ['haxelib'], special: 'json' }, { icon: 'haxecheckstyle', extensions: ['checkstyle.json'], special: 'json' }, { icon: 'haxedevelop', extensions: ['hxproj'] }, { icon: 'html', extensions: ['htm', 'html'] }, { icon: 'image', extensions: ['jpeg', 'jpg', 'gif', 'png', 'bmp', 'ico'] }, { icon: 'ionic', extensions: ['ionic'], special: 'project' }, { icon: 'ionic', extensions: ['ionic.config'], special: 'json' }, { icon: 'jade', extensions: ['jade', 'pug', 'jade-lintrc', 'pug-lintrc'] }, { icon: 'jade', extensions: ['.jade-lint.json'], special: 'json' }, { icon: 'jade', extensions: ['.pug-lintrc.js'], special: 'js' }, { icon: 'jade', extensions: ['.pug-lintrc.json'], special: 'json' }, { icon: 'java', extensions: ['java'] }, { icon: 'js', extensions: ['js'] }, { icon: 'jshintrc', extensions: ['jshintrc'] }, { icon: 'jsmap', extensions: ['.js.map'], special: 'map' }, { icon: 'jsp', extensions: ['jsp'] }, { icon: 'julia', extensions: ['jl'] }, { icon: 'log', extensions: ['log'] }, { icon: 'less', extensions: ['less'] }, { icon: 'license', extensions: ['license', 'enc'] }, { icon: 'lisp', extensions: ['bil'] }, { icon: 'lime', extensions: ['hxp'] }, { icon: 'lime', extensions: ['include.xml'], special: 'xml' }, { icon: 'lsl', extensions: ['lsl'] }, { icon: 'lua', extensions: ['lua'] }, { icon: 'm', extensions: ['m'] }, { icon: 'markdown', extensions: ['md', 'markdown'] }, { icon: 'marko', extensions: ['marko'] }, { icon: 'markojs', extensions: ['.marko.js'], special: 'js' }, { icon: 'markup', extensions: [] }, { icon: 'matlab', extensions: ['fig', 'mat', 'mex', 'mexn', 'mexrs6', 'mn', 'mum', 'mx', 'mx3', 'rwd', 'slx', 'slddc', 'smv', 'tikz', 'xvc', 'xvc'] }, { icon: 'mustache', extensions: ['mustache', 'mst'] }, { icon: 'nim', extensions: ['nim', 'nims', 'cfg'] }, { icon: 'node', extensions: ['json'] }, { icon: 'node2', extensions: ['nvmrc'] }, { icon: 'npm', extensions: ['npmignore'] }, { icon: 'npm', extensions: ['package'], special: 'json' }, { icon: 'nsi', extensions: ['nsi', 'nsh'] }, { icon: 'nunjucks', extensions: ['njk', 'nunjucks', 'nunjs', 'nunj', 'njs', 'nj'] }, { icon: 'ocaml', extensions: ['ml', 'mll', 'mli', 'mly', 'ocamlmakefile', 'merlin'] }, { icon: 'paket', extensions: ['paket.dependencies'], special: 'dependencies' }, { icon: 'paket', extensions: ['paket.lock'], special: 'lock' }, { icon: 'paket', extensions: ['paket.references'], special: 'references' }, { icon: 'paket', extensions: ['paket.template'], special: 'template' }, { icon: 'paket', extensions: ['paket.local'], special: 'local' }, { icon: 'patch', extensions: ['patch'] }, { icon: 'perl', extensions: ['perl'] }, { icon: 'poedit', extensions: ['po', 'mo'] }, { icon: 'photoshop', extensions: ['psd'] }, { icon: 'php', extensions: ['php', 'php1', 'php2', 'php3', 'php4', 'php5', 'php6', 'phps', 'phpsa', 'phpt', 'phtml', 'phar'] }, { icon: 'phpunit', extensions: ['phpunit.xml'], special: 'xml' }, { icon: 'procfile', extensions: ['procfile'] }, { icon: 'postcss', extensions: ['pcss', 'postcss'] }, { icon: 'powershell', extensions: ['ps1', 'psm1', 'psd1'] }, { icon: 'puppet', extensions: ['epp'] }, { icon: 'python', extensions: ['py', 'pyw'] }, { icon: 'r', extensions: ['r'] }, { icon: 'rails', extensions: [] }, { icon: 'raml', extensions: ['raml'] }, { icon: 'reactjs', extensions: ['jsx'] }, { icon: 'reacttemplate', extensions: ['rt'] }, { icon: 'reactts', extensions: ['tsx'] }, { icon: 'riot', extensions: ['tag'] }, { icon: 'robotframework', extensions: ['robot'] }, { icon: 'ruby', extensions: ['rb', 'gemfile'] }, { icon: 'ruby', extensions: ['gemfile'], special: 'lock' }, { icon: 'rust', extensions: ['rs'] }, { icon: 'sass', extensions: ['sass'] }, { icon: 'scala', extensions: ['scala'] }, { icon: 'scss', extensions: ['scss'] }, { icon: 'settings', extensions: [] }, { icon: 'shell', extensions: ['bat', 'sh', 'cmd', 'bash', 'zsh', 'fish'] }, { icon: 'slim', extensions: [] }, { icon: 'source', extensions: [] }, { icon: 'sql', extensions: ['sql'] }, { icon: 'sqlite', extensions: ['sqlite', 'db3'] }, { icon: 'smarty', extensions: ['tpl', 'swig'] }, { icon: 'stylelint', extensions: ['stylelintrc'] }, { icon: 'stylelint', extensions: ['stylelint.config'], special: 'js' }, { icon: 'stylus', extensions: ['styl'] }, { icon: 'svg', extensions: ['svg'] }, { icon: 'swift', extensions: ['swift'] }, { icon: 'tcl', extensions: ['tcl'] }, { icon: 'tex', extensions: ['texi', 'tex'] }, { icon: 'text', extensions: ['txt'] }, { icon: 'textile', extensions: ['textile'] }, { icon: 'todo', extensions: ['todo'] }, { icon: 'travis', extensions: ['travis.yml'], special: 'yml' }, { icon: 'twig', extensions: ['twig'] }, { icon: 'typescript', extensions: ['ts'] }, { icon: 'typescriptdef', extensions: ['.d.ts'], special: 'ts' }, { icon: 'volt', extensions: ['volt'] }, { icon: 'vbhtml', extensions: ['vbhtml'] }, { icon: 'vue', extensions: ['vue'] }, { icon: 'vscode', extensions: ['vscodeignore', 'launch', 'jsconfig', 'tsconfig'], special: 'json' }, { icon: 'xml', extensions: ['xml', 'axml', 'xaml'] }, { icon: 'yaml', extensions: ['yml', 'yaml'] }, { icon: 'zip', extensions: ['zip', 'rar', '7z', 'tar', 'gz', 'bzip2', 'xz', 'bz2'] } ], parse: function () { var s = this.replace(/\./g, '_'); if ((/^\d/).test(s)) return 'n' + s; return s; } };
add aspx to supported extensions
src/build/supportedExtensions.js
add aspx to supported extensions
<ide><path>rc/build/supportedExtensions.js <ide> { icon: 'applescript', extensions: ['app'] }, <ide> { icon: 'appveyor', extensions: ['appveyor.yml'], special: 'yml' }, <ide> { icon: 'asp', extensions: ['asp'] }, <add> { icon: 'aspx', extensions: ['aspx'] }, <ide> { icon: 'assembly', extensions: ['s', 'asm'] }, <ide> { icon: 'autohotkey', extensions: ['ahk'] }, <ide> { icon: 'babel', extensions: ['babelrc'] },
Java
apache-2.0
10754cd32e39a60136d8b9f67c3332b9ee689735
0
kongweihan/helix,dasahcc/helix,lei-xia/helix,apache/helix,dasahcc/helix,kongweihan/helix,dasahcc/helix,lei-xia/helix,kongweihan/helix,dasahcc/helix,lei-xia/helix,apache/helix,dasahcc/helix,lei-xia/helix,dasahcc/helix,lei-xia/helix,apache/helix,apache/helix,lei-xia/helix,apache/helix,apache/helix
package org.apache.helix.manager.zk; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.concurrent.atomic.AtomicBoolean; import org.apache.log4j.Logger; import org.apache.zookeeper.AsyncCallback.DataCallback; import org.apache.zookeeper.AsyncCallback.StatCallback; import org.apache.zookeeper.AsyncCallback.StringCallback; import org.apache.zookeeper.AsyncCallback.VoidCallback; import org.apache.zookeeper.KeeperException.Code; import org.apache.zookeeper.data.Stat; public class ZkAsyncCallbacks { private static Logger LOG = Logger.getLogger(ZkAsyncCallbacks.class); public static class GetDataCallbackHandler extends DefaultCallback implements DataCallback { byte[] _data; Stat _stat; @Override public void handle() { // TODO Auto-generated method stub } @Override public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { if (rc == 0) { _data = data; _stat = stat; } callback(rc, path, ctx); } } public static class SetDataCallbackHandler extends DefaultCallback implements StatCallback { Stat _stat; @Override public void handle() { // TODO Auto-generated method stub } @Override public void processResult(int rc, String path, Object ctx, Stat stat) { if (rc == 0) { _stat = stat; } callback(rc, path, ctx); } public Stat getStat() { return _stat; } } public static class ExistsCallbackHandler extends DefaultCallback implements StatCallback { Stat _stat; @Override public void handle() { // TODO Auto-generated method stub } @Override public void processResult(int rc, String path, Object ctx, Stat stat) { if (rc == 0) { _stat = stat; } callback(rc, path, ctx); } } public static class CreateCallbackHandler extends DefaultCallback implements StringCallback { @Override public void processResult(int rc, String path, Object ctx, String name) { callback(rc, path, ctx); } @Override public void handle() { // TODO Auto-generated method stub } } public static class DeleteCallbackHandler extends DefaultCallback implements VoidCallback { @Override public void processResult(int rc, String path, Object ctx) { callback(rc, path, ctx); } @Override public void handle() { // TODO Auto-generated method stub } } /** * Default callback for zookeeper async api */ public static abstract class DefaultCallback { AtomicBoolean _lock = new AtomicBoolean(false); int _rc = -1; public void callback(int rc, String path, Object ctx) { if (rc != 0 && LOG.isDebugEnabled()) { LOG.debug(this + ", rc:" + Code.get(rc) + ", path: " + path); } _rc = rc; handle(); synchronized (_lock) { _lock.set(true); _lock.notify(); } } public boolean waitForSuccess() { try { synchronized (_lock) { while (!_lock.get()) { _lock.wait(); } } } catch (InterruptedException e) { LOG.error("Interrupted waiting for success", e); } return true; } public int getRc() { return _rc; } abstract public void handle(); } }
helix-core/src/main/java/org/apache/helix/manager/zk/ZkAsyncCallbacks.java
package org.apache.helix.manager.zk; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.concurrent.atomic.AtomicBoolean; import org.apache.log4j.Logger; import org.apache.zookeeper.AsyncCallback.DataCallback; import org.apache.zookeeper.AsyncCallback.StatCallback; import org.apache.zookeeper.AsyncCallback.StringCallback; import org.apache.zookeeper.AsyncCallback.VoidCallback; import org.apache.zookeeper.KeeperException.Code; import org.apache.zookeeper.data.Stat; public class ZkAsyncCallbacks { private static Logger LOG = Logger.getLogger(ZkAsyncCallbacks.class); static class GetDataCallbackHandler extends DefaultCallback implements DataCallback { byte[] _data; Stat _stat; @Override public void handle() { // TODO Auto-generated method stub } @Override public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { if (rc == 0) { _data = data; _stat = stat; } callback(rc, path, ctx); } } static class SetDataCallbackHandler extends DefaultCallback implements StatCallback { Stat _stat; @Override public void handle() { // TODO Auto-generated method stub } @Override public void processResult(int rc, String path, Object ctx, Stat stat) { if (rc == 0) { _stat = stat; } callback(rc, path, ctx); } public Stat getStat() { return _stat; } } static class ExistsCallbackHandler extends DefaultCallback implements StatCallback { Stat _stat; @Override public void handle() { // TODO Auto-generated method stub } @Override public void processResult(int rc, String path, Object ctx, Stat stat) { if (rc == 0) { _stat = stat; } callback(rc, path, ctx); } } static class CreateCallbackHandler extends DefaultCallback implements StringCallback { @Override public void processResult(int rc, String path, Object ctx, String name) { callback(rc, path, ctx); } @Override public void handle() { // TODO Auto-generated method stub } } static class DeleteCallbackHandler extends DefaultCallback implements VoidCallback { @Override public void processResult(int rc, String path, Object ctx) { callback(rc, path, ctx); } @Override public void handle() { // TODO Auto-generated method stub } } /** * Default callback for zookeeper async api */ static abstract class DefaultCallback { AtomicBoolean _lock = new AtomicBoolean(false); int _rc = -1; public void callback(int rc, String path, Object ctx) { if (rc != 0 && LOG.isDebugEnabled()) { LOG.debug(this + ", rc:" + Code.get(rc) + ", path: " + path); } _rc = rc; handle(); synchronized (_lock) { _lock.set(true); _lock.notify(); } } public boolean waitForSuccess() { try { synchronized (_lock) { while (!_lock.get()) { _lock.wait(); } } } catch (InterruptedException e) { LOG.error("Interrupted waiting for success", e); } return true; } public int getRc() { return _rc; } abstract public void handle(); } }
Expose Callbacks that can let async operation of ZkClient function Current async related operation in ZkClient cannot be utilized as the input arguments are the Callbacks hidden in ZkAsyncCallbacks class.
helix-core/src/main/java/org/apache/helix/manager/zk/ZkAsyncCallbacks.java
Expose Callbacks that can let async operation of ZkClient function
<ide><path>elix-core/src/main/java/org/apache/helix/manager/zk/ZkAsyncCallbacks.java <ide> public class ZkAsyncCallbacks { <ide> private static Logger LOG = Logger.getLogger(ZkAsyncCallbacks.class); <ide> <del> static class GetDataCallbackHandler extends DefaultCallback implements DataCallback { <add> public static class GetDataCallbackHandler extends DefaultCallback implements DataCallback { <ide> byte[] _data; <ide> Stat _stat; <ide> <ide> } <ide> } <ide> <del> static class SetDataCallbackHandler extends DefaultCallback implements StatCallback { <add> public static class SetDataCallbackHandler extends DefaultCallback implements StatCallback { <ide> Stat _stat; <ide> <ide> @Override <ide> } <ide> } <ide> <del> static class ExistsCallbackHandler extends DefaultCallback implements StatCallback { <add> public static class ExistsCallbackHandler extends DefaultCallback implements StatCallback { <ide> Stat _stat; <ide> <ide> @Override <ide> <ide> } <ide> <del> static class CreateCallbackHandler extends DefaultCallback implements StringCallback { <add> public static class CreateCallbackHandler extends DefaultCallback implements StringCallback { <ide> @Override <ide> public void processResult(int rc, String path, Object ctx, String name) { <ide> callback(rc, path, ctx); <ide> } <ide> } <ide> <del> static class DeleteCallbackHandler extends DefaultCallback implements VoidCallback { <add> public static class DeleteCallbackHandler extends DefaultCallback implements VoidCallback { <ide> @Override <ide> public void processResult(int rc, String path, Object ctx) { <ide> callback(rc, path, ctx); <ide> /** <ide> * Default callback for zookeeper async api <ide> */ <del> static abstract class DefaultCallback { <add> public static abstract class DefaultCallback { <ide> AtomicBoolean _lock = new AtomicBoolean(false); <ide> int _rc = -1; <ide>
JavaScript
apache-2.0
848b0c0d23adb6cdd65f9aae09b4479e5aabdf09
0
subscriptions-project/swg-js,subscriptions-project/swg-js,subscriptions-project/swg-js
/** * Copyright 2018 The Subscribe with Google Authors. 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 * * 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. */ /** * @fileoverview Protos for SwG client/iframe messaging * Auto generated, do not edit */ /** * @interface */ class Message { /** * @return {string} */ label() {} /** * @param {boolean=} unusedIncludeLabel * @return {!Array<*>} */ toArray(unusedIncludeLabel = true) {} } /** @enum {number} */ const ActionType = { ACTION_TYPE_UNKNOWN: 0, ACTION_TYPE_RELOAD_PAGE: 1, ACTION_TYPE_UPDATE_COUNTER: 2, }; /** @enum {number} */ const AnalyticsEvent = { UNKNOWN: 0, IMPRESSION_PAYWALL: 1, IMPRESSION_AD: 2, IMPRESSION_OFFERS: 3, IMPRESSION_SUBSCRIBE_BUTTON: 4, IMPRESSION_SMARTBOX: 5, IMPRESSION_SWG_BUTTON: 6, IMPRESSION_CLICK_TO_SHOW_OFFERS: 7, IMPRESSION_CLICK_TO_SHOW_OFFERS_OR_ALREADY_SUBSCRIBED: 8, IMPRESSION_SUBSCRIPTION_COMPLETE: 9, IMPRESSION_ACCOUNT_CHANGED: 10, IMPRESSION_PAGE_LOAD: 11, IMPRESSION_LINK: 12, IMPRESSION_SAVE_SUBSCR_TO_GOOGLE: 13, IMPRESSION_GOOGLE_UPDATED: 14, IMPRESSION_SHOW_OFFERS_SMARTBOX: 15, IMPRESSION_SHOW_OFFERS_SWG_BUTTON: 16, IMPRESSION_SELECT_OFFER_SMARTBOX: 17, IMPRESSION_SELECT_OFFER_SWG_BUTTON: 18, IMPRESSION_SHOW_CONTRIBUTIONS_SWG_BUTTON: 19, IMPRESSION_SELECT_CONTRIBUTION_SWG_BUTTON: 20, IMPRESSION_METER_TOAST: 21, IMPRESSION_REGWALL: 22, IMPRESSION_SHOWCASE_REGWALL: 23, IMPRESSION_SWG_SUBSCRIPTION_MINI_PROMPT: 24, IMPRESSION_SWG_CONTRIBUTION_MINI_PROMPT: 25, IMPRESSION_CONTRIBUTION_OFFERS: 26, IMPRESSION_TWG_COUNTER: 27, IMPRESSION_TWG_SITE_SUPPORTER_WALL: 28, IMPRESSION_TWG_PUBLICATION: 29, IMPRESSION_TWG_STATIC_BUTTON: 30, IMPRESSION_TWG_DYNAMIC_BUTTON: 31, IMPRESSION_TWG_STICKER_SELECTION_SCREEN: 32, IMPRESSION_TWG_PUBLICATION_NOT_SET_UP: 33, IMPRESSION_REGWALL_OPT_IN: 34, IMPRESSION_NEWSLETTER_OPT_IN: 35, ACTION_SUBSCRIBE: 1000, ACTION_PAYMENT_COMPLETE: 1001, ACTION_ACCOUNT_CREATED: 1002, ACTION_ACCOUNT_ACKNOWLEDGED: 1003, ACTION_SUBSCRIPTIONS_LANDING_PAGE: 1004, ACTION_PAYMENT_FLOW_STARTED: 1005, ACTION_OFFER_SELECTED: 1006, ACTION_SWG_BUTTON_CLICK: 1007, ACTION_VIEW_OFFERS: 1008, ACTION_ALREADY_SUBSCRIBED: 1009, ACTION_NEW_DEFERRED_ACCOUNT: 1010, ACTION_LINK_CONTINUE: 1011, ACTION_LINK_CANCEL: 1012, ACTION_GOOGLE_UPDATED_CLOSE: 1013, ACTION_USER_CANCELED_PAYFLOW: 1014, ACTION_SAVE_SUBSCR_TO_GOOGLE_CONTINUE: 1015, ACTION_SAVE_SUBSCR_TO_GOOGLE_CANCEL: 1016, ACTION_SWG_BUTTON_SHOW_OFFERS_CLICK: 1017, ACTION_SWG_BUTTON_SELECT_OFFER_CLICK: 1018, ACTION_SWG_BUTTON_SHOW_CONTRIBUTIONS_CLICK: 1019, ACTION_SWG_BUTTON_SELECT_CONTRIBUTION_CLICK: 1020, ACTION_USER_CONSENT_DEFERRED_ACCOUNT: 1021, ACTION_USER_DENY_DEFERRED_ACCOUNT: 1022, ACTION_DEFERRED_ACCOUNT_REDIRECT: 1023, ACTION_GET_ENTITLEMENTS: 1024, ACTION_METER_TOAST_SUBSCRIBE_CLICK: 1025, ACTION_METER_TOAST_EXPANDED: 1026, ACTION_METER_TOAST_CLOSED_BY_ARTICLE_INTERACTION: 1027, ACTION_METER_TOAST_CLOSED_BY_SWIPE_DOWN: 1028, ACTION_METER_TOAST_CLOSED_BY_X_CLICKED: 1029, ACTION_SWG_SUBSCRIPTION_MINI_PROMPT_CLICK: 1030, ACTION_SWG_CONTRIBUTION_MINI_PROMPT_CLICK: 1031, ACTION_SWG_SUBSCRIPTION_MINI_PROMPT_CLOSE: 1032, ACTION_SWG_CONTRIBUTION_MINI_PROMPT_CLOSE: 1033, ACTION_CONTRIBUTION_OFFER_SELECTED: 1034, ACTION_SHOWCASE_REGWALL_GSI_CLICK: 1035, ACTION_SHOWCASE_REGWALL_EXISTING_ACCOUNT_CLICK: 1036, ACTION_SUBSCRIPTION_OFFERS_CLOSED: 1037, ACTION_CONTRIBUTION_OFFERS_CLOSED: 1038, ACTION_TWG_STATIC_CTA_CLICK: 1039, ACTION_TWG_DYNAMIC_CTA_CLICK: 1040, ACTION_TWG_SITE_LEVEL_SUPPORTER_WALL_CTA_CLICK: 1041, ACTION_TWG_DIALOG_SUPPORTER_WALL_CTA_CLICK: 1042, ACTION_TWG_COUNTER_CLICK: 1043, ACTION_TWG_SITE_SUPPORTER_WALL_ALL_THANKS_CLICK: 1044, ACTION_TWG_PAID_STICKER_SELECTED_SCREEN_CLOSE_CLICK: 1045, ACTION_TWG_PAID_STICKER_SELECTION_CLICK: 1046, ACTION_TWG_FREE_STICKER_SELECTION_CLICK: 1047, ACTION_TWG_MINI_SUPPORTER_WALL_CLICK: 1048, ACTION_TWG_CREATOR_BENEFIT_CLICK: 1049, ACTION_TWG_FREE_TRANSACTION_START_NEXT_BUTTON_CLICK: 1050, ACTION_TWG_PAID_TRANSACTION_START_NEXT_BUTTON_CLICK: 1051, ACTION_TWG_STICKER_SELECTION_SCREEN_CLOSE_CLICK: 1052, ACTION_TWG_ARTICLE_LEVEL_SUPPORTER_WALL_CTA_CLICK: 1053, ACTION_REGWALL_OPT_IN_BUTTON_CLICK: 1054, ACTION_REGWALL_ALREADY_OPTED_IN_CLICK: 1055, ACTION_NEWSLETTER_OPT_IN_BUTTON_CLICK: 1056, ACTION_NEWSLETTER_ALREADY_OPTED_IN_CLICK: 1057, ACTION_REGWALL_OPT_IN_CLOSE: 1058, ACTION_NEWSLETTER_OPT_IN_CLOSE: 1059, ACTION_SHOWCASE_REGWALL_SWIG_CLICK: 1060, ACTION_TWG_CHROME_APP_MENU_ENTRY_POINT_CLICK: 1061, ACTION_TWG_DISCOVER_FEED_MENU_ENTRY_POINT_CLICK: 1062, ACTION_SHOWCASE_REGWALL_3P_BUTTON_CLICK: 1063, EVENT_PAYMENT_FAILED: 2000, EVENT_REGWALL_OPT_IN_FAILED: 2001, EVENT_NEWSLETTER_OPT_IN_FAILED: 2002, EVENT_REGWALL_ALREADY_OPT_IN: 2003, EVENT_NEWSLETTER_ALREADY_OPT_IN: 2004, EVENT_CUSTOM: 3000, EVENT_CONFIRM_TX_ID: 3001, EVENT_CHANGED_TX_ID: 3002, EVENT_GPAY_NO_TX_ID: 3003, EVENT_GPAY_CANNOT_CONFIRM_TX_ID: 3004, EVENT_GOOGLE_UPDATED: 3005, EVENT_NEW_TX_ID: 3006, EVENT_UNLOCKED_BY_SUBSCRIPTION: 3007, EVENT_UNLOCKED_BY_METER: 3008, EVENT_NO_ENTITLEMENTS: 3009, EVENT_HAS_METERING_ENTITLEMENTS: 3010, EVENT_OFFERED_METER: 3011, EVENT_UNLOCKED_FREE_PAGE: 3012, EVENT_INELIGIBLE_PAYWALL: 3013, EVENT_UNLOCKED_FOR_CRAWLER: 3014, EVENT_TWG_COUNTER_VIEW: 3015, EVENT_TWG_SITE_SUPPORTER_WALL_VIEW: 3016, EVENT_TWG_STATIC_BUTTON_VIEW: 3017, EVENT_TWG_DYNAMIC_BUTTON_VIEW: 3018, EVENT_TWG_PRE_TRANSACTION_PRIVACY_SETTING_PRIVATE: 3019, EVENT_TWG_POST_TRANSACTION_SETTING_PRIVATE: 3020, EVENT_TWG_PRE_TRANSACTION_PRIVACY_SETTING_PUBLIC: 3021, EVENT_TWG_POST_TRANSACTION_SETTING_PUBLIC: 3022, EVENT_REGWALL_OPTED_IN: 3023, EVENT_NEWSLETTER_OPTED_IN: 3024, EVENT_SHOWCASE_METERING_INIT: 3025, EVENT_SUBSCRIPTION_STATE: 4000, }; /** @enum {number} */ const EntitlementResult = { UNKNOWN_ENTITLEMENT_RESULT: 0, UNLOCKED_SUBSCRIBER: 1001, UNLOCKED_FREE: 1002, UNLOCKED_METER: 1003, LOCKED_REGWALL: 2001, LOCKED_PAYWALL: 2002, INELIGIBLE_PAYWALL: 2003, }; /** @enum {number} */ const EntitlementSource = { UNKNOWN_ENTITLEMENT_SOURCE: 0, GOOGLE_SUBSCRIBER_ENTITLEMENT: 1001, GOOGLE_SHOWCASE_METERING_SERVICE: 2001, SUBSCRIBE_WITH_GOOGLE_METERING_SERVICE: 2002, PUBLISHER_ENTITLEMENT: 3001, }; /** @enum {number} */ const EventOriginator = { UNKNOWN_CLIENT: 0, SWG_CLIENT: 1, AMP_CLIENT: 2, PROPENSITY_CLIENT: 3, SWG_SERVER: 4, PUBLISHER_CLIENT: 5, SHOWCASE_CLIENT: 6, }; /** @enum {number} */ const ReaderSurfaceType = { READER_SURFACE_TYPE_UNSPECIFIED: 0, READER_SURFACE_WORDPRESS: 1, READER_SURFACE_CHROME: 2, READER_SURFACE_TENOR: 3, }; /** * @implements {Message} */ class AccountCreationRequest { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?boolean} */ this.complete_ = data[base] == null ? null : data[base]; } /** * @return {?boolean} */ getComplete() { return this.complete_; } /** * @param {boolean} value */ setComplete(value) { this.complete_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.complete_, // field 1 - complete ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'AccountCreationRequest'; } } /** * @implements {Message} */ class ActionRequest { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?ActionType} */ this.action_ = data[base] == null ? null : data[base]; } /** * @return {?ActionType} */ getAction() { return this.action_; } /** * @param {!ActionType} value */ setAction(value) { this.action_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.action_, // field 1 - action ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'ActionRequest'; } } /** * @implements {Message} */ class AlreadySubscribedResponse { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?boolean} */ this.subscriberOrMember_ = data[base] == null ? null : data[base]; /** @private {?boolean} */ this.linkRequested_ = data[1 + base] == null ? null : data[1 + base]; } /** * @return {?boolean} */ getSubscriberOrMember() { return this.subscriberOrMember_; } /** * @param {boolean} value */ setSubscriberOrMember(value) { this.subscriberOrMember_ = value; } /** * @return {?boolean} */ getLinkRequested() { return this.linkRequested_; } /** * @param {boolean} value */ setLinkRequested(value) { this.linkRequested_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.subscriberOrMember_, // field 1 - subscriber_or_member this.linkRequested_, // field 2 - link_requested ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'AlreadySubscribedResponse'; } } /** * @implements {Message} */ class AnalyticsContext { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?string} */ this.embedderOrigin_ = data[base] == null ? null : data[base]; /** @private {?string} */ this.transactionId_ = data[1 + base] == null ? null : data[1 + base]; /** @private {?string} */ this.referringOrigin_ = data[2 + base] == null ? null : data[2 + base]; /** @private {?string} */ this.utmSource_ = data[3 + base] == null ? null : data[3 + base]; /** @private {?string} */ this.utmCampaign_ = data[4 + base] == null ? null : data[4 + base]; /** @private {?string} */ this.utmMedium_ = data[5 + base] == null ? null : data[5 + base]; /** @private {?string} */ this.sku_ = data[6 + base] == null ? null : data[6 + base]; /** @private {?boolean} */ this.readyToPay_ = data[7 + base] == null ? null : data[7 + base]; /** @private {!Array<string>} */ this.label_ = data[8 + base] || []; /** @private {?string} */ this.clientVersion_ = data[9 + base] == null ? null : data[9 + base]; /** @private {?string} */ this.url_ = data[10 + base] == null ? null : data[10 + base]; /** @private {?Timestamp} */ this.clientTimestamp_ = data[11 + base] == null || data[11 + base] == undefined ? null : new Timestamp(data[11 + base], includesLabel); /** @private {?ReaderSurfaceType} */ this.readerSurfaceType_ = data[12 + base] == null ? null : data[12 + base]; /** @private {?string} */ this.integrationVersion_ = data[13 + base] == null ? null : data[13 + base]; } /** * @return {?string} */ getEmbedderOrigin() { return this.embedderOrigin_; } /** * @param {string} value */ setEmbedderOrigin(value) { this.embedderOrigin_ = value; } /** * @return {?string} */ getTransactionId() { return this.transactionId_; } /** * @param {string} value */ setTransactionId(value) { this.transactionId_ = value; } /** * @return {?string} */ getReferringOrigin() { return this.referringOrigin_; } /** * @param {string} value */ setReferringOrigin(value) { this.referringOrigin_ = value; } /** * @return {?string} */ getUtmSource() { return this.utmSource_; } /** * @param {string} value */ setUtmSource(value) { this.utmSource_ = value; } /** * @return {?string} */ getUtmCampaign() { return this.utmCampaign_; } /** * @param {string} value */ setUtmCampaign(value) { this.utmCampaign_ = value; } /** * @return {?string} */ getUtmMedium() { return this.utmMedium_; } /** * @param {string} value */ setUtmMedium(value) { this.utmMedium_ = value; } /** * @return {?string} */ getSku() { return this.sku_; } /** * @param {string} value */ setSku(value) { this.sku_ = value; } /** * @return {?boolean} */ getReadyToPay() { return this.readyToPay_; } /** * @param {boolean} value */ setReadyToPay(value) { this.readyToPay_ = value; } /** * @return {!Array<string>} */ getLabelList() { return this.label_; } /** * @param {!Array<string>} value */ setLabelList(value) { this.label_ = value; } /** * @return {?string} */ getClientVersion() { return this.clientVersion_; } /** * @param {string} value */ setClientVersion(value) { this.clientVersion_ = value; } /** * @return {?string} */ getUrl() { return this.url_; } /** * @param {string} value */ setUrl(value) { this.url_ = value; } /** * @return {?Timestamp} */ getClientTimestamp() { return this.clientTimestamp_; } /** * @param {!Timestamp} value */ setClientTimestamp(value) { this.clientTimestamp_ = value; } /** * @return {?ReaderSurfaceType} */ getReaderSurfaceType() { return this.readerSurfaceType_; } /** * @param {!ReaderSurfaceType} value */ setReaderSurfaceType(value) { this.readerSurfaceType_ = value; } /** * @return {?string} */ getIntegrationVersion() { return this.integrationVersion_; } /** * @param {string} value */ setIntegrationVersion(value) { this.integrationVersion_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.embedderOrigin_, // field 1 - embedder_origin this.transactionId_, // field 2 - transaction_id this.referringOrigin_, // field 3 - referring_origin this.utmSource_, // field 4 - utm_source this.utmCampaign_, // field 5 - utm_campaign this.utmMedium_, // field 6 - utm_medium this.sku_, // field 7 - sku this.readyToPay_, // field 8 - ready_to_pay this.label_, // field 9 - label this.clientVersion_, // field 10 - client_version this.url_, // field 11 - url this.clientTimestamp_ ? this.clientTimestamp_.toArray(includeLabel) : [], // field 12 - client_timestamp this.readerSurfaceType_, // field 13 - reader_surface_type this.integrationVersion_, // field 14 - integration_version ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'AnalyticsContext'; } } /** * @implements {Message} */ class AnalyticsEventMeta { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?EventOriginator} */ this.eventOriginator_ = data[base] == null ? null : data[base]; /** @private {?boolean} */ this.isFromUserAction_ = data[1 + base] == null ? null : data[1 + base]; } /** * @return {?EventOriginator} */ getEventOriginator() { return this.eventOriginator_; } /** * @param {!EventOriginator} value */ setEventOriginator(value) { this.eventOriginator_ = value; } /** * @return {?boolean} */ getIsFromUserAction() { return this.isFromUserAction_; } /** * @param {boolean} value */ setIsFromUserAction(value) { this.isFromUserAction_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.eventOriginator_, // field 1 - event_originator this.isFromUserAction_, // field 2 - is_from_user_action ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'AnalyticsEventMeta'; } } /** * @implements {Message} */ class AnalyticsRequest { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?AnalyticsContext} */ this.context_ = data[base] == null || data[base] == undefined ? null : new AnalyticsContext(data[base], includesLabel); /** @private {?AnalyticsEvent} */ this.event_ = data[1 + base] == null ? null : data[1 + base]; /** @private {?AnalyticsEventMeta} */ this.meta_ = data[2 + base] == null || data[2 + base] == undefined ? null : new AnalyticsEventMeta(data[2 + base], includesLabel); /** @private {?EventParams} */ this.params_ = data[3 + base] == null || data[3 + base] == undefined ? null : new EventParams(data[3 + base], includesLabel); } /** * @return {?AnalyticsContext} */ getContext() { return this.context_; } /** * @param {!AnalyticsContext} value */ setContext(value) { this.context_ = value; } /** * @return {?AnalyticsEvent} */ getEvent() { return this.event_; } /** * @param {!AnalyticsEvent} value */ setEvent(value) { this.event_ = value; } /** * @return {?AnalyticsEventMeta} */ getMeta() { return this.meta_; } /** * @param {!AnalyticsEventMeta} value */ setMeta(value) { this.meta_ = value; } /** * @return {?EventParams} */ getParams() { return this.params_; } /** * @param {!EventParams} value */ setParams(value) { this.params_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.context_ ? this.context_.toArray(includeLabel) : [], // field 1 - context this.event_, // field 2 - event this.meta_ ? this.meta_.toArray(includeLabel) : [], // field 3 - meta this.params_ ? this.params_.toArray(includeLabel) : [], // field 4 - params ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'AnalyticsRequest'; } } /** * @implements {Message} */ class AudienceActivityClientLogsRequest { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?AnalyticsEvent} */ this.event_ = data[base] == null ? null : data[base]; } /** * @return {?AnalyticsEvent} */ getEvent() { return this.event_; } /** * @param {!AnalyticsEvent} value */ setEvent(value) { this.event_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.event_, // field 1 - event ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'AudienceActivityClientLogsRequest'; } } /** * @implements {Message} */ class CompleteAudienceActionResponse { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?string} */ this.swgUserToken_ = data[base] == null ? null : data[base]; /** @private {?boolean} */ this.actionCompleted_ = data[1 + base] == null ? null : data[1 + base]; /** @private {?string} */ this.userEmail_ = data[2 + base] == null ? null : data[2 + base]; /** @private {?boolean} */ this.alreadyCompleted_ = data[3 + base] == null ? null : data[3 + base]; } /** * @return {?string} */ getSwgUserToken() { return this.swgUserToken_; } /** * @param {string} value */ setSwgUserToken(value) { this.swgUserToken_ = value; } /** * @return {?boolean} */ getActionCompleted() { return this.actionCompleted_; } /** * @param {boolean} value */ setActionCompleted(value) { this.actionCompleted_ = value; } /** * @return {?string} */ getUserEmail() { return this.userEmail_; } /** * @param {string} value */ setUserEmail(value) { this.userEmail_ = value; } /** * @return {?boolean} */ getAlreadyCompleted() { return this.alreadyCompleted_; } /** * @param {boolean} value */ setAlreadyCompleted(value) { this.alreadyCompleted_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.swgUserToken_, // field 1 - swg_user_token this.actionCompleted_, // field 2 - action_completed this.userEmail_, // field 3 - user_email this.alreadyCompleted_, // field 4 - already_completed ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'CompleteAudienceActionResponse'; } } /** * @implements {Message} */ class EntitlementJwt { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?string} */ this.jwt_ = data[base] == null ? null : data[base]; /** @private {?string} */ this.source_ = data[1 + base] == null ? null : data[1 + base]; } /** * @return {?string} */ getJwt() { return this.jwt_; } /** * @param {string} value */ setJwt(value) { this.jwt_ = value; } /** * @return {?string} */ getSource() { return this.source_; } /** * @param {string} value */ setSource(value) { this.source_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.jwt_, // field 1 - jwt this.source_, // field 2 - source ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'EntitlementJwt'; } } /** * @implements {Message} */ class EntitlementsRequest { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?EntitlementJwt} */ this.usedEntitlement_ = data[base] == null || data[base] == undefined ? null : new EntitlementJwt(data[base], includesLabel); /** @private {?Timestamp} */ this.clientEventTime_ = data[1 + base] == null || data[1 + base] == undefined ? null : new Timestamp(data[1 + base], includesLabel); /** @private {?EntitlementSource} */ this.entitlementSource_ = data[2 + base] == null ? null : data[2 + base]; /** @private {?EntitlementResult} */ this.entitlementResult_ = data[3 + base] == null ? null : data[3 + base]; /** @private {?string} */ this.token_ = data[4 + base] == null ? null : data[4 + base]; /** @private {?boolean} */ this.isUserRegistered_ = data[5 + base] == null ? null : data[5 + base]; } /** * @return {?EntitlementJwt} */ getUsedEntitlement() { return this.usedEntitlement_; } /** * @param {!EntitlementJwt} value */ setUsedEntitlement(value) { this.usedEntitlement_ = value; } /** * @return {?Timestamp} */ getClientEventTime() { return this.clientEventTime_; } /** * @param {!Timestamp} value */ setClientEventTime(value) { this.clientEventTime_ = value; } /** * @return {?EntitlementSource} */ getEntitlementSource() { return this.entitlementSource_; } /** * @param {!EntitlementSource} value */ setEntitlementSource(value) { this.entitlementSource_ = value; } /** * @return {?EntitlementResult} */ getEntitlementResult() { return this.entitlementResult_; } /** * @param {!EntitlementResult} value */ setEntitlementResult(value) { this.entitlementResult_ = value; } /** * @return {?string} */ getToken() { return this.token_; } /** * @param {string} value */ setToken(value) { this.token_ = value; } /** * @return {?boolean} */ getIsUserRegistered() { return this.isUserRegistered_; } /** * @param {boolean} value */ setIsUserRegistered(value) { this.isUserRegistered_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.usedEntitlement_ ? this.usedEntitlement_.toArray(includeLabel) : [], // field 1 - used_entitlement this.clientEventTime_ ? this.clientEventTime_.toArray(includeLabel) : [], // field 2 - client_event_time this.entitlementSource_, // field 3 - entitlement_source this.entitlementResult_, // field 4 - entitlement_result this.token_, // field 5 - token this.isUserRegistered_, // field 6 - is_user_registered ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'EntitlementsRequest'; } } /** * @implements {Message} */ class EntitlementsResponse { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?string} */ this.jwt_ = data[base] == null ? null : data[base]; /** @private {?string} */ this.swgUserToken_ = data[1 + base] == null ? null : data[1 + base]; } /** * @return {?string} */ getJwt() { return this.jwt_; } /** * @param {string} value */ setJwt(value) { this.jwt_ = value; } /** * @return {?string} */ getSwgUserToken() { return this.swgUserToken_; } /** * @param {string} value */ setSwgUserToken(value) { this.swgUserToken_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.jwt_, // field 1 - jwt this.swgUserToken_, // field 2 - swg_user_token ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'EntitlementsResponse'; } } /** * @implements {Message} */ class EventParams { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?string} */ this.smartboxMessage_ = data[base] == null ? null : data[base]; /** @private {?string} */ this.gpayTransactionId_ = data[1 + base] == null ? null : data[1 + base]; /** @private {?boolean} */ this.hadLogged_ = data[2 + base] == null ? null : data[2 + base]; /** @private {?string} */ this.sku_ = data[3 + base] == null ? null : data[3 + base]; /** @private {?string} */ this.oldTransactionId_ = data[4 + base] == null ? null : data[4 + base]; /** @private {?boolean} */ this.isUserRegistered_ = data[5 + base] == null ? null : data[5 + base]; /** @private {?string} */ this.subscriptionFlow_ = data[6 + base] == null ? null : data[6 + base]; } /** * @return {?string} */ getSmartboxMessage() { return this.smartboxMessage_; } /** * @param {string} value */ setSmartboxMessage(value) { this.smartboxMessage_ = value; } /** * @return {?string} */ getGpayTransactionId() { return this.gpayTransactionId_; } /** * @param {string} value */ setGpayTransactionId(value) { this.gpayTransactionId_ = value; } /** * @return {?boolean} */ getHadLogged() { return this.hadLogged_; } /** * @param {boolean} value */ setHadLogged(value) { this.hadLogged_ = value; } /** * @return {?string} */ getSku() { return this.sku_; } /** * @param {string} value */ setSku(value) { this.sku_ = value; } /** * @return {?string} */ getOldTransactionId() { return this.oldTransactionId_; } /** * @param {string} value */ setOldTransactionId(value) { this.oldTransactionId_ = value; } /** * @return {?boolean} */ getIsUserRegistered() { return this.isUserRegistered_; } /** * @param {boolean} value */ setIsUserRegistered(value) { this.isUserRegistered_ = value; } /** * @return {?string} */ getSubscriptionFlow() { return this.subscriptionFlow_; } /** * @param {string} value */ setSubscriptionFlow(value) { this.subscriptionFlow_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.smartboxMessage_, // field 1 - smartbox_message this.gpayTransactionId_, // field 2 - gpay_transaction_id this.hadLogged_, // field 3 - had_logged this.sku_, // field 4 - sku this.oldTransactionId_, // field 5 - old_transaction_id this.isUserRegistered_, // field 6 - is_user_registered this.subscriptionFlow_, // field 7 - subscription_flow ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'EventParams'; } } /** * @implements {Message} */ class FinishedLoggingResponse { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?boolean} */ this.complete_ = data[base] == null ? null : data[base]; /** @private {?string} */ this.error_ = data[1 + base] == null ? null : data[1 + base]; } /** * @return {?boolean} */ getComplete() { return this.complete_; } /** * @param {boolean} value */ setComplete(value) { this.complete_ = value; } /** * @return {?string} */ getError() { return this.error_; } /** * @param {string} value */ setError(value) { this.error_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.complete_, // field 1 - complete this.error_, // field 2 - error ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'FinishedLoggingResponse'; } } /** * @implements {Message} */ class LinkSaveTokenRequest { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?string} */ this.authCode_ = data[base] == null ? null : data[base]; /** @private {?string} */ this.token_ = data[1 + base] == null ? null : data[1 + base]; } /** * @return {?string} */ getAuthCode() { return this.authCode_; } /** * @param {string} value */ setAuthCode(value) { this.authCode_ = value; } /** * @return {?string} */ getToken() { return this.token_; } /** * @param {string} value */ setToken(value) { this.token_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.authCode_, // field 1 - auth_code this.token_, // field 2 - token ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'LinkSaveTokenRequest'; } } /** * @implements {Message} */ class LinkingInfoResponse { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?boolean} */ this.requested_ = data[base] == null ? null : data[base]; } /** * @return {?boolean} */ getRequested() { return this.requested_; } /** * @param {boolean} value */ setRequested(value) { this.requested_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.requested_, // field 1 - requested ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'LinkingInfoResponse'; } } /** * @implements {Message} */ class OpenDialogRequest { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?string} */ this.urlPath_ = data[base] == null ? null : data[base]; } /** * @return {?string} */ getUrlPath() { return this.urlPath_; } /** * @param {string} value */ setUrlPath(value) { this.urlPath_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.urlPath_, // field 1 - url_path ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'OpenDialogRequest'; } } /** * @implements {Message} */ class SkuSelectedResponse { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?string} */ this.sku_ = data[base] == null ? null : data[base]; /** @private {?string} */ this.oldSku_ = data[1 + base] == null ? null : data[1 + base]; /** @private {?boolean} */ this.oneTime_ = data[2 + base] == null ? null : data[2 + base]; /** @private {?string} */ this.playOffer_ = data[3 + base] == null ? null : data[3 + base]; /** @private {?string} */ this.oldPlayOffer_ = data[4 + base] == null ? null : data[4 + base]; /** @private {?string} */ this.customMessage_ = data[5 + base] == null ? null : data[5 + base]; /** @private {?boolean} */ this.anonymous_ = data[6 + base] == null ? null : data[6 + base]; } /** * @return {?string} */ getSku() { return this.sku_; } /** * @param {string} value */ setSku(value) { this.sku_ = value; } /** * @return {?string} */ getOldSku() { return this.oldSku_; } /** * @param {string} value */ setOldSku(value) { this.oldSku_ = value; } /** * @return {?boolean} */ getOneTime() { return this.oneTime_; } /** * @param {boolean} value */ setOneTime(value) { this.oneTime_ = value; } /** * @return {?string} */ getPlayOffer() { return this.playOffer_; } /** * @param {string} value */ setPlayOffer(value) { this.playOffer_ = value; } /** * @return {?string} */ getOldPlayOffer() { return this.oldPlayOffer_; } /** * @param {string} value */ setOldPlayOffer(value) { this.oldPlayOffer_ = value; } /** * @return {?string} */ getCustomMessage() { return this.customMessage_; } /** * @param {string} value */ setCustomMessage(value) { this.customMessage_ = value; } /** * @return {?boolean} */ getAnonymous() { return this.anonymous_; } /** * @param {boolean} value */ setAnonymous(value) { this.anonymous_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.sku_, // field 1 - sku this.oldSku_, // field 2 - old_sku this.oneTime_, // field 3 - one_time this.playOffer_, // field 4 - play_offer this.oldPlayOffer_, // field 5 - old_play_offer this.customMessage_, // field 6 - custom_message this.anonymous_, // field 7 - anonymous ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'SkuSelectedResponse'; } } /** * @implements {Message} */ class SmartBoxMessage { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?boolean} */ this.isClicked_ = data[base] == null ? null : data[base]; } /** * @return {?boolean} */ getIsClicked() { return this.isClicked_; } /** * @param {boolean} value */ setIsClicked(value) { this.isClicked_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.isClicked_, // field 1 - is_clicked ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'SmartBoxMessage'; } } /** * @implements {Message} */ class SubscribeResponse { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?boolean} */ this.subscribe_ = data[base] == null ? null : data[base]; } /** * @return {?boolean} */ getSubscribe() { return this.subscribe_; } /** * @param {boolean} value */ setSubscribe(value) { this.subscribe_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.subscribe_, // field 1 - subscribe ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'SubscribeResponse'; } } /** * @implements {Message} */ class Timestamp { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?number} */ this.seconds_ = data[base] == null ? null : data[base]; /** @private {?number} */ this.nanos_ = data[1 + base] == null ? null : data[1 + base]; } /** * @return {?number} */ getSeconds() { return this.seconds_; } /** * @param {number} value */ setSeconds(value) { this.seconds_ = value; } /** * @return {?number} */ getNanos() { return this.nanos_; } /** * @param {number} value */ setNanos(value) { this.nanos_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.seconds_, // field 1 - seconds this.nanos_, // field 2 - nanos ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'Timestamp'; } } /** * @implements {Message} */ class ToastCloseRequest { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?boolean} */ this.close_ = data[base] == null ? null : data[base]; } /** * @return {?boolean} */ getClose() { return this.close_; } /** * @param {boolean} value */ setClose(value) { this.close_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.close_, // field 1 - close ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'ToastCloseRequest'; } } /** * @implements {Message} */ class ViewSubscriptionsResponse { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?boolean} */ this.native_ = data[base] == null ? null : data[base]; } /** * @return {?boolean} */ getNative() { return this.native_; } /** * @param {boolean} value */ setNative(value) { this.native_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.native_, // field 1 - native ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'ViewSubscriptionsResponse'; } } const PROTO_MAP = { 'AccountCreationRequest': AccountCreationRequest, 'ActionRequest': ActionRequest, 'AlreadySubscribedResponse': AlreadySubscribedResponse, 'AnalyticsContext': AnalyticsContext, 'AnalyticsEventMeta': AnalyticsEventMeta, 'AnalyticsRequest': AnalyticsRequest, 'AudienceActivityClientLogsRequest': AudienceActivityClientLogsRequest, 'CompleteAudienceActionResponse': CompleteAudienceActionResponse, 'EntitlementJwt': EntitlementJwt, 'EntitlementsRequest': EntitlementsRequest, 'EntitlementsResponse': EntitlementsResponse, 'EventParams': EventParams, 'FinishedLoggingResponse': FinishedLoggingResponse, 'LinkSaveTokenRequest': LinkSaveTokenRequest, 'LinkingInfoResponse': LinkingInfoResponse, 'OpenDialogRequest': OpenDialogRequest, 'SkuSelectedResponse': SkuSelectedResponse, 'SmartBoxMessage': SmartBoxMessage, 'SubscribeResponse': SubscribeResponse, 'Timestamp': Timestamp, 'ToastCloseRequest': ToastCloseRequest, 'ViewSubscriptionsResponse': ViewSubscriptionsResponse, }; /** * Utility to deserialize a buffer * @param {!Array<*>} data * @return {!Message} */ function deserialize(data) { /** {?string} */ const key = data ? data[0] : null; if (key) { const ctor = PROTO_MAP[key]; if (ctor) { return new ctor(data); } } throw new Error('Deserialization failed for ' + data); } /** * @param {function(new: T)} messageType * @return {string} * @template T */ function getLabel(messageType) { const message = /** @type {!Message} */ (new messageType()); return message.label(); } export { AccountCreationRequest, ActionRequest, ActionType, AlreadySubscribedResponse, AnalyticsContext, AnalyticsEvent, AnalyticsEventMeta, AnalyticsRequest, AudienceActivityClientLogsRequest, CompleteAudienceActionResponse, EntitlementJwt, EntitlementResult, EntitlementSource, EntitlementsRequest, EntitlementsResponse, EventOriginator, EventParams, FinishedLoggingResponse, LinkSaveTokenRequest, LinkingInfoResponse, Message, OpenDialogRequest, ReaderSurfaceType, SkuSelectedResponse, SmartBoxMessage, SubscribeResponse, Timestamp, ToastCloseRequest, ViewSubscriptionsResponse, deserialize, getLabel, };
src/proto/api_messages.js
/** * Copyright 2018 The Subscribe with Google Authors. 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 * * 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. */ /** * @fileoverview Protos for SwG client/iframe messaging * Auto generated, do not edit */ /** * @interface */ class Message { /** * @return {string} */ label() {} /** * @param {boolean=} unusedIncludeLabel * @return {!Array<*>} */ toArray(unusedIncludeLabel = true) {} } /** @enum {number} */ const ActionType = { ACTION_TYPE_UNKNOWN: 0, ACTION_TYPE_RELOAD_PAGE: 1, ACTION_TYPE_UPDATE_COUNTER: 2, }; /** @enum {number} */ const AnalyticsEvent = { UNKNOWN: 0, IMPRESSION_PAYWALL: 1, IMPRESSION_AD: 2, IMPRESSION_OFFERS: 3, IMPRESSION_SUBSCRIBE_BUTTON: 4, IMPRESSION_SMARTBOX: 5, IMPRESSION_SWG_BUTTON: 6, IMPRESSION_CLICK_TO_SHOW_OFFERS: 7, IMPRESSION_CLICK_TO_SHOW_OFFERS_OR_ALREADY_SUBSCRIBED: 8, IMPRESSION_SUBSCRIPTION_COMPLETE: 9, IMPRESSION_ACCOUNT_CHANGED: 10, IMPRESSION_PAGE_LOAD: 11, IMPRESSION_LINK: 12, IMPRESSION_SAVE_SUBSCR_TO_GOOGLE: 13, IMPRESSION_GOOGLE_UPDATED: 14, IMPRESSION_SHOW_OFFERS_SMARTBOX: 15, IMPRESSION_SHOW_OFFERS_SWG_BUTTON: 16, IMPRESSION_SELECT_OFFER_SMARTBOX: 17, IMPRESSION_SELECT_OFFER_SWG_BUTTON: 18, IMPRESSION_SHOW_CONTRIBUTIONS_SWG_BUTTON: 19, IMPRESSION_SELECT_CONTRIBUTION_SWG_BUTTON: 20, IMPRESSION_METER_TOAST: 21, IMPRESSION_REGWALL: 22, IMPRESSION_SHOWCASE_REGWALL: 23, IMPRESSION_SWG_SUBSCRIPTION_MINI_PROMPT: 24, IMPRESSION_SWG_CONTRIBUTION_MINI_PROMPT: 25, IMPRESSION_CONTRIBUTION_OFFERS: 26, IMPRESSION_TWG_COUNTER: 27, IMPRESSION_TWG_SITE_SUPPORTER_WALL: 28, IMPRESSION_TWG_PUBLICATION: 29, IMPRESSION_TWG_STATIC_BUTTON: 30, IMPRESSION_TWG_DYNAMIC_BUTTON: 31, IMPRESSION_TWG_STICKER_SELECTION_SCREEN: 32, IMPRESSION_TWG_PUBLICATION_NOT_SET_UP: 33, IMPRESSION_REGWALL_OPT_IN: 34, IMPRESSION_NEWSLETTER_OPT_IN: 35, ACTION_SUBSCRIBE: 1000, ACTION_PAYMENT_COMPLETE: 1001, ACTION_ACCOUNT_CREATED: 1002, ACTION_ACCOUNT_ACKNOWLEDGED: 1003, ACTION_SUBSCRIPTIONS_LANDING_PAGE: 1004, ACTION_PAYMENT_FLOW_STARTED: 1005, ACTION_OFFER_SELECTED: 1006, ACTION_SWG_BUTTON_CLICK: 1007, ACTION_VIEW_OFFERS: 1008, ACTION_ALREADY_SUBSCRIBED: 1009, ACTION_NEW_DEFERRED_ACCOUNT: 1010, ACTION_LINK_CONTINUE: 1011, ACTION_LINK_CANCEL: 1012, ACTION_GOOGLE_UPDATED_CLOSE: 1013, ACTION_USER_CANCELED_PAYFLOW: 1014, ACTION_SAVE_SUBSCR_TO_GOOGLE_CONTINUE: 1015, ACTION_SAVE_SUBSCR_TO_GOOGLE_CANCEL: 1016, ACTION_SWG_BUTTON_SHOW_OFFERS_CLICK: 1017, ACTION_SWG_BUTTON_SELECT_OFFER_CLICK: 1018, ACTION_SWG_BUTTON_SHOW_CONTRIBUTIONS_CLICK: 1019, ACTION_SWG_BUTTON_SELECT_CONTRIBUTION_CLICK: 1020, ACTION_USER_CONSENT_DEFERRED_ACCOUNT: 1021, ACTION_USER_DENY_DEFERRED_ACCOUNT: 1022, ACTION_DEFERRED_ACCOUNT_REDIRECT: 1023, ACTION_GET_ENTITLEMENTS: 1024, ACTION_METER_TOAST_SUBSCRIBE_CLICK: 1025, ACTION_METER_TOAST_EXPANDED: 1026, ACTION_METER_TOAST_CLOSED_BY_ARTICLE_INTERACTION: 1027, ACTION_METER_TOAST_CLOSED_BY_SWIPE_DOWN: 1028, ACTION_METER_TOAST_CLOSED_BY_X_CLICKED: 1029, ACTION_SWG_SUBSCRIPTION_MINI_PROMPT_CLICK: 1030, ACTION_SWG_CONTRIBUTION_MINI_PROMPT_CLICK: 1031, ACTION_SWG_SUBSCRIPTION_MINI_PROMPT_CLOSE: 1032, ACTION_SWG_CONTRIBUTION_MINI_PROMPT_CLOSE: 1033, ACTION_CONTRIBUTION_OFFER_SELECTED: 1034, ACTION_SHOWCASE_REGWALL_GSI_CLICK: 1035, ACTION_SHOWCASE_REGWALL_EXISTING_ACCOUNT_CLICK: 1036, ACTION_SUBSCRIPTION_OFFERS_CLOSED: 1037, ACTION_CONTRIBUTION_OFFERS_CLOSED: 1038, ACTION_TWG_STATIC_CTA_CLICK: 1039, ACTION_TWG_DYNAMIC_CTA_CLICK: 1040, ACTION_TWG_SITE_LEVEL_SUPPORTER_WALL_CTA_CLICK: 1041, ACTION_TWG_DIALOG_SUPPORTER_WALL_CTA_CLICK: 1042, ACTION_TWG_COUNTER_CLICK: 1043, ACTION_TWG_SITE_SUPPORTER_WALL_ALL_THANKS_CLICK: 1044, ACTION_TWG_PAID_STICKER_SELECTED_SCREEN_CLOSE_CLICK: 1045, ACTION_TWG_PAID_STICKER_SELECTION_CLICK: 1046, ACTION_TWG_FREE_STICKER_SELECTION_CLICK: 1047, ACTION_TWG_MINI_SUPPORTER_WALL_CLICK: 1048, ACTION_TWG_CREATOR_BENEFIT_CLICK: 1049, ACTION_TWG_FREE_TRANSACTION_START_NEXT_BUTTON_CLICK: 1050, ACTION_TWG_PAID_TRANSACTION_START_NEXT_BUTTON_CLICK: 1051, ACTION_TWG_STICKER_SELECTION_SCREEN_CLOSE_CLICK: 1052, ACTION_TWG_ARTICLE_LEVEL_SUPPORTER_WALL_CTA_CLICK: 1053, ACTION_REGWALL_OPT_IN_BUTTON_CLICK: 1054, ACTION_REGWALL_ALREADY_OPTED_IN_CLICK: 1055, ACTION_NEWSLETTER_OPT_IN_BUTTON_CLICK: 1056, ACTION_NEWSLETTER_ALREADY_OPTED_IN_CLICK: 1057, ACTION_REGWALL_OPT_IN_CLOSE: 1058, ACTION_NEWSLETTER_OPT_IN_CLOSE: 1059, ACTION_SHOWCASE_REGWALL_SWIG_CLICK: 1060, ACTION_TWG_CHROME_APP_MENU_ENTRY_POINT_CLICK: 1061, ACTION_TWG_DISCOVER_FEED_MENU_ENTRY_POINT_CLICK: 1062, EVENT_PAYMENT_FAILED: 2000, EVENT_REGWALL_OPT_IN_FAILED: 2001, EVENT_NEWSLETTER_OPT_IN_FAILED: 2002, EVENT_CUSTOM: 3000, EVENT_CONFIRM_TX_ID: 3001, EVENT_CHANGED_TX_ID: 3002, EVENT_GPAY_NO_TX_ID: 3003, EVENT_GPAY_CANNOT_CONFIRM_TX_ID: 3004, EVENT_GOOGLE_UPDATED: 3005, EVENT_NEW_TX_ID: 3006, EVENT_UNLOCKED_BY_SUBSCRIPTION: 3007, EVENT_UNLOCKED_BY_METER: 3008, EVENT_NO_ENTITLEMENTS: 3009, EVENT_HAS_METERING_ENTITLEMENTS: 3010, EVENT_OFFERED_METER: 3011, EVENT_UNLOCKED_FREE_PAGE: 3012, EVENT_INELIGIBLE_PAYWALL: 3013, EVENT_UNLOCKED_FOR_CRAWLER: 3014, EVENT_TWG_COUNTER_VIEW: 3015, EVENT_TWG_SITE_SUPPORTER_WALL_VIEW: 3016, EVENT_TWG_STATIC_BUTTON_VIEW: 3017, EVENT_TWG_DYNAMIC_BUTTON_VIEW: 3018, EVENT_TWG_PRE_TRANSACTION_PRIVACY_SETTING_PRIVATE: 3019, EVENT_TWG_POST_TRANSACTION_SETTING_PRIVATE: 3020, EVENT_TWG_PRE_TRANSACTION_PRIVACY_SETTING_PUBLIC: 3021, EVENT_TWG_POST_TRANSACTION_SETTING_PUBLIC: 3022, EVENT_REGWALL_OPTED_IN: 3023, EVENT_NEWSLETTER_OPTED_IN: 3024, EVENT_SHOWCASE_METERING_INIT: 3025, EVENT_SUBSCRIPTION_STATE: 4000, }; /** @enum {number} */ const EntitlementResult = { UNKNOWN_ENTITLEMENT_RESULT: 0, UNLOCKED_SUBSCRIBER: 1001, UNLOCKED_FREE: 1002, UNLOCKED_METER: 1003, LOCKED_REGWALL: 2001, LOCKED_PAYWALL: 2002, INELIGIBLE_PAYWALL: 2003, }; /** @enum {number} */ const EntitlementSource = { UNKNOWN_ENTITLEMENT_SOURCE: 0, GOOGLE_SUBSCRIBER_ENTITLEMENT: 1001, GOOGLE_SHOWCASE_METERING_SERVICE: 2001, SUBSCRIBE_WITH_GOOGLE_METERING_SERVICE: 2002, PUBLISHER_ENTITLEMENT: 3001, }; /** @enum {number} */ const EventOriginator = { UNKNOWN_CLIENT: 0, SWG_CLIENT: 1, AMP_CLIENT: 2, PROPENSITY_CLIENT: 3, SWG_SERVER: 4, PUBLISHER_CLIENT: 5, SHOWCASE_CLIENT: 6, }; /** @enum {number} */ const ReaderSurfaceType = { READER_SURFACE_TYPE_UNSPECIFIED: 0, READER_SURFACE_WORDPRESS: 1, READER_SURFACE_CHROME: 2, READER_SURFACE_TENOR: 3, }; /** * @implements {Message} */ class AccountCreationRequest { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?boolean} */ this.complete_ = data[base] == null ? null : data[base]; } /** * @return {?boolean} */ getComplete() { return this.complete_; } /** * @param {boolean} value */ setComplete(value) { this.complete_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.complete_, // field 1 - complete ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'AccountCreationRequest'; } } /** * @implements {Message} */ class ActionRequest { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?ActionType} */ this.action_ = data[base] == null ? null : data[base]; } /** * @return {?ActionType} */ getAction() { return this.action_; } /** * @param {!ActionType} value */ setAction(value) { this.action_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.action_, // field 1 - action ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'ActionRequest'; } } /** * @implements {Message} */ class AlreadySubscribedResponse { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?boolean} */ this.subscriberOrMember_ = data[base] == null ? null : data[base]; /** @private {?boolean} */ this.linkRequested_ = data[1 + base] == null ? null : data[1 + base]; } /** * @return {?boolean} */ getSubscriberOrMember() { return this.subscriberOrMember_; } /** * @param {boolean} value */ setSubscriberOrMember(value) { this.subscriberOrMember_ = value; } /** * @return {?boolean} */ getLinkRequested() { return this.linkRequested_; } /** * @param {boolean} value */ setLinkRequested(value) { this.linkRequested_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.subscriberOrMember_, // field 1 - subscriber_or_member this.linkRequested_, // field 2 - link_requested ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'AlreadySubscribedResponse'; } } /** * @implements {Message} */ class AnalyticsContext { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?string} */ this.embedderOrigin_ = data[base] == null ? null : data[base]; /** @private {?string} */ this.transactionId_ = data[1 + base] == null ? null : data[1 + base]; /** @private {?string} */ this.referringOrigin_ = data[2 + base] == null ? null : data[2 + base]; /** @private {?string} */ this.utmSource_ = data[3 + base] == null ? null : data[3 + base]; /** @private {?string} */ this.utmCampaign_ = data[4 + base] == null ? null : data[4 + base]; /** @private {?string} */ this.utmMedium_ = data[5 + base] == null ? null : data[5 + base]; /** @private {?string} */ this.sku_ = data[6 + base] == null ? null : data[6 + base]; /** @private {?boolean} */ this.readyToPay_ = data[7 + base] == null ? null : data[7 + base]; /** @private {!Array<string>} */ this.label_ = data[8 + base] || []; /** @private {?string} */ this.clientVersion_ = data[9 + base] == null ? null : data[9 + base]; /** @private {?string} */ this.url_ = data[10 + base] == null ? null : data[10 + base]; /** @private {?Timestamp} */ this.clientTimestamp_ = data[11 + base] == null || data[11 + base] == undefined ? null : new Timestamp(data[11 + base], includesLabel); /** @private {?ReaderSurfaceType} */ this.readerSurfaceType_ = data[12 + base] == null ? null : data[12 + base]; /** @private {?string} */ this.integrationVersion_ = data[13 + base] == null ? null : data[13 + base]; } /** * @return {?string} */ getEmbedderOrigin() { return this.embedderOrigin_; } /** * @param {string} value */ setEmbedderOrigin(value) { this.embedderOrigin_ = value; } /** * @return {?string} */ getTransactionId() { return this.transactionId_; } /** * @param {string} value */ setTransactionId(value) { this.transactionId_ = value; } /** * @return {?string} */ getReferringOrigin() { return this.referringOrigin_; } /** * @param {string} value */ setReferringOrigin(value) { this.referringOrigin_ = value; } /** * @return {?string} */ getUtmSource() { return this.utmSource_; } /** * @param {string} value */ setUtmSource(value) { this.utmSource_ = value; } /** * @return {?string} */ getUtmCampaign() { return this.utmCampaign_; } /** * @param {string} value */ setUtmCampaign(value) { this.utmCampaign_ = value; } /** * @return {?string} */ getUtmMedium() { return this.utmMedium_; } /** * @param {string} value */ setUtmMedium(value) { this.utmMedium_ = value; } /** * @return {?string} */ getSku() { return this.sku_; } /** * @param {string} value */ setSku(value) { this.sku_ = value; } /** * @return {?boolean} */ getReadyToPay() { return this.readyToPay_; } /** * @param {boolean} value */ setReadyToPay(value) { this.readyToPay_ = value; } /** * @return {!Array<string>} */ getLabelList() { return this.label_; } /** * @param {!Array<string>} value */ setLabelList(value) { this.label_ = value; } /** * @return {?string} */ getClientVersion() { return this.clientVersion_; } /** * @param {string} value */ setClientVersion(value) { this.clientVersion_ = value; } /** * @return {?string} */ getUrl() { return this.url_; } /** * @param {string} value */ setUrl(value) { this.url_ = value; } /** * @return {?Timestamp} */ getClientTimestamp() { return this.clientTimestamp_; } /** * @param {!Timestamp} value */ setClientTimestamp(value) { this.clientTimestamp_ = value; } /** * @return {?ReaderSurfaceType} */ getReaderSurfaceType() { return this.readerSurfaceType_; } /** * @param {!ReaderSurfaceType} value */ setReaderSurfaceType(value) { this.readerSurfaceType_ = value; } /** * @return {?string} */ getIntegrationVersion() { return this.integrationVersion_; } /** * @param {string} value */ setIntegrationVersion(value) { this.integrationVersion_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.embedderOrigin_, // field 1 - embedder_origin this.transactionId_, // field 2 - transaction_id this.referringOrigin_, // field 3 - referring_origin this.utmSource_, // field 4 - utm_source this.utmCampaign_, // field 5 - utm_campaign this.utmMedium_, // field 6 - utm_medium this.sku_, // field 7 - sku this.readyToPay_, // field 8 - ready_to_pay this.label_, // field 9 - label this.clientVersion_, // field 10 - client_version this.url_, // field 11 - url this.clientTimestamp_ ? this.clientTimestamp_.toArray(includeLabel) : [], // field 12 - client_timestamp this.readerSurfaceType_, // field 13 - reader_surface_type this.integrationVersion_, // field 14 - integration_version ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'AnalyticsContext'; } } /** * @implements {Message} */ class AnalyticsEventMeta { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?EventOriginator} */ this.eventOriginator_ = data[base] == null ? null : data[base]; /** @private {?boolean} */ this.isFromUserAction_ = data[1 + base] == null ? null : data[1 + base]; } /** * @return {?EventOriginator} */ getEventOriginator() { return this.eventOriginator_; } /** * @param {!EventOriginator} value */ setEventOriginator(value) { this.eventOriginator_ = value; } /** * @return {?boolean} */ getIsFromUserAction() { return this.isFromUserAction_; } /** * @param {boolean} value */ setIsFromUserAction(value) { this.isFromUserAction_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.eventOriginator_, // field 1 - event_originator this.isFromUserAction_, // field 2 - is_from_user_action ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'AnalyticsEventMeta'; } } /** * @implements {Message} */ class AnalyticsRequest { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?AnalyticsContext} */ this.context_ = data[base] == null || data[base] == undefined ? null : new AnalyticsContext(data[base], includesLabel); /** @private {?AnalyticsEvent} */ this.event_ = data[1 + base] == null ? null : data[1 + base]; /** @private {?AnalyticsEventMeta} */ this.meta_ = data[2 + base] == null || data[2 + base] == undefined ? null : new AnalyticsEventMeta(data[2 + base], includesLabel); /** @private {?EventParams} */ this.params_ = data[3 + base] == null || data[3 + base] == undefined ? null : new EventParams(data[3 + base], includesLabel); } /** * @return {?AnalyticsContext} */ getContext() { return this.context_; } /** * @param {!AnalyticsContext} value */ setContext(value) { this.context_ = value; } /** * @return {?AnalyticsEvent} */ getEvent() { return this.event_; } /** * @param {!AnalyticsEvent} value */ setEvent(value) { this.event_ = value; } /** * @return {?AnalyticsEventMeta} */ getMeta() { return this.meta_; } /** * @param {!AnalyticsEventMeta} value */ setMeta(value) { this.meta_ = value; } /** * @return {?EventParams} */ getParams() { return this.params_; } /** * @param {!EventParams} value */ setParams(value) { this.params_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.context_ ? this.context_.toArray(includeLabel) : [], // field 1 - context this.event_, // field 2 - event this.meta_ ? this.meta_.toArray(includeLabel) : [], // field 3 - meta this.params_ ? this.params_.toArray(includeLabel) : [], // field 4 - params ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'AnalyticsRequest'; } } /** * @implements {Message} */ class AudienceActivityClientLogsRequest { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?AnalyticsEvent} */ this.event_ = data[base] == null ? null : data[base]; } /** * @return {?AnalyticsEvent} */ getEvent() { return this.event_; } /** * @param {!AnalyticsEvent} value */ setEvent(value) { this.event_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.event_, // field 1 - event ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'AudienceActivityClientLogsRequest'; } } /** * @implements {Message} */ class CompleteAudienceActionResponse { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?string} */ this.swgUserToken_ = data[base] == null ? null : data[base]; /** @private {?boolean} */ this.actionCompleted_ = data[1 + base] == null ? null : data[1 + base]; /** @private {?string} */ this.userEmail_ = data[2 + base] == null ? null : data[2 + base]; } /** * @return {?string} */ getSwgUserToken() { return this.swgUserToken_; } /** * @param {string} value */ setSwgUserToken(value) { this.swgUserToken_ = value; } /** * @return {?boolean} */ getActionCompleted() { return this.actionCompleted_; } /** * @param {boolean} value */ setActionCompleted(value) { this.actionCompleted_ = value; } /** * @return {?string} */ getUserEmail() { return this.userEmail_; } /** * @param {string} value */ setUserEmail(value) { this.userEmail_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.swgUserToken_, // field 1 - swg_user_token this.actionCompleted_, // field 2 - action_completed this.userEmail_, // field 3 - user_email ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'CompleteAudienceActionResponse'; } } /** * @implements {Message} */ class EntitlementJwt { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?string} */ this.jwt_ = data[base] == null ? null : data[base]; /** @private {?string} */ this.source_ = data[1 + base] == null ? null : data[1 + base]; } /** * @return {?string} */ getJwt() { return this.jwt_; } /** * @param {string} value */ setJwt(value) { this.jwt_ = value; } /** * @return {?string} */ getSource() { return this.source_; } /** * @param {string} value */ setSource(value) { this.source_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.jwt_, // field 1 - jwt this.source_, // field 2 - source ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'EntitlementJwt'; } } /** * @implements {Message} */ class EntitlementsRequest { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?EntitlementJwt} */ this.usedEntitlement_ = data[base] == null || data[base] == undefined ? null : new EntitlementJwt(data[base], includesLabel); /** @private {?Timestamp} */ this.clientEventTime_ = data[1 + base] == null || data[1 + base] == undefined ? null : new Timestamp(data[1 + base], includesLabel); /** @private {?EntitlementSource} */ this.entitlementSource_ = data[2 + base] == null ? null : data[2 + base]; /** @private {?EntitlementResult} */ this.entitlementResult_ = data[3 + base] == null ? null : data[3 + base]; /** @private {?string} */ this.token_ = data[4 + base] == null ? null : data[4 + base]; /** @private {?boolean} */ this.isUserRegistered_ = data[5 + base] == null ? null : data[5 + base]; } /** * @return {?EntitlementJwt} */ getUsedEntitlement() { return this.usedEntitlement_; } /** * @param {!EntitlementJwt} value */ setUsedEntitlement(value) { this.usedEntitlement_ = value; } /** * @return {?Timestamp} */ getClientEventTime() { return this.clientEventTime_; } /** * @param {!Timestamp} value */ setClientEventTime(value) { this.clientEventTime_ = value; } /** * @return {?EntitlementSource} */ getEntitlementSource() { return this.entitlementSource_; } /** * @param {!EntitlementSource} value */ setEntitlementSource(value) { this.entitlementSource_ = value; } /** * @return {?EntitlementResult} */ getEntitlementResult() { return this.entitlementResult_; } /** * @param {!EntitlementResult} value */ setEntitlementResult(value) { this.entitlementResult_ = value; } /** * @return {?string} */ getToken() { return this.token_; } /** * @param {string} value */ setToken(value) { this.token_ = value; } /** * @return {?boolean} */ getIsUserRegistered() { return this.isUserRegistered_; } /** * @param {boolean} value */ setIsUserRegistered(value) { this.isUserRegistered_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.usedEntitlement_ ? this.usedEntitlement_.toArray(includeLabel) : [], // field 1 - used_entitlement this.clientEventTime_ ? this.clientEventTime_.toArray(includeLabel) : [], // field 2 - client_event_time this.entitlementSource_, // field 3 - entitlement_source this.entitlementResult_, // field 4 - entitlement_result this.token_, // field 5 - token this.isUserRegistered_, // field 6 - is_user_registered ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'EntitlementsRequest'; } } /** * @implements {Message} */ class EntitlementsResponse { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?string} */ this.jwt_ = data[base] == null ? null : data[base]; /** @private {?string} */ this.swgUserToken_ = data[1 + base] == null ? null : data[1 + base]; } /** * @return {?string} */ getJwt() { return this.jwt_; } /** * @param {string} value */ setJwt(value) { this.jwt_ = value; } /** * @return {?string} */ getSwgUserToken() { return this.swgUserToken_; } /** * @param {string} value */ setSwgUserToken(value) { this.swgUserToken_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.jwt_, // field 1 - jwt this.swgUserToken_, // field 2 - swg_user_token ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'EntitlementsResponse'; } } /** * @implements {Message} */ class EventParams { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?string} */ this.smartboxMessage_ = data[base] == null ? null : data[base]; /** @private {?string} */ this.gpayTransactionId_ = data[1 + base] == null ? null : data[1 + base]; /** @private {?boolean} */ this.hadLogged_ = data[2 + base] == null ? null : data[2 + base]; /** @private {?string} */ this.sku_ = data[3 + base] == null ? null : data[3 + base]; /** @private {?string} */ this.oldTransactionId_ = data[4 + base] == null ? null : data[4 + base]; /** @private {?boolean} */ this.isUserRegistered_ = data[5 + base] == null ? null : data[5 + base]; /** @private {?string} */ this.subscriptionFlow_ = data[6 + base] == null ? null : data[6 + base]; } /** * @return {?string} */ getSmartboxMessage() { return this.smartboxMessage_; } /** * @param {string} value */ setSmartboxMessage(value) { this.smartboxMessage_ = value; } /** * @return {?string} */ getGpayTransactionId() { return this.gpayTransactionId_; } /** * @param {string} value */ setGpayTransactionId(value) { this.gpayTransactionId_ = value; } /** * @return {?boolean} */ getHadLogged() { return this.hadLogged_; } /** * @param {boolean} value */ setHadLogged(value) { this.hadLogged_ = value; } /** * @return {?string} */ getSku() { return this.sku_; } /** * @param {string} value */ setSku(value) { this.sku_ = value; } /** * @return {?string} */ getOldTransactionId() { return this.oldTransactionId_; } /** * @param {string} value */ setOldTransactionId(value) { this.oldTransactionId_ = value; } /** * @return {?boolean} */ getIsUserRegistered() { return this.isUserRegistered_; } /** * @param {boolean} value */ setIsUserRegistered(value) { this.isUserRegistered_ = value; } /** * @return {?string} */ getSubscriptionFlow() { return this.subscriptionFlow_; } /** * @param {string} value */ setSubscriptionFlow(value) { this.subscriptionFlow_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.smartboxMessage_, // field 1 - smartbox_message this.gpayTransactionId_, // field 2 - gpay_transaction_id this.hadLogged_, // field 3 - had_logged this.sku_, // field 4 - sku this.oldTransactionId_, // field 5 - old_transaction_id this.isUserRegistered_, // field 6 - is_user_registered this.subscriptionFlow_, // field 7 - subscription_flow ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'EventParams'; } } /** * @implements {Message} */ class FinishedLoggingResponse { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?boolean} */ this.complete_ = data[base] == null ? null : data[base]; /** @private {?string} */ this.error_ = data[1 + base] == null ? null : data[1 + base]; } /** * @return {?boolean} */ getComplete() { return this.complete_; } /** * @param {boolean} value */ setComplete(value) { this.complete_ = value; } /** * @return {?string} */ getError() { return this.error_; } /** * @param {string} value */ setError(value) { this.error_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.complete_, // field 1 - complete this.error_, // field 2 - error ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'FinishedLoggingResponse'; } } /** * @implements {Message} */ class LinkSaveTokenRequest { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?string} */ this.authCode_ = data[base] == null ? null : data[base]; /** @private {?string} */ this.token_ = data[1 + base] == null ? null : data[1 + base]; } /** * @return {?string} */ getAuthCode() { return this.authCode_; } /** * @param {string} value */ setAuthCode(value) { this.authCode_ = value; } /** * @return {?string} */ getToken() { return this.token_; } /** * @param {string} value */ setToken(value) { this.token_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.authCode_, // field 1 - auth_code this.token_, // field 2 - token ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'LinkSaveTokenRequest'; } } /** * @implements {Message} */ class LinkingInfoResponse { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?boolean} */ this.requested_ = data[base] == null ? null : data[base]; } /** * @return {?boolean} */ getRequested() { return this.requested_; } /** * @param {boolean} value */ setRequested(value) { this.requested_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.requested_, // field 1 - requested ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'LinkingInfoResponse'; } } /** * @implements {Message} */ class OpenDialogRequest { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?string} */ this.urlPath_ = data[base] == null ? null : data[base]; } /** * @return {?string} */ getUrlPath() { return this.urlPath_; } /** * @param {string} value */ setUrlPath(value) { this.urlPath_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.urlPath_, // field 1 - url_path ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'OpenDialogRequest'; } } /** * @implements {Message} */ class SkuSelectedResponse { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?string} */ this.sku_ = data[base] == null ? null : data[base]; /** @private {?string} */ this.oldSku_ = data[1 + base] == null ? null : data[1 + base]; /** @private {?boolean} */ this.oneTime_ = data[2 + base] == null ? null : data[2 + base]; /** @private {?string} */ this.playOffer_ = data[3 + base] == null ? null : data[3 + base]; /** @private {?string} */ this.oldPlayOffer_ = data[4 + base] == null ? null : data[4 + base]; /** @private {?string} */ this.customMessage_ = data[5 + base] == null ? null : data[5 + base]; /** @private {?boolean} */ this.anonymous_ = data[6 + base] == null ? null : data[6 + base]; } /** * @return {?string} */ getSku() { return this.sku_; } /** * @param {string} value */ setSku(value) { this.sku_ = value; } /** * @return {?string} */ getOldSku() { return this.oldSku_; } /** * @param {string} value */ setOldSku(value) { this.oldSku_ = value; } /** * @return {?boolean} */ getOneTime() { return this.oneTime_; } /** * @param {boolean} value */ setOneTime(value) { this.oneTime_ = value; } /** * @return {?string} */ getPlayOffer() { return this.playOffer_; } /** * @param {string} value */ setPlayOffer(value) { this.playOffer_ = value; } /** * @return {?string} */ getOldPlayOffer() { return this.oldPlayOffer_; } /** * @param {string} value */ setOldPlayOffer(value) { this.oldPlayOffer_ = value; } /** * @return {?string} */ getCustomMessage() { return this.customMessage_; } /** * @param {string} value */ setCustomMessage(value) { this.customMessage_ = value; } /** * @return {?boolean} */ getAnonymous() { return this.anonymous_; } /** * @param {boolean} value */ setAnonymous(value) { this.anonymous_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.sku_, // field 1 - sku this.oldSku_, // field 2 - old_sku this.oneTime_, // field 3 - one_time this.playOffer_, // field 4 - play_offer this.oldPlayOffer_, // field 5 - old_play_offer this.customMessage_, // field 6 - custom_message this.anonymous_, // field 7 - anonymous ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'SkuSelectedResponse'; } } /** * @implements {Message} */ class SmartBoxMessage { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?boolean} */ this.isClicked_ = data[base] == null ? null : data[base]; } /** * @return {?boolean} */ getIsClicked() { return this.isClicked_; } /** * @param {boolean} value */ setIsClicked(value) { this.isClicked_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.isClicked_, // field 1 - is_clicked ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'SmartBoxMessage'; } } /** * @implements {Message} */ class SubscribeResponse { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?boolean} */ this.subscribe_ = data[base] == null ? null : data[base]; } /** * @return {?boolean} */ getSubscribe() { return this.subscribe_; } /** * @param {boolean} value */ setSubscribe(value) { this.subscribe_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.subscribe_, // field 1 - subscribe ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'SubscribeResponse'; } } /** * @implements {Message} */ class Timestamp { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?number} */ this.seconds_ = data[base] == null ? null : data[base]; /** @private {?number} */ this.nanos_ = data[1 + base] == null ? null : data[1 + base]; } /** * @return {?number} */ getSeconds() { return this.seconds_; } /** * @param {number} value */ setSeconds(value) { this.seconds_ = value; } /** * @return {?number} */ getNanos() { return this.nanos_; } /** * @param {number} value */ setNanos(value) { this.nanos_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.seconds_, // field 1 - seconds this.nanos_, // field 2 - nanos ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'Timestamp'; } } /** * @implements {Message} */ class ToastCloseRequest { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?boolean} */ this.close_ = data[base] == null ? null : data[base]; } /** * @return {?boolean} */ getClose() { return this.close_; } /** * @param {boolean} value */ setClose(value) { this.close_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.close_, // field 1 - close ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'ToastCloseRequest'; } } /** * @implements {Message} */ class ViewSubscriptionsResponse { /** * @param {!Array<*>=} data * @param {boolean=} includesLabel */ constructor(data = [], includesLabel = true) { const base = includesLabel ? 1 : 0; /** @private {?boolean} */ this.native_ = data[base] == null ? null : data[base]; } /** * @return {?boolean} */ getNative() { return this.native_; } /** * @param {boolean} value */ setNative(value) { this.native_ = value; } /** * @param {boolean=} includeLabel * @return {!Array<?>} * @override */ toArray(includeLabel = true) { const arr = [ this.native_, // field 1 - native ]; if (includeLabel) { arr.unshift(this.label()); } return arr; } /** * @return {string} * @override */ label() { return 'ViewSubscriptionsResponse'; } } const PROTO_MAP = { 'AccountCreationRequest': AccountCreationRequest, 'ActionRequest': ActionRequest, 'AlreadySubscribedResponse': AlreadySubscribedResponse, 'AnalyticsContext': AnalyticsContext, 'AnalyticsEventMeta': AnalyticsEventMeta, 'AnalyticsRequest': AnalyticsRequest, 'AudienceActivityClientLogsRequest': AudienceActivityClientLogsRequest, 'CompleteAudienceActionResponse': CompleteAudienceActionResponse, 'EntitlementJwt': EntitlementJwt, 'EntitlementsRequest': EntitlementsRequest, 'EntitlementsResponse': EntitlementsResponse, 'EventParams': EventParams, 'FinishedLoggingResponse': FinishedLoggingResponse, 'LinkSaveTokenRequest': LinkSaveTokenRequest, 'LinkingInfoResponse': LinkingInfoResponse, 'OpenDialogRequest': OpenDialogRequest, 'SkuSelectedResponse': SkuSelectedResponse, 'SmartBoxMessage': SmartBoxMessage, 'SubscribeResponse': SubscribeResponse, 'Timestamp': Timestamp, 'ToastCloseRequest': ToastCloseRequest, 'ViewSubscriptionsResponse': ViewSubscriptionsResponse, }; /** * Utility to deserialize a buffer * @param {!Array<*>} data * @return {!Message} */ function deserialize(data) { /** {?string} */ const key = data ? data[0] : null; if (key) { const ctor = PROTO_MAP[key]; if (ctor) { return new ctor(data); } } throw new Error('Deserialization failed for ' + data); } /** * @param {function(new: T)} messageType * @return {string} * @template T */ function getLabel(messageType) { const message = /** @type {!Message} */ (new messageType()); return message.label(); } export { AccountCreationRequest, ActionRequest, ActionType, AlreadySubscribedResponse, AnalyticsContext, AnalyticsEvent, AnalyticsEventMeta, AnalyticsRequest, AudienceActivityClientLogsRequest, CompleteAudienceActionResponse, EntitlementJwt, EntitlementResult, EntitlementSource, EntitlementsRequest, EntitlementsResponse, EventOriginator, EventParams, FinishedLoggingResponse, LinkSaveTokenRequest, LinkingInfoResponse, Message, OpenDialogRequest, ReaderSurfaceType, SkuSelectedResponse, SmartBoxMessage, SubscribeResponse, Timestamp, ToastCloseRequest, ViewSubscriptionsResponse, deserialize, getLabel, };
Update api_messages.js
src/proto/api_messages.js
Update api_messages.js
<ide><path>rc/proto/api_messages.js <ide> ACTION_SHOWCASE_REGWALL_SWIG_CLICK: 1060, <ide> ACTION_TWG_CHROME_APP_MENU_ENTRY_POINT_CLICK: 1061, <ide> ACTION_TWG_DISCOVER_FEED_MENU_ENTRY_POINT_CLICK: 1062, <add> ACTION_SHOWCASE_REGWALL_3P_BUTTON_CLICK: 1063, <ide> EVENT_PAYMENT_FAILED: 2000, <ide> EVENT_REGWALL_OPT_IN_FAILED: 2001, <ide> EVENT_NEWSLETTER_OPT_IN_FAILED: 2002, <add> EVENT_REGWALL_ALREADY_OPT_IN: 2003, <add> EVENT_NEWSLETTER_ALREADY_OPT_IN: 2004, <ide> EVENT_CUSTOM: 3000, <ide> EVENT_CONFIRM_TX_ID: 3001, <ide> EVENT_CHANGED_TX_ID: 3002, <ide> <ide> /** @private {?string} */ <ide> this.userEmail_ = data[2 + base] == null ? null : data[2 + base]; <add> <add> /** @private {?boolean} */ <add> this.alreadyCompleted_ = data[3 + base] == null ? null : data[3 + base]; <ide> } <ide> <ide> /** <ide> */ <ide> setUserEmail(value) { <ide> this.userEmail_ = value; <add> } <add> <add> /** <add> * @return {?boolean} <add> */ <add> getAlreadyCompleted() { <add> return this.alreadyCompleted_; <add> } <add> <add> /** <add> * @param {boolean} value <add> */ <add> setAlreadyCompleted(value) { <add> this.alreadyCompleted_ = value; <ide> } <ide> <ide> /** <ide> this.swgUserToken_, // field 1 - swg_user_token <ide> this.actionCompleted_, // field 2 - action_completed <ide> this.userEmail_, // field 3 - user_email <add> this.alreadyCompleted_, // field 4 - already_completed <ide> ]; <ide> if (includeLabel) { <ide> arr.unshift(this.label());
Java
agpl-3.0
fa7f0c11b2ea479b570abd2a54c5981b2edd5edd
0
Metatavu/kunta-api-server,Metatavu/kunta-api-server,Metatavu/kunta-api-server
package fi.otavanopisto.kuntaapi.server.integrations.ptv; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import fi.otavanopisto.kuntaapi.server.settings.SystemSettingController; import fi.otavanopisto.restfulptv.client.ElectronicChannelsApi; import fi.otavanopisto.restfulptv.client.OrganizationServicesApi; import fi.otavanopisto.restfulptv.client.OrganizationsApi; import fi.otavanopisto.restfulptv.client.PhoneChannelsApi; import fi.otavanopisto.restfulptv.client.PrintableFormChannelsApi; import fi.otavanopisto.restfulptv.client.ServiceLocationChannelsApi; import fi.otavanopisto.restfulptv.client.ServicesApi; import fi.otavanopisto.restfulptv.client.StatutoryDescriptionsApi; import fi.otavanopisto.restfulptv.client.WebPageChannelsApi; @ApplicationScoped public class PtvApi { @Inject private PtvClient client; @Inject private SystemSettingController systemSettingController; public OrganizationsApi getOrganizationApi() { return new OrganizationsApi(getBaseUrl(), client); } public StatutoryDescriptionsApi getStatutoryDescriptionsApi() { return new StatutoryDescriptionsApi(getBaseUrl(), client); } public ServicesApi getServicesApi() { return new ServicesApi(getBaseUrl(), client); } public WebPageChannelsApi getWebPageChannelsApi() { return new WebPageChannelsApi(getBaseUrl(), client); } public ServiceLocationChannelsApi getServiceLocationChannelsApi() { return new ServiceLocationChannelsApi(getBaseUrl(), client); } public PrintableFormChannelsApi getPrintableFormChannelsApi() { return new PrintableFormChannelsApi(getBaseUrl(), client); } public PhoneChannelsApi getPhoneChannelsApi() { return new PhoneChannelsApi(getBaseUrl(), client); } public OrganizationServicesApi getOrganizationServicesApi() { return new OrganizationServicesApi(getBaseUrl(), client); } public ElectronicChannelsApi getElectronicChannelsApi() { return new ElectronicChannelsApi(getBaseUrl(), client); } private String getBaseUrl() { return systemSettingController.getSettingValue(PtvConsts.SYSTEM_SETTING_BASEURL); } }
src/main/java/fi/otavanopisto/kuntaapi/server/integrations/ptv/PtvApi.java
package fi.otavanopisto.kuntaapi.server.integrations.ptv; import javax.enterprise.context.Dependent; import javax.inject.Inject; import fi.otavanopisto.kuntaapi.server.settings.SystemSettingController; import fi.otavanopisto.restfulptv.client.ElectronicChannelsApi; import fi.otavanopisto.restfulptv.client.OrganizationServicesApi; import fi.otavanopisto.restfulptv.client.OrganizationsApi; import fi.otavanopisto.restfulptv.client.PhoneChannelsApi; import fi.otavanopisto.restfulptv.client.PrintableFormChannelsApi; import fi.otavanopisto.restfulptv.client.ServiceLocationChannelsApi; import fi.otavanopisto.restfulptv.client.ServicesApi; import fi.otavanopisto.restfulptv.client.StatutoryDescriptionsApi; import fi.otavanopisto.restfulptv.client.WebPageChannelsApi; @Dependent public class PtvApi { @Inject private PtvClient client; @Inject private SystemSettingController systemSettingController; public OrganizationsApi getOrganizationApi() { return new OrganizationsApi(getBaseUrl(), client); } public StatutoryDescriptionsApi getStatutoryDescriptionsApi() { return new StatutoryDescriptionsApi(getBaseUrl(), client); } public ServicesApi getServicesApi() { return new ServicesApi(getBaseUrl(), client); } public WebPageChannelsApi getWebPageChannelsApi() { return new WebPageChannelsApi(getBaseUrl(), client); } public ServiceLocationChannelsApi getServiceLocationChannelsApi() { return new ServiceLocationChannelsApi(getBaseUrl(), client); } public PrintableFormChannelsApi getPrintableFormChannelsApi() { return new PrintableFormChannelsApi(getBaseUrl(), client); } public PhoneChannelsApi getPhoneChannelsApi() { return new PhoneChannelsApi(getBaseUrl(), client); } public OrganizationServicesApi getOrganizationServicesApi() { return new OrganizationServicesApi(getBaseUrl(), client); } public ElectronicChannelsApi getElectronicChannelsApi() { return new ElectronicChannelsApi(getBaseUrl(), client); } private String getBaseUrl() { return systemSettingController.getSettingValue(PtvConsts.SYSTEM_SETTING_BASEURL); } }
Changed ptv api to be application scoped
src/main/java/fi/otavanopisto/kuntaapi/server/integrations/ptv/PtvApi.java
Changed ptv api to be application scoped
<ide><path>rc/main/java/fi/otavanopisto/kuntaapi/server/integrations/ptv/PtvApi.java <ide> package fi.otavanopisto.kuntaapi.server.integrations.ptv; <ide> <del>import javax.enterprise.context.Dependent; <add>import javax.enterprise.context.ApplicationScoped; <ide> import javax.inject.Inject; <ide> <ide> import fi.otavanopisto.kuntaapi.server.settings.SystemSettingController; <ide> import fi.otavanopisto.restfulptv.client.StatutoryDescriptionsApi; <ide> import fi.otavanopisto.restfulptv.client.WebPageChannelsApi; <ide> <del>@Dependent <add>@ApplicationScoped <ide> public class PtvApi { <ide> <ide> @Inject
Java
apache-2.0
a6dcd89872295ed3cc1499ac4c14177abcfd821f
0
easel/recurly-java-library,easel/recurly-java-library
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2015 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.billing.recurly; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import com.ning.billing.recurly.model.Account; import com.ning.billing.recurly.model.AccountBalance; import com.ning.billing.recurly.model.Accounts; import com.ning.billing.recurly.model.AddOn; import com.ning.billing.recurly.model.AddOns; import com.ning.billing.recurly.model.Adjustment; import com.ning.billing.recurly.model.Adjustments; import com.ning.billing.recurly.model.BillingInfo; import com.ning.billing.recurly.model.Coupon; import com.ning.billing.recurly.model.Coupons; import com.ning.billing.recurly.model.GiftCard; import com.ning.billing.recurly.model.Invoice; import com.ning.billing.recurly.model.Invoices; import com.ning.billing.recurly.model.Plan; import com.ning.billing.recurly.model.Redemption; import com.ning.billing.recurly.model.Redemptions; import com.ning.billing.recurly.model.RefundOption; import com.ning.billing.recurly.model.ShippingAddress; import com.ning.billing.recurly.model.ShippingAddresses; import com.ning.billing.recurly.model.Subscription; import com.ning.billing.recurly.model.SubscriptionAddOns; import com.ning.billing.recurly.model.SubscriptionUpdate; import com.ning.billing.recurly.model.SubscriptionNotes; import com.ning.billing.recurly.model.Subscriptions; import com.ning.billing.recurly.model.Transaction; import com.ning.billing.recurly.model.Transactions; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.text.PDFTextStripper; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.LocalDateTime; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class TestRecurlyClient { public static final String RECURLY_PAGE_SIZE = "recurly.page.size"; public static final String KILLBILL_PAYMENT_RECURLY_API_KEY = "killbill.payment.recurly.apiKey"; public static final String KILLBILL_PAYMENT_RECURLY_SUBDOMAIN = "killbill.payment.recurly.subDomain"; public static final String KILLBILL_PAYMENT_RECURLY_DEFAULT_CURRENCY_KEY = "killbill.payment.recurly.currency"; // Default to USD for all tests, which is expected to be supported by Recurly by default // Multi Currency Support is an enterprise add-on private static final String CURRENCY = System.getProperty(KILLBILL_PAYMENT_RECURLY_DEFAULT_CURRENCY_KEY, "USD"); private RecurlyClient recurlyClient; @BeforeMethod(groups = {"integration", "enterprise"}) public void setUp() throws Exception { final String apiKey = System.getProperty(KILLBILL_PAYMENT_RECURLY_API_KEY); String subDomainTemp = System.getProperty(KILLBILL_PAYMENT_RECURLY_SUBDOMAIN); if (apiKey == null) { Assert.fail("You need to set your Recurly api key to run integration tests:" + " -Dkillbill.payment.recurly.apiKey=..."); } if (subDomainTemp == null) { subDomainTemp = "api"; } final String subDomain = subDomainTemp; recurlyClient = new RecurlyClient(apiKey, subDomain); recurlyClient.open(); } @AfterMethod(groups = {"integration", "enterprise"}) public void tearDown() throws Exception { recurlyClient.close(); } @Test(groups = "integration") public void testUnauthorizedException() throws Exception { final String subdomain = System.getProperty(KILLBILL_PAYMENT_RECURLY_SUBDOMAIN); RecurlyClient unauthorizedRecurlyClient = new RecurlyClient("invalid-api-key", subdomain); unauthorizedRecurlyClient.open(); try { unauthorizedRecurlyClient.getAccounts(); Assert.fail("getAccounts call should not succeed with invalid credentials."); } catch (RecurlyAPIException expected) { Assert.assertEquals(expected.getRecurlyError().getSymbol(), "unauthorized"); } } @Test(groups = "integration", description = "See https://github.com/killbilling/recurly-java-library/issues/21") public void testGetEmptySubscriptions() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); try { // Create a user final Account account = recurlyClient.createAccount(accountData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); Assert.assertNotNull(billingInfo); final BillingInfo retrievedBillingInfo = recurlyClient.getBillingInfo(account.getAccountCode()); Assert.assertNotNull(retrievedBillingInfo); final Subscriptions subs = recurlyClient.getAccountSubscriptions(accountData.getAccountCode(), "active"); Assert.assertEquals(subs.size(), 0); } finally { // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); } } @Test(groups = "integration", description = "See https://github.com/killbilling/recurly-java-library/issues/23") public void testRemoveSubscriptionAddons() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); final Plan planData = TestUtils.createRandomPlan(CURRENCY); try { // Create a user final Account account = recurlyClient.createAccount(accountData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); Assert.assertNotNull(billingInfo); // Create a plan with addons final Plan plan = recurlyClient.createPlan(planData); final List<AddOn> addons = new ArrayList<AddOn>(); final int nbAddOns = 5; for (int i = 0; i < nbAddOns; i++) { final AddOn addOn = TestUtils.createRandomAddOn(CURRENCY); final AddOn addOnRecurly = recurlyClient.createPlanAddOn(plan.getPlanCode(), addOn); addons.add(addOnRecurly); } // Create a subscription with addons final Subscription subscriptionDataWithAddons = TestUtils.createRandomSubscription(CURRENCY, plan, accountData, addons); final Subscription subscriptionWithAddons = recurlyClient.createSubscription(subscriptionDataWithAddons); Assert.assertEquals(subscriptionWithAddons.getAddOns().size(), nbAddOns); for (int i = 0; i < nbAddOns; i++) { Assert.assertEquals(subscriptionWithAddons.getAddOns().get(i).getAddOnCode(), addons.get(i).getAddOnCode()); } // Fetch the corresponding invoice final Invoice subInvoice = subscriptionWithAddons.getInvoice(); Assert.assertNotNull(subInvoice); // Refetch the invoice using the getInvoice method final int invoiceID = subInvoice.getInvoiceNumber(); final Invoice gotInvoice = recurlyClient.getInvoice(invoiceID); Assert.assertEquals(subInvoice.hashCode(), gotInvoice.hashCode()); // Remove all addons final SubscriptionUpdate subscriptionUpdate = new SubscriptionUpdate(); subscriptionUpdate.setAddOns(new SubscriptionAddOns()); final Subscription subscriptionWithAddons1 = recurlyClient.updateSubscription(subscriptionWithAddons.getUuid(), subscriptionUpdate); Assert.assertTrue(subscriptionWithAddons1.getAddOns().isEmpty()); // Add them again final SubscriptionUpdate subscriptionUpdate1 = new SubscriptionUpdate(); final SubscriptionAddOns newAddons = new SubscriptionAddOns(); newAddons.addAll(subscriptionDataWithAddons.getAddOns()); subscriptionUpdate1.setAddOns(newAddons); final Subscription subscriptionWithAddons2 = recurlyClient.updateSubscription(subscriptionWithAddons.getUuid(), subscriptionUpdate1); Assert.assertEquals(subscriptionWithAddons2.getAddOns().size(), nbAddOns); for (int i = 0; i < nbAddOns; i++) { Assert.assertEquals(subscriptionWithAddons2.getAddOns().get(i).getAddOnCode(), addons.get(i).getAddOnCode()); } } finally { // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); } } @Test(groups = "integration") public void testGetSiteSubscriptions() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); final Plan planData = TestUtils.createRandomPlan(); try { final Account account = recurlyClient.createAccount(accountData); billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); final Plan plan = recurlyClient.createPlan(planData); final Subscription subscriptionData = new Subscription(); subscriptionData.setPlanCode(plan.getPlanCode()); subscriptionData.setAccount(accountData); subscriptionData.setCurrency(CURRENCY); subscriptionData.setUnitAmountInCents(1242); // makes sure we have at least one subscription recurlyClient.createSubscription(subscriptionData); // make sure we return more than one subscription Assert.assertTrue(recurlyClient.getSubscriptions().size() > 0); } finally { // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); } } @Test(groups = "integration") public void testGetCoupons() throws Exception { final Coupons retrievedCoupons = recurlyClient.getCoupons(); Assert.assertTrue(retrievedCoupons.size() >= 0); } @Test(groups="integration") public void testGetAndDeleteAdjustment() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); final Plan planData = TestUtils.createRandomPlan(); try { // Create a user final Account account = recurlyClient.createAccount(accountData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); // Create a plan final Plan plan = recurlyClient.createPlan(planData); // Subscribe the user to the plan final Subscription subscriptionData = new Subscription(); subscriptionData.setPlanCode(plan.getPlanCode()); subscriptionData.setAccount(accountData); subscriptionData.setCurrency(CURRENCY); subscriptionData.setUnitAmountInCents(1242); //Add some adjustments to the account's open invoice final Adjustment adjustmentData = new Adjustment(); adjustmentData.setCurrency("USD"); adjustmentData.setUnitAmountInCents("100"); adjustmentData.setDescription("A description of an account adjustment"); Adjustment adjustment = recurlyClient.createAccountAdjustment(account.getAccountCode(), adjustmentData); final String uuid = adjustment.getUuid(); adjustment = recurlyClient.getAdjustment(uuid); Assert.assertEquals(adjustment.getUuid(), uuid); recurlyClient.deleteAdjustment(uuid); // Check that we deleted it try { recurlyClient.getAdjustment(uuid); Assert.fail("Failed to delete the Adjustment"); } catch (final RecurlyAPIException e) { Assert.assertEquals(e.getRecurlyError().getHttpStatusCode(), 404); } } finally { // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); } } @Test(groups = "integration") public void testGetAdjustments() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); final Plan planData = TestUtils.createRandomPlan(); try { // Create a user final Account account = recurlyClient.createAccount(accountData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); Assert.assertNotNull(billingInfo); final BillingInfo retrievedBillingInfo = recurlyClient.getBillingInfo(account.getAccountCode()); Assert.assertNotNull(retrievedBillingInfo); // Create a plan final Plan plan = recurlyClient.createPlan(planData); // Subscribe the user to the plan final Subscription subscriptionData = new Subscription(); subscriptionData.setPlanCode(plan.getPlanCode()); subscriptionData.setAccount(accountData); subscriptionData.setCurrency(CURRENCY); subscriptionData.setUnitAmountInCents(1242); //Add some adjustments to the account's open invoice final Adjustment adjustment = new Adjustment(); adjustment.setCurrency("USD"); adjustment.setUnitAmountInCents("100"); adjustment.setDescription("A description of an account adjustment"); //Use an "accounting code" for one of the adjustments String adjustmentAccountCode = "example account code"; final Adjustment adjustmentWithCode = new Adjustment(); adjustmentWithCode.setAccountingCode(adjustmentAccountCode); adjustmentWithCode.setCurrency("USD"); adjustmentWithCode.setUnitAmountInCents("200"); adjustmentWithCode.setDescription("A description of an account adjustment with a code"); //Create 2 new Adjustments recurlyClient.createAccountAdjustment(accountData.getAccountCode(), adjustment); recurlyClient.createAccountAdjustment(accountData.getAccountCode(), adjustmentWithCode); // Test adjustment retrieval methods Adjustments retrievedAdjustments = recurlyClient.getAccountAdjustments(accountData.getAccountCode(), null, null); Assert.assertEquals(retrievedAdjustments.size(), 2, "Did not retrieve correct count of Adjustments of any type and state"); retrievedAdjustments = recurlyClient.getAccountAdjustments(accountData.getAccountCode(), Adjustments.AdjustmentType.CHARGE, null); Assert.assertEquals(retrievedAdjustments.size(), 2, "Did not retrieve correct count of Adjustments of type Charge"); retrievedAdjustments = recurlyClient.getAccountAdjustments(accountData.getAccountCode(), Adjustments.AdjustmentType.CHARGE, Adjustments.AdjustmentState.INVOICED); Assert.assertEquals(retrievedAdjustments.size(), 0, "Retrieved Adjustments of type Charge marked as invoiced although none should be."); retrievedAdjustments = recurlyClient.getAccountAdjustments(accountData.getAccountCode(), null, Adjustments.AdjustmentState.INVOICED); Assert.assertEquals(retrievedAdjustments.size(), 0, "Retrieved Adjustments marked as invoiced although none should be."); retrievedAdjustments = recurlyClient.getAccountAdjustments(accountData.getAccountCode(), Adjustments.AdjustmentType.CHARGE, Adjustments.AdjustmentState.PENDING); Assert.assertEquals(2, retrievedAdjustments.size(), "Did not retrieve correct count of Adjustments of type Charge in Pending state"); int adjAccountCodeCounter = 0; for (Adjustment adj : retrievedAdjustments) { if (adjustmentAccountCode.equals(adj.getAccountingCode())) { adjAccountCodeCounter++; } } Assert.assertEquals(adjAccountCodeCounter, 1, "An unexpected number of Adjustments were assigned the accountCode [" + adjustmentAccountCode + "]"); } finally { // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); // Delete the Plan recurlyClient.deletePlan(planData.getPlanCode()); } } @Test(groups = "integration") public void testPagination() throws Exception { System.setProperty(RECURLY_PAGE_SIZE, "1"); final int minNumberOfAccounts = 5; for (int i = 0; i < minNumberOfAccounts; i++) { final Account accountData = TestUtils.createRandomAccount(); recurlyClient.createAccount(accountData); } final Set<String> accountCodes = new HashSet<String>(); Accounts accounts = recurlyClient.getAccounts(); for (int i = 0; i < minNumberOfAccounts; i++) { // If the environment is used, we will have more than the ones we created Assert.assertTrue(accounts.getNbRecords() >= minNumberOfAccounts); Assert.assertEquals(accounts.size(), 1); accountCodes.add(accounts.get(0).getAccountCode()); if (i < minNumberOfAccounts - 1) { accounts = accounts.getNext(); } } Assert.assertEquals(accountCodes.size(), minNumberOfAccounts); System.setProperty(RECURLY_PAGE_SIZE, "50"); } @Test(groups = "integration") public void testCreateAccountWithBadBillingInfo() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); // See http://docs.recurly.com/payment-gateways/test billingInfoData.setNumber("4000-0000-0000-0093"); try { final Account account = recurlyClient.createAccount(accountData); billingInfoData.setAccount(account); recurlyClient.createOrUpdateBillingInfo(billingInfoData); Assert.fail(); } catch (TransactionErrorException e) { Assert.assertEquals(e.getErrors().getTransactionError().getErrorCode(), "fraud_ip_address"); Assert.assertEquals(e.getErrors().getTransactionError().getMerchantMessage(), "The payment gateway declined the transaction because it originated from an IP address known for fraudulent transactions."); Assert.assertEquals(e.getErrors().getTransactionError().getCustomerMessage(), "The transaction was declined. Please contact support."); } } @Test(groups = "integration") public void testCreateAccount() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); try { final DateTime creationDateTime = new DateTime(DateTimeZone.UTC); final Account account = recurlyClient.createAccount(accountData); // Test account creation Assert.assertNotNull(account); Assert.assertEquals(accountData.getAccountCode(), account.getAccountCode()); Assert.assertEquals(accountData.getEmail(), account.getEmail()); Assert.assertEquals(accountData.getFirstName(), account.getFirstName()); Assert.assertEquals(accountData.getLastName(), account.getLastName()); Assert.assertEquals(accountData.getUsername(), account.getUsername()); Assert.assertEquals(accountData.getAcceptLanguage(), account.getAcceptLanguage()); Assert.assertEquals(accountData.getCompanyName(), account.getCompanyName()); Assert.assertEquals(accountData.getAddress().getAddress1(), account.getAddress().getAddress1()); Assert.assertEquals(accountData.getAddress().getAddress2(), account.getAddress().getAddress2()); Assert.assertEquals(accountData.getAddress().getCity(), account.getAddress().getCity()); Assert.assertEquals(accountData.getAddress().getState(), account.getAddress().getState()); Assert.assertEquals(accountData.getAddress().getZip(), account.getAddress().getZip()); Assert.assertEquals(accountData.getAddress().getCountry(), account.getAddress().getCountry()); Assert.assertEquals(accountData.getAddress().getPhone(), account.getAddress().getPhone()); // Test getting all final Accounts retrievedAccounts = recurlyClient.getAccounts(); Assert.assertTrue(retrievedAccounts.size() > 0); // Test an account lookup final Account retrievedAccount = recurlyClient.getAccount(account.getAccountCode()); Assert.assertEquals(retrievedAccount, account); // Create a BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); // Test BillingInfo creation Assert.assertNotNull(billingInfo); Assert.assertEquals(billingInfoData.getFirstName(), billingInfo.getFirstName()); Assert.assertEquals(billingInfoData.getLastName(), billingInfo.getLastName()); Assert.assertEquals(billingInfoData.getMonth(), billingInfo.getMonth()); Assert.assertEquals(billingInfoData.getYear(), billingInfo.getYear()); Assert.assertEquals(billingInfo.getCardType(), "Visa"); // Test BillingInfo lookup final BillingInfo retrievedBillingInfo = recurlyClient.getBillingInfo(account.getAccountCode()); Assert.assertEquals(retrievedBillingInfo, billingInfo); } catch(Exception e) { System.out.print(e.getMessage()); } finally { // Clean up recurlyClient.closeAccount(accountData.getAccountCode()); } } @Test(groups = "integration") public void testGetAccountBalance() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); try { final Account account = recurlyClient.createAccount(accountData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); Assert.assertNotNull(billingInfo); final BillingInfo retrievedBillingInfo = recurlyClient.getBillingInfo(account.getAccountCode()); Assert.assertNotNull(retrievedBillingInfo); final Adjustment adjustment = new Adjustment(); adjustment.setUnitAmountInCents(150); adjustment.setCurrency(CURRENCY); recurlyClient.createAccountAdjustment(account.getAccountCode(), adjustment); final AccountBalance balance = recurlyClient.getAccountBalance(account.getAccountCode()); Assert.assertEquals(balance.getBalanceInCents().getUnitAmountUSD(), new Integer(150)); Assert.assertEquals(balance.getPastDue(), Boolean.FALSE); } finally { // Clean up recurlyClient.clearBillingInfo(accountData.getAccountCode()); recurlyClient.closeAccount(accountData.getAccountCode()); } } @Test(groups = "integration") public void testCreatePlan() throws Exception { final Plan planData = TestUtils.createRandomPlan(); try { // Create a plan final DateTime creationDateTime = new DateTime(DateTimeZone.UTC); final Plan plan = recurlyClient.createPlan(planData); final Plan retPlan = recurlyClient.getPlan(plan.getPlanCode()); // test creation of plan Assert.assertNotNull(plan); Assert.assertEquals(retPlan, plan); // Check that getting all the plans makes sense Assert.assertTrue(recurlyClient.getPlans().size() > 0); } finally { // Delete the plan recurlyClient.deletePlan(planData.getPlanCode()); // Check that we deleted it try { final Plan retrievedPlan2 = recurlyClient.getPlan(planData.getPlanCode()); Assert.fail("Failed to delete the Plan"); } catch (final RecurlyAPIException e) { // good } } } @Test(groups = "integration") public void testUpdatePlan() throws Exception { final Plan planData = TestUtils.createRandomPlan(); try { // Create a plan final DateTime creationDateTime = new DateTime(DateTimeZone.UTC); final Plan plan = recurlyClient.createPlan(planData); final Plan planChanges = new Plan(); // Start with a fresh plan object for changes Assert.assertNotNull(plan); // Set the plancode to identify which plan to change planChanges.setPlanCode(planData.getPlanCode()); // Change some attributes planChanges.setName("A new name"); planChanges.setDescription("A new description"); // Send off the changes and get the updated object final Plan updatedPlan = recurlyClient.updatePlan(planChanges); Assert.assertNotNull(updatedPlan); Assert.assertEquals(updatedPlan.getName(), "A new name"); Assert.assertEquals(updatedPlan.getDescription(), "A new description"); } finally { // Delete the plan recurlyClient.deletePlan(planData.getPlanCode()); // Check that we deleted it try { final Plan retrievedPlan2 = recurlyClient.getPlan(planData.getPlanCode()); Assert.fail("Failed to delete the Plan"); } catch (final RecurlyAPIException e) { // good } } } @Test(groups = "integration") public void testCreateSubscriptions() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); final Plan planData = TestUtils.createRandomPlan(); final Coupon couponData = TestUtils.createRandomCoupon(); final Coupon couponDataForPlan = TestUtils.createRandomCoupon(); try { // Create a user final Account account = recurlyClient.createAccount(accountData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); Assert.assertNotNull(billingInfo); final BillingInfo retrievedBillingInfo = recurlyClient.getBillingInfo(account.getAccountCode()); Assert.assertNotNull(retrievedBillingInfo); // Create a plan final Plan plan = recurlyClient.createPlan(planData); // Create a coupon Coupon coupon = recurlyClient.createCoupon(couponData); // Create a coupon for the plan couponDataForPlan.setAppliesToAllPlans(false); couponDataForPlan.setPlanCodes(Arrays.asList(plan.getPlanCode())); Coupon couponForPlan = recurlyClient.createCoupon(couponDataForPlan); // Set up a subscription final Subscription subscriptionData = new Subscription(); subscriptionData.setPlanCode(plan.getPlanCode()); subscriptionData.setAccount(accountData); subscriptionData.setCurrency(CURRENCY); subscriptionData.setUnitAmountInCents(1242); // Apply a coupon at the time of subscription creation subscriptionData.setCouponCode(couponData.getCouponCode()); // Create some notes on the subscription subscriptionData.setCustomerNotes("Customer Notes"); subscriptionData.setTermsAndConditions("Terms and Conditions"); final DateTime creationDateTime = new DateTime(DateTimeZone.UTC); // Preview the user subscribing to the plan final Subscription subscriptionPreview = recurlyClient.previewSubscription(subscriptionData); // Test the subscription preview Assert.assertNotNull(subscriptionPreview); Assert.assertEquals(subscriptionPreview.getCurrency(), subscriptionData.getCurrency()); if (null == subscriptionData.getQuantity()) { Assert.assertEquals(subscriptionPreview.getQuantity(), new Integer(1)); } else { Assert.assertEquals(subscriptionPreview.getQuantity(), subscriptionData.getQuantity()); } // Subscribe the user to the plan final Subscription subscription = recurlyClient.createSubscription(subscriptionData); // Test subscription creation Assert.assertNotNull(subscription); // Test invoice fetching via href Assert.assertNotNull(subscription.getInvoice()); Assert.assertEquals(subscription.getCurrency(), subscriptionData.getCurrency()); if (null == subscriptionData.getQuantity()) { Assert.assertEquals(subscription.getQuantity(), new Integer(1)); } else { Assert.assertEquals(subscription.getQuantity(), subscriptionData.getQuantity()); } // Test lookup for subscription final Subscription sub1 = recurlyClient.getSubscription(subscription.getUuid()); Assert.assertNotNull(sub1); Assert.assertEquals(sub1, subscription); // Do a lookup for subs for given account final Subscriptions subs = recurlyClient.getAccountSubscriptions(accountData.getAccountCode()); // Check that the newly created sub is in the list Subscription found = null; for (final Subscription s : subs) { if (s.getUuid().equals(subscription.getUuid())) { found = s; break; } } if (found == null) { Assert.fail("Could not locate the subscription in the subscriptions associated with the account"); } // Verify the subscription information, including nested parameters // See https://github.com/killbilling/recurly-java-library/issues/4 Assert.assertEquals(found.getAccount().getAccountCode(), accountData.getAccountCode()); Assert.assertEquals(found.getAccount().getFirstName(), accountData.getFirstName()); // Verify the coupon redemption final Redemption redemption = recurlyClient.getCouponRedemptionByAccount(account.getAccountCode()); Assert.assertNotNull(redemption); Assert.assertEquals(redemption.getCoupon().getCouponCode(), couponData.getCouponCode()); // Update the subscription's notes final SubscriptionNotes subscriptionNotesData = new SubscriptionNotes(); subscriptionNotesData.setTermsAndConditions("New Terms and Conditions"); subscriptionNotesData.setCustomerNotes("New Customer Notes"); recurlyClient.updateSubscriptionNotes(subscription.getUuid(), subscriptionNotesData); final Subscription subscriptionWithNotes = recurlyClient.getSubscription(subscription.getUuid()); // Verify that the notes were updated Assert.assertNotNull(subscriptionWithNotes); Assert.assertEquals(subscriptionWithNotes.getTermsAndConditions(), subscriptionNotesData.getTermsAndConditions()); Assert.assertEquals(subscriptionWithNotes.getCustomerNotes(), subscriptionNotesData.getCustomerNotes()); // Cancel a Subscription recurlyClient.cancelSubscription(subscription); final Subscription cancelledSubscription = recurlyClient.getSubscription(subscription.getUuid()); Assert.assertEquals(cancelledSubscription.getState(), "canceled"); recurlyClient.reactivateSubscription(subscription); final Subscription reactivatedSubscription = recurlyClient.getSubscription(subscription.getUuid()); Assert.assertEquals(reactivatedSubscription.getState(), "active"); // Terminate a Subscription recurlyClient.terminateSubscription(subscription, RefundOption.full); final Subscription expiredSubscription = recurlyClient.getSubscription(subscription.getUuid()); Assert.assertEquals(expiredSubscription.getState(), "expired"); } finally { // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); // Delete the Plan recurlyClient.deletePlan(planData.getPlanCode()); } } @Test(groups = "integration") public void testCreateBulkSubscriptions() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); try { final Account account = recurlyClient.createAccount(accountData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); // Test bulk subscription creation for(int i = 0; i < 3; i++) { final Plan planData = TestUtils.createRandomPlan(); final Plan plan = recurlyClient.createPlan(planData); final Subscription subscriptionData = new Subscription(); subscriptionData.setPlanCode(plan.getPlanCode()); subscriptionData.setAccount(accountData); subscriptionData.setCurrency(CURRENCY); subscriptionData.setUnitAmountInCents(1242); subscriptionData.setBulk(true); //create the subscription final Subscription subscription = recurlyClient.createSubscription(subscriptionData); // Delete the Plan recurlyClient.deletePlan(planData.getPlanCode()); } // Check that the newly created subs are in the list final Subscriptions bulkSubs = recurlyClient.getAccountSubscriptions(accountData.getAccountCode()); int count = 0; for (final Subscription s : bulkSubs) { count++; } if (count != 3) { Assert.fail("Could not create subscriptions in bulk"); } } finally { // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); } } @Test(groups = "integration") public void testCreateAndCloseInvoices() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); try { // Create a user final Account account = recurlyClient.createAccount(accountData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); Assert.assertNotNull(billingInfo); final BillingInfo retrievedBillingInfo = recurlyClient.getBillingInfo(account.getAccountCode()); Assert.assertNotNull(retrievedBillingInfo); // Create an Adjustment final Adjustment a = new Adjustment(); a.setUnitAmountInCents(150); a.setCurrency(CURRENCY); final Adjustment createdA = recurlyClient.createAccountAdjustment(accountData.getAccountCode(), a); // Post an invoice/invoice the adjustment final Invoice invoiceData = new Invoice(); invoiceData.setLineItems(null); final Invoice invoice = recurlyClient.postAccountInvoice(accountData.getAccountCode(), invoiceData); Assert.assertNotNull(invoice); // Check to see if the adjustment was invoiced properly Adjustments retrievedAdjustments = recurlyClient.getAccountAdjustments(accountData.getAccountCode(), null, Adjustments.AdjustmentState.PENDING); Assert.assertEquals(retrievedAdjustments.size(), 0, "Retrieved Adjustments marked as pending although none should be."); retrievedAdjustments = recurlyClient.getAccountAdjustments(accountData.getAccountCode(), null, Adjustments.AdjustmentState.INVOICED); Assert.assertEquals(retrievedAdjustments.size(), 1, "Not all Adjustments marked as invoiced although all should be."); // Create an Adjustment final Adjustment b = new Adjustment(); b.setUnitAmountInCents(250); b.setCurrency(CURRENCY); final Adjustment createdB = recurlyClient.createAccountAdjustment(accountData.getAccountCode(), b); // Post an invoice/invoice the adjustment final Invoice failInvoiceData = new Invoice(); failInvoiceData.setLineItems(null); final Invoice invoiceFail = recurlyClient.postAccountInvoice(accountData.getAccountCode(), failInvoiceData); Assert.assertNotNull(invoiceFail); // Check to see if the adjustment was invoiced properly retrievedAdjustments = recurlyClient.getAccountAdjustments(accountData.getAccountCode(), null, Adjustments.AdjustmentState.PENDING); Assert.assertEquals(retrievedAdjustments.size(), 0, "Retrieved Adjustments marked as pending although none should be."); retrievedAdjustments = recurlyClient.getAccountAdjustments(accountData.getAccountCode(), null, Adjustments.AdjustmentState.INVOICED); Assert.assertEquals(retrievedAdjustments.size(), 2, "Not all Adjustments marked as invoiced although all should be."); } finally { // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); } } @Test(groups = "integration") public void testCreateInvoiceAndRetrieveInvoicePdf() throws Exception { final Account accountData = TestUtils.createRandomAccount(); PDDocument pdDocument = null; try { // Create a user final Account account = recurlyClient.createAccount(accountData); // Create an Adjustment final Adjustment a = new Adjustment(); a.setUnitAmountInCents(150); a.setCurrency(CURRENCY); final Adjustment createdA = recurlyClient.createAccountAdjustment(accountData.getAccountCode(), a); // Post an invoice/invoice the adjustment final Invoice invoiceData = new Invoice(); invoiceData.setCollectionMethod("manual"); invoiceData.setLineItems(null); final Invoice invoice = recurlyClient.postAccountInvoice(accountData.getAccountCode(), invoiceData); Assert.assertNotNull(invoice); InputStream pdfInputStream = recurlyClient.getInvoicePdf(invoice.getInvoiceNumber()); Assert.assertNotNull(pdfInputStream); pdDocument = PDDocument.load(pdfInputStream); String pdfString = new PDFTextStripper().getText(pdDocument); Assert.assertNotNull(pdfString); Assert.assertTrue(pdfString.contains("Invoice # " + invoice.getInvoiceNumber())); Assert.assertTrue(pdfString.contains("Subtotal $" + 1.5)); // Attempt to close the invoice final Invoice closedInvoice = recurlyClient.markInvoiceSuccessful(invoice.getInvoiceNumber()); Assert.assertEquals(closedInvoice.getState(), "collected", "Invoice not closed successfully"); } finally { if (pdDocument != null) { pdDocument.close(); } // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); } } @Test(groups = "enterprise") public void testCreateAndCloseManualInvoices() throws Exception { final Account accountData = TestUtils.createRandomAccount(); try { // Create a user final Account account = recurlyClient.createAccount(accountData); // Create an Adjustment final Adjustment a = new Adjustment(); a.setUnitAmountInCents(150); a.setCurrency(CURRENCY); final Adjustment createdA = recurlyClient.createAccountAdjustment(accountData.getAccountCode(), a); // Post an invoice/invoice the adjustment final Invoice invoiceData = new Invoice(); invoiceData.setCollectionMethod("manual"); invoiceData.setLineItems(null); final Invoice invoice = recurlyClient.postAccountInvoice(accountData.getAccountCode(), invoiceData); Assert.assertNotNull(invoice); // Attempt to close the invoice final Invoice closedInvoice = recurlyClient.markInvoiceSuccessful(invoice.getInvoiceNumber()); Assert.assertEquals(closedInvoice.getState(), "collected", "Invoice not closed successfully"); // Create an Adjustment final Adjustment b = new Adjustment(); b.setUnitAmountInCents(250); b.setCurrency(CURRENCY); final Adjustment createdB = recurlyClient.createAccountAdjustment(accountData.getAccountCode(), b); // Post an invoice/invoice the adjustment final Invoice failInvoiceData = new Invoice(); failInvoiceData.setCollectionMethod("manual"); failInvoiceData.setLineItems(null); final Invoice invoiceFail = recurlyClient.postAccountInvoice(accountData.getAccountCode(), failInvoiceData); Assert.assertNotNull(invoiceFail); // Attempt to fail the invoice final Invoice failedInvoice = recurlyClient.markInvoiceFailed(invoiceFail.getInvoiceNumber()); Assert.assertEquals(failedInvoice.getState(), "failed", "Invoice not failed successfully"); // Create an Adjustment final Adjustment c = new Adjustment(); c.setUnitAmountInCents(450); c.setCurrency(CURRENCY); final Adjustment createdC = recurlyClient.createAccountAdjustment(accountData.getAccountCode(), c); // Post an invoice/invoice the adjustment final Invoice externalInvoiceData = new Invoice(); externalInvoiceData.setCollectionMethod("manual"); externalInvoiceData.setLineItems(null); final Invoice invoiceExternal = recurlyClient.postAccountInvoice(accountData.getAccountCode(), externalInvoiceData); Assert.assertNotNull(invoiceExternal); //create an external payment to pay off the invoice final Transaction externalPaymentData = new Transaction(); externalPaymentData.setPaymentMethod("other"); final DateTime collectionDateTime = new DateTime(DateTimeZone.UTC); externalPaymentData.setCollectedAt(collectionDateTime); externalPaymentData.setAmountInCents(450); final Transaction externalPayment = recurlyClient.enterOfflinePayment(invoiceExternal.getInvoiceNumber(), externalPaymentData); Assert.assertNotNull(externalPayment); Assert.assertEquals(externalPayment.getInvoice().getState(), "collected", "Invoice not closed successfully"); } finally { // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); } } @Test(groups = "integration") public void testCreateAndQueryTransactions() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); final Plan planData = TestUtils.createRandomPlan(); try { // Create a user final Account account = recurlyClient.createAccount(accountData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); Assert.assertNotNull(billingInfo); final BillingInfo retrievedBillingInfo = recurlyClient.getBillingInfo(account.getAccountCode()); Assert.assertNotNull(retrievedBillingInfo); // Create a plan final Plan plan = recurlyClient.createPlan(planData); // Subscribe the user to the plan final Subscription subscriptionData = new Subscription(); subscriptionData.setPlanCode(plan.getPlanCode()); subscriptionData.setAccount(accountData); subscriptionData.setUnitAmountInCents(150); subscriptionData.setCurrency(CURRENCY); recurlyClient.createSubscription(subscriptionData); // Create a transaction final Transaction t = new Transaction(); accountData.setBillingInfo(billingInfoData); t.setAccount(accountData); t.setAmountInCents(15); t.setCurrency(CURRENCY); final Transaction createdT = recurlyClient.createTransaction(t); // Test that the transaction created correctly Assert.assertNotNull(createdT); // Can't test for account equality yet as the account is only a ref and doesn't get mapped. Assert.assertEquals(createdT.getAmountInCents(), t.getAmountInCents()); Assert.assertEquals(createdT.getCurrency(), t.getCurrency()); // Test lookup on the transaction via the users account final Transactions trans = recurlyClient.getAccountTransactions(account.getAccountCode()); // 3 transactions: voided verification, $1.5 for the plan and the $0.15 transaction above Assert.assertEquals(trans.size(), 3); Transaction found = null; for (final Transaction _t : trans) { if (_t.getUuid().equals(createdT.getUuid())) { found = _t; break; } } if (found == null) { Assert.fail("Failed to locate the newly created transaction"); } // Verify the transaction information, including nested parameters // See https://github.com/killbilling/recurly-java-library/issues/4 Assert.assertEquals(found.getAccount().getAccountCode(), accountData.getAccountCode()); Assert.assertEquals(found.getAccount().getFirstName(), accountData.getFirstName()); Assert.assertEquals(found.getInvoice().getAccount().getAccountCode(), accountData.getAccountCode()); Assert.assertEquals(found.getInvoice().getAccount().getFirstName(), accountData.getFirstName()); Assert.assertEquals(found.getInvoice().getTotalInCents(), (Integer) 15); Assert.assertEquals(found.getInvoice().getCurrency(), CURRENCY); // Verify we can retrieve it Assert.assertEquals(recurlyClient.getTransaction(found.getUuid()).getUuid(), found.getUuid()); // Test Invoices retrieval final Invoices invoices = recurlyClient.getAccountInvoices(account.getAccountCode()); // 2 Invoices are present (the first one is for the transaction, the second for the subscription) Assert.assertEquals(invoices.size(), 2, "Number of Invoices incorrect"); Assert.assertEquals(invoices.get(0).getTotalInCents(), t.getAmountInCents(), "Amount in cents is not the same"); Assert.assertEquals(invoices.get(1).getTotalInCents(), subscriptionData.getUnitAmountInCents(), "Amount in cents is not the same"); } finally { // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); // Delete the Plan recurlyClient.deletePlan(planData.getPlanCode()); } } @Test(groups = "integration") public void testAddons() throws Exception { // Create a Plan final Plan planData = TestUtils.createRandomPlan(); final AddOn addOn = TestUtils.createRandomAddOn(); try { // Create an AddOn final Plan plan = recurlyClient.createPlan(planData); AddOn addOnRecurly = recurlyClient.createPlanAddOn(plan.getPlanCode(), addOn); // Test the creation Assert.assertNotNull(addOnRecurly); Assert.assertEquals(addOnRecurly.getAddOnCode(), addOn.getAddOnCode()); Assert.assertEquals(addOnRecurly.getName(), addOn.getName()); Assert.assertEquals(addOnRecurly.getUnitAmountInCents(), addOn.getUnitAmountInCents()); Assert.assertEquals(addOnRecurly.getDefaultQuantity(), addOn.getDefaultQuantity()); // Query for an AddOn addOnRecurly = recurlyClient.getAddOn(plan.getPlanCode(), addOn.getAddOnCode()); // Check the 2 are the same Assert.assertEquals(addOnRecurly.getAddOnCode(), addOn.getAddOnCode()); Assert.assertEquals(addOnRecurly.getName(), addOn.getName()); Assert.assertEquals(addOnRecurly.getDefaultQuantity(), addOn.getDefaultQuantity()); Assert.assertEquals(addOnRecurly.getDisplayQuantityOnHostedPage(), addOn.getDisplayQuantityOnHostedPage()); Assert.assertEquals(addOnRecurly.getUnitAmountInCents(), addOn.getUnitAmountInCents()); // Query for AddOns and Check again AddOns addOns = recurlyClient.getAddOns(plan.getPlanCode()); Assert.assertEquals(addOns.size(), 1); Assert.assertEquals(addOns.get(0).getAddOnCode(), addOn.getAddOnCode()); Assert.assertEquals(addOns.get(0).getName(), addOn.getName()); Assert.assertEquals(addOns.get(0).getDefaultQuantity(), addOn.getDefaultQuantity()); Assert.assertEquals(addOns.get(0).getDisplayQuantityOnHostedPage(), addOn.getDisplayQuantityOnHostedPage()); Assert.assertEquals(addOns.get(0).getUnitAmountInCents(), addOn.getUnitAmountInCents()); } finally { // Delete an AddOn recurlyClient.deleteAddOn(planData.getPlanCode(), addOn.getAddOnCode()); // Delete the plan recurlyClient.deletePlan(planData.getPlanCode()); } } @Test(groups = "integration") public void testCreateCoupon() throws Exception { final Coupon couponData = TestUtils.createRandomCoupon(); try { // Create the coupon Coupon coupon = recurlyClient.createCoupon(couponData); Assert.assertNotNull(coupon); Assert.assertEquals(coupon.getName(), couponData.getName()); Assert.assertEquals(coupon.getCouponCode(), couponData.getCouponCode()); Assert.assertEquals(coupon.getDiscountType(), couponData.getDiscountType()); Assert.assertEquals(coupon.getDiscountPercent(), couponData.getDiscountPercent()); // Get the coupon coupon = recurlyClient.getCoupon(couponData.getCouponCode()); Assert.assertNotNull(coupon); Assert.assertEquals(coupon.getName(), couponData.getName()); Assert.assertEquals(coupon.getCouponCode(), couponData.getCouponCode()); Assert.assertEquals(coupon.getDiscountType(), couponData.getDiscountType()); Assert.assertEquals(coupon.getDiscountPercent(), couponData.getDiscountPercent()); } finally { recurlyClient.deleteCoupon(couponData.getCouponCode()); } } @Test(groups = "integration") public void testUpdateSubscriptions() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); final Plan planData = TestUtils.createRandomPlan(); final Plan plan2Data = TestUtils.createRandomPlan(CURRENCY); try { // Create a user final Account account = recurlyClient.createAccount(accountData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); Assert.assertNotNull(billingInfo); final BillingInfo retrievedBillingInfo = recurlyClient.getBillingInfo(account.getAccountCode()); Assert.assertNotNull(retrievedBillingInfo); // Create a plan final Plan plan = recurlyClient.createPlan(planData); final Plan plan2 = recurlyClient.createPlan(plan2Data); // Subscribe the user to the plan final Subscription subscriptionData = new Subscription(); subscriptionData.setPlanCode(plan.getPlanCode()); subscriptionData.setAccount(accountData); subscriptionData.setCurrency(CURRENCY); subscriptionData.setUnitAmountInCents(1242); final DateTime creationDateTime = new DateTime(DateTimeZone.UTC); final Subscription subscription = recurlyClient.createSubscription(subscriptionData); Assert.assertNotNull(subscription); // Set subscription update info final SubscriptionUpdate subscriptionUpdateData = new SubscriptionUpdate(); subscriptionUpdateData.setTimeframe(SubscriptionUpdate.Timeframe.now); subscriptionUpdateData.setPlanCode(plan2.getPlanCode()); // Preview the subscription update final Subscription subscriptionUpdatedPreview = recurlyClient.updateSubscriptionPreview(subscription.getUuid(), subscriptionUpdateData); Assert.assertNotNull(subscriptionUpdatedPreview); // Test inline invoice fetch Assert.assertNotNull(subscriptionUpdatedPreview.getInvoice()); Assert.assertEquals(subscription.getUuid(), subscriptionUpdatedPreview.getUuid()); Assert.assertNotEquals(subscription.getPlan(), subscriptionUpdatedPreview.getPlan()); Assert.assertEquals(plan2.getPlanCode(), subscriptionUpdatedPreview.getPlan().getPlanCode()); // Update the subscription final Subscription subscriptionUpdated = recurlyClient.updateSubscription(subscription.getUuid(), subscriptionUpdateData); Assert.assertNotNull(subscriptionUpdated); Assert.assertEquals(subscription.getUuid(), subscriptionUpdated.getUuid()); Assert.assertNotEquals(subscription.getPlan(), subscriptionUpdated.getPlan()); Assert.assertEquals(plan2.getPlanCode(), subscriptionUpdated.getPlan().getPlanCode()); } finally { // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); // Delete the Plans recurlyClient.deletePlan(planData.getPlanCode()); recurlyClient.deletePlan(plan2Data.getPlanCode()); } } @Test(groups = "integration") public void testRedeemCoupon() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); final Plan planData = TestUtils.createRandomPlan(CURRENCY); final Coupon couponData = TestUtils.createRandomCoupon(); final Coupon secondCouponData = TestUtils.createRandomCoupon(); try { final Account account = recurlyClient.createAccount(accountData); final Plan plan = recurlyClient.createPlan(planData); final Coupon coupon = recurlyClient.createCoupon(couponData); final Coupon secondCoupon = recurlyClient.createCoupon(secondCouponData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); Assert.assertNotNull(billingInfo); // Subscribe the user to the plan final Subscription subscriptionData = new Subscription(); subscriptionData.setPlanCode(plan.getPlanCode()); subscriptionData.setAccount(accountData); subscriptionData.setCurrency(CURRENCY); subscriptionData.setUnitAmountInCents(1242); final Subscription subscription = recurlyClient.createSubscription(subscriptionData); Assert.assertNotNull(subscription); // No coupon at this point try { recurlyClient.getCouponRedemptionByAccount(account.getAccountCode()); Assert.fail("Coupon should not be found."); } catch (RecurlyAPIException expected) { Assert.assertTrue(true); } // Redeem a coupon final Redemption redemptionData = new Redemption(); redemptionData.setAccountCode(account.getAccountCode()); redemptionData.setCurrency(CURRENCY); Redemption redemption = recurlyClient.redeemCoupon(coupon.getCouponCode(), redemptionData); Assert.assertNotNull(redemption); Assert.assertEquals(redemption.getCoupon().getCouponCode(), coupon.getCouponCode()); Assert.assertEquals(redemption.getAccount().getAccountCode(), account.getAccountCode()); Assert.assertFalse(redemption.getSingleUse()); Assert.assertEquals(redemption.getTotalDiscountedInCents(), (Integer) 0); Assert.assertEquals(redemption.getState(), "active"); Assert.assertEquals(redemption.getCurrency(), CURRENCY); // Get the coupon redemption redemption = recurlyClient.getCouponRedemptionByAccount(account.getAccountCode()); Assert.assertNotNull(redemption); Assert.assertEquals(redemption.getCoupon().getCouponCode(), coupon.getCouponCode()); Assert.assertEquals(redemption.getAccount().getAccountCode(), account.getAccountCode()); // Redeem another coupon final Redemption secondRedemptionData = new Redemption(); secondRedemptionData.setAccountCode(account.getAccountCode()); secondRedemptionData.setCurrency(CURRENCY); Redemption secondRedemption = recurlyClient.redeemCoupon(secondCoupon.getCouponCode(), secondRedemptionData); Assert.assertNotNull(secondRedemption); Assert.assertEquals(secondRedemption.getCoupon().getCouponCode(), secondCoupon.getCouponCode()); Assert.assertEquals(secondRedemption.getAccount().getAccountCode(), account.getAccountCode()); Assert.assertFalse(secondRedemption.getSingleUse()); Assert.assertEquals(secondRedemption.getTotalDiscountedInCents(), (Integer) 0); Assert.assertEquals(secondRedemption.getState(), "active"); Assert.assertEquals(secondRedemption.getCurrency(), CURRENCY); Redemptions redemptions = recurlyClient.getCouponRedemptionsByAccount(account.getAccountCode()); Assert.assertEquals(redemptions.size(), 2); // Remove both coupon redemptions recurlyClient.deleteCouponRedemption(account.getAccountCode(), redemption.getUuid()); recurlyClient.deleteCouponRedemption(account.getAccountCode(), secondRedemption.getUuid()); try { recurlyClient.getCouponRedemptionByAccount(account.getAccountCode()); Assert.fail("Coupon should be removed."); } catch (RecurlyAPIException expected) { Assert.assertTrue(true); } // Redeem a coupon once again final Redemption redemptionData2 = new Redemption(); redemptionData2.setAccountCode(account.getAccountCode()); redemptionData2.setCurrency(CURRENCY); redemption = recurlyClient.redeemCoupon(coupon.getCouponCode(), redemptionData2); Assert.assertNotNull(redemption); redemption = recurlyClient.getCouponRedemptionByAccount(account.getAccountCode()); Assert.assertEquals(redemption.getCoupon().getCouponCode(), coupon.getCouponCode()); Assert.assertEquals(redemption.getAccount().getAccountCode(), account.getAccountCode()); Assert.assertFalse(redemption.getSingleUse()); Assert.assertEquals(redemption.getTotalDiscountedInCents(), (Integer) 0); Assert.assertEquals(redemption.getState(), "active"); Assert.assertEquals(redemption.getCurrency(), CURRENCY); } finally { recurlyClient.closeAccount(accountData.getAccountCode()); recurlyClient.deletePlan(planData.getPlanCode()); recurlyClient.deleteCoupon(couponData.getCouponCode()); } } @Test(groups = "integration") public void testCreateTrialExtensionCoupon() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); final Plan planData = TestUtils.createRandomPlan(CURRENCY); final Coupon couponData = TestUtils.createRandomCoupon(); couponData.setName("apitrialext"); couponData.setFreeTrialAmount(3); couponData.setFreeTrialUnit("month"); couponData.setDiscountType("free_trial"); final LocalDateTime now = LocalDateTime.now(); try { final Account account = recurlyClient.createAccount(accountData); final Plan plan = recurlyClient.createPlan(planData); final Coupon coupon = recurlyClient.createCoupon(couponData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); Assert.assertNotNull(billingInfo); // Subscribe the user to the plan final Subscription subscriptionData = new Subscription(); // set our coupon code subscriptionData.setCouponCode(coupon.getCouponCode()); subscriptionData.setPlanCode(plan.getPlanCode()); subscriptionData.setAccount(accountData); subscriptionData.setCurrency(CURRENCY); subscriptionData.setUnitAmountInCents(1242); final Subscription subscription = recurlyClient.createSubscription(subscriptionData); Assert.assertNotNull(subscription); final int expectedMonth = (now.getMonthOfYear() + 3) % 12; Assert.assertEquals(subscription.getTrialEndsAt().getMonthOfYear(), expectedMonth); } finally { recurlyClient.closeAccount(accountData.getAccountCode()); recurlyClient.deletePlan(planData.getPlanCode()); recurlyClient.deleteCoupon(couponData.getCouponCode()); } } @Test(groups = "integration") public void testRedeemGiftCardOnSubscription() throws Exception { final GiftCard giftCardData = TestUtils.createRandomGiftCard(); final Plan planData = TestUtils.createRandomPlan(CURRENCY); try { // Purchase a gift card final GiftCard giftCard = recurlyClient.purchaseGiftCard(giftCardData); Assert.assertEquals(giftCard.getProductCode(), giftCardData.getProductCode()); Assert.assertNull(giftCard.getRedeemedAt()); // Let's redeem on a subscription final Plan plan = recurlyClient.createPlan(planData); final Account account = giftCard.getGifterAccount(); final GiftCard redemptionData = new GiftCard(); final Subscription subscriptionData = new Subscription(); // set our gift card redemption data redemptionData.setRedemptionCode(giftCard.getRedemptionCode()); subscriptionData.setGiftCard(redemptionData); subscriptionData.setPlanCode(plan.getPlanCode()); subscriptionData.setAccount(account); subscriptionData.setCurrency(CURRENCY); subscriptionData.setUnitAmountInCents(1242); final Subscription subscription = recurlyClient.createSubscription(subscriptionData); Assert.assertNotNull(subscription); final GiftCard redeemedCard = recurlyClient.getGiftCard(giftCard.getId()); Assert.assertNotNull(redeemedCard.getRedeemedAt()); } finally { recurlyClient.deletePlan(planData.getPlanCode()); } } @Test(groups = "integration") public void testRedeemGiftCardOnAccount() throws Exception { final GiftCard giftCardData = TestUtils.createRandomGiftCard(); // Purchase a gift card final GiftCard giftCard = recurlyClient.purchaseGiftCard(giftCardData); Assert.assertEquals(giftCard.getProductCode(), giftCardData.getProductCode()); Assert.assertNull(giftCard.getRedeemedAt()); // Let's redeem on an account final Account gifterAccount = giftCard.getGifterAccount(); Assert.assertNotNull(gifterAccount); final String redemptionCode = giftCard.getRedemptionCode(); final String gifterAccountCode = gifterAccount.getAccountCode(); final GiftCard redeemedCard = recurlyClient.redeemGiftCard(redemptionCode, gifterAccountCode); Assert.assertNotNull(redeemedCard.getRedeemedAt()); } @Test(groups = "integration") public void testPreviewGiftCardPurchase() throws Exception { final GiftCard giftCardData = TestUtils.createRandomGiftCard(); // Preview a gift card purchase final GiftCard giftCard = recurlyClient.previewGiftCard(giftCardData); // Should be the purchased gift card Assert.assertEquals(giftCard.getProductCode(), giftCardData.getProductCode()); // But should not be created Assert.assertNull(giftCard.getId()); Assert.assertNull(giftCard.getCreatedAt()); } @Test(groups = "integration") public void testShippingAddressesOnAccount() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final ShippingAddress shippingAddress1 = TestUtils.createRandomShippingAddress(); final ShippingAddress shippingAddress2 = TestUtils.createRandomShippingAddress(); final ShippingAddresses shippingAddressesData = new ShippingAddresses(); try { shippingAddressesData.add(shippingAddress1); shippingAddressesData.add(shippingAddress2); accountData.setShippingAddresses(shippingAddressesData); final Account account = recurlyClient.createAccount(accountData); ShippingAddresses shippingAddresses = recurlyClient.getAccountShippingAddresses(account.getAccountCode()); Assert.assertEquals(shippingAddresses.size(), 2); } finally { recurlyClient.closeAccount(accountData.getAccountCode()); } } @Test(groups = "integration") public void testShippingAddressesOnSubscription() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final Plan planData = TestUtils.createRandomPlan(CURRENCY); final ShippingAddress shippingAddressData = TestUtils.createRandomShippingAddress(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); billingInfoData.setAccount(null); // null out random account fixture accountData.setBillingInfo(billingInfoData); // add the billing info to account data try { final Account account = recurlyClient.createAccount(accountData); final Plan plan = recurlyClient.createPlan(planData); // Subscribe the user to the plan final Subscription subscriptionData = new Subscription(); // set our shipping address subscriptionData.setShippingAddress(shippingAddressData); // set our sub data subscriptionData.setPlanCode(plan.getPlanCode()); subscriptionData.setCurrency(CURRENCY); subscriptionData.setUnitAmountInCents(1242); // attach the account final Account existingAccount = new Account(); existingAccount.setAccountCode(account.getAccountCode()); subscriptionData.setAccount(existingAccount); final Subscription subscription = recurlyClient.createSubscription(subscriptionData); Assert.assertNotNull(subscription.getHref()); } finally { recurlyClient.closeAccount(accountData.getAccountCode()); recurlyClient.deletePlan(planData.getPlanCode()); } } }
src/test/java/com/ning/billing/recurly/TestRecurlyClient.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2015 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.billing.recurly; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import com.ning.billing.recurly.model.Account; import com.ning.billing.recurly.model.AccountBalance; import com.ning.billing.recurly.model.Accounts; import com.ning.billing.recurly.model.AddOn; import com.ning.billing.recurly.model.AddOns; import com.ning.billing.recurly.model.Adjustment; import com.ning.billing.recurly.model.Adjustments; import com.ning.billing.recurly.model.BillingInfo; import com.ning.billing.recurly.model.Coupon; import com.ning.billing.recurly.model.Coupons; import com.ning.billing.recurly.model.GiftCard; import com.ning.billing.recurly.model.Invoice; import com.ning.billing.recurly.model.Invoices; import com.ning.billing.recurly.model.Plan; import com.ning.billing.recurly.model.Redemption; import com.ning.billing.recurly.model.Redemptions; import com.ning.billing.recurly.model.RefundOption; import com.ning.billing.recurly.model.ShippingAddress; import com.ning.billing.recurly.model.ShippingAddresses; import com.ning.billing.recurly.model.Subscription; import com.ning.billing.recurly.model.SubscriptionAddOns; import com.ning.billing.recurly.model.SubscriptionUpdate; import com.ning.billing.recurly.model.SubscriptionNotes; import com.ning.billing.recurly.model.Subscriptions; import com.ning.billing.recurly.model.Transaction; import com.ning.billing.recurly.model.Transactions; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.text.PDFTextStripper; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.LocalDateTime; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class TestRecurlyClient { public static final String RECURLY_PAGE_SIZE = "recurly.page.size"; public static final String KILLBILL_PAYMENT_RECURLY_API_KEY = "killbill.payment.recurly.apiKey"; public static final String KILLBILL_PAYMENT_RECURLY_SUBDOMAIN = "killbill.payment.recurly.subDomain"; public static final String KILLBILL_PAYMENT_RECURLY_DEFAULT_CURRENCY_KEY = "killbill.payment.recurly.currency"; // Default to USD for all tests, which is expected to be supported by Recurly by default // Multi Currency Support is an enterprise add-on private static final String CURRENCY = System.getProperty(KILLBILL_PAYMENT_RECURLY_DEFAULT_CURRENCY_KEY, "USD"); private RecurlyClient recurlyClient; @BeforeMethod(groups = {"integration", "enterprise"}) public void setUp() throws Exception { final String apiKey = System.getProperty(KILLBILL_PAYMENT_RECURLY_API_KEY); String subDomainTemp = System.getProperty(KILLBILL_PAYMENT_RECURLY_SUBDOMAIN); if (apiKey == null) { Assert.fail("You need to set your Recurly api key to run integration tests:" + " -Dkillbill.payment.recurly.apiKey=..."); } if (subDomainTemp == null) { subDomainTemp = "api"; } final String subDomain = subDomainTemp; recurlyClient = new RecurlyClient(apiKey, subDomain); recurlyClient.open(); } @AfterMethod(groups = {"integration", "enterprise"}) public void tearDown() throws Exception { recurlyClient.close(); } @Test(groups = "integration") public void testUnauthorizedException() throws Exception { final String subdomain = System.getProperty(KILLBILL_PAYMENT_RECURLY_SUBDOMAIN); RecurlyClient unauthorizedRecurlyClient = new RecurlyClient("invalid-api-key", subdomain); unauthorizedRecurlyClient.open(); try { unauthorizedRecurlyClient.getAccounts(); Assert.fail("getAccounts call should not succeed with invalid credentials."); } catch (RecurlyAPIException expected) { Assert.assertEquals(expected.getRecurlyError().getSymbol(), "unauthorized"); } } @Test(groups = "integration", description = "See https://github.com/killbilling/recurly-java-library/issues/21") public void testGetEmptySubscriptions() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); try { // Create a user final Account account = recurlyClient.createAccount(accountData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); Assert.assertNotNull(billingInfo); final BillingInfo retrievedBillingInfo = recurlyClient.getBillingInfo(account.getAccountCode()); Assert.assertNotNull(retrievedBillingInfo); final Subscriptions subs = recurlyClient.getAccountSubscriptions(accountData.getAccountCode(), "active"); Assert.assertEquals(subs.size(), 0); } finally { // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); } } @Test(groups = "integration", description = "See https://github.com/killbilling/recurly-java-library/issues/23") public void testRemoveSubscriptionAddons() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); final Plan planData = TestUtils.createRandomPlan(CURRENCY); try { // Create a user final Account account = recurlyClient.createAccount(accountData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); Assert.assertNotNull(billingInfo); // Create a plan with addons final Plan plan = recurlyClient.createPlan(planData); final List<AddOn> addons = new ArrayList<AddOn>(); final int nbAddOns = 5; for (int i = 0; i < nbAddOns; i++) { final AddOn addOn = TestUtils.createRandomAddOn(CURRENCY); final AddOn addOnRecurly = recurlyClient.createPlanAddOn(plan.getPlanCode(), addOn); addons.add(addOnRecurly); } // Create a subscription with addons final Subscription subscriptionDataWithAddons = TestUtils.createRandomSubscription(CURRENCY, plan, accountData, addons); final Subscription subscriptionWithAddons = recurlyClient.createSubscription(subscriptionDataWithAddons); Assert.assertEquals(subscriptionWithAddons.getAddOns().size(), nbAddOns); for (int i = 0; i < nbAddOns; i++) { Assert.assertEquals(subscriptionWithAddons.getAddOns().get(i).getAddOnCode(), addons.get(i).getAddOnCode()); } // Fetch the corresponding invoice final Invoice subInvoice = subscriptionWithAddons.getInvoice(); Assert.assertNotNull(subInvoice); // Refetch the invoice using the getInvoice method final int invoiceID = subInvoice.getInvoiceNumber(); final Invoice gotInvoice = recurlyClient.getInvoice(invoiceID); Assert.assertEquals(subInvoice.hashCode(), gotInvoice.hashCode()); // Remove all addons final SubscriptionUpdate subscriptionUpdate = new SubscriptionUpdate(); subscriptionUpdate.setAddOns(new SubscriptionAddOns()); final Subscription subscriptionWithAddons1 = recurlyClient.updateSubscription(subscriptionWithAddons.getUuid(), subscriptionUpdate); Assert.assertTrue(subscriptionWithAddons1.getAddOns().isEmpty()); // Add them again final SubscriptionUpdate subscriptionUpdate1 = new SubscriptionUpdate(); final SubscriptionAddOns newAddons = new SubscriptionAddOns(); newAddons.addAll(subscriptionDataWithAddons.getAddOns()); subscriptionUpdate1.setAddOns(newAddons); final Subscription subscriptionWithAddons2 = recurlyClient.updateSubscription(subscriptionWithAddons.getUuid(), subscriptionUpdate1); Assert.assertEquals(subscriptionWithAddons2.getAddOns().size(), nbAddOns); for (int i = 0; i < nbAddOns; i++) { Assert.assertEquals(subscriptionWithAddons2.getAddOns().get(i).getAddOnCode(), addons.get(i).getAddOnCode()); } } finally { // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); } } @Test(groups = "integration") public void testGetSiteSubscriptions() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); final Plan planData = TestUtils.createRandomPlan(); try { final Account account = recurlyClient.createAccount(accountData); billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); final Plan plan = recurlyClient.createPlan(planData); final Subscription subscriptionData = new Subscription(); subscriptionData.setPlanCode(plan.getPlanCode()); subscriptionData.setAccount(accountData); subscriptionData.setCurrency(CURRENCY); subscriptionData.setUnitAmountInCents(1242); // makes sure we have at least on subscription recurlyClient.createSubscription(subscriptionData); // make sure we return more than one subscription Assert.assertTrue(recurlyClient.getSubscriptions().size() > 0); } finally { // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); } } @Test(groups = "integration") public void testGetCoupons() throws Exception { final Coupons retrievedCoupons = recurlyClient.getCoupons(); Assert.assertTrue(retrievedCoupons.size() >= 0); } @Test(groups="integration") public void testGetAndDeleteAdjustment() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); final Plan planData = TestUtils.createRandomPlan(); try { // Create a user final Account account = recurlyClient.createAccount(accountData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); // Create a plan final Plan plan = recurlyClient.createPlan(planData); // Subscribe the user to the plan final Subscription subscriptionData = new Subscription(); subscriptionData.setPlanCode(plan.getPlanCode()); subscriptionData.setAccount(accountData); subscriptionData.setCurrency(CURRENCY); subscriptionData.setUnitAmountInCents(1242); //Add some adjustments to the account's open invoice final Adjustment adjustmentData = new Adjustment(); adjustmentData.setCurrency("USD"); adjustmentData.setUnitAmountInCents("100"); adjustmentData.setDescription("A description of an account adjustment"); Adjustment adjustment = recurlyClient.createAccountAdjustment(account.getAccountCode(), adjustmentData); final String uuid = adjustment.getUuid(); adjustment = recurlyClient.getAdjustment(uuid); Assert.assertEquals(adjustment.getUuid(), uuid); recurlyClient.deleteAdjustment(uuid); // Check that we deleted it try { recurlyClient.getAdjustment(uuid); Assert.fail("Failed to delete the Adjustment"); } catch (final RecurlyAPIException e) { Assert.assertEquals(e.getRecurlyError().getHttpStatusCode(), 404); } } finally { // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); } } @Test(groups = "integration") public void testGetAdjustments() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); final Plan planData = TestUtils.createRandomPlan(); try { // Create a user final Account account = recurlyClient.createAccount(accountData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); Assert.assertNotNull(billingInfo); final BillingInfo retrievedBillingInfo = recurlyClient.getBillingInfo(account.getAccountCode()); Assert.assertNotNull(retrievedBillingInfo); // Create a plan final Plan plan = recurlyClient.createPlan(planData); // Subscribe the user to the plan final Subscription subscriptionData = new Subscription(); subscriptionData.setPlanCode(plan.getPlanCode()); subscriptionData.setAccount(accountData); subscriptionData.setCurrency(CURRENCY); subscriptionData.setUnitAmountInCents(1242); //Add some adjustments to the account's open invoice final Adjustment adjustment = new Adjustment(); adjustment.setCurrency("USD"); adjustment.setUnitAmountInCents("100"); adjustment.setDescription("A description of an account adjustment"); //Use an "accounting code" for one of the adjustments String adjustmentAccountCode = "example account code"; final Adjustment adjustmentWithCode = new Adjustment(); adjustmentWithCode.setAccountingCode(adjustmentAccountCode); adjustmentWithCode.setCurrency("USD"); adjustmentWithCode.setUnitAmountInCents("200"); adjustmentWithCode.setDescription("A description of an account adjustment with a code"); //Create 2 new Adjustments recurlyClient.createAccountAdjustment(accountData.getAccountCode(), adjustment); recurlyClient.createAccountAdjustment(accountData.getAccountCode(), adjustmentWithCode); // Test adjustment retrieval methods Adjustments retrievedAdjustments = recurlyClient.getAccountAdjustments(accountData.getAccountCode(), null, null); Assert.assertEquals(retrievedAdjustments.size(), 2, "Did not retrieve correct count of Adjustments of any type and state"); retrievedAdjustments = recurlyClient.getAccountAdjustments(accountData.getAccountCode(), Adjustments.AdjustmentType.CHARGE, null); Assert.assertEquals(retrievedAdjustments.size(), 2, "Did not retrieve correct count of Adjustments of type Charge"); retrievedAdjustments = recurlyClient.getAccountAdjustments(accountData.getAccountCode(), Adjustments.AdjustmentType.CHARGE, Adjustments.AdjustmentState.INVOICED); Assert.assertEquals(retrievedAdjustments.size(), 0, "Retrieved Adjustments of type Charge marked as invoiced although none should be."); retrievedAdjustments = recurlyClient.getAccountAdjustments(accountData.getAccountCode(), null, Adjustments.AdjustmentState.INVOICED); Assert.assertEquals(retrievedAdjustments.size(), 0, "Retrieved Adjustments marked as invoiced although none should be."); retrievedAdjustments = recurlyClient.getAccountAdjustments(accountData.getAccountCode(), Adjustments.AdjustmentType.CHARGE, Adjustments.AdjustmentState.PENDING); Assert.assertEquals(2, retrievedAdjustments.size(), "Did not retrieve correct count of Adjustments of type Charge in Pending state"); int adjAccountCodeCounter = 0; for (Adjustment adj : retrievedAdjustments) { if (adjustmentAccountCode.equals(adj.getAccountingCode())) { adjAccountCodeCounter++; } } Assert.assertEquals(adjAccountCodeCounter, 1, "An unexpected number of Adjustments were assigned the accountCode [" + adjustmentAccountCode + "]"); } finally { // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); // Delete the Plan recurlyClient.deletePlan(planData.getPlanCode()); } } @Test(groups = "integration") public void testPagination() throws Exception { System.setProperty(RECURLY_PAGE_SIZE, "1"); final int minNumberOfAccounts = 5; for (int i = 0; i < minNumberOfAccounts; i++) { final Account accountData = TestUtils.createRandomAccount(); recurlyClient.createAccount(accountData); } final Set<String> accountCodes = new HashSet<String>(); Accounts accounts = recurlyClient.getAccounts(); for (int i = 0; i < minNumberOfAccounts; i++) { // If the environment is used, we will have more than the ones we created Assert.assertTrue(accounts.getNbRecords() >= minNumberOfAccounts); Assert.assertEquals(accounts.size(), 1); accountCodes.add(accounts.get(0).getAccountCode()); if (i < minNumberOfAccounts - 1) { accounts = accounts.getNext(); } } Assert.assertEquals(accountCodes.size(), minNumberOfAccounts); System.setProperty(RECURLY_PAGE_SIZE, "50"); } @Test(groups = "integration") public void testCreateAccountWithBadBillingInfo() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); // See http://docs.recurly.com/payment-gateways/test billingInfoData.setNumber("4000-0000-0000-0093"); try { final Account account = recurlyClient.createAccount(accountData); billingInfoData.setAccount(account); recurlyClient.createOrUpdateBillingInfo(billingInfoData); Assert.fail(); } catch (TransactionErrorException e) { Assert.assertEquals(e.getErrors().getTransactionError().getErrorCode(), "fraud_ip_address"); Assert.assertEquals(e.getErrors().getTransactionError().getMerchantMessage(), "The payment gateway declined the transaction because it originated from an IP address known for fraudulent transactions."); Assert.assertEquals(e.getErrors().getTransactionError().getCustomerMessage(), "The transaction was declined. Please contact support."); } } @Test(groups = "integration") public void testCreateAccount() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); try { final DateTime creationDateTime = new DateTime(DateTimeZone.UTC); final Account account = recurlyClient.createAccount(accountData); // Test account creation Assert.assertNotNull(account); Assert.assertEquals(accountData.getAccountCode(), account.getAccountCode()); Assert.assertEquals(accountData.getEmail(), account.getEmail()); Assert.assertEquals(accountData.getFirstName(), account.getFirstName()); Assert.assertEquals(accountData.getLastName(), account.getLastName()); Assert.assertEquals(accountData.getUsername(), account.getUsername()); Assert.assertEquals(accountData.getAcceptLanguage(), account.getAcceptLanguage()); Assert.assertEquals(accountData.getCompanyName(), account.getCompanyName()); Assert.assertEquals(accountData.getAddress().getAddress1(), account.getAddress().getAddress1()); Assert.assertEquals(accountData.getAddress().getAddress2(), account.getAddress().getAddress2()); Assert.assertEquals(accountData.getAddress().getCity(), account.getAddress().getCity()); Assert.assertEquals(accountData.getAddress().getState(), account.getAddress().getState()); Assert.assertEquals(accountData.getAddress().getZip(), account.getAddress().getZip()); Assert.assertEquals(accountData.getAddress().getCountry(), account.getAddress().getCountry()); Assert.assertEquals(accountData.getAddress().getPhone(), account.getAddress().getPhone()); // Test getting all final Accounts retrievedAccounts = recurlyClient.getAccounts(); Assert.assertTrue(retrievedAccounts.size() > 0); // Test an account lookup final Account retrievedAccount = recurlyClient.getAccount(account.getAccountCode()); Assert.assertEquals(retrievedAccount, account); // Create a BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); // Test BillingInfo creation Assert.assertNotNull(billingInfo); Assert.assertEquals(billingInfoData.getFirstName(), billingInfo.getFirstName()); Assert.assertEquals(billingInfoData.getLastName(), billingInfo.getLastName()); Assert.assertEquals(billingInfoData.getMonth(), billingInfo.getMonth()); Assert.assertEquals(billingInfoData.getYear(), billingInfo.getYear()); Assert.assertEquals(billingInfo.getCardType(), "Visa"); // Test BillingInfo lookup final BillingInfo retrievedBillingInfo = recurlyClient.getBillingInfo(account.getAccountCode()); Assert.assertEquals(retrievedBillingInfo, billingInfo); } catch(Exception e) { System.out.print(e.getMessage()); } finally { // Clean up recurlyClient.closeAccount(accountData.getAccountCode()); } } @Test(groups = "integration") public void testGetAccountBalance() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); try { final Account account = recurlyClient.createAccount(accountData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); Assert.assertNotNull(billingInfo); final BillingInfo retrievedBillingInfo = recurlyClient.getBillingInfo(account.getAccountCode()); Assert.assertNotNull(retrievedBillingInfo); final Adjustment adjustment = new Adjustment(); adjustment.setUnitAmountInCents(150); adjustment.setCurrency(CURRENCY); recurlyClient.createAccountAdjustment(account.getAccountCode(), adjustment); final AccountBalance balance = recurlyClient.getAccountBalance(account.getAccountCode()); Assert.assertEquals(balance.getBalanceInCents().getUnitAmountUSD(), new Integer(150)); Assert.assertEquals(balance.getPastDue(), Boolean.FALSE); } finally { // Clean up recurlyClient.clearBillingInfo(accountData.getAccountCode()); recurlyClient.closeAccount(accountData.getAccountCode()); } } @Test(groups = "integration") public void testCreatePlan() throws Exception { final Plan planData = TestUtils.createRandomPlan(); try { // Create a plan final DateTime creationDateTime = new DateTime(DateTimeZone.UTC); final Plan plan = recurlyClient.createPlan(planData); final Plan retPlan = recurlyClient.getPlan(plan.getPlanCode()); // test creation of plan Assert.assertNotNull(plan); Assert.assertEquals(retPlan, plan); // Check that getting all the plans makes sense Assert.assertTrue(recurlyClient.getPlans().size() > 0); } finally { // Delete the plan recurlyClient.deletePlan(planData.getPlanCode()); // Check that we deleted it try { final Plan retrievedPlan2 = recurlyClient.getPlan(planData.getPlanCode()); Assert.fail("Failed to delete the Plan"); } catch (final RecurlyAPIException e) { // good } } } @Test(groups = "integration") public void testUpdatePlan() throws Exception { final Plan planData = TestUtils.createRandomPlan(); try { // Create a plan final DateTime creationDateTime = new DateTime(DateTimeZone.UTC); final Plan plan = recurlyClient.createPlan(planData); final Plan planChanges = new Plan(); // Start with a fresh plan object for changes Assert.assertNotNull(plan); // Set the plancode to identify which plan to change planChanges.setPlanCode(planData.getPlanCode()); // Change some attributes planChanges.setName("A new name"); planChanges.setDescription("A new description"); // Send off the changes and get the updated object final Plan updatedPlan = recurlyClient.updatePlan(planChanges); Assert.assertNotNull(updatedPlan); Assert.assertEquals(updatedPlan.getName(), "A new name"); Assert.assertEquals(updatedPlan.getDescription(), "A new description"); } finally { // Delete the plan recurlyClient.deletePlan(planData.getPlanCode()); // Check that we deleted it try { final Plan retrievedPlan2 = recurlyClient.getPlan(planData.getPlanCode()); Assert.fail("Failed to delete the Plan"); } catch (final RecurlyAPIException e) { // good } } } @Test(groups = "integration") public void testCreateSubscriptions() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); final Plan planData = TestUtils.createRandomPlan(); final Coupon couponData = TestUtils.createRandomCoupon(); final Coupon couponDataForPlan = TestUtils.createRandomCoupon(); try { // Create a user final Account account = recurlyClient.createAccount(accountData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); Assert.assertNotNull(billingInfo); final BillingInfo retrievedBillingInfo = recurlyClient.getBillingInfo(account.getAccountCode()); Assert.assertNotNull(retrievedBillingInfo); // Create a plan final Plan plan = recurlyClient.createPlan(planData); // Create a coupon Coupon coupon = recurlyClient.createCoupon(couponData); // Create a coupon for the plan couponDataForPlan.setAppliesToAllPlans(false); couponDataForPlan.setPlanCodes(Arrays.asList(plan.getPlanCode())); Coupon couponForPlan = recurlyClient.createCoupon(couponDataForPlan); // Set up a subscription final Subscription subscriptionData = new Subscription(); subscriptionData.setPlanCode(plan.getPlanCode()); subscriptionData.setAccount(accountData); subscriptionData.setCurrency(CURRENCY); subscriptionData.setUnitAmountInCents(1242); // Apply a coupon at the time of subscription creation subscriptionData.setCouponCode(couponData.getCouponCode()); // Create some notes on the subscription subscriptionData.setCustomerNotes("Customer Notes"); subscriptionData.setTermsAndConditions("Terms and Conditions"); final DateTime creationDateTime = new DateTime(DateTimeZone.UTC); // Preview the user subscribing to the plan final Subscription subscriptionPreview = recurlyClient.previewSubscription(subscriptionData); // Test the subscription preview Assert.assertNotNull(subscriptionPreview); Assert.assertEquals(subscriptionPreview.getCurrency(), subscriptionData.getCurrency()); if (null == subscriptionData.getQuantity()) { Assert.assertEquals(subscriptionPreview.getQuantity(), new Integer(1)); } else { Assert.assertEquals(subscriptionPreview.getQuantity(), subscriptionData.getQuantity()); } // Subscribe the user to the plan final Subscription subscription = recurlyClient.createSubscription(subscriptionData); // Test subscription creation Assert.assertNotNull(subscription); // Test invoice fetching via href Assert.assertNotNull(subscription.getInvoice()); Assert.assertEquals(subscription.getCurrency(), subscriptionData.getCurrency()); if (null == subscriptionData.getQuantity()) { Assert.assertEquals(subscription.getQuantity(), new Integer(1)); } else { Assert.assertEquals(subscription.getQuantity(), subscriptionData.getQuantity()); } // Test lookup for subscription final Subscription sub1 = recurlyClient.getSubscription(subscription.getUuid()); Assert.assertNotNull(sub1); Assert.assertEquals(sub1, subscription); // Do a lookup for subs for given account final Subscriptions subs = recurlyClient.getAccountSubscriptions(accountData.getAccountCode()); // Check that the newly created sub is in the list Subscription found = null; for (final Subscription s : subs) { if (s.getUuid().equals(subscription.getUuid())) { found = s; break; } } if (found == null) { Assert.fail("Could not locate the subscription in the subscriptions associated with the account"); } // Verify the subscription information, including nested parameters // See https://github.com/killbilling/recurly-java-library/issues/4 Assert.assertEquals(found.getAccount().getAccountCode(), accountData.getAccountCode()); Assert.assertEquals(found.getAccount().getFirstName(), accountData.getFirstName()); // Verify the coupon redemption final Redemption redemption = recurlyClient.getCouponRedemptionByAccount(account.getAccountCode()); Assert.assertNotNull(redemption); Assert.assertEquals(redemption.getCoupon().getCouponCode(), couponData.getCouponCode()); // Update the subscription's notes final SubscriptionNotes subscriptionNotesData = new SubscriptionNotes(); subscriptionNotesData.setTermsAndConditions("New Terms and Conditions"); subscriptionNotesData.setCustomerNotes("New Customer Notes"); recurlyClient.updateSubscriptionNotes(subscription.getUuid(), subscriptionNotesData); final Subscription subscriptionWithNotes = recurlyClient.getSubscription(subscription.getUuid()); // Verify that the notes were updated Assert.assertNotNull(subscriptionWithNotes); Assert.assertEquals(subscriptionWithNotes.getTermsAndConditions(), subscriptionNotesData.getTermsAndConditions()); Assert.assertEquals(subscriptionWithNotes.getCustomerNotes(), subscriptionNotesData.getCustomerNotes()); // Cancel a Subscription recurlyClient.cancelSubscription(subscription); final Subscription cancelledSubscription = recurlyClient.getSubscription(subscription.getUuid()); Assert.assertEquals(cancelledSubscription.getState(), "canceled"); recurlyClient.reactivateSubscription(subscription); final Subscription reactivatedSubscription = recurlyClient.getSubscription(subscription.getUuid()); Assert.assertEquals(reactivatedSubscription.getState(), "active"); // Terminate a Subscription recurlyClient.terminateSubscription(subscription, RefundOption.full); final Subscription expiredSubscription = recurlyClient.getSubscription(subscription.getUuid()); Assert.assertEquals(expiredSubscription.getState(), "expired"); } finally { // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); // Delete the Plan recurlyClient.deletePlan(planData.getPlanCode()); } } @Test(groups = "integration") public void testCreateBulkSubscriptions() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); try { final Account account = recurlyClient.createAccount(accountData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); // Test bulk subscription creation for(int i = 0; i < 3; i++) { final Plan planData = TestUtils.createRandomPlan(); final Plan plan = recurlyClient.createPlan(planData); final Subscription subscriptionData = new Subscription(); subscriptionData.setPlanCode(plan.getPlanCode()); subscriptionData.setAccount(accountData); subscriptionData.setCurrency(CURRENCY); subscriptionData.setUnitAmountInCents(1242); subscriptionData.setBulk(true); //create the subscription final Subscription subscription = recurlyClient.createSubscription(subscriptionData); // Delete the Plan recurlyClient.deletePlan(planData.getPlanCode()); } // Check that the newly created subs are in the list final Subscriptions bulkSubs = recurlyClient.getAccountSubscriptions(accountData.getAccountCode()); int count = 0; for (final Subscription s : bulkSubs) { count++; } if (count != 3) { Assert.fail("Could not create subscriptions in bulk"); } } finally { // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); } } @Test(groups = "integration") public void testCreateAndCloseInvoices() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); try { // Create a user final Account account = recurlyClient.createAccount(accountData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); Assert.assertNotNull(billingInfo); final BillingInfo retrievedBillingInfo = recurlyClient.getBillingInfo(account.getAccountCode()); Assert.assertNotNull(retrievedBillingInfo); // Create an Adjustment final Adjustment a = new Adjustment(); a.setUnitAmountInCents(150); a.setCurrency(CURRENCY); final Adjustment createdA = recurlyClient.createAccountAdjustment(accountData.getAccountCode(), a); // Post an invoice/invoice the adjustment final Invoice invoiceData = new Invoice(); invoiceData.setLineItems(null); final Invoice invoice = recurlyClient.postAccountInvoice(accountData.getAccountCode(), invoiceData); Assert.assertNotNull(invoice); // Check to see if the adjustment was invoiced properly Adjustments retrievedAdjustments = recurlyClient.getAccountAdjustments(accountData.getAccountCode(), null, Adjustments.AdjustmentState.PENDING); Assert.assertEquals(retrievedAdjustments.size(), 0, "Retrieved Adjustments marked as pending although none should be."); retrievedAdjustments = recurlyClient.getAccountAdjustments(accountData.getAccountCode(), null, Adjustments.AdjustmentState.INVOICED); Assert.assertEquals(retrievedAdjustments.size(), 1, "Not all Adjustments marked as invoiced although all should be."); // Create an Adjustment final Adjustment b = new Adjustment(); b.setUnitAmountInCents(250); b.setCurrency(CURRENCY); final Adjustment createdB = recurlyClient.createAccountAdjustment(accountData.getAccountCode(), b); // Post an invoice/invoice the adjustment final Invoice failInvoiceData = new Invoice(); failInvoiceData.setLineItems(null); final Invoice invoiceFail = recurlyClient.postAccountInvoice(accountData.getAccountCode(), failInvoiceData); Assert.assertNotNull(invoiceFail); // Check to see if the adjustment was invoiced properly retrievedAdjustments = recurlyClient.getAccountAdjustments(accountData.getAccountCode(), null, Adjustments.AdjustmentState.PENDING); Assert.assertEquals(retrievedAdjustments.size(), 0, "Retrieved Adjustments marked as pending although none should be."); retrievedAdjustments = recurlyClient.getAccountAdjustments(accountData.getAccountCode(), null, Adjustments.AdjustmentState.INVOICED); Assert.assertEquals(retrievedAdjustments.size(), 2, "Not all Adjustments marked as invoiced although all should be."); } finally { // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); } } @Test(groups = "integration") public void testCreateInvoiceAndRetrieveInvoicePdf() throws Exception { final Account accountData = TestUtils.createRandomAccount(); PDDocument pdDocument = null; try { // Create a user final Account account = recurlyClient.createAccount(accountData); // Create an Adjustment final Adjustment a = new Adjustment(); a.setUnitAmountInCents(150); a.setCurrency(CURRENCY); final Adjustment createdA = recurlyClient.createAccountAdjustment(accountData.getAccountCode(), a); // Post an invoice/invoice the adjustment final Invoice invoiceData = new Invoice(); invoiceData.setCollectionMethod("manual"); invoiceData.setLineItems(null); final Invoice invoice = recurlyClient.postAccountInvoice(accountData.getAccountCode(), invoiceData); Assert.assertNotNull(invoice); InputStream pdfInputStream = recurlyClient.getInvoicePdf(invoice.getInvoiceNumber()); Assert.assertNotNull(pdfInputStream); pdDocument = PDDocument.load(pdfInputStream); String pdfString = new PDFTextStripper().getText(pdDocument); Assert.assertNotNull(pdfString); Assert.assertTrue(pdfString.contains("Invoice # " + invoice.getInvoiceNumber())); Assert.assertTrue(pdfString.contains("Subtotal $" + 1.5)); // Attempt to close the invoice final Invoice closedInvoice = recurlyClient.markInvoiceSuccessful(invoice.getInvoiceNumber()); Assert.assertEquals(closedInvoice.getState(), "collected", "Invoice not closed successfully"); } finally { if (pdDocument != null) { pdDocument.close(); } // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); } } @Test(groups = "enterprise") public void testCreateAndCloseManualInvoices() throws Exception { final Account accountData = TestUtils.createRandomAccount(); try { // Create a user final Account account = recurlyClient.createAccount(accountData); // Create an Adjustment final Adjustment a = new Adjustment(); a.setUnitAmountInCents(150); a.setCurrency(CURRENCY); final Adjustment createdA = recurlyClient.createAccountAdjustment(accountData.getAccountCode(), a); // Post an invoice/invoice the adjustment final Invoice invoiceData = new Invoice(); invoiceData.setCollectionMethod("manual"); invoiceData.setLineItems(null); final Invoice invoice = recurlyClient.postAccountInvoice(accountData.getAccountCode(), invoiceData); Assert.assertNotNull(invoice); // Attempt to close the invoice final Invoice closedInvoice = recurlyClient.markInvoiceSuccessful(invoice.getInvoiceNumber()); Assert.assertEquals(closedInvoice.getState(), "collected", "Invoice not closed successfully"); // Create an Adjustment final Adjustment b = new Adjustment(); b.setUnitAmountInCents(250); b.setCurrency(CURRENCY); final Adjustment createdB = recurlyClient.createAccountAdjustment(accountData.getAccountCode(), b); // Post an invoice/invoice the adjustment final Invoice failInvoiceData = new Invoice(); failInvoiceData.setCollectionMethod("manual"); failInvoiceData.setLineItems(null); final Invoice invoiceFail = recurlyClient.postAccountInvoice(accountData.getAccountCode(), failInvoiceData); Assert.assertNotNull(invoiceFail); // Attempt to fail the invoice final Invoice failedInvoice = recurlyClient.markInvoiceFailed(invoiceFail.getInvoiceNumber()); Assert.assertEquals(failedInvoice.getState(), "failed", "Invoice not failed successfully"); // Create an Adjustment final Adjustment c = new Adjustment(); c.setUnitAmountInCents(450); c.setCurrency(CURRENCY); final Adjustment createdC = recurlyClient.createAccountAdjustment(accountData.getAccountCode(), c); // Post an invoice/invoice the adjustment final Invoice externalInvoiceData = new Invoice(); externalInvoiceData.setCollectionMethod("manual"); externalInvoiceData.setLineItems(null); final Invoice invoiceExternal = recurlyClient.postAccountInvoice(accountData.getAccountCode(), externalInvoiceData); Assert.assertNotNull(invoiceExternal); //create an external payment to pay off the invoice final Transaction externalPaymentData = new Transaction(); externalPaymentData.setPaymentMethod("other"); final DateTime collectionDateTime = new DateTime(DateTimeZone.UTC); externalPaymentData.setCollectedAt(collectionDateTime); externalPaymentData.setAmountInCents(450); final Transaction externalPayment = recurlyClient.enterOfflinePayment(invoiceExternal.getInvoiceNumber(), externalPaymentData); Assert.assertNotNull(externalPayment); Assert.assertEquals(externalPayment.getInvoice().getState(), "collected", "Invoice not closed successfully"); } finally { // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); } } @Test(groups = "integration") public void testCreateAndQueryTransactions() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); final Plan planData = TestUtils.createRandomPlan(); try { // Create a user final Account account = recurlyClient.createAccount(accountData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); Assert.assertNotNull(billingInfo); final BillingInfo retrievedBillingInfo = recurlyClient.getBillingInfo(account.getAccountCode()); Assert.assertNotNull(retrievedBillingInfo); // Create a plan final Plan plan = recurlyClient.createPlan(planData); // Subscribe the user to the plan final Subscription subscriptionData = new Subscription(); subscriptionData.setPlanCode(plan.getPlanCode()); subscriptionData.setAccount(accountData); subscriptionData.setUnitAmountInCents(150); subscriptionData.setCurrency(CURRENCY); recurlyClient.createSubscription(subscriptionData); // Create a transaction final Transaction t = new Transaction(); accountData.setBillingInfo(billingInfoData); t.setAccount(accountData); t.setAmountInCents(15); t.setCurrency(CURRENCY); final Transaction createdT = recurlyClient.createTransaction(t); // Test that the transaction created correctly Assert.assertNotNull(createdT); // Can't test for account equality yet as the account is only a ref and doesn't get mapped. Assert.assertEquals(createdT.getAmountInCents(), t.getAmountInCents()); Assert.assertEquals(createdT.getCurrency(), t.getCurrency()); // Test lookup on the transaction via the users account final Transactions trans = recurlyClient.getAccountTransactions(account.getAccountCode()); // 3 transactions: voided verification, $1.5 for the plan and the $0.15 transaction above Assert.assertEquals(trans.size(), 3); Transaction found = null; for (final Transaction _t : trans) { if (_t.getUuid().equals(createdT.getUuid())) { found = _t; break; } } if (found == null) { Assert.fail("Failed to locate the newly created transaction"); } // Verify the transaction information, including nested parameters // See https://github.com/killbilling/recurly-java-library/issues/4 Assert.assertEquals(found.getAccount().getAccountCode(), accountData.getAccountCode()); Assert.assertEquals(found.getAccount().getFirstName(), accountData.getFirstName()); Assert.assertEquals(found.getInvoice().getAccount().getAccountCode(), accountData.getAccountCode()); Assert.assertEquals(found.getInvoice().getAccount().getFirstName(), accountData.getFirstName()); Assert.assertEquals(found.getInvoice().getTotalInCents(), (Integer) 15); Assert.assertEquals(found.getInvoice().getCurrency(), CURRENCY); // Verify we can retrieve it Assert.assertEquals(recurlyClient.getTransaction(found.getUuid()).getUuid(), found.getUuid()); // Test Invoices retrieval final Invoices invoices = recurlyClient.getAccountInvoices(account.getAccountCode()); // 2 Invoices are present (the first one is for the transaction, the second for the subscription) Assert.assertEquals(invoices.size(), 2, "Number of Invoices incorrect"); Assert.assertEquals(invoices.get(0).getTotalInCents(), t.getAmountInCents(), "Amount in cents is not the same"); Assert.assertEquals(invoices.get(1).getTotalInCents(), subscriptionData.getUnitAmountInCents(), "Amount in cents is not the same"); } finally { // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); // Delete the Plan recurlyClient.deletePlan(planData.getPlanCode()); } } @Test(groups = "integration") public void testAddons() throws Exception { // Create a Plan final Plan planData = TestUtils.createRandomPlan(); final AddOn addOn = TestUtils.createRandomAddOn(); try { // Create an AddOn final Plan plan = recurlyClient.createPlan(planData); AddOn addOnRecurly = recurlyClient.createPlanAddOn(plan.getPlanCode(), addOn); // Test the creation Assert.assertNotNull(addOnRecurly); Assert.assertEquals(addOnRecurly.getAddOnCode(), addOn.getAddOnCode()); Assert.assertEquals(addOnRecurly.getName(), addOn.getName()); Assert.assertEquals(addOnRecurly.getUnitAmountInCents(), addOn.getUnitAmountInCents()); Assert.assertEquals(addOnRecurly.getDefaultQuantity(), addOn.getDefaultQuantity()); // Query for an AddOn addOnRecurly = recurlyClient.getAddOn(plan.getPlanCode(), addOn.getAddOnCode()); // Check the 2 are the same Assert.assertEquals(addOnRecurly.getAddOnCode(), addOn.getAddOnCode()); Assert.assertEquals(addOnRecurly.getName(), addOn.getName()); Assert.assertEquals(addOnRecurly.getDefaultQuantity(), addOn.getDefaultQuantity()); Assert.assertEquals(addOnRecurly.getDisplayQuantityOnHostedPage(), addOn.getDisplayQuantityOnHostedPage()); Assert.assertEquals(addOnRecurly.getUnitAmountInCents(), addOn.getUnitAmountInCents()); // Query for AddOns and Check again AddOns addOns = recurlyClient.getAddOns(plan.getPlanCode()); Assert.assertEquals(addOns.size(), 1); Assert.assertEquals(addOns.get(0).getAddOnCode(), addOn.getAddOnCode()); Assert.assertEquals(addOns.get(0).getName(), addOn.getName()); Assert.assertEquals(addOns.get(0).getDefaultQuantity(), addOn.getDefaultQuantity()); Assert.assertEquals(addOns.get(0).getDisplayQuantityOnHostedPage(), addOn.getDisplayQuantityOnHostedPage()); Assert.assertEquals(addOns.get(0).getUnitAmountInCents(), addOn.getUnitAmountInCents()); } finally { // Delete an AddOn recurlyClient.deleteAddOn(planData.getPlanCode(), addOn.getAddOnCode()); // Delete the plan recurlyClient.deletePlan(planData.getPlanCode()); } } @Test(groups = "integration") public void testCreateCoupon() throws Exception { final Coupon couponData = TestUtils.createRandomCoupon(); try { // Create the coupon Coupon coupon = recurlyClient.createCoupon(couponData); Assert.assertNotNull(coupon); Assert.assertEquals(coupon.getName(), couponData.getName()); Assert.assertEquals(coupon.getCouponCode(), couponData.getCouponCode()); Assert.assertEquals(coupon.getDiscountType(), couponData.getDiscountType()); Assert.assertEquals(coupon.getDiscountPercent(), couponData.getDiscountPercent()); // Get the coupon coupon = recurlyClient.getCoupon(couponData.getCouponCode()); Assert.assertNotNull(coupon); Assert.assertEquals(coupon.getName(), couponData.getName()); Assert.assertEquals(coupon.getCouponCode(), couponData.getCouponCode()); Assert.assertEquals(coupon.getDiscountType(), couponData.getDiscountType()); Assert.assertEquals(coupon.getDiscountPercent(), couponData.getDiscountPercent()); } finally { recurlyClient.deleteCoupon(couponData.getCouponCode()); } } @Test(groups = "integration") public void testUpdateSubscriptions() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); final Plan planData = TestUtils.createRandomPlan(); final Plan plan2Data = TestUtils.createRandomPlan(CURRENCY); try { // Create a user final Account account = recurlyClient.createAccount(accountData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); Assert.assertNotNull(billingInfo); final BillingInfo retrievedBillingInfo = recurlyClient.getBillingInfo(account.getAccountCode()); Assert.assertNotNull(retrievedBillingInfo); // Create a plan final Plan plan = recurlyClient.createPlan(planData); final Plan plan2 = recurlyClient.createPlan(plan2Data); // Subscribe the user to the plan final Subscription subscriptionData = new Subscription(); subscriptionData.setPlanCode(plan.getPlanCode()); subscriptionData.setAccount(accountData); subscriptionData.setCurrency(CURRENCY); subscriptionData.setUnitAmountInCents(1242); final DateTime creationDateTime = new DateTime(DateTimeZone.UTC); final Subscription subscription = recurlyClient.createSubscription(subscriptionData); Assert.assertNotNull(subscription); // Set subscription update info final SubscriptionUpdate subscriptionUpdateData = new SubscriptionUpdate(); subscriptionUpdateData.setTimeframe(SubscriptionUpdate.Timeframe.now); subscriptionUpdateData.setPlanCode(plan2.getPlanCode()); // Preview the subscription update final Subscription subscriptionUpdatedPreview = recurlyClient.updateSubscriptionPreview(subscription.getUuid(), subscriptionUpdateData); Assert.assertNotNull(subscriptionUpdatedPreview); // Test inline invoice fetch Assert.assertNotNull(subscriptionUpdatedPreview.getInvoice()); Assert.assertEquals(subscription.getUuid(), subscriptionUpdatedPreview.getUuid()); Assert.assertNotEquals(subscription.getPlan(), subscriptionUpdatedPreview.getPlan()); Assert.assertEquals(plan2.getPlanCode(), subscriptionUpdatedPreview.getPlan().getPlanCode()); // Update the subscription final Subscription subscriptionUpdated = recurlyClient.updateSubscription(subscription.getUuid(), subscriptionUpdateData); Assert.assertNotNull(subscriptionUpdated); Assert.assertEquals(subscription.getUuid(), subscriptionUpdated.getUuid()); Assert.assertNotEquals(subscription.getPlan(), subscriptionUpdated.getPlan()); Assert.assertEquals(plan2.getPlanCode(), subscriptionUpdated.getPlan().getPlanCode()); } finally { // Close the account recurlyClient.closeAccount(accountData.getAccountCode()); // Delete the Plans recurlyClient.deletePlan(planData.getPlanCode()); recurlyClient.deletePlan(plan2Data.getPlanCode()); } } @Test(groups = "integration") public void testRedeemCoupon() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); final Plan planData = TestUtils.createRandomPlan(CURRENCY); final Coupon couponData = TestUtils.createRandomCoupon(); final Coupon secondCouponData = TestUtils.createRandomCoupon(); try { final Account account = recurlyClient.createAccount(accountData); final Plan plan = recurlyClient.createPlan(planData); final Coupon coupon = recurlyClient.createCoupon(couponData); final Coupon secondCoupon = recurlyClient.createCoupon(secondCouponData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); Assert.assertNotNull(billingInfo); // Subscribe the user to the plan final Subscription subscriptionData = new Subscription(); subscriptionData.setPlanCode(plan.getPlanCode()); subscriptionData.setAccount(accountData); subscriptionData.setCurrency(CURRENCY); subscriptionData.setUnitAmountInCents(1242); final Subscription subscription = recurlyClient.createSubscription(subscriptionData); Assert.assertNotNull(subscription); // No coupon at this point try { recurlyClient.getCouponRedemptionByAccount(account.getAccountCode()); Assert.fail("Coupon should not be found."); } catch (RecurlyAPIException expected) { Assert.assertTrue(true); } // Redeem a coupon final Redemption redemptionData = new Redemption(); redemptionData.setAccountCode(account.getAccountCode()); redemptionData.setCurrency(CURRENCY); Redemption redemption = recurlyClient.redeemCoupon(coupon.getCouponCode(), redemptionData); Assert.assertNotNull(redemption); Assert.assertEquals(redemption.getCoupon().getCouponCode(), coupon.getCouponCode()); Assert.assertEquals(redemption.getAccount().getAccountCode(), account.getAccountCode()); Assert.assertFalse(redemption.getSingleUse()); Assert.assertEquals(redemption.getTotalDiscountedInCents(), (Integer) 0); Assert.assertEquals(redemption.getState(), "active"); Assert.assertEquals(redemption.getCurrency(), CURRENCY); // Get the coupon redemption redemption = recurlyClient.getCouponRedemptionByAccount(account.getAccountCode()); Assert.assertNotNull(redemption); Assert.assertEquals(redemption.getCoupon().getCouponCode(), coupon.getCouponCode()); Assert.assertEquals(redemption.getAccount().getAccountCode(), account.getAccountCode()); // Redeem another coupon final Redemption secondRedemptionData = new Redemption(); secondRedemptionData.setAccountCode(account.getAccountCode()); secondRedemptionData.setCurrency(CURRENCY); Redemption secondRedemption = recurlyClient.redeemCoupon(secondCoupon.getCouponCode(), secondRedemptionData); Assert.assertNotNull(secondRedemption); Assert.assertEquals(secondRedemption.getCoupon().getCouponCode(), secondCoupon.getCouponCode()); Assert.assertEquals(secondRedemption.getAccount().getAccountCode(), account.getAccountCode()); Assert.assertFalse(secondRedemption.getSingleUse()); Assert.assertEquals(secondRedemption.getTotalDiscountedInCents(), (Integer) 0); Assert.assertEquals(secondRedemption.getState(), "active"); Assert.assertEquals(secondRedemption.getCurrency(), CURRENCY); Redemptions redemptions = recurlyClient.getCouponRedemptionsByAccount(account.getAccountCode()); Assert.assertEquals(redemptions.size(), 2); // Remove both coupon redemptions recurlyClient.deleteCouponRedemption(account.getAccountCode(), redemption.getUuid()); recurlyClient.deleteCouponRedemption(account.getAccountCode(), secondRedemption.getUuid()); try { recurlyClient.getCouponRedemptionByAccount(account.getAccountCode()); Assert.fail("Coupon should be removed."); } catch (RecurlyAPIException expected) { Assert.assertTrue(true); } // Redeem a coupon once again final Redemption redemptionData2 = new Redemption(); redemptionData2.setAccountCode(account.getAccountCode()); redemptionData2.setCurrency(CURRENCY); redemption = recurlyClient.redeemCoupon(coupon.getCouponCode(), redemptionData2); Assert.assertNotNull(redemption); redemption = recurlyClient.getCouponRedemptionByAccount(account.getAccountCode()); Assert.assertEquals(redemption.getCoupon().getCouponCode(), coupon.getCouponCode()); Assert.assertEquals(redemption.getAccount().getAccountCode(), account.getAccountCode()); Assert.assertFalse(redemption.getSingleUse()); Assert.assertEquals(redemption.getTotalDiscountedInCents(), (Integer) 0); Assert.assertEquals(redemption.getState(), "active"); Assert.assertEquals(redemption.getCurrency(), CURRENCY); } finally { recurlyClient.closeAccount(accountData.getAccountCode()); recurlyClient.deletePlan(planData.getPlanCode()); recurlyClient.deleteCoupon(couponData.getCouponCode()); } } @Test(groups = "integration") public void testCreateTrialExtensionCoupon() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); final Plan planData = TestUtils.createRandomPlan(CURRENCY); final Coupon couponData = TestUtils.createRandomCoupon(); couponData.setName("apitrialext"); couponData.setFreeTrialAmount(3); couponData.setFreeTrialUnit("month"); couponData.setDiscountType("free_trial"); final LocalDateTime now = LocalDateTime.now(); try { final Account account = recurlyClient.createAccount(accountData); final Plan plan = recurlyClient.createPlan(planData); final Coupon coupon = recurlyClient.createCoupon(couponData); // Create BillingInfo billingInfoData.setAccount(account); final BillingInfo billingInfo = recurlyClient.createOrUpdateBillingInfo(billingInfoData); Assert.assertNotNull(billingInfo); // Subscribe the user to the plan final Subscription subscriptionData = new Subscription(); // set our coupon code subscriptionData.setCouponCode(coupon.getCouponCode()); subscriptionData.setPlanCode(plan.getPlanCode()); subscriptionData.setAccount(accountData); subscriptionData.setCurrency(CURRENCY); subscriptionData.setUnitAmountInCents(1242); final Subscription subscription = recurlyClient.createSubscription(subscriptionData); Assert.assertNotNull(subscription); final int expectedMonth = (now.getMonthOfYear() + 3) % 12; Assert.assertEquals(subscription.getTrialEndsAt().getMonthOfYear(), expectedMonth); } finally { recurlyClient.closeAccount(accountData.getAccountCode()); recurlyClient.deletePlan(planData.getPlanCode()); recurlyClient.deleteCoupon(couponData.getCouponCode()); } } @Test(groups = "integration") public void testRedeemGiftCardOnSubscription() throws Exception { final GiftCard giftCardData = TestUtils.createRandomGiftCard(); final Plan planData = TestUtils.createRandomPlan(CURRENCY); try { // Purchase a gift card final GiftCard giftCard = recurlyClient.purchaseGiftCard(giftCardData); Assert.assertEquals(giftCard.getProductCode(), giftCardData.getProductCode()); Assert.assertNull(giftCard.getRedeemedAt()); // Let's redeem on a subscription final Plan plan = recurlyClient.createPlan(planData); final Account account = giftCard.getGifterAccount(); final GiftCard redemptionData = new GiftCard(); final Subscription subscriptionData = new Subscription(); // set our gift card redemption data redemptionData.setRedemptionCode(giftCard.getRedemptionCode()); subscriptionData.setGiftCard(redemptionData); subscriptionData.setPlanCode(plan.getPlanCode()); subscriptionData.setAccount(account); subscriptionData.setCurrency(CURRENCY); subscriptionData.setUnitAmountInCents(1242); final Subscription subscription = recurlyClient.createSubscription(subscriptionData); Assert.assertNotNull(subscription); final GiftCard redeemedCard = recurlyClient.getGiftCard(giftCard.getId()); Assert.assertNotNull(redeemedCard.getRedeemedAt()); } finally { recurlyClient.deletePlan(planData.getPlanCode()); } } @Test(groups = "integration") public void testRedeemGiftCardOnAccount() throws Exception { final GiftCard giftCardData = TestUtils.createRandomGiftCard(); // Purchase a gift card final GiftCard giftCard = recurlyClient.purchaseGiftCard(giftCardData); Assert.assertEquals(giftCard.getProductCode(), giftCardData.getProductCode()); Assert.assertNull(giftCard.getRedeemedAt()); // Let's redeem on an account final Account gifterAccount = giftCard.getGifterAccount(); Assert.assertNotNull(gifterAccount); final String redemptionCode = giftCard.getRedemptionCode(); final String gifterAccountCode = gifterAccount.getAccountCode(); final GiftCard redeemedCard = recurlyClient.redeemGiftCard(redemptionCode, gifterAccountCode); Assert.assertNotNull(redeemedCard.getRedeemedAt()); } @Test(groups = "integration") public void testPreviewGiftCardPurchase() throws Exception { final GiftCard giftCardData = TestUtils.createRandomGiftCard(); // Preview a gift card purchase final GiftCard giftCard = recurlyClient.previewGiftCard(giftCardData); // Should be the purchased gift card Assert.assertEquals(giftCard.getProductCode(), giftCardData.getProductCode()); // But should not be created Assert.assertNull(giftCard.getId()); Assert.assertNull(giftCard.getCreatedAt()); } @Test(groups = "integration") public void testShippingAddressesOnAccount() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final ShippingAddress shippingAddress1 = TestUtils.createRandomShippingAddress(); final ShippingAddress shippingAddress2 = TestUtils.createRandomShippingAddress(); final ShippingAddresses shippingAddressesData = new ShippingAddresses(); try { shippingAddressesData.add(shippingAddress1); shippingAddressesData.add(shippingAddress2); accountData.setShippingAddresses(shippingAddressesData); final Account account = recurlyClient.createAccount(accountData); ShippingAddresses shippingAddresses = recurlyClient.getAccountShippingAddresses(account.getAccountCode()); Assert.assertEquals(shippingAddresses.size(), 2); } finally { recurlyClient.closeAccount(accountData.getAccountCode()); } } @Test(groups = "integration") public void testShippingAddressesOnSubscription() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final Plan planData = TestUtils.createRandomPlan(CURRENCY); final ShippingAddress shippingAddressData = TestUtils.createRandomShippingAddress(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); billingInfoData.setAccount(null); // null out random account fixture accountData.setBillingInfo(billingInfoData); // add the billing info to account data try { final Account account = recurlyClient.createAccount(accountData); final Plan plan = recurlyClient.createPlan(planData); // Subscribe the user to the plan final Subscription subscriptionData = new Subscription(); // set our shipping address subscriptionData.setShippingAddress(shippingAddressData); // set our sub data subscriptionData.setPlanCode(plan.getPlanCode()); subscriptionData.setCurrency(CURRENCY); subscriptionData.setUnitAmountInCents(1242); // attach the account final Account existingAccount = new Account(); existingAccount.setAccountCode(account.getAccountCode()); subscriptionData.setAccount(existingAccount); final Subscription subscription = recurlyClient.createSubscription(subscriptionData); Assert.assertNotNull(subscription.getHref()); } finally { recurlyClient.closeAccount(accountData.getAccountCode()); recurlyClient.deletePlan(planData.getPlanCode()); } } }
fix comment spelling
src/test/java/com/ning/billing/recurly/TestRecurlyClient.java
fix comment spelling
<ide><path>rc/test/java/com/ning/billing/recurly/TestRecurlyClient.java <ide> subscriptionData.setCurrency(CURRENCY); <ide> subscriptionData.setUnitAmountInCents(1242); <ide> <del> // makes sure we have at least on subscription <add> // makes sure we have at least one subscription <ide> recurlyClient.createSubscription(subscriptionData); <ide> <ide> // make sure we return more than one subscription <ide> <ide> // Verify we can retrieve it <ide> Assert.assertEquals(recurlyClient.getTransaction(found.getUuid()).getUuid(), found.getUuid()); <del> <add> <ide> // Test Invoices retrieval <ide> final Invoices invoices = recurlyClient.getAccountInvoices(account.getAccountCode()); <ide> // 2 Invoices are present (the first one is for the transaction, the second for the subscription)
JavaScript
apache-2.0
9cf352f011068ea5e36c231c4f08d27cecdae973
0
PolicyStat/combokeys,mousetrap-js/mousetrap,ccampbell/mousetrap,mousetrap-js/mousetrap,ccampbell/mousetrap
/** * Copyright 2012 Craig Campbell * * 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. * * Mousetrap is a simple keyboard shortcut library for Javascript with * no external dependencies * * @version 1.1.3 * @url craig.is/killing/mice */ (function() { /** * mapping of special keycodes to their corresponding keys * * everything in this dictionary cannot use keypress events * so it has to be here to map to the correct keycodes for * keyup/keydown events * * @type {Object} */ var _MAP = { 8: 'backspace', 9: 'tab', 13: 'enter', 16: 'shift', 17: 'ctrl', 18: 'alt', 20: 'capslock', 27: 'esc', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down', 45: 'ins', 46: 'del', 91: 'meta', 93: 'meta', 224: 'meta' }, /** * mapping for special characters so they can support * * this dictionary is only used incase you want to bind a * keyup or keydown event to one of these keys * * @type {Object} */ _KEYCODE_MAP = { 106: '*', 107: '+', 109: '-', 110: '.', 111 : '/', 186: ';', 187: '=', 188: ',', 189: '-', 190: '.', 191: '/', 192: '`', 219: '[', 220: '\\', 221: ']', 222: '\'' }, /** * this is a mapping of keys that require shift on a US keypad * back to the non shift equivelents * * this is so you can use keyup events with these keys * * note that this will only work reliably on US keyboards * * @type {Object} */ _SHIFT_MAP = { '~': '`', '!': '1', '@': '2', '#': '3', '$': '4', '%': '5', '^': '6', '&': '7', '*': '8', '(': '9', ')': '0', '_': '-', '+': '=', ':': ';', '\"': '\'', '<': ',', '>': '.', '?': '/', '|': '\\' }, /** * this is a list of special strings you can use to map * to modifier keys when you specify your keyboard shortcuts * * @type {Object} */ _SPECIAL_ALIASES = { 'option': 'alt', 'command': 'meta', 'return': 'enter', 'escape': 'esc' }, /** * variable to store the flipped version of _MAP from above * needed to check if we should use keypress or not when no action * is specified * * @type {Object|undefined} */ _REVERSE_MAP, /** * a list of all the callbacks setup via Mousetrap.bind() * * @type {Object} */ _callbacks = {}, /** * direct map of string combinations to callbacks used for trigger() * * @type {Object} */ _direct_map = {}, /** * keeps track of what level each sequence is at since multiple * sequences can start out with the same sequence * * @type {Object} */ _sequence_levels = {}, /** * variable to store the setTimeout call * * @type {null|number} */ _reset_timer, /** * temporary state where we will ignore the next keyup * * @type {boolean|string} */ _ignore_next_keyup = false, /** * are we currently inside of a sequence? * type of action ("keyup" or "keydown" or "keypress") or false * * @type {boolean|string} */ _inside_sequence = false; /** * loop through the f keys, f1 to f19 and add them to the map * programatically */ for (var i = 1; i < 20; ++i) { _MAP[111 + i] = 'f' + i; } /** * loop through to map numbers on the numeric keypad */ for (i = 0; i <= 9; ++i) { _MAP[i + 96] = i; } /** * cross browser add event method * * @param {Element|HTMLDocument} object * @param {string} type * @param {Function} callback * @returns void */ function _addEvent(object, type, callback) { if (object.addEventListener) { object.addEventListener(type, callback, false); return; } object.attachEvent('on' + type, callback); } /** * takes the event and returns the key character * * @param {Event} e * @return {string} */ function _characterFromEvent(e) { // for keypress events we should return the character as is if (e.type == 'keypress') { return String.fromCharCode(e.which); } // for non keypress events the special maps are needed if (_MAP[e.which]) { return _MAP[e.which]; } if (_KEYCODE_MAP[e.which]) { return _KEYCODE_MAP[e.which]; } // if it is not in the special map return String.fromCharCode(e.which).toLowerCase(); } /** * checks if two arrays are equal * * @param {Array} modifiers1 * @param {Array} modifiers2 * @returns {boolean} */ function _modifiersMatch(modifiers1, modifiers2) { return modifiers1.sort().join(',') === modifiers2.sort().join(','); } /** * resets all sequence counters except for the ones passed in * * @param {Object} do_not_reset * @returns void */ function _resetSequences(do_not_reset) { do_not_reset = do_not_reset || {}; var active_sequences = false, key; for (key in _sequence_levels) { if (do_not_reset[key]) { active_sequences = true; continue; } _sequence_levels[key] = 0; } if (!active_sequences) { _inside_sequence = false; } } /** * finds all callbacks that match based on the keycode, modifiers, * and action * * @param {string} character * @param {Array} modifiers * @param {Event|Object} e * @param {boolean=} remove - should we remove any matches * @param {string=} combination * @returns {Array} */ function _getMatches(character, modifiers, e, remove, combination) { var i, callback, matches = [], action = e.type; // if there are no events related to this keycode if (!_callbacks[character]) { return []; } // if a modifier key is coming up on its own we should allow it if (action == 'keyup' && _isModifier(character)) { modifiers = [character]; } // loop through all callbacks for the key that was pressed // and see if any of them match for (i = 0; i < _callbacks[character].length; ++i) { callback = _callbacks[character][i]; // if this is a sequence but it is not at the right level // then move onto the next match if (callback.seq && _sequence_levels[callback.seq] != callback.level) { continue; } // if the action we are looking for doesn't match the action we got // then we should keep going if (action != callback.action) { continue; } // if this is a keypress event and the meta key and control key // are not pressed that means that we need to only look at the // character, otherwise check the modifiers as well // // chrome will not fire a keypress if meta or control is down // safari will fire a keypress if meta or meta+shift is down // firefox will fire a keypress if meta or control is down if ((action == 'keypress' && !e.metaKey && !e.ctrlKey) || _modifiersMatch(modifiers, callback.modifiers)) { // remove is used so if you change your mind and call bind a // second time with a new function the first one is overwritten if (remove && callback.combo == combination) { _callbacks[character].splice(i, 1); } matches.push(callback); } } return matches; } /** * takes a key event and figures out what the modifiers are * * @param {Event} e * @returns {Array} */ function _eventModifiers(e) { var modifiers = []; if (e.shiftKey) { modifiers.push('shift'); } if (e.altKey) { modifiers.push('alt'); } if (e.ctrlKey) { modifiers.push('ctrl'); } if (e.metaKey) { modifiers.push('meta'); } return modifiers; } /** * actually calls the callback function * * if your callback function returns false this will use the jquery * convention - prevent default and stop propogation on the event * * @param {Function} callback * @param {Event} e * @returns void */ function _fireCallback(callback, e) { if (callback(e) === false) { if (e.preventDefault) { e.preventDefault(); } if (e.stopPropagation) { e.stopPropagation(); } e.returnValue = false; e.cancelBubble = true; } } /** * handles a character key event * * @param {string} character * @param {Event} e * @returns void */ function _handleCharacter(character, e) { // if this event should not happen stop here if (Mousetrap.stopCallback(e, e.target || e.srcElement)) { return; } var callbacks = _getMatches(character, _eventModifiers(e), e), i, do_not_reset = {}, processed_sequence_callback = false; // loop through matching callbacks for this key event for (i = 0; i < callbacks.length; ++i) { // fire for all sequence callbacks // this is because if for example you have multiple sequences // bound such as "g i" and "g t" they both need to fire the // callback for matching g cause otherwise you can only ever // match the first one if (callbacks[i].seq) { processed_sequence_callback = true; // keep a list of which sequences were matches for later do_not_reset[callbacks[i].seq] = 1; _fireCallback(callbacks[i].callback, e); continue; } // if there were no sequence matches but we are still here // that means this is a regular match so we should fire that if (!processed_sequence_callback && !_inside_sequence) { _fireCallback(callbacks[i].callback, e); } } // if you are inside of a sequence and the key you are pressing // is not a modifier key then we should reset all sequences // that were not matched by this key event if (e.type == _inside_sequence && !_isModifier(character)) { _resetSequences(do_not_reset); } } /** * handles a keydown event * * @param {Event} e * @returns void */ function _handleKey(e) { // normalize e.which for key events // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion e.which = typeof e.which == "number" ? e.which : e.keyCode; var character = _characterFromEvent(e); // no character found then stop if (!character) { return; } if (e.type == 'keyup' && _ignore_next_keyup == character) { _ignore_next_keyup = false; return; } _handleCharacter(character, e); } /** * determines if the keycode specified is a modifier key or not * * @param {string} key * @returns {boolean} */ function _isModifier(key) { return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta'; } /** * called to set a 1 second timeout on the specified sequence * * this is so after each key press in the sequence you have 1 second * to press the next key before you have to start over * * @returns void */ function _resetSequenceTimer() { clearTimeout(_reset_timer); _reset_timer = setTimeout(_resetSequences, 1000); } /** * reverses the map lookup so that we can look for specific keys * to see what can and can't use keypress * * @return {Object} */ function _getReverseMap() { if (!_REVERSE_MAP) { _REVERSE_MAP = {}; for (var key in _MAP) { // pull out the numeric keypad from here cause keypress should // be able to detect the keys from the character if (key > 95 && key < 112) { continue; } if (_MAP.hasOwnProperty(key)) { _REVERSE_MAP[_MAP[key]] = key; } } } return _REVERSE_MAP; } /** * picks the best action based on the key combination * * @param {string} key - character for key * @param {Array} modifiers * @param {string=} action passed in */ function _pickBestAction(key, modifiers, action) { // if no action was picked in we should try to pick the one // that we think would work best for this key if (!action) { action = _getReverseMap()[key] ? 'keydown' : 'keypress'; } // modifier keys don't work as expected with keypress, // switch to keydown if (action == 'keypress' && modifiers.length) { action = 'keydown'; } return action; } /** * binds a key sequence to an event * * @param {string} combo - combo specified in bind call * @param {Array} keys * @param {Function} callback * @param {string=} action * @returns void */ function _bindSequence(combo, keys, callback, action) { // start off by adding a sequence level record for this combination // and setting the level to 0 _sequence_levels[combo] = 0; // if there is no action pick the best one for the first key // in the sequence if (!action) { action = _pickBestAction(keys[0], []); } /** * callback to increase the sequence level for this sequence and reset * all other sequences that were active * * @param {Event} e * @returns void */ var _increaseSequence = function(e) { _inside_sequence = action; ++_sequence_levels[combo]; _resetSequenceTimer(); }, /** * wraps the specified callback inside of another function in order * to reset all sequence counters as soon as this sequence is done * * @param {Event} e * @returns void */ _callbackAndReset = function(e) { _fireCallback(callback, e); // we should ignore the next key up if the action is key down // or keypress. this is so if you finish a sequence and // release the key the final key will not trigger a keyup if (action !== 'keyup') { _ignore_next_keyup = _characterFromEvent(e); } // weird race condition if a sequence ends with the key // another sequence begins with setTimeout(_resetSequences, 10); }, i; // loop through keys one at a time and bind the appropriate callback // function. for any key leading up to the final one it should // increase the sequence. after the final, it should reset all sequences for (i = 0; i < keys.length; ++i) { _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i); } } /** * binds a single keyboard combination * * @param {string} combination * @param {Function} callback * @param {string=} action * @param {string=} sequence_name - name of sequence if part of sequence * @param {number=} level - what part of the sequence the command is * @returns void */ function _bindSingle(combination, callback, action, sequence_name, level) { // make sure multiple spaces in a row become a single space combination = combination.replace(/\s+/g, ' '); var sequence = combination.split(' '), i, key, keys, modifiers = []; // if this pattern is a sequence of keys then run through this method // to reprocess each pattern one key at a time if (sequence.length > 1) { _bindSequence(combination, sequence, callback, action); return; } // take the keys from this pattern and figure out what the actual // pattern is all about keys = combination === '+' ? ['+'] : combination.split('+'); for (i = 0; i < keys.length; ++i) { key = keys[i]; // normalize key names if (_SPECIAL_ALIASES[key]) { key = _SPECIAL_ALIASES[key]; } // if this is not a keypress event then we should // be smart about using shift keys // this will only work for US keyboards however if (action && action != 'keypress' && _SHIFT_MAP[key]) { key = _SHIFT_MAP[key]; modifiers.push('shift'); } // if this key is a modifier then add it to the list of modifiers if (_isModifier(key)) { modifiers.push(key); } } // depending on what the key combination is // we will try to pick the best event for it action = _pickBestAction(key, modifiers, action); // make sure to initialize array if this is the first time // a callback is added for this key if (!_callbacks[key]) { _callbacks[key] = []; } // remove an existing match if there is one _getMatches(key, modifiers, {type: action}, !sequence_name, combination); // add this call back to the array // if it is a sequence put it at the beginning // if not put it at the end // // this is important because the way these are processed expects // the sequence ones to come first _callbacks[key][sequence_name ? 'unshift' : 'push']({ callback: callback, modifiers: modifiers, action: action, seq: sequence_name, level: level, combo: combination }); } /** * binds multiple combinations to the same callback * * @param {Array} combinations * @param {Function} callback * @param {string|undefined} action * @returns void */ function _bindMultiple(combinations, callback, action) { for (var i = 0; i < combinations.length; ++i) { _bindSingle(combinations[i], callback, action); } } // start! _addEvent(document, 'keypress', _handleKey); _addEvent(document, 'keydown', _handleKey); _addEvent(document, 'keyup', _handleKey); var Mousetrap = { /** * binds an event to mousetrap * * can be a single key, a combination of keys separated with +, * an array of keys, or a sequence of keys separated by spaces * * be sure to list the modifier keys first to make sure that the * correct key ends up getting bound (the last key in the pattern) * * @param {string|Array} keys * @param {Function} callback * @param {string=} action - 'keypress', 'keydown', or 'keyup' * @returns void */ bind: function(keys, callback, action) { _bindMultiple(keys instanceof Array ? keys : [keys], callback, action); _direct_map[keys + ':' + action] = callback; return this; }, /** * unbinds an event to mousetrap * * the unbinding sets the callback function of the specified key combo * to an empty function and deletes the corresponding key in the * _direct_map dict. * * the keycombo+action has to be exactly the same as * it was defined in the bind method * * TODO: actually remove this from the _callbacks dictionary instead * of binding an empty function * * @param {string|Array} keys * @param {string} action * @returns void */ unbind: function(keys, action) { if (_direct_map[keys + ':' + action]) { delete _direct_map[keys + ':' + action]; this.bind(keys, function() {}, action); } return this; }, /** * triggers an event that has already been bound * * @param {string} keys * @param {string=} action * @returns void */ trigger: function(keys, action) { _direct_map[keys + ':' + action](); return this; }, /** * resets the library back to its initial state. this is useful * if you want to clear out the current keyboard shortcuts and bind * new ones - for example if you switch to another page * * @returns void */ reset: function() { _callbacks = {}; _direct_map = {}; return this; }, /** * should we stop this event before firing off callbacks * * @param {Event} e * @param {Element} element * @return {boolean} */ var element = e.target || e.srcElement, tag_name = element.tagName; stopCallback: function(e, element) { // if the element has the class "mousetrap" then no need to stop if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) { return false; } // stop for input, select, and textarea return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true'); } }; // expose mousetrap to the global object window.Mousetrap = Mousetrap; // expose mousetrap as an AMD module if (typeof define == 'function' && define.amd) { define('mousetrap', function() { return Mousetrap; }); } }) ();
mousetrap.js
/** * Copyright 2012 Craig Campbell * * 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. * * Mousetrap is a simple keyboard shortcut library for Javascript with * no external dependencies * * @version 1.1.3 * @url craig.is/killing/mice */ (function() { /** * mapping of special keycodes to their corresponding keys * * everything in this dictionary cannot use keypress events * so it has to be here to map to the correct keycodes for * keyup/keydown events * * @type {Object} */ var _MAP = { 8: 'backspace', 9: 'tab', 13: 'enter', 16: 'shift', 17: 'ctrl', 18: 'alt', 20: 'capslock', 27: 'esc', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down', 45: 'ins', 46: 'del', 91: 'meta', 93: 'meta', 224: 'meta' }, /** * mapping for special characters so they can support * * this dictionary is only used incase you want to bind a * keyup or keydown event to one of these keys * * @type {Object} */ _KEYCODE_MAP = { 106: '*', 107: '+', 109: '-', 110: '.', 111 : '/', 186: ';', 187: '=', 188: ',', 189: '-', 190: '.', 191: '/', 192: '`', 219: '[', 220: '\\', 221: ']', 222: '\'' }, /** * this is a mapping of keys that require shift on a US keypad * back to the non shift equivelents * * this is so you can use keyup events with these keys * * note that this will only work reliably on US keyboards * * @type {Object} */ _SHIFT_MAP = { '~': '`', '!': '1', '@': '2', '#': '3', '$': '4', '%': '5', '^': '6', '&': '7', '*': '8', '(': '9', ')': '0', '_': '-', '+': '=', ':': ';', '\"': '\'', '<': ',', '>': '.', '?': '/', '|': '\\' }, /** * this is a list of special strings you can use to map * to modifier keys when you specify your keyboard shortcuts * * @type {Object} */ _SPECIAL_ALIASES = { 'option': 'alt', 'command': 'meta', 'return': 'enter', 'escape': 'esc' }, /** * variable to store the flipped version of _MAP from above * needed to check if we should use keypress or not when no action * is specified * * @type {Object|undefined} */ _REVERSE_MAP, /** * a list of all the callbacks setup via Mousetrap.bind() * * @type {Object} */ _callbacks = {}, /** * direct map of string combinations to callbacks used for trigger() * * @type {Object} */ _direct_map = {}, /** * keeps track of what level each sequence is at since multiple * sequences can start out with the same sequence * * @type {Object} */ _sequence_levels = {}, /** * variable to store the setTimeout call * * @type {null|number} */ _reset_timer, /** * temporary state where we will ignore the next keyup * * @type {boolean|string} */ _ignore_next_keyup = false, /** * are we currently inside of a sequence? * type of action ("keyup" or "keydown" or "keypress") or false * * @type {boolean|string} */ _inside_sequence = false; /** * loop through the f keys, f1 to f19 and add them to the map * programatically */ for (var i = 1; i < 20; ++i) { _MAP[111 + i] = 'f' + i; } /** * loop through to map numbers on the numeric keypad */ for (i = 0; i <= 9; ++i) { _MAP[i + 96] = i; } /** * cross browser add event method * * @param {Element|HTMLDocument} object * @param {string} type * @param {Function} callback * @returns void */ function _addEvent(object, type, callback) { if (object.addEventListener) { object.addEventListener(type, callback, false); return; } object.attachEvent('on' + type, callback); } /** * takes the event and returns the key character * * @param {Event} e * @return {string} */ function _characterFromEvent(e) { // for keypress events we should return the character as is if (e.type == 'keypress') { return String.fromCharCode(e.which); } // for non keypress events the special maps are needed if (_MAP[e.which]) { return _MAP[e.which]; } if (_KEYCODE_MAP[e.which]) { return _KEYCODE_MAP[e.which]; } // if it is not in the special map return String.fromCharCode(e.which).toLowerCase(); } /** * checks if two arrays are equal * * @param {Array} modifiers1 * @param {Array} modifiers2 * @returns {boolean} */ function _modifiersMatch(modifiers1, modifiers2) { return modifiers1.sort().join(',') === modifiers2.sort().join(','); } /** * resets all sequence counters except for the ones passed in * * @param {Object} do_not_reset * @returns void */ function _resetSequences(do_not_reset) { do_not_reset = do_not_reset || {}; var active_sequences = false, key; for (key in _sequence_levels) { if (do_not_reset[key]) { active_sequences = true; continue; } _sequence_levels[key] = 0; } if (!active_sequences) { _inside_sequence = false; } } /** * finds all callbacks that match based on the keycode, modifiers, * and action * * @param {string} character * @param {Array} modifiers * @param {Event|Object} e * @param {boolean=} remove - should we remove any matches * @param {string=} combination * @returns {Array} */ function _getMatches(character, modifiers, e, remove, combination) { var i, callback, matches = [], action = e.type; // if there are no events related to this keycode if (!_callbacks[character]) { return []; } // if a modifier key is coming up on its own we should allow it if (action == 'keyup' && _isModifier(character)) { modifiers = [character]; } // loop through all callbacks for the key that was pressed // and see if any of them match for (i = 0; i < _callbacks[character].length; ++i) { callback = _callbacks[character][i]; // if this is a sequence but it is not at the right level // then move onto the next match if (callback.seq && _sequence_levels[callback.seq] != callback.level) { continue; } // if the action we are looking for doesn't match the action we got // then we should keep going if (action != callback.action) { continue; } // if this is a keypress event and the meta key and control key // are not pressed that means that we need to only look at the // character, otherwise check the modifiers as well // // chrome will not fire a keypress if meta or control is down // safari will fire a keypress if meta or meta+shift is down // firefox will fire a keypress if meta or control is down if ((action == 'keypress' && !e.metaKey && !e.ctrlKey) || _modifiersMatch(modifiers, callback.modifiers)) { // remove is used so if you change your mind and call bind a // second time with a new function the first one is overwritten if (remove && callback.combo == combination) { _callbacks[character].splice(i, 1); } matches.push(callback); } } return matches; } /** * takes a key event and figures out what the modifiers are * * @param {Event} e * @returns {Array} */ function _eventModifiers(e) { var modifiers = []; if (e.shiftKey) { modifiers.push('shift'); } if (e.altKey) { modifiers.push('alt'); } if (e.ctrlKey) { modifiers.push('ctrl'); } if (e.metaKey) { modifiers.push('meta'); } return modifiers; } /** * actually calls the callback function * * if your callback function returns false this will use the jquery * convention - prevent default and stop propogation on the event * * @param {Function} callback * @param {Event} e * @returns void */ function _fireCallback(callback, e) { if (callback(e) === false) { if (e.preventDefault) { e.preventDefault(); } if (e.stopPropagation) { e.stopPropagation(); } e.returnValue = false; e.cancelBubble = true; } } /** * handles a character key event * * @param {string} character * @param {Event} e * @returns void */ function _handleCharacter(character, e) { // if this event should not happen stop here if (Mousetrap.stopCallback(e, e.target || e.srcElement)) { return; } var callbacks = _getMatches(character, _eventModifiers(e), e), i, do_not_reset = {}, processed_sequence_callback = false; // loop through matching callbacks for this key event for (i = 0; i < callbacks.length; ++i) { // fire for all sequence callbacks // this is because if for example you have multiple sequences // bound such as "g i" and "g t" they both need to fire the // callback for matching g cause otherwise you can only ever // match the first one if (callbacks[i].seq) { processed_sequence_callback = true; // keep a list of which sequences were matches for later do_not_reset[callbacks[i].seq] = 1; _fireCallback(callbacks[i].callback, e); continue; } // if there were no sequence matches but we are still here // that means this is a regular match so we should fire that if (!processed_sequence_callback && !_inside_sequence) { _fireCallback(callbacks[i].callback, e); } } // if you are inside of a sequence and the key you are pressing // is not a modifier key then we should reset all sequences // that were not matched by this key event if (e.type == _inside_sequence && !_isModifier(character)) { _resetSequences(do_not_reset); } } /** * handles a keydown event * * @param {Event} e * @returns void */ function _handleKey(e) { // normalize e.which for key events // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion e.which = typeof e.which == "number" ? e.which : e.keyCode; var character = _characterFromEvent(e); // no character found then stop if (!character) { return; } if (e.type == 'keyup' && _ignore_next_keyup == character) { _ignore_next_keyup = false; return; } _handleCharacter(character, e); } /** * determines if the keycode specified is a modifier key or not * * @param {string} key * @returns {boolean} */ function _isModifier(key) { return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta'; } /** * called to set a 1 second timeout on the specified sequence * * this is so after each key press in the sequence you have 1 second * to press the next key before you have to start over * * @returns void */ function _resetSequenceTimer() { clearTimeout(_reset_timer); _reset_timer = setTimeout(_resetSequences, 1000); } /** * reverses the map lookup so that we can look for specific keys * to see what can and can't use keypress * * @return {Object} */ function _getReverseMap() { if (!_REVERSE_MAP) { _REVERSE_MAP = {}; for (var key in _MAP) { // pull out the numeric keypad from here cause keypress should // be able to detect the keys from the character if (key > 95 && key < 112) { continue; } if (_MAP.hasOwnProperty(key)) { _REVERSE_MAP[_MAP[key]] = key; } } } return _REVERSE_MAP; } /** * picks the best action based on the key combination * * @param {string} key - character for key * @param {Array} modifiers * @param {string=} action passed in */ function _pickBestAction(key, modifiers, action) { // if no action was picked in we should try to pick the one // that we think would work best for this key if (!action) { action = _getReverseMap()[key] ? 'keydown' : 'keypress'; } // modifier keys don't work as expected with keypress, // switch to keydown if (action == 'keypress' && modifiers.length) { action = 'keydown'; } return action; } /** * binds a key sequence to an event * * @param {string} combo - combo specified in bind call * @param {Array} keys * @param {Function} callback * @param {string=} action * @returns void */ function _bindSequence(combo, keys, callback, action) { // start off by adding a sequence level record for this combination // and setting the level to 0 _sequence_levels[combo] = 0; // if there is no action pick the best one for the first key // in the sequence if (!action) { action = _pickBestAction(keys[0], []); } /** * callback to increase the sequence level for this sequence and reset * all other sequences that were active * * @param {Event} e * @returns void */ var _increaseSequence = function(e) { _inside_sequence = action; ++_sequence_levels[combo]; _resetSequenceTimer(); }, /** * wraps the specified callback inside of another function in order * to reset all sequence counters as soon as this sequence is done * * @param {Event} e * @returns void */ _callbackAndReset = function(e) { _fireCallback(callback, e); // we should ignore the next key up if the action is key down // or keypress. this is so if you finish a sequence and // release the key the final key will not trigger a keyup if (action !== 'keyup') { _ignore_next_keyup = _characterFromEvent(e); } // weird race condition if a sequence ends with the key // another sequence begins with setTimeout(_resetSequences, 10); }, i; // loop through keys one at a time and bind the appropriate callback // function. for any key leading up to the final one it should // increase the sequence. after the final, it should reset all sequences for (i = 0; i < keys.length; ++i) { _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i); } } /** * binds a single keyboard combination * * @param {string} combination * @param {Function} callback * @param {string=} action * @param {string=} sequence_name - name of sequence if part of sequence * @param {number=} level - what part of the sequence the command is * @returns void */ function _bindSingle(combination, callback, action, sequence_name, level) { // make sure multiple spaces in a row become a single space combination = combination.replace(/\s+/g, ' '); var sequence = combination.split(' '), i, key, keys, modifiers = []; // if this pattern is a sequence of keys then run through this method // to reprocess each pattern one key at a time if (sequence.length > 1) { _bindSequence(combination, sequence, callback, action); return; } // take the keys from this pattern and figure out what the actual // pattern is all about keys = combination === '+' ? ['+'] : combination.split('+'); for (i = 0; i < keys.length; ++i) { key = keys[i]; // normalize key names if (_SPECIAL_ALIASES[key]) { key = _SPECIAL_ALIASES[key]; } // if this is not a keypress event then we should // be smart about using shift keys // this will only work for US keyboards however if (action && action != 'keypress' && _SHIFT_MAP[key]) { key = _SHIFT_MAP[key]; modifiers.push('shift'); } // if this key is a modifier then add it to the list of modifiers if (_isModifier(key)) { modifiers.push(key); } } // depending on what the key combination is // we will try to pick the best event for it action = _pickBestAction(key, modifiers, action); // make sure to initialize array if this is the first time // a callback is added for this key if (!_callbacks[key]) { _callbacks[key] = []; } // remove an existing match if there is one _getMatches(key, modifiers, {type: action}, !sequence_name, combination); // add this call back to the array // if it is a sequence put it at the beginning // if not put it at the end // // this is important because the way these are processed expects // the sequence ones to come first _callbacks[key][sequence_name ? 'unshift' : 'push']({ callback: callback, modifiers: modifiers, action: action, seq: sequence_name, level: level, combo: combination }); } /** * binds multiple combinations to the same callback * * @param {Array} combinations * @param {Function} callback * @param {string|undefined} action * @returns void */ function _bindMultiple(combinations, callback, action) { for (var i = 0; i < combinations.length; ++i) { _bindSingle(combinations[i], callback, action); } } // start! _addEvent(document, 'keypress', _handleKey); _addEvent(document, 'keydown', _handleKey); _addEvent(document, 'keyup', _handleKey); var mousetrap = { /** * binds an event to mousetrap * * can be a single key, a combination of keys separated with +, * an array of keys, or a sequence of keys separated by spaces * * be sure to list the modifier keys first to make sure that the * correct key ends up getting bound (the last key in the pattern) * * @param {string|Array} keys * @param {Function} callback * @param {string=} action - 'keypress', 'keydown', or 'keyup' * @returns void */ bind: function(keys, callback, action) { _bindMultiple(keys instanceof Array ? keys : [keys], callback, action); _direct_map[keys + ':' + action] = callback; return this; }, /** * unbinds an event to mousetrap * * the unbinding sets the callback function of the specified key combo * to an empty function and deletes the corresponding key in the * _direct_map dict. * * the keycombo+action has to be exactly the same as * it was defined in the bind method * * TODO: actually remove this from the _callbacks dictionary instead * of binding an empty function * * @param {string|Array} keys * @param {string} action * @returns void */ unbind: function(keys, action) { if (_direct_map[keys + ':' + action]) { delete _direct_map[keys + ':' + action]; this.bind(keys, function() {}, action); } return this; }, /** * triggers an event that has already been bound * * @param {string} keys * @param {string=} action * @returns void */ trigger: function(keys, action) { _direct_map[keys + ':' + action](); return this; }, /** * resets the library back to its initial state. this is useful * if you want to clear out the current keyboard shortcuts and bind * new ones - for example if you switch to another page * * @returns void */ reset: function() { _callbacks = {}; _direct_map = {}; return this; }, /** * should we stop this event before firing off callbacks * * @param {Event} e * @param {Element} element * @return {boolean} */ var element = e.target || e.srcElement, tag_name = element.tagName; stopCallback: function(e, element) { // if the element has the class "mousetrap" then no need to stop if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) { return false; } // stop for input, select, and textarea return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true'); } }; // expose mousetrap to the global object window.Mousetrap = mousetrap; // expose mousetrap as an AMD module if (typeof define == 'function' && define.amd) { define('mousetrap', function() { return mousetrap; }); } }) ();
Capitalize mousetrap to save gzip space
mousetrap.js
Capitalize mousetrap to save gzip space
<ide><path>ousetrap.js <ide> _addEvent(document, 'keydown', _handleKey); <ide> _addEvent(document, 'keyup', _handleKey); <ide> <del> var mousetrap = { <add> var Mousetrap = { <ide> <ide> /** <ide> * binds an event to mousetrap <ide> }; <ide> <ide> // expose mousetrap to the global object <del> window.Mousetrap = mousetrap; <add> window.Mousetrap = Mousetrap; <ide> <ide> // expose mousetrap as an AMD module <ide> if (typeof define == 'function' && define.amd) { <del> define('mousetrap', function() { return mousetrap; }); <add> define('mousetrap', function() { return Mousetrap; }); <ide> } <ide> }) ();
Java
mit
7857ef4ffa46f00a6de079fb9d66c4052db2eb30
0
AddstarMC/Minigames
package com.pauldavdesign.mineauz.minigames.presets; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import com.pauldavdesign.mineauz.minigames.Minigame; import com.pauldavdesign.mineauz.minigames.PlayerLoadout; public class InfectionPreset implements BasePreset { @Override public String getName() { return "Infection"; } @Override public String getInfo() { return "Creates balanced settings for an Infection game. This is based off the \"Introducing Infection\" video on the Minigames 1.5 release. " + "It gives survivors a stone knockback 2 sword and power 10 bow with 24 arrows (insta kill) and give the Infected a sharpness 3 sword (2 hit kill), jump boost 2 " + "and speed 2 for unlimited time (also a zombie head). The games timer is 5 minutes."; } @Override public void execute(Minigame minigame) { //Loadouts minigame.addLoadout("red"); minigame.addLoadout("blue"); PlayerLoadout red = minigame.getLoadout("red"); PlayerLoadout blue = minigame.getLoadout("blue"); ItemStack zsword = new ItemStack(Material.DIAMOND_SWORD); ItemStack zhead = new ItemStack(Material.SKULL_ITEM); ItemStack ssword = new ItemStack(Material.STONE_SWORD); ItemStack sbow = new ItemStack(Material.BOW); ItemStack sarrows = new ItemStack(Material.ARROW, 24); zsword.addUnsafeEnchantment(Enchantment.DAMAGE_ALL, 3); zhead.setDurability((short)2); ssword.addUnsafeEnchantment(Enchantment.KNOCKBACK, 2); sbow.addUnsafeEnchantment(Enchantment.ARROW_DAMAGE, 10); red.addItemToLoadout(zsword); red.addItemToLoadout(zhead); blue.addItemToLoadout(ssword); blue.addItemToLoadout(sbow); blue.addItemToLoadout(sarrows); red.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 200000, 2, true)); red.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 200000, 2, true)); //Settings minigame.setScoreType("infection"); minigame.setDefaultWinner("blue"); minigame.setType("teamdm"); minigame.setMinPlayers(4); minigame.setMaxPlayers(16); minigame.setTimer(300); minigame.saveMinigame(); } }
src/com/pauldavdesign/mineauz/minigames/presets/InfectionPreset.java
package com.pauldavdesign.mineauz.minigames.presets; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import com.pauldavdesign.mineauz.minigames.Minigame; import com.pauldavdesign.mineauz.minigames.PlayerLoadout; public class InfectionPreset implements BasePreset { @Override public String getName() { return "Infection"; } @Override public String getInfo() { return "Creates balanced settings for an Infection game. This is based off the \"Introducing Infection\" video on the Minigames 1.5 release. " + "It gives survivors a stone knockback 2 sword and power 10 bow with 24 arrows (insta kill) and give the Infected a sharpness 3 sword (2 hit kill), jump boost 2 " + "and speed 2 for unlimited time (also a zombie head). The games timer is 5 minutes."; } @Override public void execute(Minigame minigame) { //Loadouts minigame.addLoadout("red"); minigame.addLoadout("blue"); PlayerLoadout red = minigame.getLoadout("red"); PlayerLoadout blue = minigame.getLoadout("blue"); ItemStack zsword = new ItemStack(Material.DIAMOND_SWORD); ItemStack zhead = new ItemStack(Material.SKULL_ITEM); ItemStack ssword = new ItemStack(Material.STONE_SWORD); ItemStack sbow = new ItemStack(Material.BOW); ItemStack sarrows = new ItemStack(Material.ARROW, 24); zsword.addEnchantment(Enchantment.DAMAGE_ALL, 3); zhead.setDurability((short)2); ssword.addEnchantment(Enchantment.KNOCKBACK, 2); sbow.addEnchantment(Enchantment.ARROW_DAMAGE, 10); red.addItemToLoadout(zsword); red.addItemToLoadout(zhead); blue.addItemToLoadout(ssword); blue.addItemToLoadout(sbow); blue.addItemToLoadout(sarrows); red.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 200000, 2, true)); red.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 200000, 2, true)); //Settings minigame.setScoreType("infection"); minigame.setDefaultWinner("blue"); minigame.setType("teamdm"); minigame.setMinPlayers(4); minigame.setMaxPlayers(16); minigame.setTimer(300); minigame.saveMinigame(); } }
Fix for unsafe enchantments
src/com/pauldavdesign/mineauz/minigames/presets/InfectionPreset.java
Fix for unsafe enchantments
<ide><path>rc/com/pauldavdesign/mineauz/minigames/presets/InfectionPreset.java <ide> ItemStack sbow = new ItemStack(Material.BOW); <ide> ItemStack sarrows = new ItemStack(Material.ARROW, 24); <ide> <del> zsword.addEnchantment(Enchantment.DAMAGE_ALL, 3); <add> zsword.addUnsafeEnchantment(Enchantment.DAMAGE_ALL, 3); <ide> zhead.setDurability((short)2); <del> ssword.addEnchantment(Enchantment.KNOCKBACK, 2); <del> sbow.addEnchantment(Enchantment.ARROW_DAMAGE, 10); <add> ssword.addUnsafeEnchantment(Enchantment.KNOCKBACK, 2); <add> sbow.addUnsafeEnchantment(Enchantment.ARROW_DAMAGE, 10); <ide> <ide> red.addItemToLoadout(zsword); <ide> red.addItemToLoadout(zhead);
Java
apache-2.0
7b70dd0f3d774ef663baab2eaf16d1c5eeeb7640
0
pyamsoft/power-manager,pyamsoft/power-manager
/* * Copyright 2016 Peter Kenji Yamanaka * * 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.pyamsoft.powermanager.dagger.queuer; import android.content.Context; import android.content.Intent; import android.support.annotation.CheckResult; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.pyamsoft.powermanager.app.logger.Logger; import com.pyamsoft.powermanager.app.modifier.BooleanInterestModifier; import com.pyamsoft.powermanager.app.observer.BooleanInterestObserver; import com.pyamsoft.powermanager.dagger.wrapper.JobQueuerWrapper; import com.pyamsoft.pydroidrx.SubscriptionHelper; import java.util.concurrent.TimeUnit; import rx.Observable; import rx.Scheduler; import rx.Subscription; abstract class QueuerImpl implements Queuer { private static final long LARGEST_TIME_WITHOUT_ALARM = 60L; @NonNull final Logger logger; @NonNull final BooleanInterestObserver stateObserver; @NonNull final BooleanInterestModifier stateModifier; @NonNull final BooleanInterestObserver chargingObserver; @SuppressWarnings("WeakerAccess") @NonNull final String jobTag; @NonNull private final JobQueuerWrapper jobQueuerWrapper; @NonNull private final Scheduler handlerScheduler; @SuppressWarnings("WeakerAccess") @Nullable Subscription smallTimeQueuedSubscription; @SuppressWarnings("WeakerAccess") @Nullable QueuerType type; @SuppressWarnings("WeakerAccess") int ignoreCharging; private long delayTime; @NonNull private Context appContext; private long periodicEnableTime; private long periodicDisableTime; private int periodic; private boolean set; private boolean cancelRunning; QueuerImpl(@NonNull String jobTag, @NonNull Context context, @NonNull JobQueuerWrapper jobQueuerWrapper, @NonNull Scheduler handlerScheduler, @NonNull BooleanInterestObserver stateObserver, @NonNull BooleanInterestModifier stateModifier, @NonNull BooleanInterestObserver chargingObserver, @NonNull Logger logger) { this.jobTag = jobTag; this.appContext = context.getApplicationContext(); this.jobQueuerWrapper = jobQueuerWrapper; this.handlerScheduler = handlerScheduler; this.chargingObserver = chargingObserver; this.stateObserver = stateObserver; this.stateModifier = stateModifier; this.logger = logger; reset(); } private void reset() { set = false; type = null; delayTime = -1L; periodicDisableTime = -1L; periodicEnableTime = -1L; periodic = -1; ignoreCharging = -1; cancelRunning = false; } private void checkAll() { if (type == null) { throw new IllegalStateException("Type is NULL1"); } if (delayTime < 0) { throw new IllegalStateException("Delay time is less than 0"); } if (periodicDisableTime < 0) { throw new IllegalStateException("Periodic Disable time is less than 0"); } if (periodicEnableTime < 0) { throw new IllegalStateException("Periodic Enable time is less than 0"); } if (periodic < 0) { throw new IllegalStateException("Periodic is not set"); } if (ignoreCharging < 0) { throw new IllegalStateException("Ignore Charging is not set"); } if (set) { throw new IllegalStateException("Must be reset before we can queue"); } } @NonNull @Override public Queuer cancel() { reset(); cancelRunning = true; return this; } @NonNull @Override public Queuer setType(@NonNull QueuerType queuerType) { type = queuerType; return this; } @NonNull @Override public Queuer setDelayTime(long time) { delayTime = time; return this; } @NonNull @Override public Queuer setPeriodic(boolean periodic) { this.periodic = (periodic ? 1 : 0); return this; } @NonNull @Override public Queuer setIgnoreCharging(boolean ignore) { ignoreCharging = (ignore ? 1 : 0); return this; } @NonNull @Override public Queuer setPeriodicEnableTime(long time) { periodicEnableTime = time; return this; } @NonNull @Override public Queuer setPeriodicDisableTime(long time) { periodicDisableTime = time; return this; } @Override public void queue() { checkAll(); set = true; if (cancelRunning) { logger.d("Cancel any previous jobs for %s", jobTag); jobQueuerWrapper.cancel(getLongTermIntent(appContext)); SubscriptionHelper.unsubscribe(smallTimeQueuedSubscription); } if (delayTime <= LARGEST_TIME_WITHOUT_ALARM * 1000L) { queueShort(); } else { queueLong(); } } private void queueShort() { logger.d("Queue short term job with delay: %d (%s)", delayTime, jobTag); SubscriptionHelper.unsubscribe(smallTimeQueuedSubscription); smallTimeQueuedSubscription = Observable.defer(() -> Observable.just(true)) .delay(delayTime, TimeUnit.MILLISECONDS) .subscribeOn(handlerScheduler) .observeOn(handlerScheduler) .subscribe(ignore -> { if (type == null) { throw new IllegalStateException("Type is NULL"); } logger.d("Run short queue job: %s", jobTag); QueueRunner.run(jobTag, type, stateObserver, stateModifier, chargingObserver, logger, ignoreCharging); queuePeriodic(System.currentTimeMillis()); }, throwable -> logger.e("%s onError Queuer queueShort", throwable.toString()), () -> SubscriptionHelper.unsubscribe(smallTimeQueuedSubscription)); } private void queueLong() { if (type == null) { throw new IllegalStateException("QueueType is NULL"); } final Intent intent = getQueueIntent(appContext); intent.putExtra(BaseLongTermService.EXTRA_JOB_TYPE, type.name()); logger.d("Queue long term job with delay: %d (%s)", delayTime, jobTag); jobQueuerWrapper.cancel(intent); final long triggerAtTime = System.currentTimeMillis() + delayTime; jobQueuerWrapper.set(intent, triggerAtTime); queuePeriodic(triggerAtTime); } @SuppressWarnings("WeakerAccess") void queuePeriodic(long timeOfFirstTrigger) { if (periodic < 1) { logger.i("This job %s is not periodic. Skip", jobTag); return; } if (periodicEnableTime < 60L) { logger.w("Periodic Enable time for %s is too low %d. Must be at least 60", jobTag, periodicEnableTime); return; } if (periodicDisableTime < 60L) { logger.w("Periodic Disable time for %s is too low %d. Must be at least 60", jobTag, periodicDisableTime); return; } // Remember that the times are switched to make the logic work correctly even if naming is confusing final long intervalUntilReEnable = periodicDisableTime * 1000L; final long intervalUntilReDisable = periodicEnableTime * 1000L; final long reEnableTime = timeOfFirstTrigger + intervalUntilReEnable; final long reDisableTime = reEnableTime + intervalUntilReDisable; if (type == null) { throw new IllegalStateException("QueueType is NULL"); } final Intent intent = getQueueIntent(appContext); final QueuerType newType; if (type == QueuerType.ENABLE) { newType = QueuerType.DISABLE; } else if (type == QueuerType.DISABLE) { newType = QueuerType.ENABLE; } else if (type == QueuerType.TOGGLE_ENABLE) { newType = QueuerType.TOGGLE_DISABLE; } else if (type == QueuerType.TOGGLE_DISABLE) { newType = QueuerType.TOGGLE_ENABLE; } else { throw new IllegalStateException("Invalid queue type"); } // Queue a constant re-enable job with the same Type as original logger.i("Set repeating enable job %s starting at %d window %d", jobTag, reEnableTime, intervalUntilReEnable); intent.putExtra(BaseLongTermService.EXTRA_JOB_TYPE, type.name()); jobQueuerWrapper.setRepeating(intent, reEnableTime, intervalUntilReEnable); // Queue a constant re-disable job with the opposite type final Intent newIntent = getQueueIntent(appContext); logger.i("Set repeating disable job %s starting at %d window %d", jobTag, reDisableTime, intervalUntilReDisable); newIntent.putExtra(BaseLongTermService.EXTRA_JOB_TYPE, newType.name()); jobQueuerWrapper.setRepeating(newIntent, reDisableTime, intervalUntilReDisable); } @CheckResult @NonNull private Intent getQueueIntent(@NonNull Context context) { final Intent intent = getLongTermIntent(context); intent.putExtra(BaseLongTermService.EXTRA_IGNORE_CHARGING, ignoreCharging); return intent; } @CheckResult @NonNull abstract Intent getLongTermIntent(@NonNull Context context); }
src/main/java/com/pyamsoft/powermanager/dagger/queuer/QueuerImpl.java
/* * Copyright 2016 Peter Kenji Yamanaka * * 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.pyamsoft.powermanager.dagger.queuer; import android.content.Context; import android.content.Intent; import android.support.annotation.CheckResult; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.pyamsoft.powermanager.app.logger.Logger; import com.pyamsoft.powermanager.app.modifier.BooleanInterestModifier; import com.pyamsoft.powermanager.app.observer.BooleanInterestObserver; import com.pyamsoft.powermanager.dagger.wrapper.JobQueuerWrapper; import com.pyamsoft.pydroidrx.SubscriptionHelper; import java.util.concurrent.TimeUnit; import rx.Observable; import rx.Scheduler; import rx.Subscription; abstract class QueuerImpl implements Queuer { private static final long LARGEST_TIME_WITHOUT_ALARM = 120L; @NonNull final Logger logger; @NonNull final BooleanInterestObserver stateObserver; @NonNull final BooleanInterestModifier stateModifier; @NonNull final BooleanInterestObserver chargingObserver; @SuppressWarnings("WeakerAccess") @NonNull final String jobTag; @NonNull private final JobQueuerWrapper jobQueuerWrapper; @NonNull private final Scheduler handlerScheduler; @SuppressWarnings("WeakerAccess") @Nullable Subscription smallTimeQueuedSubscription; @SuppressWarnings("WeakerAccess") @Nullable QueuerType type; @SuppressWarnings("WeakerAccess") int ignoreCharging; private long delayTime; @NonNull private Context appContext; private long periodicEnableTime; private long periodicDisableTime; private int periodic; private boolean set; private boolean cancelRunning; QueuerImpl(@NonNull String jobTag, @NonNull Context context, @NonNull JobQueuerWrapper jobQueuerWrapper, @NonNull Scheduler handlerScheduler, @NonNull BooleanInterestObserver stateObserver, @NonNull BooleanInterestModifier stateModifier, @NonNull BooleanInterestObserver chargingObserver, @NonNull Logger logger) { this.jobTag = jobTag; this.appContext = context.getApplicationContext(); this.jobQueuerWrapper = jobQueuerWrapper; this.handlerScheduler = handlerScheduler; this.chargingObserver = chargingObserver; this.stateObserver = stateObserver; this.stateModifier = stateModifier; this.logger = logger; reset(); } private void reset() { set = false; type = null; delayTime = -1L; periodicDisableTime = -1L; periodicEnableTime = -1L; periodic = -1; ignoreCharging = -1; cancelRunning = false; } private void checkAll() { if (type == null) { throw new IllegalStateException("Type is NULL1"); } if (delayTime < 0) { throw new IllegalStateException("Delay time is less than 0"); } if (periodicDisableTime < 0) { throw new IllegalStateException("Periodic Disable time is less than 0"); } if (periodicEnableTime < 0) { throw new IllegalStateException("Periodic Enable time is less than 0"); } if (periodic < 0) { throw new IllegalStateException("Periodic is not set"); } if (ignoreCharging < 0) { throw new IllegalStateException("Ignore Charging is not set"); } if (set) { throw new IllegalStateException("Must be reset before we can queue"); } } @NonNull @Override public Queuer cancel() { reset(); cancelRunning = true; return this; } @NonNull @Override public Queuer setType(@NonNull QueuerType queuerType) { type = queuerType; return this; } @NonNull @Override public Queuer setDelayTime(long time) { delayTime = time; return this; } @NonNull @Override public Queuer setPeriodic(boolean periodic) { this.periodic = (periodic ? 1 : 0); return this; } @NonNull @Override public Queuer setIgnoreCharging(boolean ignore) { ignoreCharging = (ignore ? 1 : 0); return this; } @NonNull @Override public Queuer setPeriodicEnableTime(long time) { periodicEnableTime = time; return this; } @NonNull @Override public Queuer setPeriodicDisableTime(long time) { periodicDisableTime = time; return this; } @Override public void queue() { checkAll(); set = true; if (cancelRunning) { logger.d("Cancel any previous jobs for %s", jobTag); jobQueuerWrapper.cancel(getLongTermIntent(appContext)); SubscriptionHelper.unsubscribe(smallTimeQueuedSubscription); } if (delayTime <= LARGEST_TIME_WITHOUT_ALARM * 1000L) { queueShort(); } else { queueLong(); } } private void queueShort() { logger.d("Queue short term job with delay: %d (%s)", delayTime, jobTag); SubscriptionHelper.unsubscribe(smallTimeQueuedSubscription); smallTimeQueuedSubscription = Observable.defer(() -> Observable.just(true)) .delay(delayTime, TimeUnit.MILLISECONDS) .subscribeOn(handlerScheduler) .observeOn(handlerScheduler) .subscribe(ignore -> { if (type == null) { throw new IllegalStateException("Type is NULL"); } logger.d("Run short queue job: %s", jobTag); QueueRunner.run(jobTag, type, stateObserver, stateModifier, chargingObserver, logger, ignoreCharging); queuePeriodic(System.currentTimeMillis()); }, throwable -> logger.e("%s onError Queuer queueShort", throwable.toString()), () -> SubscriptionHelper.unsubscribe(smallTimeQueuedSubscription)); } private void queueLong() { if (type == null) { throw new IllegalStateException("QueueType is NULL"); } final Intent intent = getQueueIntent(appContext); intent.putExtra(BaseLongTermService.EXTRA_JOB_TYPE, type.name()); logger.d("Queue long term job with delay: %d (%s)", delayTime, jobTag); jobQueuerWrapper.cancel(intent); final long triggerAtTime = System.currentTimeMillis() + delayTime; jobQueuerWrapper.set(intent, triggerAtTime); queuePeriodic(triggerAtTime); } @SuppressWarnings("WeakerAccess") void queuePeriodic(long timeOfFirstTrigger) { if (periodic < 1) { logger.i("This job %s is not periodic. Skip", jobTag); return; } if (periodicEnableTime < 60L) { logger.w("Periodic Enable time for %s is too low %d. Must be at least 60", jobTag, periodicEnableTime); return; } if (periodicDisableTime < 60L) { logger.w("Periodic Disable time for %s is too low %d. Must be at least 60", jobTag, periodicDisableTime); return; } // Remember that the times are switched to make the logic work correctly even if naming is confusing final long intervalUntilReEnable = periodicDisableTime * 1000L; final long intervalUntilReDisable = periodicEnableTime * 1000L; final long reEnableTime = timeOfFirstTrigger + intervalUntilReEnable; final long reDisableTime = reEnableTime + intervalUntilReDisable; if (type == null) { throw new IllegalStateException("QueueType is NULL"); } final Intent intent = getQueueIntent(appContext); final QueuerType newType; if (type == QueuerType.ENABLE) { newType = QueuerType.DISABLE; } else if (type == QueuerType.DISABLE) { newType = QueuerType.ENABLE; } else if (type == QueuerType.TOGGLE_ENABLE) { newType = QueuerType.TOGGLE_DISABLE; } else if (type == QueuerType.TOGGLE_DISABLE) { newType = QueuerType.TOGGLE_ENABLE; } else { throw new IllegalStateException("Invalid queue type"); } // Queue a constant re-enable job with the same Type as original logger.i("Set repeating enable job %s starting at %d window %d", jobTag, reEnableTime, intervalUntilReEnable); intent.putExtra(BaseLongTermService.EXTRA_JOB_TYPE, type.name()); jobQueuerWrapper.setRepeating(intent, reEnableTime, intervalUntilReEnable); // Queue a constant re-disable job with the opposite type final Intent newIntent = getQueueIntent(appContext); logger.i("Set repeating disable job %s starting at %d window %d", jobTag, reDisableTime, intervalUntilReDisable); newIntent.putExtra(BaseLongTermService.EXTRA_JOB_TYPE, newType.name()); jobQueuerWrapper.setRepeating(newIntent, reDisableTime, intervalUntilReDisable); } @CheckResult @NonNull private Intent getQueueIntent(@NonNull Context context) { final Intent intent = getLongTermIntent(context); intent.putExtra(BaseLongTermService.EXTRA_IGNORE_CHARGING, ignoreCharging); return intent; } @CheckResult @NonNull abstract Intent getLongTermIntent(@NonNull Context context); }
Run rx short queuer only up to 1 minute
src/main/java/com/pyamsoft/powermanager/dagger/queuer/QueuerImpl.java
Run rx short queuer only up to 1 minute
<ide><path>rc/main/java/com/pyamsoft/powermanager/dagger/queuer/QueuerImpl.java <ide> <ide> abstract class QueuerImpl implements Queuer { <ide> <del> private static final long LARGEST_TIME_WITHOUT_ALARM = 120L; <add> private static final long LARGEST_TIME_WITHOUT_ALARM = 60L; <ide> @NonNull final Logger logger; <ide> @NonNull final BooleanInterestObserver stateObserver; <ide> @NonNull final BooleanInterestModifier stateModifier;
Java
lgpl-2.1
649bc6d7788d31a5c3c5ff27bd883734d555967a
0
cscenter/Arduino,ntruchsess/Arduino-1,niggor/Arduino_cc,vbextreme/Arduino,bsmr-arduino/Arduino,adamkh/Arduino,eddyst/Arduino-SourceCode,jmgonzalez00449/Arduino,vbextreme/Arduino,garci66/Arduino,KlaasDeNys/Arduino,eddyst/Arduino-SourceCode,wayoda/Arduino,Chris--A/Arduino,PeterVH/Arduino,ikbelkirasan/Arduino,nandojve/Arduino,wayoda/Arduino,NicoHood/Arduino,ikbelkirasan/Arduino,cscenter/Arduino,nandojve/Arduino,tbowmo/Arduino,eddyst/Arduino-SourceCode,bigjosh/Arduino,NaSymbol/Arduino,ccoenen/Arduino,vbextreme/Arduino,ari-analytics/Arduino,PaoloP74/Arduino,HCastano/Arduino,ikbelkirasan/Arduino,chaveiro/Arduino,superboonie/Arduino,KlaasDeNys/Arduino,byran/Arduino,kidswong999/Arduino,nandojve/Arduino,henningpohl/Arduino,talhaburak/Arduino,eddyst/Arduino-SourceCode,eddyst/Arduino-SourceCode,tomkrus007/Arduino,eggfly/arduino,shannonshsu/Arduino,NaSymbol/Arduino,KlaasDeNys/Arduino,jmgonzalez00449/Arduino,niggor/Arduino_cc,majenkotech/Arduino,tskurauskas/Arduino,talhaburak/Arduino,majenkotech/Arduino,zaiexx/Arduino,niggor/Arduino_cc,eddyst/Arduino-SourceCode,niggor/Arduino_cc,stickbreaker/Arduino,NaSymbol/Arduino,KlaasDeNys/Arduino,Gourav2906/Arduino,garci66/Arduino,talhaburak/Arduino,adamkh/Arduino,majenkotech/Arduino,kidswong999/Arduino,tskurauskas/Arduino,eggfly/arduino,jabezGit/Arduino,NicoHood/Arduino,henningpohl/Arduino,chaveiro/Arduino,me-no-dev/Arduino-1,acosinwork/Arduino,zaiexx/Arduino,Gourav2906/Arduino,jaimemaretoli/Arduino,nandojve/Arduino,NicoHood/Arduino,bsmr-arduino/Arduino,kidswong999/Arduino,wayoda/Arduino,superboonie/Arduino,stevemayhew/Arduino,jaimemaretoli/Arduino,PaoloP74/Arduino,xxxajk/Arduino-1,henningpohl/Arduino,byran/Arduino,NaSymbol/Arduino,jaimemaretoli/Arduino,tbowmo/Arduino,chaveiro/Arduino,jabezGit/Arduino,cscenter/Arduino,ThoughtWorksIoTGurgaon/Arduino,PeterVH/Arduino,majenkotech/Arduino,kidswong999/Arduino,xxxajk/Arduino-1,pdNor/Arduino,cscenter/Arduino,niggor/Arduino_cc,adamkh/Arduino,NicoHood/Arduino,me-no-dev/Arduino-1,garci66/Arduino,kidswong999/Arduino,tskurauskas/Arduino,byran/Arduino,tskurauskas/Arduino,shannonshsu/Arduino,majenkotech/Arduino,acosinwork/Arduino,ari-analytics/Arduino,me-no-dev/Arduino-1,NaSymbol/Arduino,ikbelkirasan/Arduino,nandojve/Arduino,tomkrus007/Arduino,garci66/Arduino,NicoHood/Arduino,Gourav2906/Arduino,Chris--A/Arduino,ThoughtWorksIoTGurgaon/Arduino,jmgonzalez00449/Arduino,jmgonzalez00449/Arduino,ikbelkirasan/Arduino,vbextreme/Arduino,superboonie/Arduino,HCastano/Arduino,KlaasDeNys/Arduino,PaoloP74/Arduino,xxxajk/Arduino-1,eggfly/arduino,ari-analytics/Arduino,chaveiro/Arduino,PaoloP74/Arduino,PaoloP74/Arduino,ccoenen/Arduino,shannonshsu/Arduino,HCastano/Arduino,chaveiro/Arduino,jabezGit/Arduino,zaiexx/Arduino,KlaasDeNys/Arduino,eggfly/arduino,bigjosh/Arduino,PeterVH/Arduino,NicoHood/Arduino,me-no-dev/Arduino-1,xxxajk/Arduino-1,eggfly/arduino,talhaburak/Arduino,shannonshsu/Arduino,ccoenen/Arduino,wayoda/Arduino,ikbelkirasan/Arduino,superboonie/Arduino,xxxajk/Arduino-1,HCastano/Arduino,stickbreaker/Arduino,pdNor/Arduino,bsmr-arduino/Arduino,lukeWal/Arduino,garci66/Arduino,chaveiro/Arduino,garci66/Arduino,stickbreaker/Arduino,PaoloP74/Arduino,stevemayhew/Arduino,HCastano/Arduino,jabezGit/Arduino,pdNor/Arduino,adamkh/Arduino,stevemayhew/Arduino,acosinwork/Arduino,tbowmo/Arduino,tbowmo/Arduino,acosinwork/Arduino,PaoloP74/Arduino,jmgonzalez00449/Arduino,me-no-dev/Arduino-1,stickbreaker/Arduino,ntruchsess/Arduino-1,Chris--A/Arduino,ntruchsess/Arduino-1,NaSymbol/Arduino,acosinwork/Arduino,PeterVH/Arduino,jmgonzalez00449/Arduino,Chris--A/Arduino,eddyst/Arduino-SourceCode,tbowmo/Arduino,Chris--A/Arduino,xxxajk/Arduino-1,jaimemaretoli/Arduino,pdNor/Arduino,stevemayhew/Arduino,tbowmo/Arduino,PeterVH/Arduino,jaimemaretoli/Arduino,ThoughtWorksIoTGurgaon/Arduino,stevemayhew/Arduino,henningpohl/Arduino,pdNor/Arduino,wayoda/Arduino,pdNor/Arduino,tbowmo/Arduino,stickbreaker/Arduino,eddyst/Arduino-SourceCode,shannonshsu/Arduino,jabezGit/Arduino,ntruchsess/Arduino-1,ari-analytics/Arduino,PaoloP74/Arduino,bigjosh/Arduino,tskurauskas/Arduino,niggor/Arduino_cc,bsmr-arduino/Arduino,NicoHood/Arduino,kidswong999/Arduino,Gourav2906/Arduino,bigjosh/Arduino,HCastano/Arduino,pdNor/Arduino,nandojve/Arduino,ntruchsess/Arduino-1,ThoughtWorksIoTGurgaon/Arduino,HCastano/Arduino,NaSymbol/Arduino,Chris--A/Arduino,superboonie/Arduino,henningpohl/Arduino,superboonie/Arduino,ari-analytics/Arduino,Chris--A/Arduino,cscenter/Arduino,ccoenen/Arduino,nandojve/Arduino,vbextreme/Arduino,tomkrus007/Arduino,eggfly/arduino,lukeWal/Arduino,me-no-dev/Arduino-1,tomkrus007/Arduino,adamkh/Arduino,superboonie/Arduino,henningpohl/Arduino,Gourav2906/Arduino,lukeWal/Arduino,bigjosh/Arduino,tbowmo/Arduino,Gourav2906/Arduino,bsmr-arduino/Arduino,KlaasDeNys/Arduino,ThoughtWorksIoTGurgaon/Arduino,niggor/Arduino_cc,zaiexx/Arduino,shannonshsu/Arduino,stickbreaker/Arduino,Chris--A/Arduino,ntruchsess/Arduino-1,majenkotech/Arduino,acosinwork/Arduino,bigjosh/Arduino,stickbreaker/Arduino,talhaburak/Arduino,byran/Arduino,superboonie/Arduino,lukeWal/Arduino,ari-analytics/Arduino,adamkh/Arduino,ThoughtWorksIoTGurgaon/Arduino,stevemayhew/Arduino,NicoHood/Arduino,PeterVH/Arduino,ccoenen/Arduino,ThoughtWorksIoTGurgaon/Arduino,zaiexx/Arduino,eggfly/arduino,niggor/Arduino_cc,byran/Arduino,bsmr-arduino/Arduino,bigjosh/Arduino,vbextreme/Arduino,talhaburak/Arduino,tomkrus007/Arduino,stevemayhew/Arduino,chaveiro/Arduino,Gourav2906/Arduino,wayoda/Arduino,majenkotech/Arduino,kidswong999/Arduino,Gourav2906/Arduino,ikbelkirasan/Arduino,lukeWal/Arduino,ccoenen/Arduino,ikbelkirasan/Arduino,xxxajk/Arduino-1,zaiexx/Arduino,shannonshsu/Arduino,ntruchsess/Arduino-1,ccoenen/Arduino,bsmr-arduino/Arduino,garci66/Arduino,henningpohl/Arduino,adamkh/Arduino,tomkrus007/Arduino,me-no-dev/Arduino-1,pdNor/Arduino,lukeWal/Arduino,nandojve/Arduino,me-no-dev/Arduino-1,chaveiro/Arduino,vbextreme/Arduino,bsmr-arduino/Arduino,byran/Arduino,lukeWal/Arduino,jaimemaretoli/Arduino,bigjosh/Arduino,jabezGit/Arduino,zaiexx/Arduino,lukeWal/Arduino,KlaasDeNys/Arduino,PeterVH/Arduino,tomkrus007/Arduino,jaimemaretoli/Arduino,cscenter/Arduino,ccoenen/Arduino,ThoughtWorksIoTGurgaon/Arduino,tskurauskas/Arduino,acosinwork/Arduino,cscenter/Arduino,ntruchsess/Arduino-1,vbextreme/Arduino,tskurauskas/Arduino,garci66/Arduino,shannonshsu/Arduino,tomkrus007/Arduino,stevemayhew/Arduino,byran/Arduino,jabezGit/Arduino,talhaburak/Arduino,NaSymbol/Arduino,byran/Arduino,jmgonzalez00449/Arduino,acosinwork/Arduino,cscenter/Arduino,ari-analytics/Arduino,xxxajk/Arduino-1,jabezGit/Arduino,jaimemaretoli/Arduino,adamkh/Arduino,jmgonzalez00449/Arduino,wayoda/Arduino,henningpohl/Arduino,eggfly/arduino,wayoda/Arduino,zaiexx/Arduino,tskurauskas/Arduino,niggor/Arduino_cc,PeterVH/Arduino,kidswong999/Arduino,HCastano/Arduino,ari-analytics/Arduino,talhaburak/Arduino
package processing.app.syntax; import org.fife.ui.rsyntaxtextarea.RSyntaxTextAreaDefaultInputMap; import org.fife.ui.rsyntaxtextarea.RSyntaxTextAreaEditorKit; import org.fife.ui.rtextarea.RTextArea; import org.fife.ui.rtextarea.RTextAreaEditorKit; import processing.app.PreferencesData; import javax.swing.*; import javax.swing.text.DefaultEditorKit; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; public class SketchTextAreaDefaultInputMap extends RSyntaxTextAreaDefaultInputMap { public SketchTextAreaDefaultInputMap() { int defaultModifier = getDefaultModifier(); int alt = InputEvent.ALT_MASK; int shift = InputEvent.SHIFT_MASK; boolean isOSX = RTextArea.isOSX(); int moveByWordMod = isOSX ? alt : defaultModifier; remove(KeyStroke.getKeyStroke(KeyEvent.VK_K, defaultModifier)); if (PreferencesData.getBoolean("editor.advanced")) { put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, alt), RTextAreaEditorKit.rtaLineDownAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, alt), RTextAreaEditorKit.rtaLineUpAction); } else { remove(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, alt)); remove(KeyStroke.getKeyStroke(KeyEvent.VK_UP, alt)); } remove(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, defaultModifier)); put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, moveByWordMod), RTextAreaEditorKit.rtaDeletePrevWordAction); if (isOSX) { put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, defaultModifier), SketchTextAreaEditorKit.rtaDeleteLineToCursorAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, defaultModifier), DefaultEditorKit.beginAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, defaultModifier), DefaultEditorKit.endAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, defaultModifier | shift), DefaultEditorKit.selectionBeginLineAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, defaultModifier | shift), DefaultEditorKit.selectionEndLineAction); remove(KeyStroke.getKeyStroke(KeyEvent.VK_J, defaultModifier)); put(KeyStroke.getKeyStroke(KeyEvent.VK_OPEN_BRACKET, defaultModifier), DefaultEditorKit.insertTabAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_CLOSE_BRACKET, defaultModifier), RSyntaxTextAreaEditorKit.rstaDecreaseIndentAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, defaultModifier | shift), DefaultEditorKit.selectionBeginAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, defaultModifier | shift), DefaultEditorKit.selectionEndAction); if (!PreferencesData.getBoolean("editor.keys.home_and_end_beginning_end_of_doc")) { put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0), DefaultEditorKit.beginLineAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_END, 0), DefaultEditorKit.endLineAction); } } put(KeyStroke.getKeyStroke(KeyEvent.VK_DIVIDE, defaultModifier), RSyntaxTextAreaEditorKit.rstaToggleCommentAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_LEFT, 0), DefaultEditorKit.backwardAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_RIGHT, 0), DefaultEditorKit.forwardAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_DOWN, 0), DefaultEditorKit.downAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_UP, 0), DefaultEditorKit.upAction); } }
app/src/processing/app/syntax/SketchTextAreaDefaultInputMap.java
package processing.app.syntax; import org.fife.ui.rsyntaxtextarea.RSyntaxTextAreaDefaultInputMap; import org.fife.ui.rsyntaxtextarea.RSyntaxTextAreaEditorKit; import org.fife.ui.rtextarea.RTextArea; import org.fife.ui.rtextarea.RTextAreaEditorKit; import processing.app.PreferencesData; import javax.swing.*; import javax.swing.text.DefaultEditorKit; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; public class SketchTextAreaDefaultInputMap extends RSyntaxTextAreaDefaultInputMap { public SketchTextAreaDefaultInputMap() { int defaultModifier = getDefaultModifier(); int alt = InputEvent.ALT_MASK; int shift = InputEvent.SHIFT_MASK; boolean isOSX = RTextArea.isOSX(); int moveByWordMod = isOSX ? alt : defaultModifier; remove(KeyStroke.getKeyStroke(KeyEvent.VK_K, defaultModifier)); if (PreferencesData.getBoolean("editor.advanced")) { put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, alt), RTextAreaEditorKit.rtaLineDownAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, alt), RTextAreaEditorKit.rtaLineUpAction); } else { remove(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, alt)); remove(KeyStroke.getKeyStroke(KeyEvent.VK_UP, alt)); } remove(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, defaultModifier)); put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, moveByWordMod), RTextAreaEditorKit.rtaDeletePrevWordAction); if (isOSX) { put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, defaultModifier), SketchTextAreaEditorKit.rtaDeleteLineToCursorAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, defaultModifier), DefaultEditorKit.beginAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, defaultModifier), DefaultEditorKit.endAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, defaultModifier | shift), DefaultEditorKit.selectionBeginLineAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, defaultModifier | shift), DefaultEditorKit.selectionEndLineAction); remove(KeyStroke.getKeyStroke(KeyEvent.VK_J, defaultModifier)); put(KeyStroke.getKeyStroke(KeyEvent.VK_OPEN_BRACKET, defaultModifier), DefaultEditorKit.insertTabAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_CLOSE_BRACKET, defaultModifier), RSyntaxTextAreaEditorKit.rstaDecreaseIndentAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, defaultModifier | shift), DefaultEditorKit.selectionBeginAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, defaultModifier | shift), DefaultEditorKit.selectionEndAction); if (PreferencesData.getBoolean("editor.keys.home_and_end_to_start_end_of_doc")) { put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0), DefaultEditorKit.beginLineAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_END, 0), DefaultEditorKit.endLineAction); } } put(KeyStroke.getKeyStroke(KeyEvent.VK_DIVIDE, defaultModifier), RSyntaxTextAreaEditorKit.rstaToggleCommentAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_LEFT, 0), DefaultEditorKit.backwardAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_RIGHT, 0), DefaultEditorKit.forwardAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_DOWN, 0), DefaultEditorKit.downAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_UP, 0), DefaultEditorKit.upAction); } }
MacOSX: Home/End key preference was coded backwards. Fixed. See #3715
app/src/processing/app/syntax/SketchTextAreaDefaultInputMap.java
MacOSX: Home/End key preference was coded backwards. Fixed. See #3715
<ide><path>pp/src/processing/app/syntax/SketchTextAreaDefaultInputMap.java <ide> put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, defaultModifier | shift), DefaultEditorKit.selectionBeginAction); <ide> put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, defaultModifier | shift), DefaultEditorKit.selectionEndAction); <ide> <del> if (PreferencesData.getBoolean("editor.keys.home_and_end_to_start_end_of_doc")) { <add> if (!PreferencesData.getBoolean("editor.keys.home_and_end_beginning_end_of_doc")) { <ide> put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0), DefaultEditorKit.beginLineAction); <ide> put(KeyStroke.getKeyStroke(KeyEvent.VK_END, 0), DefaultEditorKit.endLineAction); <ide> }
Java
apache-2.0
error: pathspec 'platform/util/src/com/intellij/util/indexing/impl/forward/MapForwardIndexAccessor.java' did not match any file(s) known to git
c6d66ff92131c7e53330e91048a4c9f9292bbf45
1
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.indexing.impl.forward; import com.intellij.util.indexing.impl.InputDataDiffBuilder; import com.intellij.util.indexing.impl.MapInputDataDiffBuilder; import com.intellij.util.io.DataExternalizer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Map; public class MapForwardIndexAccessor<Key, Value, Input> extends AbstractForwardIndexAccessor<Key, Value, Map<Key, Value>, Input> { public MapForwardIndexAccessor(@NotNull DataExternalizer<Map<Key, Value>> externalizer) { super(externalizer); } @Override protected InputDataDiffBuilder<Key, Value> createDiffBuilder(int inputId, @Nullable Map<Key, Value> inputData) { return new MapInputDataDiffBuilder<>(inputId, inputData); } @Override protected Map<Key, Value> convertToDataType(@Nullable Map<Key, Value> map, @Nullable Input content) { return map; } }
platform/util/src/com/intellij/util/indexing/impl/forward/MapForwardIndexAccessor.java
forward index accessor for key-value map
platform/util/src/com/intellij/util/indexing/impl/forward/MapForwardIndexAccessor.java
forward index accessor for key-value map
<ide><path>latform/util/src/com/intellij/util/indexing/impl/forward/MapForwardIndexAccessor.java <add>// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. <add>package com.intellij.util.indexing.impl.forward; <add> <add>import com.intellij.util.indexing.impl.InputDataDiffBuilder; <add>import com.intellij.util.indexing.impl.MapInputDataDiffBuilder; <add>import com.intellij.util.io.DataExternalizer; <add>import org.jetbrains.annotations.NotNull; <add>import org.jetbrains.annotations.Nullable; <add> <add>import java.util.Map; <add> <add>public class MapForwardIndexAccessor<Key, Value, Input> extends AbstractForwardIndexAccessor<Key, Value, Map<Key, Value>, Input> { <add> public MapForwardIndexAccessor(@NotNull DataExternalizer<Map<Key, Value>> externalizer) { <add> super(externalizer); <add> } <add> <add> @Override <add> protected InputDataDiffBuilder<Key, Value> createDiffBuilder(int inputId, @Nullable Map<Key, Value> inputData) { <add> return new MapInputDataDiffBuilder<>(inputId, inputData); <add> } <add> <add> @Override <add> protected Map<Key, Value> convertToDataType(@Nullable Map<Key, Value> map, @Nullable Input content) { <add> return map; <add> } <add>}
JavaScript
mit
2cb9b89853c1ac006f1e2ee45c0dede2af7ae893
0
Kueste-gegen-Plastik/replace-plastic-api,Kueste-gegen-Plastik/replace-plastic-api
var OpenGtinDB = require('opengtindb-client'), Barcoder = require('barcoder'), utf8 = require('utf8'); var searchProduct = function(bc, hook) { var result = { barcode : bc }; try { var eanDb = new OpenGtinDB(hook.app.settings.opengtindb); return eanDb.get(bc).then(res => { if(res.hasOwnProperty('error') && parseInt(res.error) == 0) { res.data[0].contents = res.data[0].contents.join(','); res.data[0].pack = res.data[0].pack.join(','); Object.assign(result, res.data[0]); } return hook.app.service('product').create(result).then(res => { if(typeof res.data === 'undefined') { return res; } var productsMapped = res.data.map(product => { return product.get({ plain: true }) }); return productsMapped; }); }); } catch(err) { return Promise.reject(err); } } module.exports = function(options) { return function(hook) { var bc = hook.id || undefined; if(typeof bc === 'undefined' || !Barcoder.validate(bc + '')) { throw new Error('Bitte geben Sie einen gültigen Barcode ein.'); } return hook.app.service('product').find({ query: { barcode: bc, $limit : 1, $select: ['id', 'barcode', 'name', 'detailname', 'maincat', 'descr', 'vendor'] }, plain: true, raw : true }).then(products => { // product already existant, add the product id to the payload if(products.hasOwnProperty('total') && products.total > 0) { var productsMapped = products.data.map(product => { return product.get({ plain: true }) }); hook.result = productsMapped; return Promise.resolve(hook); } else { // product not existant: query the gtindb return searchProduct(bc, hook).then(res => { hook.result = res.data; console.log("RES!", res); console.log("RESDATA!", res.data); Promise.resolve(hook); }); } }).catch(err => { throw new Error(err.message); }) }; };
src/services/product/hooks/handleEan.js
var OpenGtinDB = require('opengtindb-client'), Barcoder = require('barcoder'), utf8 = require('utf8'); var searchProduct = function(bc, hook) { var result = { barcode : bc }; try { var eanDb = new OpenGtinDB(hook.app.settings.opengtindb); return eanDb.get(bc).then(res => { if(res.hasOwnProperty('error') && parseInt(res.error) == 0) { res.data[0].contents = res.data[0].contents.join(','); res.data[0].pack = res.data[0].pack.join(','); Object.assign(result, res.data[0]); } return hook.app.service('product').create(result).then(res => { var productsMapped = res.data.map(product => { return product.get({ plain: true }) }); return productsMapped; }); }); } catch(err) { return Promise.reject(err); } } module.exports = function(options) { return function(hook) { var bc = hook.id || undefined; if(typeof bc === 'undefined' || !Barcoder.validate(bc + '')) { throw new Error('Bitte geben Sie einen gültigen Barcode ein.'); } return hook.app.service('product').find({ query: { barcode: bc, $limit : 1, $select: ['id', 'barcode', 'name', 'detailname', 'maincat', 'descr', 'vendor'] }, plain: true, raw : true }).then(products => { // product already existant, add the product id to the payload if(products.hasOwnProperty('total') && products.total > 0) { var productsMapped = products.data.map(product => { return product.get({ plain: true }) }); hook.result = productsMapped; return Promise.resolve(hook); } else { // product not existant: query the gtindb return searchProduct(bc, hook).then(res => { hook.result = res.data; console.log("RES!", res); console.log("RESDATA!", res.data); Promise.resolve(hook); }); } }).catch(err => { throw new Error(err.message); }) }; };
Bugfixes
src/services/product/hooks/handleEan.js
Bugfixes
<ide><path>rc/services/product/hooks/handleEan.js <ide> Object.assign(result, res.data[0]); <ide> } <ide> return hook.app.service('product').create(result).then(res => { <add> if(typeof res.data === 'undefined') { <add> return res; <add> } <ide> var productsMapped = res.data.map(product => { <ide> return product.get({ plain: true }) <ide> });
Java
apache-2.0
087fb9351f323a0f74086d96f978175d56430f8b
0
eisnerd/mupeace,eisnerd/mupeace,eisnerd/mupeace
package org.musicpd.android.fragments; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collections; import org.a0z.mpd.Item; import org.a0z.mpd.exception.MPDServerException; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import org.xmlpull.v1.XmlSerializer; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import android.text.TextUtils; import android.util.Xml; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager.BadTokenException; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.EditText; import android.widget.ListView; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import org.musicpd.android.R; import org.musicpd.android.tools.Log; import org.musicpd.android.tools.StreamFetcher; import org.musicpd.android.tools.Tools; public class StreamsFragment extends BrowseFragment { ArrayList<Stream> streams = null; private static class Stream extends Item { private String name = null; private String url = null; public Stream(String name, String url) { this.name = name; this.url = url; } @Override public String getName() { return name; } public String getUrl() { return url; } } public static final int EDIT = 101; public static final int DELETE = 102; private static final String FILE_NAME = "streams.xml"; private void loadStreams(Activity activity) { streams = new ArrayList<Stream>(); try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(activity.openFileInput(FILE_NAME), "UTF-8"); int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (xpp.getName().equals("stream")) { streams.add(new Stream(xpp.getAttributeValue("", "name"), xpp.getAttributeValue("", "url"))); } } eventType = xpp.next(); } } catch (Exception e) { Log.w(e); } Collections.sort(streams); items = streams; } private void saveStreams(Activity activity) { XmlSerializer serializer = Xml.newSerializer(); try { serializer.setOutput(activity.openFileOutput(FILE_NAME, Context.MODE_PRIVATE), "UTF-8"); serializer.startDocument("UTF-8", true); serializer.startTag("", "streams"); if (null != streams) { for (Stream s : streams) { serializer.startTag("", "stream"); serializer.attribute("", "name", s.getName()); serializer.attribute("", "url", s.getUrl()); serializer.endTag("", "stream"); } } serializer.endTag("", "streams"); serializer.flush(); } catch (Exception e) { Log.w(e); } } public StreamsFragment() { super(R.string.addStream, R.string.streamAdded, null); } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return super.onCreateView(inflater, container, savedInstanceState); } @Override public int getLoadingText() { return R.string.loadingStreams; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); registerForContextMenu(list); UpdateList(); getActivity().setTitle(getResources().getString(R.string.streams)); } @Override public void onItemClick(AdapterView adapterView, View v, int position, long id) { } @Override protected void asyncUpdate() { loadStreams(getActivity()); } @Override protected void add(Item item, boolean replace, boolean play) { try { final Stream s = (Stream) item; app.oMPDAsyncHelper.oMPD.add(StreamFetcher.instance().get(s.getUrl(), s.getName()), replace, play); Tools.notifyUser(String.format(getResources().getString(irAdded), item), getActivity()); } catch (Exception e) { Log.w(e); } } @Override protected void add(Item item, String playlist) { } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); android.view.MenuItem editItem = menu.add(ContextMenu.NONE, EDIT, 0, R.string.editStream); editItem.setOnMenuItemClickListener(this); android.view.MenuItem addAndReplaceItem = menu.add(ContextMenu.NONE, DELETE, 0, R.string.deleteStream); addAndReplaceItem.setOnMenuItemClickListener(this); } @Override public boolean onMenuItemClick(android.view.MenuItem item) { final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { case EDIT: addEdit((int) info.id); break; case DELETE: final Activity activity = getActivity(); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(getResources().getString(R.string.deleteStream)); builder.setMessage(String.format(getResources().getString(R.string.deleteStreamPrompt), items.get((int) info.id).getName())); DeleteDialogClickListener oDialogClickListener = new DeleteDialogClickListener((int) info.id, activity); builder.setNegativeButton(getResources().getString(android.R.string.no), oDialogClickListener); builder.setPositiveButton(getResources().getString(R.string.deleteStream), oDialogClickListener); try { builder.show(); } catch (BadTokenException e) { // Can't display it. Don't care. } break; default: return super.onMenuItemClick(item); } return false; } class DeleteDialogClickListener implements OnClickListener { private final int itemIndex; private final Activity activity; DeleteDialogClickListener(int itemIndex, Activity activity) { this.itemIndex = itemIndex; this.activity = activity; } public void onClick(DialogInterface dialog, int which) { switch (which) { case AlertDialog.BUTTON_NEGATIVE: break; case AlertDialog.BUTTON_POSITIVE: String name = items.get(itemIndex).getName(); try { Tools.notifyUser(String.format(getResources().getString(R.string.streamDeleted), name), getActivity()); } catch (Exception e) { Log.w(e); } items.remove(itemIndex); saveStreams(activity); UpdateList(); break; } } } public void addStream(String name, String url, int index, Activity activity) { if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(url)) { if (streams == null) loadStreams(activity); if (index >= 0 && index < streams.size()) { streams.remove(index); } streams.add(new Stream(name, url)); Collections.sort(streams); items = streams; saveStreams(activity); UpdateList(); } } private void addEdit() { addEdit(-1); } private void addEdit(int idx) { LayoutInflater factory = LayoutInflater.from(getActivity()); final View view = factory.inflate(R.layout.stream_dialog, null); final int index = idx; if (index >= 0 && index < streams.size()) { Stream s = streams.get(idx); EditText nameEdit = (EditText) view.findViewById(R.id.name_edit); EditText urlEdit = (EditText) view.findViewById(R.id.url_edit); if (null != nameEdit) { nameEdit.setText(s.getName()); } if (null != urlEdit) { urlEdit.setText(s.getUrl()); } } final Activity activity = getActivity(); new AlertDialog.Builder(activity) .setTitle(idx < 0 ? R.string.addStream : R.string.editStream) .setMessage(R.string.streamDetails) .setView(view) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { EditText nameEdit = (EditText) view.findViewById(R.id.name_edit); EditText urlEdit = (EditText) view.findViewById(R.id.url_edit); String name = null == nameEdit ? null : nameEdit.getText().toString().trim(); String url = null == urlEdit ? null : urlEdit.getText().toString().trim(); addStream(name, url, index, activity); } }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Do nothing. } }).show(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.mpd_streamsmenu, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.add: addEdit(); return true; default: return false; } } }
main/src/org/musicpd/android/fragments/StreamsFragment.java
package org.musicpd.android.fragments; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collections; import org.a0z.mpd.Item; import org.a0z.mpd.exception.MPDServerException; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import org.xmlpull.v1.XmlSerializer; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import android.text.TextUtils; import android.util.Xml; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager.BadTokenException; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.EditText; import android.widget.ListView; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import org.musicpd.android.R; import org.musicpd.android.tools.Log; import org.musicpd.android.tools.StreamFetcher; import org.musicpd.android.tools.Tools; public class StreamsFragment extends BrowseFragment { ArrayList<Stream> streams = null; private static class Stream extends Item { private String name = null; private String url = null; public Stream(String name, String url) { this.name = name; this.url = url; } @Override public String getName() { return name; } public String getUrl() { return url; } } public static final int EDIT = 101; public static final int DELETE = 102; private static final String FILE_NAME = "streams.xml"; private void loadStreams(Activity activity) { streams = new ArrayList<Stream>(); try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(activity.openFileInput(FILE_NAME), "UTF-8"); int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (xpp.getName().equals("stream")) { streams.add(new Stream(xpp.getAttributeValue("", "name"), xpp.getAttributeValue("", "url"))); } } eventType = xpp.next(); } } catch (Exception e) { Log.w(e); } Collections.sort(streams); items = streams; } private void saveStreams(Activity activity) { XmlSerializer serializer = Xml.newSerializer(); try { serializer.setOutput(activity.openFileOutput(FILE_NAME, Context.MODE_PRIVATE), "UTF-8"); serializer.startDocument("UTF-8", true); serializer.startTag("", "streams"); if (null != streams) { for (Stream s : streams) { serializer.startTag("", "stream"); serializer.attribute("", "name", s.getName()); serializer.attribute("", "url", s.getUrl()); serializer.endTag("", "stream"); } } serializer.endTag("", "streams"); serializer.flush(); } catch (Exception e) { Log.w(e); } } public StreamsFragment() { super(R.string.addStream, R.string.streamAdded, null); } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return super.onCreateView(inflater, container, savedInstanceState); } @Override public int getLoadingText() { return R.string.loadingStreams; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); registerForContextMenu(list); UpdateList(); getActivity().setTitle(getResources().getString(R.string.streams)); } @Override public void onItemClick(AdapterView adapterView, View v, int position, long id) { } @Override protected void asyncUpdate() { loadStreams(getActivity()); } @Override protected void add(Item item, boolean replace, boolean play) { try { final Stream s = (Stream) item; app.oMPDAsyncHelper.oMPD.add(StreamFetcher.instance().get(s.getUrl(), s.getName()), replace, play); Tools.notifyUser(String.format(getResources().getString(irAdded), item), getActivity()); } catch (Exception e) { Log.w(e); } } @Override protected void add(Item item, String playlist) { } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); android.view.MenuItem editItem = menu.add(ContextMenu.NONE, EDIT, 0, R.string.editStream); editItem.setOnMenuItemClickListener(this); android.view.MenuItem addAndReplaceItem = menu.add(ContextMenu.NONE, DELETE, 0, R.string.deleteStream); addAndReplaceItem.setOnMenuItemClickListener(this); } @Override public boolean onMenuItemClick(android.view.MenuItem item) { final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { case EDIT: addEdit((int) info.id); break; case DELETE: AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(getResources().getString(R.string.deleteStream)); builder.setMessage(String.format(getResources().getString(R.string.deleteStreamPrompt), items.get((int) info.id).getName())); DeleteDialogClickListener oDialogClickListener = new DeleteDialogClickListener((int) info.id); builder.setNegativeButton(getResources().getString(android.R.string.no), oDialogClickListener); builder.setPositiveButton(getResources().getString(R.string.deleteStream), oDialogClickListener); try { builder.show(); } catch (BadTokenException e) { // Can't display it. Don't care. } break; default: return super.onMenuItemClick(item); } return false; } class DeleteDialogClickListener implements OnClickListener { private final int itemIndex; DeleteDialogClickListener(int itemIndex) { this.itemIndex = itemIndex; } public void onClick(DialogInterface dialog, int which) { switch (which) { case AlertDialog.BUTTON_NEGATIVE: break; case AlertDialog.BUTTON_POSITIVE: String name = items.get(itemIndex).getName(); try { Tools.notifyUser(String.format(getResources().getString(R.string.streamDeleted), name), getActivity()); } catch (Exception e) { Log.w(e); } items.remove(itemIndex); updateFromItems(); break; } } } public void addStream(String name, String url, int index, Activity activity) { if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(url)) { if (streams == null) loadStreams(activity); if (index >= 0 && index < streams.size()) { streams.remove(index); } streams.add(new Stream(name, url)); Collections.sort(streams); items = streams; saveStreams(activity); UpdateList(); } } private void addEdit() { addEdit(-1); } private void addEdit(int idx) { LayoutInflater factory = LayoutInflater.from(getActivity()); final View view = factory.inflate(R.layout.stream_dialog, null); final int index = idx; if (index >= 0 && index < streams.size()) { Stream s = streams.get(idx); EditText nameEdit = (EditText) view.findViewById(R.id.name_edit); EditText urlEdit = (EditText) view.findViewById(R.id.url_edit); if (null != nameEdit) { nameEdit.setText(s.getName()); } if (null != urlEdit) { urlEdit.setText(s.getUrl()); } } final Activity activity = getActivity(); new AlertDialog.Builder(activity) .setTitle(idx < 0 ? R.string.addStream : R.string.editStream) .setMessage(R.string.streamDetails) .setView(view) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { EditText nameEdit = (EditText) view.findViewById(R.id.name_edit); EditText urlEdit = (EditText) view.findViewById(R.id.url_edit); String name = null == nameEdit ? null : nameEdit.getText().toString().trim(); String url = null == urlEdit ? null : urlEdit.getText().toString().trim(); addStream(name, url, index, activity); } }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Do nothing. } }).show(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.mpd_streamsmenu, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.add: addEdit(); return true; default: return false; } } }
Save streams list after deletes Fixes #4
main/src/org/musicpd/android/fragments/StreamsFragment.java
Save streams list after deletes
<ide><path>ain/src/org/musicpd/android/fragments/StreamsFragment.java <ide> addEdit((int) info.id); <ide> break; <ide> case DELETE: <add> final Activity activity = getActivity(); <ide> AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); <ide> builder.setTitle(getResources().getString(R.string.deleteStream)); <ide> builder.setMessage(String.format(getResources().getString(R.string.deleteStreamPrompt), items.get((int) info.id).getName())); <ide> <del> DeleteDialogClickListener oDialogClickListener = new DeleteDialogClickListener((int) info.id); <add> DeleteDialogClickListener oDialogClickListener = new DeleteDialogClickListener((int) info.id, activity); <ide> builder.setNegativeButton(getResources().getString(android.R.string.no), oDialogClickListener); <ide> builder.setPositiveButton(getResources().getString(R.string.deleteStream), oDialogClickListener); <ide> try { <ide> <ide> class DeleteDialogClickListener implements OnClickListener { <ide> private final int itemIndex; <del> <del> DeleteDialogClickListener(int itemIndex) { <add> private final Activity activity; <add> <add> <add> DeleteDialogClickListener(int itemIndex, Activity activity) { <ide> this.itemIndex = itemIndex; <add> this.activity = activity; <ide> } <ide> <ide> public void onClick(DialogInterface dialog, int which) { <ide> Log.w(e); <ide> } <ide> items.remove(itemIndex); <del> updateFromItems(); <add> saveStreams(activity); <add> UpdateList(); <ide> break; <ide> } <ide> }
Java
apache-2.0
2586a55e5da8a64ed8402ff86ae04c7ed1e5f2b7
0
Pastor/modules,Pastor/modules,Pastor/modules,Pastor/modules
package ru.phi.modules.security; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import ru.phi.modules.entity.Token; import ru.phi.modules.entity.UserRole; import ru.phi.modules.exceptions.AccessScopeException; import ru.phi.modules.repository.TokenRepository; import java.util.Optional; import java.util.Set; import static java.text.MessageFormat.format; @SuppressWarnings("unused") @Aspect @Component final class AuthorizedScopeMonitor { @Autowired private TokenRepository repository; @Transactional @Around("execution(@ru.phi.modules.security.AuthorizedScope * *.*(..)) && @annotation(scope)") public Object scoped(ProceedingJoinPoint point, AuthorizedScope scope) throws Throwable { final Optional<Token> token = SecurityUtilities.currentToken(); if (token.isPresent()) { final Token one = repository.findOne(token.get().getId()); final Set<ru.phi.modules.entity.Scope> scopes = one.getScopes(); for (String s : scope.scopes()) { final ru.phi.modules.entity.Scope ss = new ru.phi.modules.entity.Scope(); ss.setName(s.toLowerCase()); boolean found = false; for (UserRole scopeRole : scope.roles()) { ss.setRole(scopeRole); if (scopes.contains(ss)) { found = true; break; } } if (!found) throw new AccessScopeException(format("Область доступа \"{0}\" в ключе не зарегистрирована", s.toLowerCase())); } } else { throw new AccessScopeException("Ключ доступ не установлен"); } return point.proceed(); } }
rest-api/src/main/java/ru/phi/modules/security/AuthorizedScopeMonitor.java
package ru.phi.modules.security; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import ru.phi.modules.entity.Token; import ru.phi.modules.entity.UserRole; import ru.phi.modules.exceptions.AccessScopeException; import ru.phi.modules.repository.TokenRepository; import java.util.Optional; import java.util.Set; import static java.text.MessageFormat.format; @SuppressWarnings("unused") @Aspect @Component final class AuthorizedScopeMonitor { @Autowired private TokenRepository repository; @Transactional @Around("execution(@ru.phi.modules.security.AuthorizedScope * *.*(..)) && @annotation(scope)") public Object scoped(ProceedingJoinPoint point, AuthorizedScope scope) throws Throwable { final Optional<Token> token = SecurityUtilities.currentToken(); if (token.isPresent()) { final Token one = repository.findOne(token.get().getId()); final UserRole role = one.getUser().getRole(); final Set<ru.phi.modules.entity.Scope> scopes = one.getScopes(); for (String s : scope.scopes()) { final ru.phi.modules.entity.Scope ss = new ru.phi.modules.entity.Scope(); ss.setName(s.toLowerCase()); //FIXME: Проверяется искуственно. Необходимо в параметр annotation добавть поле ролей, к которым она относится ss.setRole(role); if (!scopes.contains(ss)) throw new AccessScopeException(format("Область доступа \"{0}\" в ключе не зарегистрирована", s.toLowerCase())); } } else { throw new AccessScopeException("Ключ доступ не установлен"); } return point.proceed(); } }
Исправления областей доступа
rest-api/src/main/java/ru/phi/modules/security/AuthorizedScopeMonitor.java
Исправления областей доступа
<ide><path>est-api/src/main/java/ru/phi/modules/security/AuthorizedScopeMonitor.java <ide> final Optional<Token> token = SecurityUtilities.currentToken(); <ide> if (token.isPresent()) { <ide> final Token one = repository.findOne(token.get().getId()); <del> final UserRole role = one.getUser().getRole(); <ide> final Set<ru.phi.modules.entity.Scope> scopes = one.getScopes(); <ide> for (String s : scope.scopes()) { <ide> final ru.phi.modules.entity.Scope ss = new ru.phi.modules.entity.Scope(); <ide> ss.setName(s.toLowerCase()); <del> //FIXME: Проверяется искуственно. Необходимо в параметр annotation добавть поле ролей, к которым она относится <del> ss.setRole(role); <del> if (!scopes.contains(ss)) <add> boolean found = false; <add> for (UserRole scopeRole : scope.roles()) { <add> ss.setRole(scopeRole); <add> if (scopes.contains(ss)) { <add> found = true; <add> break; <add> } <add> } <add> if (!found) <ide> throw new AccessScopeException(format("Область доступа \"{0}\" в ключе не зарегистрирована", s.toLowerCase())); <ide> } <ide> } else {
JavaScript
mit
5ab107b5fa414f91d1444ed661f84612c3d3a7fc
0
CodeForCharlotte/cmpd-holiday-gift-backend,CodeForCharlotte/CMPD-Holiday-Gift,CodeForCharlotte/CMPD-Holiday-Gift,CodeForCharlotte/cmpd-holiday-gift-backend,CodeForCharlotte/CMPD-Holiday-Gift,CodeForCharlotte/CMPD-Holiday-Gift,CodeForCharlotte/cmpd-holiday-gift-backend
// @flow import * as React from 'react'; import HouseholdForm from './form/head-of-household'; import AddressForm from './form/address'; import PhoneNumbers from './form/phone-numbers'; import ChildForm from './form/child'; import { Row, Col, Button } from 'react-bootstrap'; import { Form } from 'neoform'; import { FormValidation } from 'neoform-validation'; import Files from './form/files'; const Household = ({ onSubmit, onInvalid, onSaveDraft, onUpdate, validate, data, addChild, removeChild, affiliations, onFileChange, onAddressChange, saved }) => { return ( <form onSubmit={e => { e.preventDefault(); validate(data.household && data.household.id ? onUpdate : onSaveDraft, onInvalid); }}> <HouseholdForm /> <AddressForm onChange={onAddressChange}/> <PhoneNumbers /> <ChildForm nominations={data.nominations} addChild={addChild} removeChild={removeChild} affiliations={affiliations} /> {(saved || data.household.id) && <Files files={data.files} onChange={onFileChange} />} <Row> <Col xs={12}> <Button type="submit">{data.household && data.household.id ? 'Update' : 'Save Draft'}</Button> {saved && <Button onClick={onSubmit}>Submit Nomination</Button>} </Col> </Row> </form> ); }; export default Form(FormValidation(Household));
src/app/dashboard/household/components/household-form.js
// @flow import * as React from 'react'; import HouseholdForm from './form/head-of-household'; import AddressForm from './form/address'; import PhoneNumbers from './form/phone-numbers'; import ChildForm from './form/child'; import { Row, Col, Button } from 'react-bootstrap'; import { Form } from 'neoform'; import { FormValidation } from 'neoform-validation'; import Files from './form/files'; const Household = ({ onSubmit, onInvalid, onSaveDraft, onUpdate, validate, data, addChild, removeChild, affiliations, onFileChange, onAddressChange, saved }) => { return ( <form onSubmit={e => { e.preventDefault(); validate(onSaveDraft, onInvalid); }}> <HouseholdForm /> <AddressForm onChange={onAddressChange}/> <PhoneNumbers /> <ChildForm nominations={data.nominations} addChild={addChild} removeChild={removeChild} affiliations={affiliations} /> {(saved || data.household.id) && <Files files={data.files} onChange={onFileChange} />} <Row> <Col xs={12}> <Button type="submit">{data.household && data.household.id ? 'Update' : 'Save Draft'}</Button> {saved && <Button onClick={onSubmit}>Submit Nomination</Button>} </Col> </Row> </form> ); }; export default Form(FormValidation(Household));
fix edits
src/app/dashboard/household/components/household-form.js
fix edits
<ide><path>rc/app/dashboard/household/components/household-form.js <ide> <form <ide> onSubmit={e => { <ide> e.preventDefault(); <del> validate(onSaveDraft, onInvalid); <add> <add> validate(data.household && data.household.id ? onUpdate : onSaveDraft, onInvalid); <ide> <ide> }}> <ide> <HouseholdForm />
Java
apache-2.0
c78733861f1dbcf272d3b8f6a74eb55d5fbf3972
0
BURAI-team/burai
/* * Copyright (C) 2016 Satomichi Nishihara * * This file is distributed under the terms of the * GNU General Public License. See the file `LICENSE' * in the root directory of the present distribution, * or http://www.gnu.org/copyleft/gpl.txt . */ package burai.app; import java.io.File; import java.net.URL; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.Queue; import java.util.ResourceBundle; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Rectangle2D; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TextField; import javafx.scene.control.Tooltip; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyCode; import javafx.scene.input.TransferMode; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.web.WebEngine; import javafx.stage.Screen; import javafx.stage.Stage; import javafx.stage.WindowEvent; import burai.app.about.QEFXAboutDialog; import burai.app.explorer.QEFXExplorer; import burai.app.explorer.QEFXExplorerFacade; import burai.app.icon.QEFXIcon; import burai.app.icon.QEFXProjectIcon; import burai.app.icon.QEFXWebIcon; import burai.app.matapi.QEFXMatAPIDialog; import burai.app.onclose.QEFXSavingDialog; import burai.app.proxy.QEFXProxyDialog; import burai.app.tab.QEFXTabManager; import burai.com.env.Environments; import burai.com.graphic.svg.SVGLibrary; import burai.com.graphic.svg.SVGLibrary.SVGData; import burai.com.life.Life; import burai.matapi.MaterialsAPILoader; import burai.project.Project; import burai.run.RunningManager; import burai.ver.Version; public class QEFXMainController implements Initializable { private static final long SLEEP_TIME_TO_DROP_FILES = 650L; private static final double TOPMENU_GRAPHIC_SIZE = 16.0; private static final String TOPMENU_GRAPHIC_CLASS = "picblack-button"; private static final double HOME_GRAPHIC_SIZE = 20.0; private static final String HOME_GRAPHIC_CLASS = "pichome-button"; private static final double SEARCH_GRAPHIC_SIZE = 14.0; private static final String SEARCH_GRAPHIC_CLASS = "picblack-button"; private Stage stage; private QEFXTabManager tabManager; private QEFXExplorerFacade explorerFacade; private Queue<HomeTabSelected> onHomeTabSelectedQueue; @FXML private BorderPane basePane; @FXML private Menu topMenu; @FXML private MenuItem aboutMItem; @FXML private MenuItem docsMItem; @FXML private MenuItem qeMItem; @FXML private MenuItem pseudoMItem; @FXML private MenuItem manPwMItem; @FXML private MenuItem manDosMItem; @FXML private MenuItem manProjMItem; @FXML private MenuItem manBandMItem; @FXML private MenuItem proxyMItem; @FXML private MenuItem fullScrMItem; @FXML private MenuItem quitMItem; @FXML private TabPane tabPane; @FXML private Tab homeTab; @FXML private AnchorPane homePane; @FXML private Button matApiButton; @FXML private TextField matApiField; public QEFXMainController() { this.stage = null; this.tabManager = null; this.explorerFacade = null; this.onHomeTabSelectedQueue = null; } @Override public void initialize(URL location, ResourceBundle resources) { this.setupBasePane(); this.setupTopMenu(); this.setupMenuItems(); this.setupTabPane(); this.setupHomeTab(); this.setupMatApiButton(); this.setupMatApiField(); } private void setupBasePane() { if (this.basePane == null) { return; } this.basePane.setOnDragOver(event -> { Dragboard board = event == null ? null : event.getDragboard(); if (board == null) { return; } if (board.hasFiles()) { event.acceptTransferModes(TransferMode.COPY); } }); this.basePane.setOnDragDropped(event -> { Dragboard board = event == null ? null : event.getDragboard(); if (board == null) { return; } if (!board.hasFiles()) { event.setDropCompleted(false); return; } List<File> files = board.getFiles(); if (files != null) { Thread thread = new Thread(() -> { for (File file : files) { this.showDroppedFile(file); synchronized (files) { try { files.wait(SLEEP_TIME_TO_DROP_FILES); } catch (Exception e) { e.printStackTrace(); } } } }); thread.start(); } event.setDropCompleted(true); }); } private void showDroppedFile(File file) { QEFXIcon icon = file == null ? null : QEFXIcon.getInstance(file); if (icon == null) { return; } Platform.runLater(() -> { if (icon != null && icon instanceof QEFXProjectIcon) { Project project = ((QEFXProjectIcon) icon).getContent(); if (project != null) { this.showProject(project); } } else if (icon != null && icon instanceof QEFXWebIcon) { String url = ((QEFXWebIcon) icon).getInitialURL(); if (url != null && !(url.trim().isEmpty())) { this.showWebPage(url); } } }); } private void setupTopMenu() { if (this.topMenu == null) { return; } this.topMenu.setText(""); this.topMenu.setGraphic( SVGLibrary.getGraphic(SVGData.VECTOR_RIGHT, TOPMENU_GRAPHIC_SIZE, null, TOPMENU_GRAPHIC_CLASS)); this.topMenu.showingProperty().addListener(o -> { if (this.topMenu.isShowing()) { this.topMenu.setGraphic(SVGLibrary.getGraphic( SVGData.VECTOR_DOWN, TOPMENU_GRAPHIC_SIZE, null, TOPMENU_GRAPHIC_CLASS)); } else { this.topMenu.setGraphic(SVGLibrary.getGraphic( SVGData.VECTOR_RIGHT, TOPMENU_GRAPHIC_SIZE, null, TOPMENU_GRAPHIC_CLASS)); } }); } private void setupMenuItems() { if (this.aboutMItem != null) { this.aboutMItem.setOnAction(event -> { QEFXAboutDialog dialog = new QEFXAboutDialog(); dialog.showAndWait(); }); } if (this.docsMItem != null) { this.docsMItem.setOnAction(event -> { this.showWebPage(Environments.getDocumentsWebsite()); }); } if (this.qeMItem != null) { this.qeMItem.setOnAction(event -> { this.showWebPage(Environments.getEspressoWebsite()); }); } if (this.pseudoMItem != null) { this.pseudoMItem.setOnAction(event -> { this.showWebPage(Environments.getPseudoWebsite()); }); } if (this.manPwMItem != null) { this.manPwMItem.setOnAction(event -> { this.showWebPage(Environments.getManPwscfWebsite()); }); } if (this.manDosMItem != null) { this.manDosMItem.setOnAction(event -> { this.showWebPage(Environments.getManDosWebsite()); }); } if (this.manProjMItem != null) { this.manProjMItem.setOnAction(event -> { this.showWebPage(Environments.getManProjwfcWebsite()); }); } if (this.manBandMItem != null) { this.manBandMItem.setOnAction(event -> { this.showWebPage(Environments.getManBandsWebsite()); }); } if (this.proxyMItem != null) { this.proxyMItem.setOnAction(event -> { QEFXProxyDialog dialog = new QEFXProxyDialog(); dialog.showAndSetProperties(); }); } if (this.fullScrMItem != null) { this.fullScrMItem.setOnAction(event -> { if (this.stage != null && this.stage.isFullScreen()) { this.setFullScreen(false); } else { this.setFullScreen(true); } }); } if (this.quitMItem != null) { this.quitMItem.setOnAction(event -> { this.quitSystem(); }); } } private void setupTabPane() { if (this.tabPane == null) { return; } this.tabManager = new QEFXTabManager(this, this.tabPane); } private void setupHomeTab() { if (this.homeTab == null) { return; } this.homeTab.setText(""); this.homeTab.setGraphic( SVGLibrary.getGraphic(SVGData.HOME, HOME_GRAPHIC_SIZE, null, HOME_GRAPHIC_CLASS)); this.homeTab.setClosable(false); this.homeTab.setTooltip(new Tooltip("home")); this.homeTab.setOnSelectionChanged(event -> { if (this.homeTab.isSelected()) { this.executeOnHomeTabSelected(); } }); } private void executeOnHomeTabSelected() { if (this.onHomeTabSelectedQueue == null) { return; } if (this.explorerFacade != null) { this.explorerFacade.startSingleReloadMode(); } while (!this.onHomeTabSelectedQueue.isEmpty()) { HomeTabSelected onHomeTabSelected = this.onHomeTabSelectedQueue.poll(); if (onHomeTabSelected != null && this.explorerFacade != null) { onHomeTabSelected.onHomeTabSelected(this.explorerFacade); } } if (this.explorerFacade != null) { this.explorerFacade.endSingleReloadMode(); } } private void setupMatApiButton() { if (this.matApiButton == null) { return; } this.matApiButton.setGraphic( SVGLibrary.getGraphic(SVGData.SEARCH, SEARCH_GRAPHIC_SIZE, null, SEARCH_GRAPHIC_CLASS)); this.matApiButton.setOnAction(event -> { QEFXMatAPIDialog dialog = new QEFXMatAPIDialog(); dialog.showAndSetProperties(); }); } private void setupMatApiField() { if (this.matApiField == null) { return; } String messageTip = ""; messageTip = messageTip + "1) Li-Fe-O" + System.lineSeparator(); messageTip = messageTip + "2) Fe2O3"; this.matApiField.setTooltip(new Tooltip(messageTip)); this.matApiField.setOnAction(event -> { String text = this.matApiField.getText(); text = text == null ? null : text.trim(); if (text == null || text.isEmpty()) { MaterialsAPILoader.deleteLoader(); return; } MaterialsAPILoader matApiLoader = new MaterialsAPILoader(text); if (matApiLoader.numMaterialIDs() > 0) { this.matApiField.setText(matApiLoader.getFormula()); if (this.explorerFacade != null) { this.explorerFacade.setMaterialsAPILoader(matApiLoader); this.explorerFacade.setSearchedMode(); this.showHome(); } } else { String message = "The Materials API says there are no data of " + matApiLoader.getFormula() + "."; Alert alert = new Alert(AlertType.ERROR); QEFXMain.initializeDialogOwner(alert); alert.setHeaderText(message); alert.showAndWait(); } }); } public Stage getStage() { return this.stage; } protected void setStage(Stage stage) { this.stage = stage; if (this.stage == null) { return; } Rectangle2D rectangle2d = Screen.getPrimary().getVisualBounds(); double width = rectangle2d.getWidth(); double height = rectangle2d.getHeight(); this.stage.setWidth(width); this.stage.setHeight(height); this.stage.setTitle("BURAI" + Version.VERSION + ", a GUI of Quantum ESPRESSO."); this.stage.setOnCloseRequest(event -> this.actionOnCloseRequest(event)); this.stage.setOnHidden(event -> this.actionOnHidden(event)); Scene scene = this.stage.getScene(); if (scene != null) { scene.setOnKeyPressed(event -> { if (event == null) { return; } if (event.isControlDown() && KeyCode.Q.equals(event.getCode())) { this.quitSystem(); } }); } } private void actionOnCloseRequest(WindowEvent event) { List<Project> projects = this.tabManager == null ? null : this.tabManager.getProjects(); if (projects != null && (!projects.isEmpty())) { QEFXSavingDialog dialog = new QEFXSavingDialog(projects); if (dialog.hasProjects()) { boolean status = dialog.showAndSave(); if (!status) { if (event != null) { event.consume(); } } } } if (event != null && event.isConsumed()) { return; } if (!RunningManager.getInstance().isEmpty()) { Alert alert = new Alert(AlertType.WARNING); QEFXMain.initializeDialogOwner(alert); alert.setHeaderText("Calculations are running. Do you delete them ?"); alert.getButtonTypes().clear(); alert.getButtonTypes().add(ButtonType.YES); alert.getButtonTypes().add(ButtonType.NO); Optional<ButtonType> optButtonType = alert.showAndWait(); ButtonType buttonType = null; if (optButtonType != null && optButtonType.isPresent()) { buttonType = optButtonType.get(); } if (!ButtonType.YES.equals(buttonType)) { if (event != null) { event.consume(); } } } } private void actionOnHidden(WindowEvent event) { if (event != null && event.isConsumed()) { return; } if (this.tabManager != null) { this.tabManager.hideAllTabs(); } Life.getInstance().toBeDead(); } public void quitSystem() { if (this.stage != null) { WindowEvent event = new WindowEvent(this.stage, WindowEvent.ANY); if (!event.isConsumed()) { if (this.stage.getOnCloseRequest() != null) { this.stage.getOnCloseRequest().handle(event); } } if (!event.isConsumed()) { this.stage.hide(); } } } public void setMaximized(boolean maximized) { if (this.stage != null) { this.stage.setMaximized(maximized); } } public void setFullScreen(boolean fullScreen) { if (this.stage != null) { this.stage.setFullScreen(fullScreen); } } public void setResizable(boolean resizable) { if (this.stage != null) { this.stage.setResizable(resizable); } } protected void setExplorer(QEFXExplorer explorer) { if (explorer == null) { return; } if (this.homePane != null) { Node node = explorer.getNode(); if (node != null) { this.homePane.getChildren().clear(); this.homePane.getChildren().add(node); this.explorerFacade = explorer.getFacade(); } } } public void refreshProjectOnExplorer(Project project) { if (project == null) { return; } if (this.explorerFacade != null) { this.explorerFacade.refreshProject(project); } } public void offerOnHomeTabSelected(HomeTabSelected onHomeTabSelected) { if (onHomeTabSelected == null) { return; } if (this.onHomeTabSelectedQueue == null) { this.onHomeTabSelectedQueue = new LinkedList<HomeTabSelected>(); } this.onHomeTabSelectedQueue.offer(onHomeTabSelected); } public boolean showHome() { if (this.tabManager != null) { return this.tabManager.showHomeTab(); } return false; } public Project showProject(Project project) { if (project == null) { return null; } if (this.tabManager != null) { Project project2 = this.tabManager.showTab(project); if (project2 != null) { Environments.addRecentFilePath(project2.getRelatedFilePath()); this.offerOnHomeTabSelected(explorerFacade -> { if (explorerFacade != null && explorerFacade.isRecentlyUsedMode()) { explorerFacade.reloadLocation(); } }); } return project2; } return null; } public WebEngine showWebPage(String url) { if (url == null || url.trim().isEmpty()) { return null; } if (this.tabManager != null) { return this.tabManager.showTab(url); } return null; } public boolean hideProject(Project project) { if (project == null) { return false; } if (this.tabManager != null) { return this.tabManager.hideTab(project); } return false; } public boolean hideWebPage(WebEngine engine) { if (engine == null) { return false; } if (this.tabManager != null) { return this.tabManager.hideTab(engine); } return false; } public List<Project> getShownProjects() { if (this.tabManager != null) { return this.tabManager.getProjects(); } return null; } }
src/burai/app/QEFXMainController.java
/* * Copyright (C) 2016 Satomichi Nishihara * * This file is distributed under the terms of the * GNU General Public License. See the file `LICENSE' * in the root directory of the present distribution, * or http://www.gnu.org/copyleft/gpl.txt . */ package burai.app; import java.io.File; import java.net.URL; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.Queue; import java.util.ResourceBundle; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Rectangle2D; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TextField; import javafx.scene.control.Tooltip; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyCode; import javafx.scene.input.TransferMode; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.web.WebEngine; import javafx.stage.Screen; import javafx.stage.Stage; import javafx.stage.WindowEvent; import burai.app.about.QEFXAboutDialog; import burai.app.explorer.QEFXExplorer; import burai.app.explorer.QEFXExplorerFacade; import burai.app.icon.QEFXIcon; import burai.app.icon.QEFXProjectIcon; import burai.app.icon.QEFXWebIcon; import burai.app.matapi.QEFXMatAPIDialog; import burai.app.onclose.QEFXSavingDialog; import burai.app.proxy.QEFXProxyDialog; import burai.app.tab.QEFXTabManager; import burai.com.env.Environments; import burai.com.graphic.svg.SVGLibrary; import burai.com.graphic.svg.SVGLibrary.SVGData; import burai.com.life.Life; import burai.matapi.MaterialsAPILoader; import burai.project.Project; import burai.run.RunningManager; import burai.ver.Version; public class QEFXMainController implements Initializable { private static final long SLEEP_TIME_TO_DROP_FILES = 850L; private static final double TOPMENU_GRAPHIC_SIZE = 16.0; private static final String TOPMENU_GRAPHIC_CLASS = "picblack-button"; private static final double HOME_GRAPHIC_SIZE = 20.0; private static final String HOME_GRAPHIC_CLASS = "pichome-button"; private static final double SEARCH_GRAPHIC_SIZE = 14.0; private static final String SEARCH_GRAPHIC_CLASS = "picblack-button"; private Stage stage; private QEFXTabManager tabManager; private QEFXExplorerFacade explorerFacade; private Queue<HomeTabSelected> onHomeTabSelectedQueue; @FXML private BorderPane basePane; @FXML private Menu topMenu; @FXML private MenuItem aboutMItem; @FXML private MenuItem docsMItem; @FXML private MenuItem qeMItem; @FXML private MenuItem pseudoMItem; @FXML private MenuItem manPwMItem; @FXML private MenuItem manDosMItem; @FXML private MenuItem manProjMItem; @FXML private MenuItem manBandMItem; @FXML private MenuItem proxyMItem; @FXML private MenuItem fullScrMItem; @FXML private MenuItem quitMItem; @FXML private TabPane tabPane; @FXML private Tab homeTab; @FXML private AnchorPane homePane; @FXML private Button matApiButton; @FXML private TextField matApiField; public QEFXMainController() { this.stage = null; this.tabManager = null; this.explorerFacade = null; this.onHomeTabSelectedQueue = null; } @Override public void initialize(URL location, ResourceBundle resources) { this.setupBasePane(); this.setupTopMenu(); this.setupMenuItems(); this.setupTabPane(); this.setupHomeTab(); this.setupMatApiButton(); this.setupMatApiField(); } private void setupBasePane() { if (this.basePane == null) { return; } this.basePane.setOnDragOver(event -> { Dragboard board = event == null ? null : event.getDragboard(); if (board == null) { return; } if (board.hasFiles()) { event.acceptTransferModes(TransferMode.COPY); } }); this.basePane.setOnDragDropped(event -> { Dragboard board = event == null ? null : event.getDragboard(); if (board == null) { return; } if (!board.hasFiles()) { event.setDropCompleted(false); return; } List<File> files = board.getFiles(); if (files != null) { Thread thread = new Thread(() -> { for (File file : files) { this.showDroppedFile(file); synchronized (files) { try { files.wait(SLEEP_TIME_TO_DROP_FILES); } catch (Exception e) { e.printStackTrace(); } } } }); thread.start(); } event.setDropCompleted(true); }); } private void showDroppedFile(File file) { QEFXIcon icon = file == null ? null : QEFXIcon.getInstance(file); if (icon == null) { return; } Platform.runLater(() -> { if (icon != null && icon instanceof QEFXProjectIcon) { Project project = ((QEFXProjectIcon) icon).getContent(); if (project != null) { this.showProject(project); } } else if (icon != null && icon instanceof QEFXWebIcon) { String url = ((QEFXWebIcon) icon).getInitialURL(); if (url != null && !(url.trim().isEmpty())) { this.showWebPage(url); } } }); } private void setupTopMenu() { if (this.topMenu == null) { return; } this.topMenu.setText(""); this.topMenu.setGraphic( SVGLibrary.getGraphic(SVGData.VECTOR_RIGHT, TOPMENU_GRAPHIC_SIZE, null, TOPMENU_GRAPHIC_CLASS)); this.topMenu.showingProperty().addListener(o -> { if (this.topMenu.isShowing()) { this.topMenu.setGraphic(SVGLibrary.getGraphic( SVGData.VECTOR_DOWN, TOPMENU_GRAPHIC_SIZE, null, TOPMENU_GRAPHIC_CLASS)); } else { this.topMenu.setGraphic(SVGLibrary.getGraphic( SVGData.VECTOR_RIGHT, TOPMENU_GRAPHIC_SIZE, null, TOPMENU_GRAPHIC_CLASS)); } }); } private void setupMenuItems() { if (this.aboutMItem != null) { this.aboutMItem.setOnAction(event -> { QEFXAboutDialog dialog = new QEFXAboutDialog(); dialog.showAndWait(); }); } if (this.docsMItem != null) { this.docsMItem.setOnAction(event -> { this.showWebPage(Environments.getDocumentsWebsite()); }); } if (this.qeMItem != null) { this.qeMItem.setOnAction(event -> { this.showWebPage(Environments.getEspressoWebsite()); }); } if (this.pseudoMItem != null) { this.pseudoMItem.setOnAction(event -> { this.showWebPage(Environments.getPseudoWebsite()); }); } if (this.manPwMItem != null) { this.manPwMItem.setOnAction(event -> { this.showWebPage(Environments.getManPwscfWebsite()); }); } if (this.manDosMItem != null) { this.manDosMItem.setOnAction(event -> { this.showWebPage(Environments.getManDosWebsite()); }); } if (this.manProjMItem != null) { this.manProjMItem.setOnAction(event -> { this.showWebPage(Environments.getManProjwfcWebsite()); }); } if (this.manBandMItem != null) { this.manBandMItem.setOnAction(event -> { this.showWebPage(Environments.getManBandsWebsite()); }); } if (this.proxyMItem != null) { this.proxyMItem.setOnAction(event -> { QEFXProxyDialog dialog = new QEFXProxyDialog(); dialog.showAndSetProperties(); }); } if (this.fullScrMItem != null) { this.fullScrMItem.setOnAction(event -> { if (this.stage != null && this.stage.isFullScreen()) { this.setFullScreen(false); } else { this.setFullScreen(true); } }); } if (this.quitMItem != null) { this.quitMItem.setOnAction(event -> { this.quitSystem(); }); } } private void setupTabPane() { if (this.tabPane == null) { return; } this.tabManager = new QEFXTabManager(this, this.tabPane); } private void setupHomeTab() { if (this.homeTab == null) { return; } this.homeTab.setText(""); this.homeTab.setGraphic( SVGLibrary.getGraphic(SVGData.HOME, HOME_GRAPHIC_SIZE, null, HOME_GRAPHIC_CLASS)); this.homeTab.setClosable(false); this.homeTab.setTooltip(new Tooltip("home")); this.homeTab.setOnSelectionChanged(event -> { if (this.homeTab.isSelected()) { this.executeOnHomeTabSelected(); } }); } private void executeOnHomeTabSelected() { if (this.onHomeTabSelectedQueue == null) { return; } if (this.explorerFacade != null) { this.explorerFacade.startSingleReloadMode(); } while (!this.onHomeTabSelectedQueue.isEmpty()) { HomeTabSelected onHomeTabSelected = this.onHomeTabSelectedQueue.poll(); if (onHomeTabSelected != null && this.explorerFacade != null) { onHomeTabSelected.onHomeTabSelected(this.explorerFacade); } } if (this.explorerFacade != null) { this.explorerFacade.endSingleReloadMode(); } } private void setupMatApiButton() { if (this.matApiButton == null) { return; } this.matApiButton.setGraphic( SVGLibrary.getGraphic(SVGData.SEARCH, SEARCH_GRAPHIC_SIZE, null, SEARCH_GRAPHIC_CLASS)); this.matApiButton.setOnAction(event -> { QEFXMatAPIDialog dialog = new QEFXMatAPIDialog(); dialog.showAndSetProperties(); }); } private void setupMatApiField() { if (this.matApiField == null) { return; } String messageTip = ""; messageTip = messageTip + "1) Li-Fe-O" + System.lineSeparator(); messageTip = messageTip + "2) Fe2O3"; this.matApiField.setTooltip(new Tooltip(messageTip)); this.matApiField.setOnAction(event -> { String text = this.matApiField.getText(); text = text == null ? null : text.trim(); if (text == null || text.isEmpty()) { MaterialsAPILoader.deleteLoader(); return; } MaterialsAPILoader matApiLoader = new MaterialsAPILoader(text); if (matApiLoader.numMaterialIDs() > 0) { this.matApiField.setText(matApiLoader.getFormula()); if (this.explorerFacade != null) { this.explorerFacade.setMaterialsAPILoader(matApiLoader); this.explorerFacade.setSearchedMode(); this.showHome(); } } else { String message = "The Materials API says there are no data of " + matApiLoader.getFormula() + "."; Alert alert = new Alert(AlertType.ERROR); QEFXMain.initializeDialogOwner(alert); alert.setHeaderText(message); alert.showAndWait(); } }); } public Stage getStage() { return this.stage; } protected void setStage(Stage stage) { this.stage = stage; if (this.stage == null) { return; } Rectangle2D rectangle2d = Screen.getPrimary().getVisualBounds(); double width = rectangle2d.getWidth(); double height = rectangle2d.getHeight(); this.stage.setWidth(width); this.stage.setHeight(height); this.stage.setTitle("BURAI" + Version.VERSION + ", a GUI of Quantum ESPRESSO."); this.stage.setOnCloseRequest(event -> this.actionOnCloseRequest(event)); this.stage.setOnHidden(event -> this.actionOnHidden(event)); Scene scene = this.stage.getScene(); if (scene != null) { scene.setOnKeyPressed(event -> { if (event == null) { return; } if (event.isControlDown() && KeyCode.Q.equals(event.getCode())) { this.quitSystem(); } }); } } private void actionOnCloseRequest(WindowEvent event) { List<Project> projects = this.tabManager == null ? null : this.tabManager.getProjects(); if (projects != null && (!projects.isEmpty())) { QEFXSavingDialog dialog = new QEFXSavingDialog(projects); if (dialog.hasProjects()) { boolean status = dialog.showAndSave(); if (!status) { if (event != null) { event.consume(); } } } } if (event != null && event.isConsumed()) { return; } if (!RunningManager.getInstance().isEmpty()) { Alert alert = new Alert(AlertType.WARNING); QEFXMain.initializeDialogOwner(alert); alert.setHeaderText("Calculations are running. Do you delete them ?"); alert.getButtonTypes().clear(); alert.getButtonTypes().add(ButtonType.YES); alert.getButtonTypes().add(ButtonType.NO); Optional<ButtonType> optButtonType = alert.showAndWait(); ButtonType buttonType = null; if (optButtonType != null && optButtonType.isPresent()) { buttonType = optButtonType.get(); } if (!ButtonType.YES.equals(buttonType)) { if (event != null) { event.consume(); } } } } private void actionOnHidden(WindowEvent event) { if (event != null && event.isConsumed()) { return; } if (this.tabManager != null) { this.tabManager.hideAllTabs(); } Life.getInstance().toBeDead(); } public void quitSystem() { if (this.stage != null) { WindowEvent event = new WindowEvent(this.stage, WindowEvent.ANY); if (!event.isConsumed()) { if (this.stage.getOnCloseRequest() != null) { this.stage.getOnCloseRequest().handle(event); } } if (!event.isConsumed()) { this.stage.hide(); } } } public void setMaximized(boolean maximized) { if (this.stage != null) { this.stage.setMaximized(maximized); } } public void setFullScreen(boolean fullScreen) { if (this.stage != null) { this.stage.setFullScreen(fullScreen); } } public void setResizable(boolean resizable) { if (this.stage != null) { this.stage.setResizable(resizable); } } protected void setExplorer(QEFXExplorer explorer) { if (explorer == null) { return; } if (this.homePane != null) { Node node = explorer.getNode(); if (node != null) { this.homePane.getChildren().clear(); this.homePane.getChildren().add(node); this.explorerFacade = explorer.getFacade(); } } } public void refreshProjectOnExplorer(Project project) { if (project == null) { return; } if (this.explorerFacade != null) { this.explorerFacade.refreshProject(project); } } public void offerOnHomeTabSelected(HomeTabSelected onHomeTabSelected) { if (onHomeTabSelected == null) { return; } if (this.onHomeTabSelectedQueue == null) { this.onHomeTabSelectedQueue = new LinkedList<HomeTabSelected>(); } this.onHomeTabSelectedQueue.offer(onHomeTabSelected); } public boolean showHome() { if (this.tabManager != null) { return this.tabManager.showHomeTab(); } return false; } public Project showProject(Project project) { if (project == null) { return null; } if (this.tabManager != null) { Project project2 = this.tabManager.showTab(project); if (project2 != null) { Environments.addRecentFilePath(project2.getRelatedFilePath()); this.offerOnHomeTabSelected(explorerFacade -> { if (explorerFacade != null && explorerFacade.isRecentlyUsedMode()) { explorerFacade.reloadLocation(); } }); } return project2; } return null; } public WebEngine showWebPage(String url) { if (url == null || url.trim().isEmpty()) { return null; } if (this.tabManager != null) { return this.tabManager.showTab(url); } return null; } public boolean hideProject(Project project) { if (project == null) { return false; } if (this.tabManager != null) { return this.tabManager.hideTab(project); } return false; } public boolean hideWebPage(WebEngine engine) { if (engine == null) { return false; } if (this.tabManager != null) { return this.tabManager.hideTab(engine); } return false; } public List<Project> getShownProjects() { if (this.tabManager != null) { return this.tabManager.getProjects(); } return null; } }
tune DropFiles
src/burai/app/QEFXMainController.java
tune DropFiles
<ide><path>rc/burai/app/QEFXMainController.java <ide> <ide> public class QEFXMainController implements Initializable { <ide> <del> private static final long SLEEP_TIME_TO_DROP_FILES = 850L; <add> private static final long SLEEP_TIME_TO_DROP_FILES = 650L; <ide> <ide> private static final double TOPMENU_GRAPHIC_SIZE = 16.0; <ide> private static final String TOPMENU_GRAPHIC_CLASS = "picblack-button";
Java
apache-2.0
0371ff7ceec638aa77dc3a037279a007c795fa3a
0
anylineorg/anyline,anylineorg/anyline
package org.anyline.amap.util; import org.anyline.entity.*; import org.anyline.exception.AnylineException; import org.anyline.net.HttpUtil; import org.anyline.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; /** * 高德云图 * @author zh * */ public class AmapUtil { private static Logger log = LoggerFactory.getLogger(AmapUtil.class); public AmapConfig config = null; private static Hashtable<String, AmapUtil> instances = new Hashtable<>(); public static Hashtable<String, AmapUtil> getInstances(){ return instances; } public AmapConfig getConfig(){ return config; } public static AmapUtil getInstance() { return getInstance("default"); } public static AmapUtil getInstance(String key) { if (BasicUtil.isEmpty(key)) { key = "default"; } AmapUtil util = instances.get(key); if (null == util) { AmapConfig config = AmapConfig.getInstance(key); if(null != config) { util = new AmapUtil(); util.config = config; instances.put(key, util); } } return util; } /** * 添加记录 * @param name name * @param loctype 1:经纬度 2:地址 * @param lng 经度 * @param lat 纬度 * @param address address * @param extras extras * @return String */ public String create(String name, int loctype, String lng, String lat, String address, Map<String, Object> extras){ String url = AmapConfig.DEFAULT_HOST + "/datamanage/data/create"; Map<String,Object> params = new HashMap<>(); params.put("key", config.KEY); params.put("tableid", config.TABLE); params.put("loctype", loctype+""); Map<String,Object> data = new HashMap<>(); if(null != extras){ Iterator<String> keys = extras.keySet().iterator(); while(keys.hasNext()){ String key = keys.next(); Object value = extras.get(key); if(BasicUtil.isNotEmpty(value)){ data.put(key, value); } } } data.put("_name", name); if(BasicUtil.isNotEmpty(lng) && BasicUtil.isNotEmpty(lat)){ data.put("_location", lng+","+lat); } if(BasicUtil.isNotEmpty(address)){ data.put("_address", address); } params.put("data", BeanUtil.map2json(data)); String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.post(url, "UTF-8", params).getText(); String id = null; try{ DataRow row = DataRow.parseJson(txt); if(row.containsKey("status")){ String status = row.getString("status"); if("1".equals(status) && row.containsKey("_id")){ id = row.getString("_id"); log.warn("[添加标注完成][id:{}][name:{}]",id,name); }else{ log.warn("[添加标注失败][name:{}][info:{}]", name, row.getString("info")); log.warn("[param:{}]",BeanUtil.map2string(params)); } } }catch(Exception e){ e.printStackTrace(); } return id; } public String create(String name, String lng, String lat, String address, Map<String,Object> extras){ return create(name, 1, lng, lat, address, extras); } public String create(String name, String lng, String lat, Map<String,Object> extras){ return create(name, 1, lng, lat, null, extras); } public String create(String name, int loctype, String lng, String lat, String address){ return create(name, loctype, lng, lat, address, null); } public String create(String name, String lng, String lat, String address){ return create(name, lng, lat, address, null); } public String create(String name, String lng, String lat){ return create(name, lng, lat, null, null); } public String create(String name, String address){ return create(name, null, null, address); } /** * 删除标注 * @param ids ids * @return int */ public int delete(String ... ids){ if(null == ids){ return 0; } List<String> list = new ArrayList<>(); for(String id:ids){ list.add(id); } return delete(list); } public int delete(List<String> ids){ int cnt = 0; if(null == ids || ids.size() ==0){ return cnt; } String param = ""; int size = ids.size(); // 一次删除最多50条 大于50打后拆分数据 if(size > 50){ int navi = (size-1)/50 + 1; for(int i=0; i<navi; i++){ int fr = i*50; int to = i*50 + 49; if(to > size-1){ to = size - 1; } List<String> clds = ids.subList(fr, to); cnt += delete(clds); } return cnt; } for(int i=0; i<size; i++){ if(i==0){ param += ids.get(i); }else{ param += "," + ids.get(i); } } Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("tableid", config.TABLE); params.put("ids", param); params.put("sig", sign(params)); String url = AmapConfig.DEFAULT_HOST + "/datamanage/data/delete"; String txt = HttpUtil.post(url, "UTF-8", params).getText(); if(ConfigTable.isDebug() && log.isWarnEnabled()){ log.warn("[删除标注][param:{}]",BeanUtil.map2string(params)); } try{ DataRow json = DataRow.parseJson(txt); if(json.containsKey("status")){ String status = json.getString("status"); if("1".equals(status)){ cnt = json.getInt("success"); log.warn("[删除标注完成][success:{}][fail:{}]", cnt,json.getInt("fail")); }else{ log.warn("[删除标注失败][info:{}]",json.getString("info")); } } }catch(Exception e){ e.printStackTrace(); cnt = -1; } return cnt; } /** * 更新地图 * @param id id * @param name name * @param loctype loctype * @param lng 经度 * @param lat 纬度 * @param address address * @param extras extras * @return int 0:更新失败,没有对应的id 1:更新完成 -1:异常 */ public int update(String id, String name, int loctype, String lng, String lat, String address, Map<String,Object> extras){ int cnt = 0; String url = AmapConfig.DEFAULT_HOST + "/datamanage/data/update"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("tableid", config.TABLE); params.put("loctype", loctype+""); Map<String,Object> data = new HashMap<>(); if(null != extras){ Iterator<String> keys = extras.keySet().iterator(); while(keys.hasNext()){ String key = keys.next(); Object value = extras.get(key); data.put(key, value); } } data.put("_id", id); data.put("_name", name); if(BasicUtil.isNotEmpty(lng) && BasicUtil.isNotEmpty(lat)){ data.put("_location", lng+","+lat); } if(BasicUtil.isNotEmpty(address)){ data.put("_address", address); } params.put("data", BeanUtil.map2json(data)); params.put("sig", sign(params)); String txt = HttpUtil.post(url, "UTF-8", params).getText(); if(ConfigTable.isDebug() && log.isWarnEnabled()){ log.warn("[更新标注][param:{}]",BeanUtil.map2string(params)); } try{ DataRow json = DataRow.parseJson(txt); if(json.containsKey("status")){ String status = json.getString("status"); if("1".equals(status)){ cnt = 1; log.warn("[更新标注完成][id:{}][name:{}]",id,name); }else{ log.warn("[更新标注失败][name:{}][info:{}]",name,json.getString("info")); cnt = 0; } } }catch(Exception e){ e.printStackTrace(); cnt = -1; } return cnt; } public int update(String id, String name, String lng, String lat, String address, Map<String,Object> extras){ return update(id, name, 1, lng, lat, address, extras); } public int update(String id, String name, String lng, String lat, Map<String,Object> extras){ return update(id, name, 1, lng, lat, null, extras); } public int update(String id, String name, int loctype, String lng, String lat, String address){ return update(id, name, loctype, lng, lat, address, null); } public int update(String id, String name, String lng, String lat, String address){ return update(id, name, lng, lat, address, null); } public int update(String id, String name, String lng, String lat){ return update(id, name, lng, lat, null, null); } public int update(String id, String name, String address){ return update(id, name, null, null, address); } public int update(String id, String name){ return update(id, name, null); } /** * 创建新地图 * @param name name * @return String */ public String createTable(String name){ String tableId = null; String url = AmapConfig.DEFAULT_HOST + "/datamanage/table/create"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("name", name); String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.post(url, "UTF-8", params).getText(); DataRow json = DataRow.parseJson(txt); if(json.containsKey("tableid")){ tableId = json.getString("tableid"); log.warn("[创建地图完成][tableid:{}]",tableId); }else{ log.warn("[创建地图失败][info:{}][param:{}]",txt,BeanUtil.map2string(params)); } return tableId; } /** * 本地检索 检索指定云图tableid里,对应城市(全国/省/市/区县)范围的POI信息 * API:http://lbs.amap.com/yuntu/reference/cloudsearch/#t1 * @param keywords keywords * @param city city * @param filter filter * @param sortrule sortrule * @param limit limit * @param page page * @return DataSet */ public DataSet local(String keywords, String city, String filter, String sortrule, int limit, int page){ DataSet set = null; String url = AmapConfig.DEFAULT_HOST + "/datasearch/local"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("tableid", config.TABLE); params.put("keywords", keywords); if(BasicUtil.isEmpty(city)){ city = "全国"; } params.put("city", city); params.put("filter", filter); params.put("sortrule", sortrule); limit = NumberUtil.min(limit, 100); params.put("limit", limit+""); page = NumberUtil.max(page, 1); params.put("page", page+""); String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.post(url, "UTF-8", params).getText(); PageNavi navi = new DefaultPageNavi(); navi.setCurPage(page); navi.setPageRows(limit); try{ DataRow json = DataRow.parseJson(txt); if(json.containsKey("count")){ navi.setTotalRow(json.getInt("count")); } if(json.containsKey("datas")){ set = json.getSet("datas"); }else{ set = new DataSet(); log.warn("[本地搜索失败][info:{}]",json.getString("info")); log.warn("[本地搜索失败][params:{}]",BeanUtil.map2string(params)); set.setException(new Exception(json.getString("info"))); } }catch(Exception e){ log.warn("[本地搜索失败][info:{}]",e.getMessage()); set = new DataSet(); set.setException(e); } set.setNavi(navi); log.warn("[本地搜索][size:{}]",navi.getTotalRow()); return set; } /** * 周边搜索 在指定tableid的数据表内,搜索指定中心点和半径范围内,符合筛选条件的位置数据 * API:http://lbs.amap.com/yuntu/reference/cloudsearch/#t2 * @param center center * @param radius 查询半径 * @param keywords 关键词 * @param filters 过滤条件 * @param sortrule 排序 * @param limit 每页多少条 * @param page 第几页 * @return DataSet */ public DataSet around(String center, int radius, String keywords, Map<String,String> filters, String sortrule, int limit, int page){ DataSet set = null; String url = AmapConfig.DEFAULT_HOST + "/datasearch/around"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("tableid", config.TABLE); params.put("center", center); params.put("radius", radius+""); if(BasicUtil.isNotEmpty(keywords)){ params.put("keywords", keywords); } // 过滤条件 if(null != filters && !filters.isEmpty()){ String filter = ""; Iterator<String> keys = filters.keySet().iterator(); while(keys.hasNext()){ String key = keys.next(); String value = filters.get(key); if(BasicUtil.isEmpty(value)){ continue; } if("".equals(filter)){ filter = key + ":" + value; }else{ filter = filter + "+" + key + ":" + value; } } if(!"".equals(filter)){ params.put("filter", filter); } } if(BasicUtil.isNotEmpty(sortrule)){ params.put("sortrule", sortrule); } limit = NumberUtil.min(limit, 100); params.put("limit", limit+""); page = NumberUtil.max(page, 1); params.put("page", page+""); String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.post(url, "UTF-8", params).getText(); PageNavi navi = new DefaultPageNavi(); navi.setCurPage(page); navi.setPageRows(limit); try{ DataRow json = DataRow.parseJson(txt); if(json.containsKey("count")){ navi.setTotalRow(json.getInt("count")); } if(json.containsKey("datas")){ set = json.getSet("datas"); }else{ log.warn("[周边搜索失败][info:{}]",json.getString("info")); log.warn("[周边搜索失败][params:{}]",BeanUtil.map2string(params)); set = new DataSet(); set.setException(new Exception(json.getString("info"))); } }catch(Exception e){ log.warn("[周边搜索失败][error:{}]",e.getMessage()); e.printStackTrace(); set = new DataSet(); set.setException(e); } set.setNavi(navi); log.warn("[周边搜索][size:{}]",navi.getTotalRow()); return set; } public DataSet around(String center, int radius, Map<String,String> filters, String sortrule, int limit, int page){ return around(center, radius, null, filters, sortrule, limit, page); } public DataSet around(String center, int radius, Map<String,String> filters, int limit, int page){ return around(center, radius, null, filters, null, limit, page); } public DataSet around(String center, int radius, Map<String,String> filters, int limit){ return around(center, radius, null, filters, null, limit, 1); } public DataSet around(String center, int radius, String keywords, String sortrule, int limit, int page){ Map<String,String> filter = new HashMap<String,String>(); return around(center, radius, keywords, filter, sortrule, limit, page); } public DataSet around(String center, int radius, String keywords, int limit, int page){ return around(center, radius, keywords, "", limit, page); } public DataSet around(String center, int radius, int limit, int page){ return around(center, radius, "", limit, page); } public DataSet around(String center, int radius, int limit){ return around(center, radius, "", limit, 1); } public DataSet around(String center, int radius){ return around(center, radius, "", 100, 1); } public DataSet around(String center){ return around(center, ConfigTable.getInt("AMAP_MAX_RADIUS")); } /** * 按条件检索数据(可遍历整表数据) 根据筛选条件检索指定tableid数据表中的数据 * API:http://lbs.amap.com/yuntu/reference/cloudsearch/#t5 * AmapUtil.getInstance(TABLE_TENANT).list("tenant_id:1","shop_id:1", 10, 1); * @param filter 查询条件 * filter=key1:value1+key2:[value2,value3] * filter=type:酒店+star:[3,5] 等同于SQL语句的: WHERE type = "酒店" AND star BETWEEN 3 AND 5 * @param sortrule 排序条件 * 支持按用户自选的字段(仅支持数值类型字段)升降序排序.1:升序,0:降序 * 若不填升降序,默认按升序排列. 示例:按年龄age字段升序排序 sortrule = age:1 * @param limit 每页最大记录数为100 * @param page 当前页数 &gt;=1 * @return DataSet */ public DataSet list(String filter, String sortrule, int limit, int page){ DataSet set = null; String url = AmapConfig.DEFAULT_HOST + "/datamanage/data/list"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("tableid", config.TABLE); params.put("filter", filter); if(BasicUtil.isNotEmpty(sortrule)){ params.put("sortrule", sortrule); } limit = NumberUtil.min(limit, 100); params.put("limit", limit+""); page = NumberUtil.max(page, 1); params.put("page", page+""); String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.post(url, "UTF-8", params).getText(); PageNavi navi = new DefaultPageNavi(); navi.setCurPage(page); navi.setPageRows(limit); try{ DataRow json = DataRow.parseJson(txt); if(json.containsKey("count")){ navi.setTotalRow(json.getInt("count")); } if(json.containsKey("datas")){ set = json.getSet("datas"); if(ConfigTable.isDebug() && log.isWarnEnabled()){ log.warn("[条件搜索][结果数量:{}]",set.size()); } }else{ set = new DataSet(); log.warn("[条件搜索失败][info:{}]",json.getString("info")); log.warn("[条件搜索失败][params:{}]",BeanUtil.map2string(params)); set.setException(new Exception(json.getString("info"))); } }catch(Exception e){ log.warn("[条件搜索失败][error:{}]",e.getMessage()); set = new DataSet(); set.setException(e); } set.setNavi(navi); log.warn("[条件搜索][size:{}]",navi.getTotalRow()); return set; } /** * ID检索 在指定tableid的数据表内,查询对应数据id的数据详情 * API:http://lbs.amap.com/yuntu/reference/cloudsearch/#t4 * API:在指定tableid的数据表内,查询对应数据id的数据详情 * @param id id * @return DataRow */ public DataRow info(String id){ DataRow row = null; String url = AmapConfig.DEFAULT_HOST + "/datasearch/id"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("tableid", config.TABLE); params.put("_id", id); String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.post(url, "UTF-8", params).getText(); try{ DataRow json = DataRow.parseJson(txt); if(json.containsKey("datas")){ DataSet set = json.getSet("datas"); if(set.size() > 0){ row = set.getRow(0); } }else{ log.warn("[周边搜索失败][info:{}]",json.getString("info")); log.warn("[周边搜索失败][params:{}]",BeanUtil.map2string(params)); } }catch(Exception e){ log.warn("[周边搜索失败][error:{}]",e.getMessage()); e.printStackTrace(); } return row; } /** * 省数据分布检索 检索指定云图tableid里,全表数据或按照一定查询或筛选过滤而返回的数据中,含有数据的省名称(中文名称)和对应POI个数(count)的信息列表,按照count从高到低的排序展现 * API:http://lbs.amap.com/yuntu/reference/cloudsearch/#t6 * @param keywords 关键字 必须 * @param country ""或null时 默认:中国 * @param filter 条件 * @return DataSet */ public DataSet statByProvince(String keywords, String country, String filter){ DataSet set = null; String url = AmapConfig.DEFAULT_HOST + "/datasearch/statistics/province"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("tableid", config.TABLE); params.put("filter", filter); params.put("keywords", keywords); country = BasicUtil.evl(country, "中国")+""; params.put("country", country); String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.post(url, "UTF-8", params).getText(); try{ DataRow json = DataRow.parseJson(txt); if(json.containsKey("datas")){ set = json.getSet("datas"); }else{ set = new DataSet(); log.warn("[数据分布检索失败][info:{}]",json.getString("info")); log.warn("[数据分布检索失败][params:{}]",BeanUtil.map2string(params)); set.setException(new Exception(json.getString("info"))); } }catch(Exception e){ log.warn("[数据分布检索失败][error:{}]",e.getMessage()); set = new DataSet(); set.setException(e); } return set; } /** * 市数据分布检索 检索指定云图tableid里,全表数据或按照一定查询或筛选过滤而返回的数据中,含有数据的市名称(中文名称)和对应POI个数(count)的信息列表,按照count从高到低的排序展现 * API:http://lbs.amap.com/yuntu/reference/cloudsearch/#t6 * @param keywords 关键字 必须 * @param province ""或null时 默认:全国 * @param filter 条件 * @return DataSet */ public DataSet statByCity(String keywords, String province, String filter){ DataSet set = null; String url = AmapConfig.DEFAULT_HOST + "/datasearch/statistics/city"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("tableid", config.TABLE); params.put("filter", filter); params.put("keywords", keywords); province = BasicUtil.evl(province, "全国")+""; params.put("country", province); String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.post(url, "UTF-8", params).getText(); try{ DataRow json = DataRow.parseJson(txt); if(json.containsKey("datas")){ set = json.getSet("datas"); }else{ set = new DataSet(); log.warn("[数据分布检索失败][info:{}]",json.getString("info")); log.warn("[数据分布检索失败][params:{}]",BeanUtil.map2string(params)); set.setException(new Exception(json.getString("info"))); } }catch(Exception e){ log.warn("[数据分布检索失败][error:{}]",e.getMessage()); set = new DataSet(); set.setException(e); } return set; } /** * 区数据分布检索 检索指定云图tableid里,在指定的省,市下面全表数据或按照一定查询或筛选过滤而返回的数据中,所有区县名称(中文名称)和对应POI个数(count)的信息列表,按照count从高到低的排序展现 * API:http://lbs.amap.com/yuntu/reference/cloudsearch/#t6 * @param keywords 关键字 必须 * @param province province * @param city city * @param filter 条件 * @return DataSet */ public DataSet statByDistrict(String keywords, String province, String city, String filter){ DataSet set = null; String url = AmapConfig.DEFAULT_HOST + "/datasearch/statistics/province"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("tableid", config.TABLE); params.put("filter", filter); params.put("keywords", keywords); params.put("province", province); params.put("city", city); String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.post(url, "UTF-8", params).getText(); try{ DataRow json = DataRow.parseJson(txt); if(json.containsKey("datas")){ set = json.getSet("datas"); }else{ set = new DataSet(); log.warn("[数据分布检索失败][info:{}]",json.getString("info")); log.warn("[数据分布检索失败][params:{}]",BeanUtil.map2string(params)); set.setException(new Exception(json.getString("info"))); } }catch(Exception e){ log.warn("[数据分布检索失败][error:{}]",e.getMessage()); set = new DataSet(); set.setException(e); } return set; } /** * 检索1个中心点,周边一定公里范围内(直线距离或者导航距离最大10公里),一定时间范围内(最大24小时)上传过用户位置信息的用户,返回用户标识,经纬度,距离中心点距离. * @param center center * @param radius radius * @param limit limit * @param timerange timerange * @return DataSet */ public DataSet nearby(String center, String radius, int limit, int timerange ){ DataSet set = null; String url = AmapConfig.DEFAULT_HOST + "/datasearch/statistics/province"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("center", center); params.put("radius", radius); params.put("searchtype", "0"); params.put("limit", NumberUtil.min(limit, 100)+""); params.put("timerange", BasicUtil.evl(timerange,"1800")+""); String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.post(url, "UTF-8", params).getText(); try{ DataRow json = DataRow.parseJson(txt); if(json.containsKey("datas")){ set = json.getSet("datas"); }else{ set = new DataSet(); log.warn("[附近检索失败][info:}{}]",json.getString("info")); log.warn("[附近检索失败][params:{}]",BeanUtil.map2string(params)); set.setException(new Exception(json.getString("info"))); } }catch(Exception e){ log.warn("[附近检索失败][error:{}]",e.getMessage()); set = new DataSet(); set.setException(e); } return set; } /** * 逆地理编码 按坐标查地址 * "country" :"中国", * "province" :"山东省", * "city" :"青岛市", * "citycode" :"0532", * "district" :"市南区", * "adcode" :"370215", * "township" :"**街道", * "towncode" :"370215010000", * * @param coordinate 坐标 * @return Coordinate */ public Coordinate regeo(Coordinate coordinate) { Coordinate.TYPE _type = coordinate.getType(); Double _lng = coordinate.getLng(); Double _lat = coordinate.getLat(); coordinate.convert(Coordinate.TYPE.GCJ02LL); coordinate.setSuccess(false); DataRow row = null; String url = "http://restapi.amap.com/v3/geocode/regeo"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("location", coordinate.getLng()+","+coordinate.getLat()); String sign = sign(params); params.put("sig", sign); // 换回原坐标系 coordinate.setLng(_lng); coordinate.setLat(_lat); coordinate.setType(_type); String txt = HttpUtil.get(url, "UTF-8", params).getText(); row = DataRow.parseJson(txt); if(null != row){ int status = row.getInt("STATUS",0); if(status ==0){ // [逆地理编码][执行失败][code:10044][info:USER_DAILY_QUERY_OVER_LIMIT] log.warn("[逆地理编码][执行失败][code:{}][info:{}]", row.getString("INFOCODE"), row.getString("INFO")); log.warn("[逆地理编码][response:{}]",txt); String info_code = row.getString("INFOCODE"); if("10044".equals(info_code)) { throw new AnylineException("API_OVER_LIMIT", "访问已超出日访问量"); }else if("10019".equals(info_code) || "10020".equals(info_code) || "10021".equals(info_code)){ log.warn("QPS已达到上限,sleep 50 ..."); try { Thread.sleep(50); }catch (Exception e){ e.printStackTrace(); } return regeo(coordinate); }else{ throw new AnylineException(status, row.getString("INFO")); } }else { row = row.getRow("regeocode"); if (null != row) { coordinate.setAddress(row.getString("formatted_address")); DataRow adr = row.getRow("addressComponent"); if (null != adr) { String adcode = adr.getString("adcode"); String provinceCode = adcode.substring(0,2); String cityCode = adcode.substring(0,4); coordinate.setProvinceCode(provinceCode); coordinate.setProvinceName(adr.getString("province")); coordinate.setCityCode(cityCode); coordinate.setCityName(adr.getString("city")); coordinate.setCountyCode(adcode); coordinate.setCountyName(adr.getString("district")); coordinate.setTownCode(adr.getString("towncode")); coordinate.setTownName(adr.getString("township")); DataRow street = adr.getRow("streetNumber"); if(null != street){ coordinate.setStreet(street.getString("street")); coordinate.setStreetNumber(street.getString("number")); } } } } } if(null != coordinate) { coordinate.setSuccess(true); } return coordinate; } /** * 逆地址解析 * @param lng 经度 * @param lat 纬度 * @return Coordinate */ public Coordinate regeo(Coordinate.TYPE type, Double lng, Double lat){ Coordinate coordinate = new Coordinate(type, lng, lat); return regeo(coordinate); } public Coordinate regeo(Coordinate.TYPE type, String lng, String lat) { return regeo(type, BasicUtil.parseDouble(lng, null), BasicUtil.parseDouble(lat, null)); } public Coordinate regeo(Coordinate.TYPE type, String point) { String[] points = point.split(","); return regeo(type, BasicUtil.parseDouble(points[0], null), BasicUtil.parseDouble(points[1], null)); } public Coordinate regeo(String point) { return regeo(Coordinate.TYPE.GCJ02LL, point); } public Coordinate regeo(String lng, String lat){ return regeo(BasicUtil.parseDouble(lng, null), BasicUtil.parseDouble(lat, null)); } public Coordinate regeo(Coordinate.TYPE type, double lng, double lat){ return regeo(type,lng+","+lat); } public Coordinate regeo(double lng, double lat){ return regeo(Coordinate.TYPE.GCJ02LL,lng, lat); } public Coordinate regeo(Coordinate.TYPE type, String[] point){ return regeo(type, point[0],point[1]); } public Coordinate regeo(String[] point){ return regeo(point[0],point[1]); } public Coordinate regeo(Coordinate.TYPE type, double[] point){ return regeo(type, point[0],point[1]); } public Coordinate regeo(double[] point){ return regeo(point[0],point[1]); } /** * 根据地址查坐标 * @param address address * @param city city * @return Coordinate */ public Coordinate geo(String address, String city){ Coordinate coordinate = null; String url = "http://restapi.amap.com/v3/geocode/geo"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("address", address); if(BasicUtil.isNotEmpty(city)){ params.put("city", city); } String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.get(url, "UTF-8", params).getText(); try{ DataRow row = DataRow.parseJson(txt); if(null != row){ int status = row.getInt("STATUS",0); if(status ==0){ // [逆地理编码][执行失败][code:10044][info:USER_DAILY_QUERY_OVER_LIMIT] log.warn("[地理编码][执行失败][code:{}][info:{}]", row.getString("INFOCODE"), row.getString("INFO")); log.warn("[地理编码][response:{}]",txt); String info_code = row.getString("INFOCODE"); if("10044".equals(info_code)) { throw new AnylineException("API_OVER_LIMIT", "访问已超出日访问量"); }else if("10019".equals(info_code) || "10020".equals(info_code) || "10021".equals(info_code)){ log.warn("QPS已达到上限,sleep 50 ..."); try { Thread.sleep(50); }catch (Exception e){ e.printStackTrace(); } return regeo(coordinate); }else{ throw new AnylineException(status, row.getString("INFO")); } }else { DataSet set = null; if(row.containsKey("geocodes")){ set = row.getSet("geocodes"); if(set.size()>0){ DataRow first = set.getRow(0); coordinate = new Coordinate(first.getString("LOCATION")); String adcode = first.getString("ADCODE"); coordinate.setCode(adcode); coordinate.setProvinceCode(BasicUtil.cut(adcode,0,2)); coordinate.setProvinceName(first.getString("PROVINCE")); coordinate.setCityCode(BasicUtil.cut(adcode,0,4)); coordinate.setCityName(first.getString("CITY")); coordinate.setCountyCode(first.getString("ADCODE")); coordinate.setCountyName(first.getString("DISTRICT")); coordinate.setAddress(first.getString("FORMATTED_ADDRESS")); coordinate.setLevel(first.getInt("LEVEL",0)); coordinate.setStreet(first.getString("STREET")); coordinate.setStreetNumber(first.getString("NUMBER")); } }else{ log.warn("[坐标查询失败][info:{}][params:{}]",row.getString("info"),BeanUtil.map2string(params)); } } } }catch(Exception e){ log.warn("[坐标查询失败][error:{}]",e.getMessage()); } if(null != coordinate) { coordinate.setType(Coordinate.TYPE.GCJ02LL); } return coordinate; } public Coordinate geo(String address){ return geo(address, null); } /** * 驾车路线规划 * http://lbs.amap.com/api/webservice/guide/api/direction#driving * @param origin 出发地 origin 出发地 * @param destination 目的地 destination 目的地 * @param points 途经地 最多支持16个 坐标点之间用";"分隔 * @param strategy 选路策略 0,不考虑当时路况,返回耗时最短的路线,但是此路线不一定距离最短 * 1,不走收费路段,且耗时最少的路线 * 2,不考虑路况,仅走距离最短的路线,但是可能存在穿越小路/小区的情况 * @return DataRow */ @SuppressWarnings({ "rawtypes", "unchecked" }) public DataRow directionDrive(String origin, String destination, String points, int strategy){ DataRow row = null; String url = "http://restapi.amap.com/v3/direction/driving"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("origin", origin); params.put("destination", destination); params.put("strategy", strategy+""); if(BasicUtil.isNotEmpty(points)){ params.put("points", points); } String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.get(url, "UTF-8", params).getText(); try{ row = DataRow.parseJson(txt); DataRow route = row.getRow("route"); if(null != route){ List paths = route.getList("PATHS"); if(paths.size()>0){ DataRow path = (DataRow)paths.get(0); row = path; List<DataRow> steps = (List<DataRow>)path.getList("steps"); List<String> polylines = new ArrayList<>(); for(DataRow step:steps){ String polyline = step.getString("polyline"); String[] tmps = polyline.split(";"); for(String tmp:tmps){ polylines.add(tmp); } } row.put("polylines", polylines); } } }catch(Exception e){ log.warn("[线路规划失败][error:{}]",e.getMessage()); } return row; } public DataRow directionDrive(String origin, String destination){ return directionDrive(origin, destination, null, 0); } public DataRow directionDrive(String origin, String destination, String points){ return directionDrive(origin, destination, points, 0); } public DataSet poi(String city, String keywords){ DataSet set = new DataSet(); String url = "https://restapi.amap.com/v5/place/text"; Map<String,Object> params = new HashMap<String,Object>(); params.put("city", city); params.put("keywords", keywords); params.put("page","1"); params.put("offset","20"); DataRow row = api(url,params); if(row.getInt("status",0)==1){ List<DataRow> items = (List<DataRow>)row.get("POIS"); for(DataRow item:items){ set.add(item); } } return set; } public DataRow api(String url, Map<String,Object> params){ params.put("key", config.KEY); String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.get(url, "UTF-8", params).getText(); DataRow row = null; try { row = DataRow.parseJson(txt); }catch (Exception e){ row = new DataRow(); row.put("status",0); row.put("info", e.getMessage()); e.printStackTrace(); } return row; } /** * 签名 * @param params params * @return String */ public String sign(Map<String,Object> params){ String sign = ""; sign = BeanUtil.map2string(params) + config.SECRET; sign = MD5Util.sign(sign,"UTF-8"); return sign; } }
anyline-amap/src/main/java/org/anyline/amap/util/AmapUtil.java
package org.anyline.amap.util; import org.anyline.entity.*; import org.anyline.exception.AnylineException; import org.anyline.net.HttpUtil; import org.anyline.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; /** * 高德云图 * @author zh * */ public class AmapUtil { private static Logger log = LoggerFactory.getLogger(AmapUtil.class); public AmapConfig config = null; private static Hashtable<String, AmapUtil> instances = new Hashtable<>(); public static Hashtable<String, AmapUtil> getInstances(){ return instances; } public AmapConfig getConfig(){ return config; } public static AmapUtil getInstance() { return getInstance("default"); } public static AmapUtil getInstance(String key) { if (BasicUtil.isEmpty(key)) { key = "default"; } AmapUtil util = instances.get(key); if (null == util) { AmapConfig config = AmapConfig.getInstance(key); if(null != config) { util = new AmapUtil(); util.config = config; instances.put(key, util); } } return util; } /** * 添加记录 * @param name name * @param loctype 1:经纬度 2:地址 * @param lng 经度 * @param lat 纬度 * @param address address * @param extras extras * @return String */ public String create(String name, int loctype, String lng, String lat, String address, Map<String, Object> extras){ String url = AmapConfig.DEFAULT_HOST + "/datamanage/data/create"; Map<String,Object> params = new HashMap<>(); params.put("key", config.KEY); params.put("tableid", config.TABLE); params.put("loctype", loctype+""); Map<String,Object> data = new HashMap<>(); if(null != extras){ Iterator<String> keys = extras.keySet().iterator(); while(keys.hasNext()){ String key = keys.next(); Object value = extras.get(key); if(BasicUtil.isNotEmpty(value)){ data.put(key, value); } } } data.put("_name", name); if(BasicUtil.isNotEmpty(lng) && BasicUtil.isNotEmpty(lat)){ data.put("_location", lng+","+lat); } if(BasicUtil.isNotEmpty(address)){ data.put("_address", address); } params.put("data", BeanUtil.map2json(data)); String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.post(url, "UTF-8", params).getText(); String id = null; try{ DataRow row = DataRow.parseJson(txt); if(row.containsKey("status")){ String status = row.getString("status"); if("1".equals(status) && row.containsKey("_id")){ id = row.getString("_id"); log.warn("[添加标注完成][id:{}][name:{}]",id,name); }else{ log.warn("[添加标注失败][name:{}][info:{}]", name, row.getString("info")); log.warn("[param:{}]",BeanUtil.map2string(params)); } } }catch(Exception e){ e.printStackTrace(); } return id; } public String create(String name, String lng, String lat, String address, Map<String,Object> extras){ return create(name, 1, lng, lat, address, extras); } public String create(String name, String lng, String lat, Map<String,Object> extras){ return create(name, 1, lng, lat, null, extras); } public String create(String name, int loctype, String lng, String lat, String address){ return create(name, loctype, lng, lat, address, null); } public String create(String name, String lng, String lat, String address){ return create(name, lng, lat, address, null); } public String create(String name, String lng, String lat){ return create(name, lng, lat, null, null); } public String create(String name, String address){ return create(name, null, null, address); } /** * 删除标注 * @param ids ids * @return int */ public int delete(String ... ids){ if(null == ids){ return 0; } List<String> list = new ArrayList<>(); for(String id:ids){ list.add(id); } return delete(list); } public int delete(List<String> ids){ int cnt = 0; if(null == ids || ids.size() ==0){ return cnt; } String param = ""; int size = ids.size(); // 一次删除最多50条 大于50打后拆分数据 if(size > 50){ int navi = (size-1)/50 + 1; for(int i=0; i<navi; i++){ int fr = i*50; int to = i*50 + 49; if(to > size-1){ to = size - 1; } List<String> clds = ids.subList(fr, to); cnt += delete(clds); } return cnt; } for(int i=0; i<size; i++){ if(i==0){ param += ids.get(i); }else{ param += "," + ids.get(i); } } Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("tableid", config.TABLE); params.put("ids", param); params.put("sig", sign(params)); String url = AmapConfig.DEFAULT_HOST + "/datamanage/data/delete"; String txt = HttpUtil.post(url, "UTF-8", params).getText(); if(ConfigTable.isDebug() && log.isWarnEnabled()){ log.warn("[删除标注][param:{}]",BeanUtil.map2string(params)); } try{ DataRow json = DataRow.parseJson(txt); if(json.containsKey("status")){ String status = json.getString("status"); if("1".equals(status)){ cnt = json.getInt("success"); log.warn("[删除标注完成][success:{}][fail:{}]", cnt,json.getInt("fail")); }else{ log.warn("[删除标注失败][info:{}]",json.getString("info")); } } }catch(Exception e){ e.printStackTrace(); cnt = -1; } return cnt; } /** * 更新地图 * @param id id * @param name name * @param loctype loctype * @param lng 经度 * @param lat 纬度 * @param address address * @param extras extras * @return int 0:更新失败,没有对应的id 1:更新完成 -1:异常 */ public int update(String id, String name, int loctype, String lng, String lat, String address, Map<String,Object> extras){ int cnt = 0; String url = AmapConfig.DEFAULT_HOST + "/datamanage/data/update"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("tableid", config.TABLE); params.put("loctype", loctype+""); Map<String,Object> data = new HashMap<>(); if(null != extras){ Iterator<String> keys = extras.keySet().iterator(); while(keys.hasNext()){ String key = keys.next(); Object value = extras.get(key); data.put(key, value); } } data.put("_id", id); data.put("_name", name); if(BasicUtil.isNotEmpty(lng) && BasicUtil.isNotEmpty(lat)){ data.put("_location", lng+","+lat); } if(BasicUtil.isNotEmpty(address)){ data.put("_address", address); } params.put("data", BeanUtil.map2json(data)); params.put("sig", sign(params)); String txt = HttpUtil.post(url, "UTF-8", params).getText(); if(ConfigTable.isDebug() && log.isWarnEnabled()){ log.warn("[更新标注][param:{}]",BeanUtil.map2string(params)); } try{ DataRow json = DataRow.parseJson(txt); if(json.containsKey("status")){ String status = json.getString("status"); if("1".equals(status)){ cnt = 1; log.warn("[更新标注完成][id:{}][name:{}]",id,name); }else{ log.warn("[更新标注失败][name:{}][info:{}]",name,json.getString("info")); cnt = 0; } } }catch(Exception e){ e.printStackTrace(); cnt = -1; } return cnt; } public int update(String id, String name, String lng, String lat, String address, Map<String,Object> extras){ return update(id, name, 1, lng, lat, address, extras); } public int update(String id, String name, String lng, String lat, Map<String,Object> extras){ return update(id, name, 1, lng, lat, null, extras); } public int update(String id, String name, int loctype, String lng, String lat, String address){ return update(id, name, loctype, lng, lat, address, null); } public int update(String id, String name, String lng, String lat, String address){ return update(id, name, lng, lat, address, null); } public int update(String id, String name, String lng, String lat){ return update(id, name, lng, lat, null, null); } public int update(String id, String name, String address){ return update(id, name, null, null, address); } public int update(String id, String name){ return update(id, name, null); } /** * 创建新地图 * @param name name * @return String */ public String createTable(String name){ String tableId = null; String url = AmapConfig.DEFAULT_HOST + "/datamanage/table/create"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("name", name); String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.post(url, "UTF-8", params).getText(); DataRow json = DataRow.parseJson(txt); if(json.containsKey("tableid")){ tableId = json.getString("tableid"); log.warn("[创建地图完成][tableid:{}]",tableId); }else{ log.warn("[创建地图失败][info:{}][param:{}]",txt,BeanUtil.map2string(params)); } return tableId; } /** * 本地检索 检索指定云图tableid里,对应城市(全国/省/市/区县)范围的POI信息 * API:http://lbs.amap.com/yuntu/reference/cloudsearch/#t1 * @param keywords keywords * @param city city * @param filter filter * @param sortrule sortrule * @param limit limit * @param page page * @return DataSet */ public DataSet local(String keywords, String city, String filter, String sortrule, int limit, int page){ DataSet set = null; String url = AmapConfig.DEFAULT_HOST + "/datasearch/local"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("tableid", config.TABLE); params.put("keywords", keywords); if(BasicUtil.isEmpty(city)){ city = "全国"; } params.put("city", city); params.put("filter", filter); params.put("sortrule", sortrule); limit = NumberUtil.min(limit, 100); params.put("limit", limit+""); page = NumberUtil.max(page, 1); params.put("page", page+""); String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.post(url, "UTF-8", params).getText(); PageNavi navi = new DefaultPageNavi(); navi.setCurPage(page); navi.setPageRows(limit); try{ DataRow json = DataRow.parseJson(txt); if(json.containsKey("count")){ navi.setTotalRow(json.getInt("count")); } if(json.containsKey("datas")){ set = json.getSet("datas"); }else{ set = new DataSet(); log.warn("[本地搜索失败][info:{}]",json.getString("info")); log.warn("[本地搜索失败][params:{}]",BeanUtil.map2string(params)); set.setException(new Exception(json.getString("info"))); } }catch(Exception e){ log.warn("[本地搜索失败][info:{}]",e.getMessage()); set = new DataSet(); set.setException(e); } set.setNavi(navi); log.warn("[本地搜索][size:{}]",navi.getTotalRow()); return set; } /** * 周边搜索 在指定tableid的数据表内,搜索指定中心点和半径范围内,符合筛选条件的位置数据 * API:http://lbs.amap.com/yuntu/reference/cloudsearch/#t2 * @param center center * @param radius 查询半径 * @param keywords 关键词 * @param filters 过滤条件 * @param sortrule 排序 * @param limit 每页多少条 * @param page 第几页 * @return DataSet */ public DataSet around(String center, int radius, String keywords, Map<String,String> filters, String sortrule, int limit, int page){ DataSet set = null; String url = AmapConfig.DEFAULT_HOST + "/datasearch/around"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("tableid", config.TABLE); params.put("center", center); params.put("radius", radius+""); if(BasicUtil.isNotEmpty(keywords)){ params.put("keywords", keywords); } // 过滤条件 if(null != filters && !filters.isEmpty()){ String filter = ""; Iterator<String> keys = filters.keySet().iterator(); while(keys.hasNext()){ String key = keys.next(); String value = filters.get(key); if(BasicUtil.isEmpty(value)){ continue; } if("".equals(filter)){ filter = key + ":" + value; }else{ filter = filter + "+" + key + ":" + value; } } if(!"".equals(filter)){ params.put("filter", filter); } } if(BasicUtil.isNotEmpty(sortrule)){ params.put("sortrule", sortrule); } limit = NumberUtil.min(limit, 100); params.put("limit", limit+""); page = NumberUtil.max(page, 1); params.put("page", page+""); String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.post(url, "UTF-8", params).getText(); PageNavi navi = new DefaultPageNavi(); navi.setCurPage(page); navi.setPageRows(limit); try{ DataRow json = DataRow.parseJson(txt); if(json.containsKey("count")){ navi.setTotalRow(json.getInt("count")); } if(json.containsKey("datas")){ set = json.getSet("datas"); }else{ log.warn("[周边搜索失败][info:{}]",json.getString("info")); log.warn("[周边搜索失败][params:{}]",BeanUtil.map2string(params)); set = new DataSet(); set.setException(new Exception(json.getString("info"))); } }catch(Exception e){ log.warn("[周边搜索失败][error:{}]",e.getMessage()); e.printStackTrace(); set = new DataSet(); set.setException(e); } set.setNavi(navi); log.warn("[周边搜索][size:{}]",navi.getTotalRow()); return set; } public DataSet around(String center, int radius, Map<String,String> filters, String sortrule, int limit, int page){ return around(center, radius, null, filters, sortrule, limit, page); } public DataSet around(String center, int radius, Map<String,String> filters, int limit, int page){ return around(center, radius, null, filters, null, limit, page); } public DataSet around(String center, int radius, Map<String,String> filters, int limit){ return around(center, radius, null, filters, null, limit, 1); } public DataSet around(String center, int radius, String keywords, String sortrule, int limit, int page){ Map<String,String> filter = new HashMap<String,String>(); return around(center, radius, keywords, filter, sortrule, limit, page); } public DataSet around(String center, int radius, String keywords, int limit, int page){ return around(center, radius, keywords, "", limit, page); } public DataSet around(String center, int radius, int limit, int page){ return around(center, radius, "", limit, page); } public DataSet around(String center, int radius, int limit){ return around(center, radius, "", limit, 1); } public DataSet around(String center, int radius){ return around(center, radius, "", 100, 1); } public DataSet around(String center){ return around(center, ConfigTable.getInt("AMAP_MAX_RADIUS")); } /** * 按条件检索数据(可遍历整表数据) 根据筛选条件检索指定tableid数据表中的数据 * API:http://lbs.amap.com/yuntu/reference/cloudsearch/#t5 * AmapUtil.getInstance(TABLE_TENANT).list("tenant_id:1","shop_id:1", 10, 1); * @param filter 查询条件 * filter=key1:value1+key2:[value2,value3] * filter=type:酒店+star:[3,5] 等同于SQL语句的: WHERE type = "酒店" AND star BETWEEN 3 AND 5 * @param sortrule 排序条件 * 支持按用户自选的字段(仅支持数值类型字段)升降序排序.1:升序,0:降序 * 若不填升降序,默认按升序排列. 示例:按年龄age字段升序排序 sortrule = age:1 * @param limit 每页最大记录数为100 * @param page 当前页数 &gt;=1 * @return DataSet */ public DataSet list(String filter, String sortrule, int limit, int page){ DataSet set = null; String url = AmapConfig.DEFAULT_HOST + "/datamanage/data/list"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("tableid", config.TABLE); params.put("filter", filter); if(BasicUtil.isNotEmpty(sortrule)){ params.put("sortrule", sortrule); } limit = NumberUtil.min(limit, 100); params.put("limit", limit+""); page = NumberUtil.max(page, 1); params.put("page", page+""); String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.post(url, "UTF-8", params).getText(); PageNavi navi = new DefaultPageNavi(); navi.setCurPage(page); navi.setPageRows(limit); try{ DataRow json = DataRow.parseJson(txt); if(json.containsKey("count")){ navi.setTotalRow(json.getInt("count")); } if(json.containsKey("datas")){ set = json.getSet("datas"); if(ConfigTable.isDebug() && log.isWarnEnabled()){ log.warn("[条件搜索][结果数量:{}]",set.size()); } }else{ set = new DataSet(); log.warn("[条件搜索失败][info:{}]",json.getString("info")); log.warn("[条件搜索失败][params:{}]",BeanUtil.map2string(params)); set.setException(new Exception(json.getString("info"))); } }catch(Exception e){ log.warn("[条件搜索失败][error:{}]",e.getMessage()); set = new DataSet(); set.setException(e); } set.setNavi(navi); log.warn("[条件搜索][size:{}]",navi.getTotalRow()); return set; } /** * ID检索 在指定tableid的数据表内,查询对应数据id的数据详情 * API:http://lbs.amap.com/yuntu/reference/cloudsearch/#t4 * API:在指定tableid的数据表内,查询对应数据id的数据详情 * @param id id * @return DataRow */ public DataRow info(String id){ DataRow row = null; String url = AmapConfig.DEFAULT_HOST + "/datasearch/id"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("tableid", config.TABLE); params.put("_id", id); String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.post(url, "UTF-8", params).getText(); try{ DataRow json = DataRow.parseJson(txt); if(json.containsKey("datas")){ DataSet set = json.getSet("datas"); if(set.size() > 0){ row = set.getRow(0); } }else{ log.warn("[周边搜索失败][info:{}]",json.getString("info")); log.warn("[周边搜索失败][params:{}]",BeanUtil.map2string(params)); } }catch(Exception e){ log.warn("[周边搜索失败][error:{}]",e.getMessage()); e.printStackTrace(); } return row; } /** * 省数据分布检索 检索指定云图tableid里,全表数据或按照一定查询或筛选过滤而返回的数据中,含有数据的省名称(中文名称)和对应POI个数(count)的信息列表,按照count从高到低的排序展现 * API:http://lbs.amap.com/yuntu/reference/cloudsearch/#t6 * @param keywords 关键字 必须 * @param country ""或null时 默认:中国 * @param filter 条件 * @return DataSet */ public DataSet statByProvince(String keywords, String country, String filter){ DataSet set = null; String url = AmapConfig.DEFAULT_HOST + "/datasearch/statistics/province"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("tableid", config.TABLE); params.put("filter", filter); params.put("keywords", keywords); country = BasicUtil.evl(country, "中国")+""; params.put("country", country); String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.post(url, "UTF-8", params).getText(); try{ DataRow json = DataRow.parseJson(txt); if(json.containsKey("datas")){ set = json.getSet("datas"); }else{ set = new DataSet(); log.warn("[数据分布检索失败][info:{}]",json.getString("info")); log.warn("[数据分布检索失败][params:{}]",BeanUtil.map2string(params)); set.setException(new Exception(json.getString("info"))); } }catch(Exception e){ log.warn("[数据分布检索失败][error:{}]",e.getMessage()); set = new DataSet(); set.setException(e); } return set; } /** * 市数据分布检索 检索指定云图tableid里,全表数据或按照一定查询或筛选过滤而返回的数据中,含有数据的市名称(中文名称)和对应POI个数(count)的信息列表,按照count从高到低的排序展现 * API:http://lbs.amap.com/yuntu/reference/cloudsearch/#t6 * @param keywords 关键字 必须 * @param province ""或null时 默认:全国 * @param filter 条件 * @return DataSet */ public DataSet statByCity(String keywords, String province, String filter){ DataSet set = null; String url = AmapConfig.DEFAULT_HOST + "/datasearch/statistics/city"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("tableid", config.TABLE); params.put("filter", filter); params.put("keywords", keywords); province = BasicUtil.evl(province, "全国")+""; params.put("country", province); String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.post(url, "UTF-8", params).getText(); try{ DataRow json = DataRow.parseJson(txt); if(json.containsKey("datas")){ set = json.getSet("datas"); }else{ set = new DataSet(); log.warn("[数据分布检索失败][info:{}]",json.getString("info")); log.warn("[数据分布检索失败][params:{}]",BeanUtil.map2string(params)); set.setException(new Exception(json.getString("info"))); } }catch(Exception e){ log.warn("[数据分布检索失败][error:{}]",e.getMessage()); set = new DataSet(); set.setException(e); } return set; } /** * 区数据分布检索 检索指定云图tableid里,在指定的省,市下面全表数据或按照一定查询或筛选过滤而返回的数据中,所有区县名称(中文名称)和对应POI个数(count)的信息列表,按照count从高到低的排序展现 * API:http://lbs.amap.com/yuntu/reference/cloudsearch/#t6 * @param keywords 关键字 必须 * @param province province * @param city city * @param filter 条件 * @return DataSet */ public DataSet statByDistrict(String keywords, String province, String city, String filter){ DataSet set = null; String url = AmapConfig.DEFAULT_HOST + "/datasearch/statistics/province"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("tableid", config.TABLE); params.put("filter", filter); params.put("keywords", keywords); params.put("province", province); params.put("city", city); String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.post(url, "UTF-8", params).getText(); try{ DataRow json = DataRow.parseJson(txt); if(json.containsKey("datas")){ set = json.getSet("datas"); }else{ set = new DataSet(); log.warn("[数据分布检索失败][info:{}]",json.getString("info")); log.warn("[数据分布检索失败][params:{}]",BeanUtil.map2string(params)); set.setException(new Exception(json.getString("info"))); } }catch(Exception e){ log.warn("[数据分布检索失败][error:{}]",e.getMessage()); set = new DataSet(); set.setException(e); } return set; } /** * 检索1个中心点,周边一定公里范围内(直线距离或者导航距离最大10公里),一定时间范围内(最大24小时)上传过用户位置信息的用户,返回用户标识,经纬度,距离中心点距离. * @param center center * @param radius radius * @param limit limit * @param timerange timerange * @return DataSet */ public DataSet nearby(String center, String radius, int limit, int timerange ){ DataSet set = null; String url = AmapConfig.DEFAULT_HOST + "/datasearch/statistics/province"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("center", center); params.put("radius", radius); params.put("searchtype", "0"); params.put("limit", NumberUtil.min(limit, 100)+""); params.put("timerange", BasicUtil.evl(timerange,"1800")+""); String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.post(url, "UTF-8", params).getText(); try{ DataRow json = DataRow.parseJson(txt); if(json.containsKey("datas")){ set = json.getSet("datas"); }else{ set = new DataSet(); log.warn("[附近检索失败][info:}{}]",json.getString("info")); log.warn("[附近检索失败][params:{}]",BeanUtil.map2string(params)); set.setException(new Exception(json.getString("info"))); } }catch(Exception e){ log.warn("[附近检索失败][error:{}]",e.getMessage()); set = new DataSet(); set.setException(e); } return set; } /** * 逆地理编码 按坐标查地址 * "country" :"中国", * "province" :"山东省", * "city" :"青岛市", * "citycode" :"0532", * "district" :"市南区", * "adcode" :"370215", * "township" :"**街道", * "towncode" :"370215010000", * * @param coordinate 坐标 * @return Coordinate */ public Coordinate regeo(Coordinate coordinate) { Coordinate.TYPE _type = coordinate.getType(); Double _lng = coordinate.getLng(); Double _lat = coordinate.getLat(); coordinate.convert(Coordinate.TYPE.GCJ02LL); coordinate.setSuccess(false); DataRow row = null; String url = "http://restapi.amap.com/v3/geocode/regeo"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("location", coordinate.getLng()+","+coordinate.getLat()); String sign = sign(params); params.put("sig", sign); // 换回原坐标系 coordinate.setLng(_lng); coordinate.setLat(_lat); coordinate.setType(_type); String txt = HttpUtil.get(url, "UTF-8", params).getText(); row = DataRow.parseJson(txt); if(null != row){ int status = row.getInt("STATUS",0); if(status ==0){ // [逆地理编码][执行失败][code:10044][info:USER_DAILY_QUERY_OVER_LIMIT] log.warn("[逆地理编码][执行失败][code:{}][info:{}]", row.getString("INFOCODE"), row.getString("INFO")); log.warn("[逆地理编码][response:{}]",txt); if("10044".equals(row.getString("INFOCODE"))) { throw new AnylineException("API_OVER_LIMIT", "访问已超出日访问量"); }else{ throw new AnylineException(status, row.getString("INFO")); } }else { row = row.getRow("regeocode"); if (null != row) { coordinate.setAddress(row.getString("formatted_address")); DataRow adr = row.getRow("addressComponent"); if (null != adr) { String adcode = adr.getString("adcode"); String provinceCode = adcode.substring(0,2); String cityCode = adcode.substring(0,4); coordinate.setProvinceCode(provinceCode); coordinate.setProvinceName(adr.getString("province")); coordinate.setCityCode(cityCode); coordinate.setCityName(adr.getString("city")); coordinate.setCountyCode(adcode); coordinate.setCountyName(adr.getString("district")); coordinate.setTownCode(adr.getString("towncode")); coordinate.setTownName(adr.getString("township")); } } } } if(null != coordinate) { coordinate.setSuccess(true); } return coordinate; } /** * 逆地址解析 * @param lng 经度 * @param lat 纬度 * @return Coordinate */ public Coordinate regeo(Coordinate.TYPE type, Double lng, Double lat){ Coordinate coordinate = new Coordinate(type, lng, lat); return regeo(coordinate); } public Coordinate regeo(Coordinate.TYPE type, String lng, String lat) { return regeo(type, BasicUtil.parseDouble(lng, null), BasicUtil.parseDouble(lat, null)); } public Coordinate regeo(Coordinate.TYPE type, String point) { String[] points = point.split(","); return regeo(type, BasicUtil.parseDouble(points[0], null), BasicUtil.parseDouble(points[1], null)); } public Coordinate regeo(String point) { return regeo(Coordinate.TYPE.GCJ02LL, point); } public Coordinate regeo(String lng, String lat){ return regeo(BasicUtil.parseDouble(lng, null), BasicUtil.parseDouble(lat, null)); } public Coordinate regeo(Coordinate.TYPE type, double lng, double lat){ return regeo(type,lng+","+lat); } public Coordinate regeo(double lng, double lat){ return regeo(Coordinate.TYPE.GCJ02LL,lng, lat); } public Coordinate regeo(Coordinate.TYPE type, String[] point){ return regeo(type, point[0],point[1]); } public Coordinate regeo(String[] point){ return regeo(point[0],point[1]); } public Coordinate regeo(Coordinate.TYPE type, double[] point){ return regeo(type, point[0],point[1]); } public Coordinate regeo(double[] point){ return regeo(point[0],point[1]); } /** * 根据地址查坐标 * @param address address * @param city city * @return Coordinate */ public Coordinate geo(String address, String city){ Coordinate coordinate = null; String url = "http://restapi.amap.com/v3/geocode/geo"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("address", address); if(BasicUtil.isNotEmpty(city)){ params.put("city", city); } String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.get(url, "UTF-8", params).getText(); try{ DataRow json = DataRow.parseJson(txt); DataSet set = null; if(json.containsKey("geocodes")){ set = json.getSet("geocodes"); if(set.size()>0){ DataRow row = set.getRow(0); coordinate = new Coordinate(row.getString("LOCATION")); coordinate.setCode(row.getString("ADCODE")); coordinate.setProvinceCode(BasicUtil.cut(row.getString("ADCODE"),0,4)); coordinate.setProvinceName(row.getString("PROVINCE")); coordinate.setCityCode(row.getString("CITYCODE")); coordinate.setCityName(row.getString("CITY")); coordinate.setCountyCode(row.getString("ADCODE")); coordinate.setCountyName(row.getString("DISTRICT")); coordinate.setAddress(row.getString("FORMATTED_ADDRESS")); coordinate.setLevel(row.getInt("LEVEL",0)); } }else{ log.warn("[坐标查询失败][info:{}][params:{}]",json.getString("info"),BeanUtil.map2string(params)); } }catch(Exception e){ log.warn("[坐标查询失败][error:{}]",e.getMessage()); } if(null != coordinate) { coordinate.setType(Coordinate.TYPE.GCJ02LL); } return coordinate; } public Coordinate geo(String address){ return geo(address, null); } /** * 驾车路线规划 * http://lbs.amap.com/api/webservice/guide/api/direction#driving * @param origin 出发地 origin 出发地 * @param destination 目的地 destination 目的地 * @param points 途经地 最多支持16个 坐标点之间用";"分隔 * @param strategy 选路策略 0,不考虑当时路况,返回耗时最短的路线,但是此路线不一定距离最短 * 1,不走收费路段,且耗时最少的路线 * 2,不考虑路况,仅走距离最短的路线,但是可能存在穿越小路/小区的情况 * @return DataRow */ @SuppressWarnings({ "rawtypes", "unchecked" }) public DataRow directionDrive(String origin, String destination, String points, int strategy){ DataRow row = null; String url = "http://restapi.amap.com/v3/direction/driving"; Map<String,Object> params = new HashMap<String,Object>(); params.put("key", config.KEY); params.put("origin", origin); params.put("destination", destination); params.put("strategy", strategy+""); if(BasicUtil.isNotEmpty(points)){ params.put("points", points); } String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.get(url, "UTF-8", params).getText(); try{ row = DataRow.parseJson(txt); DataRow route = row.getRow("route"); if(null != route){ List paths = route.getList("PATHS"); if(paths.size()>0){ DataRow path = (DataRow)paths.get(0); row = path; List<DataRow> steps = (List<DataRow>)path.getList("steps"); List<String> polylines = new ArrayList<>(); for(DataRow step:steps){ String polyline = step.getString("polyline"); String[] tmps = polyline.split(";"); for(String tmp:tmps){ polylines.add(tmp); } } row.put("polylines", polylines); } } }catch(Exception e){ log.warn("[线路规划失败][error:{}]",e.getMessage()); } return row; } public DataRow directionDrive(String origin, String destination){ return directionDrive(origin, destination, null, 0); } public DataRow directionDrive(String origin, String destination, String points){ return directionDrive(origin, destination, points, 0); } public DataSet poi(String city, String keywords){ DataSet set = new DataSet(); String url = "https://restapi.amap.com/v5/place/text"; Map<String,Object> params = new HashMap<String,Object>(); params.put("city", city); params.put("keywords", keywords); params.put("page","1"); params.put("offset","20"); DataRow row = api(url,params); if(row.getInt("status",0)==1){ List<DataRow> items = (List<DataRow>)row.get("POIS"); for(DataRow item:items){ set.add(item); } } return set; } public DataRow api(String url, Map<String,Object> params){ params.put("key", config.KEY); String sign = sign(params); params.put("sig", sign); String txt = HttpUtil.get(url, "UTF-8", params).getText(); DataRow row = null; try { row = DataRow.parseJson(txt); }catch (Exception e){ row = new DataRow(); row.put("status",0); row.put("info", e.getMessage()); e.printStackTrace(); } return row; } /** * 签名 * @param params params * @return String */ public String sign(Map<String,Object> params){ String sign = ""; sign = BeanUtil.map2string(params) + config.SECRET; sign = MD5Util.sign(sign,"UTF-8"); return sign; } }
高德geo
anyline-amap/src/main/java/org/anyline/amap/util/AmapUtil.java
高德geo
<ide><path>nyline-amap/src/main/java/org/anyline/amap/util/AmapUtil.java <ide> // [逆地理编码][执行失败][code:10044][info:USER_DAILY_QUERY_OVER_LIMIT] <ide> log.warn("[逆地理编码][执行失败][code:{}][info:{}]", row.getString("INFOCODE"), row.getString("INFO")); <ide> log.warn("[逆地理编码][response:{}]",txt); <del> if("10044".equals(row.getString("INFOCODE"))) { <add> String info_code = row.getString("INFOCODE"); <add> if("10044".equals(info_code)) { <ide> throw new AnylineException("API_OVER_LIMIT", "访问已超出日访问量"); <add> }else if("10019".equals(info_code) || "10020".equals(info_code) || "10021".equals(info_code)){ <add> log.warn("QPS已达到上限,sleep 50 ..."); <add> try { <add> Thread.sleep(50); <add> }catch (Exception e){ <add> e.printStackTrace(); <add> } <add> return regeo(coordinate); <ide> }else{ <ide> throw new AnylineException(status, row.getString("INFO")); <ide> } <ide> coordinate.setCountyName(adr.getString("district")); <ide> coordinate.setTownCode(adr.getString("towncode")); <ide> coordinate.setTownName(adr.getString("township")); <add> DataRow street = adr.getRow("streetNumber"); <add> if(null != street){ <add> coordinate.setStreet(street.getString("street")); <add> coordinate.setStreetNumber(street.getString("number")); <add> } <ide> } <ide> <ide> } <ide> params.put("sig", sign); <ide> String txt = HttpUtil.get(url, "UTF-8", params).getText(); <ide> try{ <del> DataRow json = DataRow.parseJson(txt); <del> DataSet set = null; <del> if(json.containsKey("geocodes")){ <del> set = json.getSet("geocodes"); <del> if(set.size()>0){ <del> DataRow row = set.getRow(0); <del> coordinate = new Coordinate(row.getString("LOCATION")); <del> coordinate.setCode(row.getString("ADCODE")); <del> coordinate.setProvinceCode(BasicUtil.cut(row.getString("ADCODE"),0,4)); <del> coordinate.setProvinceName(row.getString("PROVINCE")); <del> coordinate.setCityCode(row.getString("CITYCODE")); <del> coordinate.setCityName(row.getString("CITY")); <del> coordinate.setCountyCode(row.getString("ADCODE")); <del> coordinate.setCountyName(row.getString("DISTRICT")); <del> coordinate.setAddress(row.getString("FORMATTED_ADDRESS")); <del> coordinate.setLevel(row.getInt("LEVEL",0)); <del> } <del> }else{ <del> log.warn("[坐标查询失败][info:{}][params:{}]",json.getString("info"),BeanUtil.map2string(params)); <del> } <add> DataRow row = DataRow.parseJson(txt); <add> if(null != row){ <add> <add> int status = row.getInt("STATUS",0); <add> if(status ==0){ <add> // [逆地理编码][执行失败][code:10044][info:USER_DAILY_QUERY_OVER_LIMIT] <add> log.warn("[地理编码][执行失败][code:{}][info:{}]", row.getString("INFOCODE"), row.getString("INFO")); <add> log.warn("[地理编码][response:{}]",txt); <add> String info_code = row.getString("INFOCODE"); <add> if("10044".equals(info_code)) { <add> throw new AnylineException("API_OVER_LIMIT", "访问已超出日访问量"); <add> }else if("10019".equals(info_code) || "10020".equals(info_code) || "10021".equals(info_code)){ <add> log.warn("QPS已达到上限,sleep 50 ..."); <add> try { <add> Thread.sleep(50); <add> }catch (Exception e){ <add> e.printStackTrace(); <add> } <add> return regeo(coordinate); <add> }else{ <add> throw new AnylineException(status, row.getString("INFO")); <add> } <add> }else { <add> DataSet set = null; <add> if(row.containsKey("geocodes")){ <add> set = row.getSet("geocodes"); <add> if(set.size()>0){ <add> DataRow first = set.getRow(0); <add> coordinate = new Coordinate(first.getString("LOCATION")); <add> String adcode = first.getString("ADCODE"); <add> coordinate.setCode(adcode); <add> coordinate.setProvinceCode(BasicUtil.cut(adcode,0,2)); <add> coordinate.setProvinceName(first.getString("PROVINCE")); <add> coordinate.setCityCode(BasicUtil.cut(adcode,0,4)); <add> coordinate.setCityName(first.getString("CITY")); <add> coordinate.setCountyCode(first.getString("ADCODE")); <add> coordinate.setCountyName(first.getString("DISTRICT")); <add> coordinate.setAddress(first.getString("FORMATTED_ADDRESS")); <add> coordinate.setLevel(first.getInt("LEVEL",0)); <add> coordinate.setStreet(first.getString("STREET")); <add> coordinate.setStreetNumber(first.getString("NUMBER")); <add> } <add> }else{ <add> log.warn("[坐标查询失败][info:{}][params:{}]",row.getString("info"),BeanUtil.map2string(params)); <add> } <add> } <add> } <ide> }catch(Exception e){ <ide> log.warn("[坐标查询失败][error:{}]",e.getMessage()); <ide> }
Java
apache-2.0
80982e2d5d3de7959a24dbcdf0f3d5c1b39ecafc
0
RWTH-i5-IDSG/BikeMan,RWTH-i5-IDSG/BikeMan,RWTH-i5-IDSG/BikeMan
package de.rwth.idsg.bikeman.ixsi; import com.google.common.base.Strings; import de.rwth.idsg.bikeman.config.IxsiConfiguration; import de.rwth.idsg.bikeman.ixsi.repository.SystemValidator; import de.rwth.idsg.bikeman.web.rest.exception.DatabaseException; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor; import javax.servlet.http.HttpServletRequest; import java.net.InetSocketAddress; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Created by max on 08/09/14. */ @Slf4j @RequiredArgsConstructor public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor { private final SystemValidator systemValidator; @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception { String systemId = getSystemID(request); if (systemId == null) { throw new DatabaseException("This ip address is not allowed for WebSocket communication"); } else { // to be be used in future attributes.put(IxsiConfiguration.SYSTEM_ID_KEY, systemId); return super.beforeHandshake(request, response, wsHandler, attributes); } } @Override public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) { super.afterHandshake(request, response, wsHandler, ex); log.trace("Handshake complete with {}", request.getRemoteAddress()); } private String getSystemID(ServerHttpRequest request) { Set<String> ipAddresses = getPossibleIpAddresses(request); log.info("ipAddresses for this request: {}", ipAddresses); for (String ip : ipAddresses) { try { return systemValidator.getSystemID(ip); } catch (DatabaseException e) { // not in db, continue with the next in the list } } return null; } // ------------------------------------------------------------------------- // Since Spring uses many abstractions for different APIs, we try every // possible extraction method there available. // ------------------------------------------------------------------------- private static Set<String> getPossibleIpAddresses(ServerHttpRequest request) { Set<String> ipAddressList = new HashSet<>(); getFromProxy(request).stream() .filter(s -> !Strings.isNullOrEmpty(s)) .forEach(ipAddressList::add); ipAddressList.add(getWithInstanceOf(request)); ipAddressList.add(getFromRemote(request)); ipAddressList.add(getFromContext()); return ipAddressList; } private static Set<String> getFromProxy(ServerHttpRequest request) { List<String> strings = request.getHeaders().get("X-FORWARDED-FOR"); if (strings == null) { return Collections.emptySet(); } else { return new HashSet<>(strings); } } private static String getWithInstanceOf(ServerHttpRequest request) { if (request instanceof ServletServerHttpRequest) { ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request; String ipAddress = servletRequest.getServletRequest().getHeader("X-FORWARDED-FOR"); if (ipAddress == null) { ipAddress = servletRequest.getServletRequest().getRemoteAddr(); } return ipAddress; } return null; } private static String getFromRemote(ServerHttpRequest request) { InetSocketAddress inetSocketAddress = request.getRemoteAddress(); return inetSocketAddress.getAddress().getHostAddress(); } private static String getFromContext() { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); return request.getRemoteAddr(); } }
src/main/java/de/rwth/idsg/bikeman/ixsi/HandshakeInterceptor.java
package de.rwth.idsg.bikeman.ixsi; import com.google.common.base.Strings; import de.rwth.idsg.bikeman.config.IxsiConfiguration; import de.rwth.idsg.bikeman.ixsi.repository.SystemValidator; import de.rwth.idsg.bikeman.web.rest.exception.DatabaseException; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor; import javax.servlet.http.HttpServletRequest; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * Created by max on 08/09/14. */ @Slf4j @RequiredArgsConstructor public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor { private final SystemValidator systemValidator; @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception { String systemId = getSystemID(request); if (systemId == null) { throw new DatabaseException("This ip address is not allowed for WebSocket communication"); } else { // to be be used in future attributes.put(IxsiConfiguration.SYSTEM_ID_KEY, systemId); return super.beforeHandshake(request, response, wsHandler, attributes); } } @Override public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) { super.afterHandshake(request, response, wsHandler, ex); log.trace("Handshake complete with {}", request.getRemoteAddress()); } private String getSystemID(ServerHttpRequest request) { List<String> ipAddressList = getPossibleIpAddresses(request); log.info("ipAddressList for this request: {}", ipAddressList); for (String ip : ipAddressList) { try { return systemValidator.getSystemID(ip); } catch (DatabaseException e) { // not in db, continue with the next in the list } } return null; } private static List<String> getPossibleIpAddresses(ServerHttpRequest request) { List<String> ipAddressList = new ArrayList<>(); getFromProxy(request).stream() .filter(s -> !Strings.isNullOrEmpty(s)) .forEach(ipAddressList::add); ipAddressList.add(getWithInstanceOf(request)); ipAddressList.add(getFromRemote(request)); ipAddressList.add(getFromContext()); return ipAddressList; } private static List<String> getFromProxy(ServerHttpRequest request) { List<String> strings = request.getHeaders().get("X-FORWARDED-FOR"); if (strings == null) { return Collections.emptyList(); } else { return strings; } } private static String getWithInstanceOf(ServerHttpRequest request) { if (request instanceof ServletServerHttpRequest) { ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request; String ipAddress = servletRequest.getServletRequest().getHeader("X-FORWARDED-FOR"); if (ipAddress == null) { ipAddress = servletRequest.getServletRequest().getRemoteAddr(); } return ipAddress; } return null; } private static String getFromRemote(ServerHttpRequest request) { InetSocketAddress inetSocketAddress = request.getRemoteAddress(); return inetSocketAddress.getAddress().getHostAddress(); } private static String getFromContext() { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); return request.getRemoteAddr(); } }
improve HandshakeInterceptor impl
src/main/java/de/rwth/idsg/bikeman/ixsi/HandshakeInterceptor.java
improve HandshakeInterceptor impl
<ide><path>rc/main/java/de/rwth/idsg/bikeman/ixsi/HandshakeInterceptor.java <ide> <ide> import javax.servlet.http.HttpServletRequest; <ide> import java.net.InetSocketAddress; <del>import java.util.ArrayList; <ide> import java.util.Collections; <add>import java.util.HashSet; <ide> import java.util.List; <ide> import java.util.Map; <add>import java.util.Set; <ide> <ide> /** <ide> * Created by max on 08/09/14. <ide> } <ide> <ide> private String getSystemID(ServerHttpRequest request) { <del> List<String> ipAddressList = getPossibleIpAddresses(request); <del> log.info("ipAddressList for this request: {}", ipAddressList); <add> Set<String> ipAddresses = getPossibleIpAddresses(request); <add> log.info("ipAddresses for this request: {}", ipAddresses); <ide> <del> for (String ip : ipAddressList) { <add> for (String ip : ipAddresses) { <ide> try { <ide> return systemValidator.getSystemID(ip); <ide> } catch (DatabaseException e) { <ide> return null; <ide> } <ide> <del> private static List<String> getPossibleIpAddresses(ServerHttpRequest request) { <del> List<String> ipAddressList = new ArrayList<>(); <add> // ------------------------------------------------------------------------- <add> // Since Spring uses many abstractions for different APIs, we try every <add> // possible extraction method there available. <add> // ------------------------------------------------------------------------- <add> <add> private static Set<String> getPossibleIpAddresses(ServerHttpRequest request) { <add> Set<String> ipAddressList = new HashSet<>(); <ide> <ide> getFromProxy(request).stream() <ide> .filter(s -> !Strings.isNullOrEmpty(s)) <ide> return ipAddressList; <ide> } <ide> <del> private static List<String> getFromProxy(ServerHttpRequest request) { <add> private static Set<String> getFromProxy(ServerHttpRequest request) { <ide> List<String> strings = request.getHeaders().get("X-FORWARDED-FOR"); <ide> if (strings == null) { <del> return Collections.emptyList(); <add> return Collections.emptySet(); <ide> } else { <del> return strings; <add> return new HashSet<>(strings); <ide> } <ide> } <ide>
Java
mit
error: pathspec 'src/codingbat/logic1/FizzStringTest.java' did not match any file(s) known to git
9e106e19469ea5c3edbd9f4777311dc1f487406b
1
raeffu/codingbat
package codingbat.logic1; /* * Given a string str, if the string starts with "f" return "Fizz". * If the string ends with "b" return "Buzz". If both the "f" and "b" * conditions are true, return "FizzBuzz". In all other cases, * return the string unchanged. (See also: FizzBuzz Code) * * fizzString("fig") = "Fizz" * fizzString("dib") = "Buzz" * fizzString("fib") = "FizzBuzz" */ public class FizzStringTest { public static void main(String[] args) { FizzStringTest test = new FizzStringTest(); System.out.println(">" + test.fizzString("fig") + "<"); System.out.println(">" + test.fizzString("dib") + "<"); System.out.println(">" + test.fizzString("fib") + "<"); } public String fizzString(String str) { boolean fizz = false; boolean buzz = false; if(str.length() > 0){ fizz = str.substring(0,1).equals("f"); buzz = str.substring(str.length()-1, str.length()).equals("b"); } if(fizz && buzz){ return "FizzBuzz"; } else if(fizz){ return "Fizz"; } else if(buzz){ return "Buzz"; } else { return str; } } }
src/codingbat/logic1/FizzStringTest.java
add task fizzString
src/codingbat/logic1/FizzStringTest.java
add task fizzString
<ide><path>rc/codingbat/logic1/FizzStringTest.java <add>package codingbat.logic1; <add> <add> <add>/* <add> * Given a string str, if the string starts with "f" return "Fizz". <add> * If the string ends with "b" return "Buzz". If both the "f" and "b" <add> * conditions are true, return "FizzBuzz". In all other cases, <add> * return the string unchanged. (See also: FizzBuzz Code) <add> * <add> * fizzString("fig") = "Fizz" <add> * fizzString("dib") = "Buzz" <add> * fizzString("fib") = "FizzBuzz" <add> */ <add> <add>public class FizzStringTest { <add> <add> public static void main(String[] args) { <add> FizzStringTest test = new FizzStringTest(); <add> <add> System.out.println(">" + test.fizzString("fig") + "<"); <add> System.out.println(">" + test.fizzString("dib") + "<"); <add> System.out.println(">" + test.fizzString("fib") + "<"); <add> } <add> <add> public String fizzString(String str) { <add> boolean fizz = false; <add> boolean buzz = false; <add> <add> if(str.length() > 0){ <add> fizz = str.substring(0,1).equals("f"); <add> buzz = str.substring(str.length()-1, str.length()).equals("b"); <add> } <add> <add> if(fizz && buzz){ <add> return "FizzBuzz"; <add> } <add> else if(fizz){ <add> return "Fizz"; <add> } <add> else if(buzz){ <add> return "Buzz"; <add> } <add> else { <add> return str; <add> } <add> } <add> <add>}
Java
mit
3910f10eb472174a4f6aa762923133478b4012b5
0
chrislo27/Stray-core
package stray.blocks; import java.util.HashMap; import stray.LevelEditor.EditorGroup; import stray.Main; import stray.Settings; import stray.entity.Entity; import stray.util.AssetMap; import stray.util.MathHelper; import stray.util.Utils; import stray.world.World; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; public class Block { /** * * @param path * actual path; omit .png! */ public Block(String path) { this.path = path; } public static final int globalMagicNumber = Main.getRandom().nextInt(); protected boolean connectedTextures = false; protected boolean variants = false; protected String animationlink = null; protected int varianttypes = 4; protected int solidFaces = SolidFaces.NONE; protected boolean usingMissingTex = false; public EditorGroup levelEditorGroup = EditorGroup.NORMAL; public void tickUpdate(World world, int x, int y) { } public float getDragCoefficient(World world, int x, int y) { return 1; } public boolean isRenderedFront() { return false; } public Block solidify(int faces) { solidFaces = faces; return this; } public void onCollideLeftFace(World world, int x, int y, Entity e) { } public void onCollideRightFace(World world, int x, int y, Entity e) { } public void onCollideUpFace(World world, int x, int y, Entity e) { } public void onCollideDownFace(World world, int x, int y, Entity e) { } public int isSolid(World world, int x, int y) { return solidFaces; } public String getAnimation() { return animationlink; } public Block setAnimation(String animationlink) { this.animationlink = animationlink; return this; } public void dispose() { } public int getTickRate() { return 1; } /** * turns off connected textures too * * @return itself for chaining */ public Block hasVariants(int types) { variants = true; varianttypes = types; connectedTextures = false; return this; } public Block useConTextures() { connectedTextures = true; return this; } public Block setEditorGroup(EditorGroup i) { levelEditorGroup = i; return this; } public void addTextures(Main main) { if (path == null) return; if (animationlink != null) { // assumes animation is loaded already return; } if (!connectedTextures) { if (!Gdx.files.internal(path + ".png").exists() && !variants) { Main.logger.warn("WARNING: a block has no texture (" + path + ".png); using missing texture"); connectedTextures = false; variants = false; usingMissingTex = true; return; } } else { if (!Gdx.files.internal(path + "-full.png").exists() && !variants) { Main.logger.warn("WARNING: a block has no \"full\" texture (" + path + ".png); using missing texture"); connectedTextures = false; variants = false; usingMissingTex = true; return; } } if (!connectedTextures) { if (!variants) { main.manager.load(path + ".png", Texture.class); } else { for (int i = 0; i < varianttypes; i++) { main.manager.load(path + i + ".png", Texture.class); } } } else { main.manager.load(path + "-full.png", Texture.class); main.manager.load(path + "-corner.png", Texture.class); main.manager.load(path + "-edgehor.png", Texture.class); main.manager.load(path + "-edgever.png", Texture.class); } } public void postLoad(Main main) { sprites = new HashMap<String, String>(); if (animationlink != null) return; if (path == null) return; if (usingMissingTex) return; if (connectedTextures) { sprites.put("full", path + "-full.png"); sprites.put("corner", path + "-corner.png"); sprites.put("edgehor", path + "-edgehor.png"); sprites.put("edgever", path + "-edgever.png"); } else { if (!variants) { sprites.put("defaulttex", path + ".png"); } else { for (int i = 0; i < varianttypes; i++) { sprites.put("defaulttex" + i, path + i + ".png"); } } } } // protected void drawAt(Batch batch, Texture sprite, float f, float g) { // batch.draw(sprite, f, Main.convertY(g + World.tilesizey), // World.tilesizex, World.tilesizey); // } /** * only used for connected textures connected: full, corner, edgehor, * edgever */ protected HashMap<String, String> sprites; protected String path = ""; private int getVarFromTime() { int time = (MathHelper.getNthDigit(System.currentTimeMillis(), 1)) + (MathHelper.getNthDigit(System.currentTimeMillis(), 2) * 10) + (MathHelper.getNthDigit(System.currentTimeMillis(), 3) * 100) + (MathHelper.getNthDigit(System.currentTimeMillis(), 4) * 1000); // 10k return ((int) time / (10000 / varianttypes)); } // /** // * topleft origin! // * // * @param batch // * @param x // * @param y // */ // public void renderModel(World world, int x, int y) { // Batch batch = world.batch; // if (path == null) return; // if (usingMissingTex) { // batch.draw(world.main.manager.get(AssetMap.get("blockmissingtexture"), // Texture.class), // x, Main.convertY(y + World.tilesizey), World.tilesizex, World.tilesizey); // return; // } // // if (animationlink != null) { // batch.draw(world.main.animations.get(animationlink).getCurrentFrame(), x, // Main.convertY(y + World.tilesizey), World.tilesizex, World.tilesizey); // return; // } // // if (!connectedTextures) { // if (!variants) { // drawAt(batch, world.main.manager.get(sprites.get("defaulttex"), // Texture.class), x, // y); // } else { // drawAt(batch, world.main.manager.get(sprites.get("defaulttex" + // getVarFromTime()), // Texture.class), x, y); // } // } else { // drawAt(batch, world.main.manager.get(sprites.get("full"), Texture.class), // x, y); // } // } public static int variantNum(World world, int x, int y) { return variantNum(world.magicnumber, x, y); } public static int variantNum(int magic, int x, int y) { return ((int) ((magic + (x + 17) * (y + 53) * 214013L + 2531011L) >> 16) & 0x7fff); } public static int variantNum(int x, int y) { return variantNum(Block.globalMagicNumber, x, y); } // public void renderPlain(Main main, float camerax, float cameray, int x, // int y, int magic) { // if (animationlink != null) { // main.batch.draw(main.animations.get(animationlink).getCurrentFrame(), x // * World.tilesizex - camerax, y * World.tilesizey - cameray, // World.tilesizex, // World.tilesizey); // return; // } // // if (usingMissingTex) { // main.batch.draw(main.manager.get(AssetMap.get("blockmissingtexture"), // Texture.class), x // * World.tilesizex - camerax, y * World.tilesizey - cameray, // World.tilesizex, // World.tilesizey); // return; // } // // if (path == null) return; // // if (!connectedTextures) { // if (!variants) { // drawAt(main.batch, main.manager.get(sprites.get("defaulttex"), // Texture.class), x // * World.tilesizex - camerax, y * World.tilesizey - cameray); // } else { // drawAt(main.batch, main.manager.get(sprites.get("defaulttex" // + ((variantNum(magic, x, y)) & (varianttypes - 1))), Texture.class), x // * World.tilesizex - camerax, y * World.tilesizey - cameray); // } // } else { // drawAt(main.batch, main.manager.get(sprites.get("full"), Texture.class), // x // * World.tilesizex - camerax, y * World.tilesizey - cameray); // // } // } public void render(World world, int x, int y) { renderWithOffset(world, x, y, 0, 0); } public void renderWithOffset(World world, int x, int y, float offx, float offy) { if (usingMissingTex) { world.batch.draw( world.main.manager.get(AssetMap.get("blockmissingtexture"), Texture.class), x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); return; } if (animationlink != null) { world.batch.draw( world.main.animations.get(animationlink).getCurrentFrame(), x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); return; } if (path == null) return; if (!connectedTextures) { if (!variants) { world.batch.draw( world.main.manager.get(sprites.get("defaulttex"), Texture.class), x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); } else { world.batch.draw(world.main.manager.get(sprites.get("defaulttex" + ((variantNum(world, x, y)) & (varianttypes - 1))), Texture.class), x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); } } else { drawConnectedTexture(world, x, y, offx, offy, world.main.manager.get(sprites.get("corner"), Texture.class), world.main.manager.get(sprites.get("full"), Texture.class), world.main.manager.get(sprites.get("edgever"), Texture.class), world.main.manager.get(sprites.get("edgehor"), Texture.class)); } } public void drawConnectedTexture(World world, int x, int y, float offx, float offy, Texture corner, Texture full, Texture ver, Texture hor) { boolean up, down, left, right; up = world.getBlock(x, y - 1) == this; down = world.getBlock(x, y + 1) == this; left = world.getBlock(x - 1, y) == this; right = world.getBlock(x + 1, y) == this; if (up && down && left && right) { if (world.getBlock(x + 1, y + 1) != this || world.getBlock(x + 1, y - 1) != this || world.getBlock(x - 1, y + 1) != this || world.getBlock(x - 1, y - 1) != this) { world.batch.draw( corner, x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); } else world.batch.draw(full, x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); } else if (up && down && (left == false || right == false)) { world.batch.draw(ver, x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); } else if (left && right && (up == false || down == false)) { world.batch.draw(hor, x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); } else { world.batch.draw(corner, x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); } } public void drawConnectedTexture(World world, int x, int y, float offx, float offy, TextureRegion corner, TextureRegion full, TextureRegion ver, TextureRegion hor) { boolean up, down, left, right; up = world.getBlock(x, y - 1) == this; down = world.getBlock(x, y + 1) == this; left = world.getBlock(x - 1, y) == this; right = world.getBlock(x + 1, y) == this; if (up && down && left && right) { if (world.getBlock(x + 1, y + 1) != this || world.getBlock(x + 1, y - 1) != this || world.getBlock(x - 1, y + 1) != this || world.getBlock(x - 1, y - 1) != this) { world.batch.draw( corner, x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey)); } else world.batch.draw(full, x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); } else if (up && down && (left == false || right == false)) { world.batch.draw(ver, x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); } else if (left && right && (up == false || down == false)) { world.batch.draw(hor, x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); } else { world.batch.draw(corner, x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); } } // protected void drawAt(SpriteBatch batch, TextureRegion corner, float f, // float g) { // batch.draw(corner, f, Main.convertY(g + World.tilesizey), // World.tilesizex, World.tilesizey); // } public static boolean isEntityNear(World world, int x, int y, int rad, Class<?> cls) { for (int i = 0; i < world.entities.size; i++) { Entity e = world.entities.get(i); if (!(cls.isInstance(e))) continue; if (MathHelper.intersects(e.x, e.y, e.sizex, e.sizey, x - rad + 1, y - rad + 1, rad * 2 - 1, rad * 2 - 1)) return true; } return false; } public static Entity getNearestEntity(World world, int x, int y, int rad, Class<?> cls) { if (isEntityNear(world, x, y, rad, cls)) { for (int i = 0; i < world.entities.size; i++) { Entity e = world.entities.get(i); if (!(cls.isInstance(e))) continue; if (MathHelper.intersects(e.x, e.y, e.sizex, e.sizey, x - rad + 1, y - rad + 1, rad * 2 - 1, rad * 2 - 1)) return e; } } return null; } public static boolean entityIntersects(World world, double x, double y, Entity e) { return entityIntersects(world, x, y, e, 1, 1); } public static boolean entityIntersects(World world, double x, double y, Entity e, double sizex, double sizey) { if (e == null) return false; return MathHelper.intersects(x, y, sizex, sizey, e.x, e.y, e.sizex, e.sizey); } public static boolean isBlockVisible(float camx, float camy, int x, int y) { return MathHelper.intersects(x * World.tilesizex, y * World.tilesizey, World.tilesizex, World.tilesizey, camx, camy, Settings.DEFAULT_WIDTH, Gdx.graphics.getHeight()); } public static boolean playSound(int x, int y, float camx, float camy, Sound sound, float vol, float pitch, boolean mustbevisible) { if (!Block.isBlockVisible(camx, camy, x, y) && mustbevisible) return false; sound.play(vol * Settings.soundVolume, pitch, Utils.getSoundPan(x, camx)); return true; } public static boolean playSound(int x, int y, float camx, float camy, Sound sound, float vol, float pitch) { return playSound(x, y, camx, camy, sound, vol, pitch, true); } public static class SolidFaces{ public static final int NONE = 0; public static final int ALL = 15; public static final int UP = 1; public static final int DOWN = 2; public static final int LEFT = 4; public static final int RIGHT = 8; } }
src/stray/blocks/Block.java
package stray.blocks; import java.util.HashMap; import stray.LevelEditor.EditorGroup; import stray.Main; import stray.Settings; import stray.entity.Entity; import stray.util.AssetMap; import stray.util.MathHelper; import stray.util.Utils; import stray.world.World; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; public class Block { /** * * @param path * actual path; omit .png! */ public Block(String path) { this.path = path; } public static final int globalMagicNumber = Main.getRandom().nextInt(); protected boolean connectedTextures = false; protected boolean variants = false; protected String animationlink = null; protected int varianttypes = 4; protected int solidFaces = SolidFaces.NONE; protected boolean usingMissingTex = false; public EditorGroup levelEditorGroup = EditorGroup.NORMAL; public void tickUpdate(World world, int x, int y) { } public float getDragCoefficient(World world, int x, int y) { return 1; } public boolean isRenderedFront() { return false; } public Block solidify(int faces) { solidFaces = faces; return this; } public void onCollideLeftFace(World world, int x, int y, Entity e) { } public void onCollideRightFace(World world, int x, int y, Entity e) { } public void onCollideUpFace(World world, int x, int y, Entity e) { } public void onCollideDownFace(World world, int x, int y, Entity e) { } public int isSolid(World world, int x, int y) { return solidFaces; } public String getAnimation() { return animationlink; } public Block setAnimation(String animationlink) { this.animationlink = animationlink; return this; } public void dispose() { } public int getTickRate() { return 1; } /** * turns off connected textures too * * @return itself for chaining */ public Block hasVariants(int types) { variants = true; varianttypes = types; connectedTextures = false; return this; } public Block useConTextures() { connectedTextures = true; return this; } public Block setEditorGroup(EditorGroup i) { levelEditorGroup = i; return this; } public void addTextures(Main main) { if (path == null) return; if (animationlink != null) { // assumes animation is loaded already return; } if (!connectedTextures) { if (!Gdx.files.internal(path + ".png").exists() && !variants) { Main.logger.warn("WARNING: a block has no texture (" + path + ".png); using missing texture"); connectedTextures = false; variants = false; usingMissingTex = true; return; } } else { if (!Gdx.files.internal(path + "-full.png").exists() && !variants) { Main.logger.warn("WARNING: a block has no \"full\" texture (" + path + ".png); using missing texture"); connectedTextures = false; variants = false; usingMissingTex = true; return; } } if (!connectedTextures) { if (!variants) { main.manager.load(path + ".png", Texture.class); } else { for (int i = 0; i < varianttypes; i++) { main.manager.load(path + i + ".png", Texture.class); } } } else { main.manager.load(path + "-full.png", Texture.class); main.manager.load(path + "-corner.png", Texture.class); main.manager.load(path + "-edgehor.png", Texture.class); main.manager.load(path + "-edgever.png", Texture.class); } } public void postLoad(Main main) { sprites = new HashMap<String, String>(); if (animationlink != null) return; if (path == null) return; if (usingMissingTex) return; if (connectedTextures) { sprites.put("full", path + "-full.png"); sprites.put("corner", path + "-corner.png"); sprites.put("edgehor", path + "-edgehor.png"); sprites.put("edgever", path + "-edgever.png"); } else { if (!variants) { sprites.put("defaulttex", path + ".png"); } else { for (int i = 0; i < varianttypes; i++) { sprites.put("defaulttex" + i, path + i + ".png"); } } } } // protected void drawAt(Batch batch, Texture sprite, float f, float g) { // batch.draw(sprite, f, Main.convertY(g + World.tilesizey), // World.tilesizex, World.tilesizey); // } /** * only used for connected textures connected: full, corner, edgehor, * edgever */ protected HashMap<String, String> sprites; protected String path = ""; private int getVarFromTime() { int time = (MathHelper.getNthDigit(System.currentTimeMillis(), 1)) + (MathHelper.getNthDigit(System.currentTimeMillis(), 2) * 10) + (MathHelper.getNthDigit(System.currentTimeMillis(), 3) * 100) + (MathHelper.getNthDigit(System.currentTimeMillis(), 4) * 1000); // 10k return ((int) time / (10000 / varianttypes)); } // /** // * topleft origin! // * // * @param batch // * @param x // * @param y // */ // public void renderModel(World world, int x, int y) { // Batch batch = world.batch; // if (path == null) return; // if (usingMissingTex) { // batch.draw(world.main.manager.get(AssetMap.get("blockmissingtexture"), // Texture.class), // x, Main.convertY(y + World.tilesizey), World.tilesizex, World.tilesizey); // return; // } // // if (animationlink != null) { // batch.draw(world.main.animations.get(animationlink).getCurrentFrame(), x, // Main.convertY(y + World.tilesizey), World.tilesizex, World.tilesizey); // return; // } // // if (!connectedTextures) { // if (!variants) { // drawAt(batch, world.main.manager.get(sprites.get("defaulttex"), // Texture.class), x, // y); // } else { // drawAt(batch, world.main.manager.get(sprites.get("defaulttex" + // getVarFromTime()), // Texture.class), x, y); // } // } else { // drawAt(batch, world.main.manager.get(sprites.get("full"), Texture.class), // x, y); // } // } public static int variantNum(World world, int x, int y) { return variantNum(world.magicnumber, x, y); } public static int variantNum(int magic, int x, int y) { return ((int) ((magic + (x + 17) * (y + 53) * 214013L + 2531011L) >> 16) & 0x7fff); } public static int variantNum(int x, int y) { return variantNum(Block.globalMagicNumber, x, y); } // public void renderPlain(Main main, float camerax, float cameray, int x, // int y, int magic) { // if (animationlink != null) { // main.batch.draw(main.animations.get(animationlink).getCurrentFrame(), x // * World.tilesizex - camerax, y * World.tilesizey - cameray, // World.tilesizex, // World.tilesizey); // return; // } // // if (usingMissingTex) { // main.batch.draw(main.manager.get(AssetMap.get("blockmissingtexture"), // Texture.class), x // * World.tilesizex - camerax, y * World.tilesizey - cameray, // World.tilesizex, // World.tilesizey); // return; // } // // if (path == null) return; // // if (!connectedTextures) { // if (!variants) { // drawAt(main.batch, main.manager.get(sprites.get("defaulttex"), // Texture.class), x // * World.tilesizex - camerax, y * World.tilesizey - cameray); // } else { // drawAt(main.batch, main.manager.get(sprites.get("defaulttex" // + ((variantNum(magic, x, y)) & (varianttypes - 1))), Texture.class), x // * World.tilesizex - camerax, y * World.tilesizey - cameray); // } // } else { // drawAt(main.batch, main.manager.get(sprites.get("full"), Texture.class), // x // * World.tilesizex - camerax, y * World.tilesizey - cameray); // // } // } public void render(World world, int x, int y) { renderWithOffset(world, x, y, 0, 0); } public void renderWithOffset(World world, int x, int y, float offx, float offy) { if (usingMissingTex) { world.batch.draw( world.main.manager.get(AssetMap.get("blockmissingtexture"), Texture.class), x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); return; } if (animationlink != null) { world.batch.draw( world.main.animations.get(animationlink).getCurrentFrame(), x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); return; } if (path == null) return; if (!connectedTextures) { if (!variants) { world.batch.draw( world.main.manager.get(sprites.get("defaulttex"), Texture.class), x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); } else { world.batch.draw(world.main.manager.get(sprites.get("defaulttex" + ((variantNum(world, x, y)) & (varianttypes - 1))), Texture.class), x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); } } else { drawConnectedTexture(world, x, y, offx, offy, world.main.manager.get(sprites.get("corner"), Texture.class), world.main.manager.get(sprites.get("full"), Texture.class), world.main.manager.get(sprites.get("edgever"), Texture.class), world.main.manager.get(sprites.get("edgehor"), Texture.class)); } } public void drawConnectedTexture(World world, int x, int y, float offx, float offy, Texture corner, Texture full, Texture ver, Texture hor) { boolean up, down, left, right; up = world.getBlock(x, y - 1) == this; down = world.getBlock(x, y + 1) == this; left = world.getBlock(x - 1, y) == this; right = world.getBlock(x + 1, y) == this; if (up && down && left && right) { if (world.getBlock(x + 1, y + 1) != this || world.getBlock(x + 1, y - 1) != this || world.getBlock(x - 1, y + 1) != this || world.getBlock(x - 1, y - 1) != this) { world.batch.draw( corner, x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); } else world.batch.draw(full, x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); } else if (up && down && (left == false || right == false)) { world.batch.draw(ver, x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); } else if (left && right && (up == false || down == false)) { world.batch.draw(hor, x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); } else { world.batch.draw(corner, x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); } } public void drawConnectedTexture(World world, int x, int y, float offx, float offy, TextureRegion corner, TextureRegion full, TextureRegion ver, TextureRegion hor) { boolean up, down, left, right; up = world.getBlock(x, y - 1) == this; down = world.getBlock(x, y + 1) == this; left = world.getBlock(x - 1, y) == this; right = world.getBlock(x + 1, y) == this; if (up && down && left && right) { if (world.getBlock(x + 1, y + 1) != this || world.getBlock(x + 1, y - 1) != this || world.getBlock(x - 1, y + 1) != this || world.getBlock(x - 1, y - 1) != this) { world.batch.draw( corner, x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey)); } else world.batch.draw(full, x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); } else if (up && down && (left == false || right == false)) { world.batch.draw(ver, x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); } else if (left && right && (up == false || down == false)) { world.batch.draw(hor, x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); } else { world.batch.draw(corner, x * world.tilesizex - world.camera.camerax + offx, Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey + offy)); } } // protected void drawAt(SpriteBatch batch, TextureRegion corner, float f, // float g) { // batch.draw(corner, f, Main.convertY(g + World.tilesizey), // World.tilesizex, World.tilesizey); // } public static boolean isEntityNear(World world, int x, int y, int rad, Class<?> cls) { for (int i = 0; i < world.entities.size; i++) { Entity e = world.entities.get(i); if (!(cls.isInstance(e))) continue; if (MathHelper.intersects(e.x, e.y, e.sizex, e.sizey, x - rad + 1, y - rad + 1, rad * 2 - 1, rad * 2 - 1)) return true; } return false; } public static Entity getNearestEntity(World world, int x, int y, int rad, Class<?> cls) { if (isEntityNear(world, x, y, rad, cls)) { for (int i = 0; i < world.entities.size; i++) { Entity e = world.entities.get(i); if (!(cls.isInstance(e))) continue; if (MathHelper.intersects(e.x, e.y, e.sizex, e.sizey, x - rad + 1, y - rad + 1, rad * 2 - 1, rad * 2 - 1)) return e; } } return null; } public static boolean entityIntersects(World world, double x, double y, Entity e) { return entityIntersects(world, x, y, e, 1, 1); } public static boolean entityIntersects(World world, double x, double y, Entity e, double sizex, double sizey) { if (e == null) return false; return MathHelper.intersects(x, y, sizex, sizey, e.x, e.y, e.sizex, e.sizey); } public static boolean isBlockVisible(float camx, float camy, int x, int y) { return MathHelper.intersects(x * World.tilesizex, y * World.tilesizey, World.tilesizex, World.tilesizey, camx, camy, Settings.DEFAULT_WIDTH, Gdx.graphics.getHeight()); } public static boolean playSound(int x, int y, float camx, float camy, Sound sound, float vol, float pitch, boolean mustbevisible) { if (!Block.isBlockVisible(camx, camy, x, y) && mustbevisible) return false; sound.play(vol * Settings.soundVolume, pitch, Utils.getSoundPan(x, camx)); return true; } public static boolean playSound(int x, int y, float camx, float camy, Sound sound, float vol, float pitch) { return playSound(x, y, camx, camy, sound, vol, pitch, true); } public static class SolidFaces{ public static final int NONE = 0; public static final int ALL = 15; public static final int LEFT = 1; public static final int RIGHT = 2; public static final int UP = 4; public static final int DOWN = 8; } }
New values for the faces
src/stray/blocks/Block.java
New values for the faces
<ide><path>rc/stray/blocks/Block.java <ide> <ide> public static final int NONE = 0; <ide> public static final int ALL = 15; <del> public static final int LEFT = 1; <del> public static final int RIGHT = 2; <del> public static final int UP = 4; <del> public static final int DOWN = 8; <add> public static final int UP = 1; <add> public static final int DOWN = 2; <add> public static final int LEFT = 4; <add> public static final int RIGHT = 8; <ide> <ide> } <ide>
Java
isc
a1693a23e7c7a5b0aad388c8362eac11b9507e81
0
junenn/ormlite-android,zhupengGitHub/ormlite-android,ssnhqzj/ormlite-android,happytutu/ormlite-android,nekdenis/ormlite-android,ylfonline/ormlite-android,Juneor/ormlite-android,moon-sky/ormlite-android,hgl888/ormlite-android,lobo12/ormlite-android,Pannarrow/ormlite-android,j256/ormlite-android,dankito/ormlite-jpa-android
package com.j256.ormlite.android; import java.sql.SQLException; import java.sql.Savepoint; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; import com.j256.ormlite.dao.ObjectCache; import com.j256.ormlite.field.FieldType; import com.j256.ormlite.logger.Logger; import com.j256.ormlite.logger.LoggerFactory; import com.j256.ormlite.misc.SqlExceptionUtil; import com.j256.ormlite.stmt.GenericRowMapper; import com.j256.ormlite.stmt.StatementBuilder.StatementType; import com.j256.ormlite.support.CompiledStatement; import com.j256.ormlite.support.DatabaseConnection; import com.j256.ormlite.support.GeneratedKeyHolder; /** * Database connection for Android. * * @author kevingalligan, graywatson */ public class AndroidDatabaseConnection implements DatabaseConnection { private static Logger logger = LoggerFactory.getLogger(AndroidDatabaseConnection.class); private final SQLiteDatabase db; private final boolean readWrite; public AndroidDatabaseConnection(SQLiteDatabase db, boolean readWrite) { this.db = db; this.readWrite = readWrite; logger.trace("databased opened, read-write = {}: {}", readWrite, db); } public boolean isAutoCommitSupported() { return false; } public boolean getAutoCommit() throws SQLException { try { boolean inTransaction = db.inTransaction(); logger.trace("database in transaction is {}", inTransaction); // You have to explicitly commit your transactions, so this is sort of correct return !inTransaction; } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("problems getting auto-commit from database", e); } } public void setAutoCommit(boolean autoCommit) { // always in auto-commit mode } public Savepoint setSavePoint(String name) throws SQLException { try { db.beginTransaction(); logger.trace("save-point set with name {}", name); return new OurSavePoint(name); } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("problems beginning transaction " + name, e); } } /** * Return whether this connection is read-write or not (real-only). */ public boolean isReadWrite() { return readWrite; } public void commit(Savepoint savepoint) throws SQLException { try { db.setTransactionSuccessful(); db.endTransaction(); if (savepoint == null) { logger.trace("database transaction is successfuly ended"); } else { logger.trace("database transaction {} is successfuly ended", savepoint.getSavepointName()); } } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("problems commiting transaction " + savepoint.getSavepointName(), e); } } public void rollback(Savepoint savepoint) throws SQLException { try { // no setTransactionSuccessful() means it is a rollback db.endTransaction(); if (savepoint == null) { logger.trace("database transaction is ended, unsuccessfuly"); } else { logger.trace("database transaction {} is ended, unsuccessfuly", savepoint.getSavepointName()); } } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("problems rolling back transaction " + savepoint.getSavepointName(), e); } } public CompiledStatement compileStatement(String statement, StatementType type, FieldType[] argFieldTypes) { CompiledStatement stmt = new AndroidCompiledStatement(statement, db, type); logger.trace("compiled statement: {}", statement); return stmt; } public int insert(String statement, Object[] args, FieldType[] argFieldTypes, GeneratedKeyHolder keyHolder) throws SQLException { SQLiteStatement stmt = null; try { stmt = db.compileStatement(statement); bindArgs(stmt, args, argFieldTypes); long rowId = stmt.executeInsert(); if (keyHolder != null) { keyHolder.addKey(rowId); } logger.trace("insert statement is compiled and executed: {}", statement); return 1; } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("inserting to database failed: " + statement, e); } finally { if (stmt != null) { stmt.close(); } } } public int update(String statement, Object[] args, FieldType[] argFieldTypes) throws SQLException { return update(statement, args, argFieldTypes, "updated"); } public int delete(String statement, Object[] args, FieldType[] argFieldTypes) throws SQLException { // delete is the same as update return update(statement, args, argFieldTypes, "deleted"); } public <T> Object queryForOne(String statement, Object[] args, FieldType[] argFieldTypes, GenericRowMapper<T> rowMapper, ObjectCache objectCache) throws SQLException { Cursor cursor = null; try { cursor = db.rawQuery(statement, toStrings(args)); AndroidDatabaseResults results = new AndroidDatabaseResults(cursor, objectCache); logger.trace("queried for one result with {}", statement); if (!results.next()) { return null; } else { T first = rowMapper.mapRow(results); if (results.next()) { return MORE_THAN_ONE; } else { return first; } } } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("queryForOne from database failed: " + statement, e); } finally { if (cursor != null) { cursor.close(); } } } public long queryForLong(String statement) throws SQLException { SQLiteStatement stmt = null; try { stmt = db.compileStatement(statement); long result = stmt.simpleQueryForLong(); logger.trace("query for long simple query returned {}: {}", result, statement); return result; } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("queryForLong from database failed: " + statement, e); } finally { if (stmt != null) { stmt.close(); } } } public long queryForLong(String statement, Object[] args, FieldType[] argFieldTypes) throws SQLException { Cursor cursor = null; try { cursor = db.rawQuery(statement, toStrings(args)); AndroidDatabaseResults results = new AndroidDatabaseResults(cursor, null); logger.trace("query for long raw query executed: {}", statement); if (results.next()) { return results.getLong(0); } else { return 0L; } } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("queryForLong from database failed: " + statement, e); } finally { if (cursor != null) { cursor.close(); } } } public void close() throws SQLException { try { db.close(); logger.trace("database closed: {}", db); } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("problems closing the database connection", e); } } public boolean isClosed() throws SQLException { try { boolean isOpen = db.isOpen(); logger.trace("database is open returned {}", isOpen); return !isOpen; } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("problems detecting if the database is closed", e); } } public boolean isTableExists(String tableName) { Cursor cursor = db.rawQuery("SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name = '" + tableName + "'", null); if (cursor != null && cursor.getCount() > 0) { return true; } else { return false; } } private int update(String statement, Object[] args, FieldType[] argFieldTypes, String label) throws SQLException { SQLiteStatement stmt = null; try { stmt = db.compileStatement(statement); bindArgs(stmt, args, argFieldTypes); stmt.execute(); logger.trace("{} statement is compiled and executed: {}", label, statement); return 1; } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("updating database failed: " + statement, e); } finally { if (stmt != null) { stmt.close(); } } } private void bindArgs(SQLiteStatement stmt, Object[] args, FieldType[] argFieldTypes) throws SQLException { if (args == null) { return; } for (int i = 0; i < args.length; i++) { Object arg = args[i]; if (arg == null) { stmt.bindNull(i + 1); } else { switch (argFieldTypes[i].getSqlType()) { case CHAR : case STRING : case LONG_STRING : stmt.bindString(i + 1, arg.toString()); break; case BOOLEAN : case BYTE : case SHORT : case INTEGER : case LONG : stmt.bindLong(i + 1, ((Number) arg).longValue()); break; case FLOAT : case DOUBLE : stmt.bindDouble(i + 1, ((Number) arg).doubleValue()); break; case BYTE_ARRAY : case SERIALIZABLE : stmt.bindBlob(i + 1, (byte[]) arg); break; default : throw new SQLException("Unknown sql argument type " + argFieldTypes[i].getSqlType()); } } } } private String[] toStrings(Object[] args) { if (args == null || args.length == 0) { return null; } String[] strings = new String[args.length]; for (int i = 0; i < args.length; i++) { Object arg = args[i]; if (arg == null) { strings[i] = null; } else { strings[i] = arg.toString(); } } return strings; } private static class OurSavePoint implements Savepoint { private String name; public OurSavePoint(String name) { this.name = name; } public int getSavepointId() { return 0; } public String getSavepointName() { return name; } } }
src/main/java/com/j256/ormlite/android/AndroidDatabaseConnection.java
package com.j256.ormlite.android; import java.sql.SQLException; import java.sql.Savepoint; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; import com.j256.ormlite.dao.ObjectCache; import com.j256.ormlite.field.FieldType; import com.j256.ormlite.logger.Logger; import com.j256.ormlite.logger.LoggerFactory; import com.j256.ormlite.misc.SqlExceptionUtil; import com.j256.ormlite.stmt.GenericRowMapper; import com.j256.ormlite.stmt.StatementBuilder.StatementType; import com.j256.ormlite.support.CompiledStatement; import com.j256.ormlite.support.DatabaseConnection; import com.j256.ormlite.support.GeneratedKeyHolder; /** * Database connection for Android. * * @author kevingalligan, graywatson */ public class AndroidDatabaseConnection implements DatabaseConnection { private static Logger logger = LoggerFactory.getLogger(AndroidDatabaseConnection.class); private final SQLiteDatabase db; private final boolean readWrite; public AndroidDatabaseConnection(SQLiteDatabase db, boolean readWrite) { this.db = db; this.readWrite = readWrite; logger.trace("databased opened, read-write = {}: {}", readWrite, db); } public boolean isAutoCommitSupported() { return false; } public boolean getAutoCommit() throws SQLException { try { boolean inTransaction = db.inTransaction(); logger.trace("database in transaction is {}", inTransaction); // You have to explicitly commit your transactions, so this is sort of correct return !inTransaction; } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("problems getting auto-commit from database", e); } } public void setAutoCommit(boolean autoCommit) { // always in auto-commit mode } public Savepoint setSavePoint(String name) throws SQLException { try { db.beginTransaction(); logger.trace("save-point set with name {}", name); return new OurSavePoint(name); } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("problems beginning transaction " + name, e); } } /** * Return whether this connection is read-write or not (real-only). */ public boolean isReadWrite() { return readWrite; } public void commit(Savepoint savepoint) throws SQLException { try { db.setTransactionSuccessful(); db.endTransaction(); if (savepoint == null) { logger.trace("database transaction is successfuly ended"); } else { logger.trace("database transaction {} is successfuly ended", savepoint.getSavepointName()); } } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("problems commiting transaction " + savepoint.getSavepointName(), e); } } public void rollback(Savepoint savepoint) throws SQLException { try { // no setTransactionSuccessful() means it is a rollback db.endTransaction(); if (savepoint == null) { logger.trace("database transaction is ended, unsuccessfuly"); } else { logger.trace("database transaction {} is ended, unsuccessfuly", savepoint.getSavepointName()); } } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("problems rolling back transaction " + savepoint.getSavepointName(), e); } } public CompiledStatement compileStatement(String statement, StatementType type, FieldType[] argFieldTypes) { CompiledStatement stmt = new AndroidCompiledStatement(statement, db, type); logger.trace("compiled statement: {}", statement); return stmt; } public int insert(String statement, Object[] args, FieldType[] argFieldTypes, GeneratedKeyHolder keyHolder) throws SQLException { SQLiteStatement stmt = null; try { stmt = db.compileStatement(statement); bindArgs(stmt, args, argFieldTypes); long rowId = stmt.executeInsert(); if (keyHolder != null) { keyHolder.addKey(rowId); } logger.trace("insert statement is compiled and executed: {}", statement); return 1; } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("inserting to database failed: " + statement, e); } finally { if (stmt != null) { stmt.close(); } } } public int update(String statement, Object[] args, FieldType[] argFieldTypes) throws SQLException { return update(statement, args, argFieldTypes, "updated"); } public int delete(String statement, Object[] args, FieldType[] argFieldTypes) throws SQLException { // delete is the same as update return update(statement, args, argFieldTypes, "deleted"); } public <T> Object queryForOne(String statement, Object[] args, FieldType[] argFieldTypes, GenericRowMapper<T> rowMapper, ObjectCache objectCache) throws SQLException { Cursor cursor = null; try { cursor = db.rawQuery(statement, toStrings(args)); AndroidDatabaseResults results = new AndroidDatabaseResults(cursor, objectCache); logger.trace("queried for one result with {}", statement); if (!results.next()) { return null; } else { T first = rowMapper.mapRow(results); if (results.next()) { return MORE_THAN_ONE; } else { return first; } } } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("queryForOne from database failed: " + statement, e); } finally { if (cursor != null) { cursor.close(); } } } public long queryForLong(String statement) throws SQLException { SQLiteStatement stmt = null; try { stmt = db.compileStatement(statement); long result = stmt.simpleQueryForLong(); logger.trace("query for long simple query returned {}: {}", result, statement); return result; } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("queryForLong from database failed: " + statement, e); } finally { if (stmt != null) { stmt.close(); } } } public long queryForLong(String statement, Object[] args, FieldType[] argFieldTypes) throws SQLException { Cursor cursor = null; try { cursor = db.rawQuery(statement, toStrings(args)); AndroidDatabaseResults results = new AndroidDatabaseResults(cursor, null); logger.trace("query for long raw query executed: {}", statement); if (results.next()) { return results.getLong(0); } else { return 0L; } } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("queryForLong from database failed: " + statement, e); } finally { if (cursor != null) { cursor.close(); } } } public void close() throws SQLException { try { db.close(); logger.trace("database closed: {}", db); } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("problems closing the database connection", e); } } public boolean isClosed() throws SQLException { try { boolean isOpen = db.isOpen(); logger.trace("database is open returned {}", isOpen); return !isOpen; } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("problems detecting if the database is closed", e); } } public boolean isTableExists(String tableName) { // NOTE: it is non trivial to do this check since the helper will auto-create if it doesn't exist return true; } private int update(String statement, Object[] args, FieldType[] argFieldTypes, String label) throws SQLException { SQLiteStatement stmt = null; try { stmt = db.compileStatement(statement); bindArgs(stmt, args, argFieldTypes); stmt.execute(); logger.trace("{} statement is compiled and executed: {}", label, statement); return 1; } catch (android.database.SQLException e) { throw SqlExceptionUtil.create("updating database failed: " + statement, e); } finally { if (stmt != null) { stmt.close(); } } } private void bindArgs(SQLiteStatement stmt, Object[] args, FieldType[] argFieldTypes) throws SQLException { if (args == null) { return; } for (int i = 0; i < args.length; i++) { Object arg = args[i]; if (arg == null) { stmt.bindNull(i + 1); } else { switch (argFieldTypes[i].getSqlType()) { case CHAR : case STRING : case LONG_STRING : stmt.bindString(i + 1, arg.toString()); break; case BOOLEAN : case BYTE : case SHORT : case INTEGER : case LONG : stmt.bindLong(i + 1, ((Number) arg).longValue()); break; case FLOAT : case DOUBLE : stmt.bindDouble(i + 1, ((Number) arg).doubleValue()); break; case BYTE_ARRAY : case SERIALIZABLE : stmt.bindBlob(i + 1, (byte[]) arg); break; default : throw new SQLException("Unknown sql argument type " + argFieldTypes[i].getSqlType()); } } } } private String[] toStrings(Object[] args) { if (args == null || args.length == 0) { return null; } String[] strings = new String[args.length]; for (int i = 0; i < args.length; i++) { Object arg = args[i]; if (arg == null) { strings[i] = null; } else { strings[i] = arg.toString(); } } return strings; } private static class OurSavePoint implements Savepoint { private String name; public OurSavePoint(String name) { this.name = name; } public int getSavepointId() { return 0; } public String getSavepointName() { return name; } } }
Added isTableExists() support to Dao/AndroidDatabaseConnection. Thanks to Patrick. Fixes feature #3475173.
src/main/java/com/j256/ormlite/android/AndroidDatabaseConnection.java
Added isTableExists() support to Dao/AndroidDatabaseConnection. Thanks to Patrick. Fixes feature #3475173.
<ide><path>rc/main/java/com/j256/ormlite/android/AndroidDatabaseConnection.java <ide> } <ide> <ide> public boolean isTableExists(String tableName) { <del> // NOTE: it is non trivial to do this check since the helper will auto-create if it doesn't exist <del> return true; <add> Cursor cursor = <add> db.rawQuery("SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name = '" + tableName + "'", null); <add> if (cursor != null && cursor.getCount() > 0) { <add> return true; <add> } else { <add> return false; <add> } <ide> } <ide> <ide> private int update(String statement, Object[] args, FieldType[] argFieldTypes, String label) throws SQLException {
JavaScript
apache-2.0
aaf628e6317672c8a99dfa866546aa0125b69ae0
0
projectfluent/fluent.js,projectfluent/fluent.js,zbraniecki/l20n.js,zbraniecki/fluent.js,projectfluent/fluent.js,zbraniecki/fluent.js,stasm/l20n.js,l20n/l20n.js
import { L10nError } from './errors'; const KNOWN_BUILTINS = ['PLURAL', 'NUMBER', 'LIST']; const MAX_PLACEABLE_LENGTH = 2500; // Unicode bidi isolation characters const FSI = '\u2068'; const PDI = '\u2069'; // Helper for converting primitives into builtins function wrap(res, expr) { if (typeof expr === 'object' && expr.equals) { return expr; } if (typeof expr === 'number') { return res.ctx._getBuiltin(res.lang, 'NUMBER')(expr); } if (typeof expr === 'string') { return { equals(other) { return other === expr; }, format() { return expr; } }; } } // Helper functions for inserting a placeable value into a string function stringify(res, value) { const wrapped = wrap(res, value); return FSI + wrapped.format( elem => stringify(res, elem) ) + PDI; } function stringifyList(res, list) { // the most common scenario; avoid creating a ListFormat instance if (list.length === 1) { return stringify(res, list[0]); } const builtin = res.ctx._getBuiltin(res.lang, 'LIST'); return builtin(...list).format( elem => stringify(res, elem) ); // XXX add this back later // if (value.length >= MAX_PLACEABLE_LENGTH) { // throw new L10nError( // 'Too many characters in placeable (' + value.length + // ', max allowed is ' + MAX_PLACEABLE_LENGTH + ')' // ); // } } // Helper for choosing entity value function DefaultMember(members) { for (let member of members) { if (member.default) { return member; } } throw new L10nError('No default.'); } // Half-resolved expressions function Expression(res, expr) { switch (expr.type) { case 'EntityReference': return EntityReference(res, expr); case 'MemberExpression': return MemberExpression(res, expr); case 'PlaceableExpression': return SelectExpression(res, expr); default: return expr; } } function EntityReference(res, expr) { const entity = res.ctx._getEntity(res.lang, expr.id); if (!entity) { throw new L10nError('Unknown entity: ' + expr.id); } return entity; } function MemberExpression(res, expr) { const entity = Expression(res, expr.idref); const key = Value(res, expr.keyword); for (let trait of entity.traits) { if (key === Value(res, trait.key)) { return trait; } } throw new L10nError('Unknown trait: ' + key); } function SelectExpression(res, expr) { // XXX remove if (expr.variants === null) { return Expression(res, expr.expression); } const wrapped = wrap(res, Value(res, expr.expression)); for (let variant of expr.variants) { if (wrapped.equals(Value(res, variant.key))) { return variant; } } return DefaultMember(expr.variants); } // Fully-resolved expressions function Value(res, expr) { const node = Expression(res, expr); switch (node.type) { case 'TextElement': case 'Keyword': return node.value; case 'Number': return parseFloat(node.value); case 'Variable': return Variable(res, node); case 'Placeable': return Placeable(res, node); case 'CallExpression': return CallExpression(res, expr); case 'String': return Pattern(res, node); case 'Member': return Pattern(res, node.value); case 'Entity': return Entity(res, node); default: throw new L10nError('Unknown expression type'); } } function Variable(res, expr) { const id = expr.id; const args = res.args; if (args && args.hasOwnProperty(id)) { return args[id]; } throw new L10nError('Unknown variable: ' + id); } function Placeable(res, placeable) { return placeable.expressions.map( expr => Value(res, expr) ); } function CallExpression(res, expr) { const callee = expr.callee.id; if (KNOWN_BUILTINS.indexOf(callee) === -1) { throw new L10nError('Unknown built-in: ' + callee); } const builtin = res.ctx._getBuiltin(res.lang, callee); const args = expr.args.map( arg => Value(res, arg) ); return builtin(...args); } function Pattern(res, ptn) { if (res.dirty.has(ptn)) { const ref = ptn.id || ptn.key; throw new L10nError('Cyclic reference: ' + ref); } res.dirty.add(ptn); const [errs, str] = formatPattern(res, ptn); if (errs.length) { throw new L10nError('Broken value.'); } return str; } function Entity(res, entity) { const value = entity.value !== null ? entity.value : DefaultMember(entity.traits).value; return Pattern(res, value); } // formatPattern collects errors and returns them as the first element of // the return tuple: [errors, value] function formatPattern(res, ptn) { return ptn.elements.reduce(([errs, seq], elem) => { if (elem.type === 'TextElement') { return [errs, seq + elem.value]; } else if (elem.type === 'Placeable') { try { return [errs, seq + stringifyList(res, Value(res, elem))]; } catch(e) { return [[...errs, e], seq + stringify(res, '{' + elem.source + '}')]; } } }, [[], '']); } export function format(ctx, lang, args, entity) { const res = { ctx, lang, args, errors: [], dirty: new WeakSet() }; try { const value = entity.value !== null ? entity.value : DefaultMember(entity.traits).value; res.dirty.add(value); return formatPattern(res, value); } catch (e) { const err = new L10nError('No value: ' + entity.id); return [[err], null]; } }
src/lib/resolver.js
import { L10nError } from './errors'; const KNOWN_BUILTINS = ['PLURAL', 'NUMBER', 'LIST']; const MAX_PLACEABLE_LENGTH = 2500; // Unicode bidi isolation characters const FSI = '\u2068'; const PDI = '\u2069'; // Helper for converting primitives into builtins function wrap(res, expr) { if (typeof expr === 'object' && expr.equals) { return expr; } if (typeof expr === 'number') { return res.ctx._getBuiltin(res.lang, 'NUMBER')(expr); } if (typeof expr === 'string') { return { equals(other) { return other === expr; }, format() { return expr; } }; } } // Helper functions for inserting a placeable value into a string function stringify(res, value) { const wrapped = wrap(res, value); return FSI + wrapped.format( elem => stringify(res, elem) ) + PDI; } function stringifyList(res, list) { // the most common scenario; avoid creating a ListFormat instance if (list.length === 1) { return stringify(res, list[0]); } const builtin = res.ctx._getBuiltin(res.lang, 'LIST'); return builtin(...list).format( elem => stringify(res, elem) ); // XXX add this back later // if (value.length >= MAX_PLACEABLE_LENGTH) { // throw new L10nError( // 'Too many characters in placeable (' + value.length + // ', max allowed is ' + MAX_PLACEABLE_LENGTH + ')' // ); // } } // Helper for choosing entity value function getValueNode(entity) { if (entity.value !== null) { return entity; } for (let trait of entity.traits) { if (trait.default) { return trait; } } throw new L10nError('No value: ' + entity.id); } function Expression(res, expr) { switch (expr.type) { case 'EntityReference': return EntityReference(res, expr); case 'MemberExpression': return MemberExpression(res, expr); case 'PlaceableExpression': return SelectExpression(res, expr); default: return expr; } } function EntityReference(res, expr) { const entity = res.ctx._getEntity(res.lang, expr.id); if (!entity) { throw new L10nError('Unknown entity: ' + expr.id); } return entity; } function MemberExpression(res, expr) { const entity = Expression(res, expr.idref); const key = Value(res, expr.keyword); for (let trait of entity.traits) { if (key === Value(res, trait.key)) { return trait; } } throw new L10nError('Unknown trait: ' + key); } function SelectExpression(res, expr) { // XXX remove if (expr.variants === null) { return Expression(res, expr.expression); } const wrapped = wrap(res, Value(res, expr.expression)); for (let variant of expr.variants) { if (wrapped.equals(Value(res, variant.key))) { return variant; } } for (let variant of expr.variants) { if (variant.default) { return variant; } } throw new L10nError('No default variant found'); } function Value(res, expr) { const node = Expression(res, expr); switch (node.type) { case 'TextElement': case 'Keyword': return node.value; case 'Number': return parseFloat(node.value); case 'Variable': return Variable(res, node); case 'Placeable': return Placeable(res, node); case 'CallExpression': return CallExpression(res, expr); case 'String': return Pattern(res, node); case 'Member': return Pattern(res, node.value); case 'Entity': return Pattern(res, getValueNode(node).value); default: throw new L10nError('Unknown expression type'); } } function Variable(res, expr) { const id = expr.id; const args = res.args; if (args && args.hasOwnProperty(id)) { return args[id]; } throw new L10nError('Unknown variable: ' + id); } function Placeable(res, placeable) { return placeable.expressions.map( expr => Value(res, expr) ); } function CallExpression(res, expr) { const callee = expr.callee.id; if (KNOWN_BUILTINS.indexOf(callee) === -1) { throw new L10nError('Unknown built-in: ' + callee); } const builtin = res.ctx._getBuiltin(res.lang, callee); const args = expr.args.map( arg => Value(res, arg) ); return builtin(...args); } function Pattern(res, ptn) { if (res.dirty.has(ptn)) { const ref = ptn.id || ptn.key; throw new L10nError('Cyclic reference: ' + ref); } res.dirty.add(ptn); const [errs, str] = formatPattern(res, ptn); if (errs.length) { throw new L10nError('Broken value.'); } return str; } // formatPattern collects errors and returns them as the first element of // the return tuple: [errors, value] function formatPattern(res, ptn) { return ptn.elements.reduce(([errs, seq], elem) => { if (elem.type === 'TextElement') { return [errs, seq + elem.value]; } else if (elem.type === 'Placeable') { try { return [errs, seq + stringifyList(res, Value(res, elem))]; } catch(e) { return [[...errs, e], seq + stringify(res, '{' + elem.source + '}')]; } } }, [[], '']); } export function format(ctx, lang, args, entity) { const res = { ctx, lang, args, errors: [], dirty: new WeakSet() }; const node = getValueNode(entity); if (node === null) { const err = new L10nError('No value: ' + entity.id); return [[err], null]; } res.dirty.add(node); return formatPattern(res, node.value); }
DefaultMember
src/lib/resolver.js
DefaultMember
<ide><path>rc/lib/resolver.js <ide> <ide> // Helper for choosing entity value <ide> <del>function getValueNode(entity) { <del> if (entity.value !== null) { <del> return entity; <del> } <del> <del> for (let trait of entity.traits) { <del> if (trait.default) { <del> return trait; <del> } <del> } <del> <del> throw new L10nError('No value: ' + entity.id); <del>} <del> <add>function DefaultMember(members) { <add> for (let member of members) { <add> if (member.default) { <add> return member; <add> } <add> } <add> <add> throw new L10nError('No default.'); <add>} <add> <add> <add>// Half-resolved expressions <ide> <ide> function Expression(res, expr) { <ide> switch (expr.type) { <ide> } <ide> } <ide> <del> for (let variant of expr.variants) { <del> if (variant.default) { <del> return variant; <del> } <del> } <del> <del> throw new L10nError('No default variant found'); <del>} <del> <add> return DefaultMember(expr.variants); <add>} <add> <add> <add>// Fully-resolved expressions <ide> <ide> function Value(res, expr) { <ide> const node = Expression(res, expr); <ide> case 'Member': <ide> return Pattern(res, node.value); <ide> case 'Entity': <del> return Pattern(res, getValueNode(node).value); <add> return Entity(res, node); <ide> default: <ide> throw new L10nError('Unknown expression type'); <ide> } <ide> } <ide> <ide> return str; <add>} <add> <add>function Entity(res, entity) { <add> const value = entity.value !== null ? <add> entity.value : DefaultMember(entity.traits).value; <add> <add> return Pattern(res, value); <ide> } <ide> <ide> <ide> dirty: new WeakSet() <ide> }; <ide> <del> const node = getValueNode(entity); <del> if (node === null) { <add> try { <add> const value = entity.value !== null ? <add> entity.value : DefaultMember(entity.traits).value; <add> res.dirty.add(value); <add> return formatPattern(res, value); <add> } catch (e) { <ide> const err = new L10nError('No value: ' + entity.id); <ide> return [[err], null]; <ide> } <del> <del> res.dirty.add(node); <del> return formatPattern(res, node.value); <del>} <add>}
Java
mit
50fca839ba1a43e9104eb0ea7282f3a5b5e1743e
0
cs2103aug2014-t17-1j/main
package taskDo; import java.util.ArrayList; import commonClasses.StorageList; public class CategoryList { //Members private static ArrayList<Category> categoryList; //Constructor private CategoryList() { } //Accessor public static ArrayList<Category> getCategoryList() { if(categoryList == null) { categoryList = new ArrayList<Category>(); } return categoryList; } //Mutator public static boolean addCategory(String name) { categoryList.add(new Category(name)); return true; } public static boolean deleteCategory(String name) { for(int i=0; i<categoryList.size(); i++) { if(categoryList.get(i).getName().toLowerCase().equals(name.toLowerCase())) { categoryList.remove(i); return true; } } return false; } //Extra methods public static void updateCategoryList() { categoryList.clear(); ArrayList<Task> updatedTask = StorageList.getInstance().getTaskList(); for(int i=0;i<updatedTask.size();i++) { String categoryName = updatedTask.get(i).getCategory(); if(categoryName != null) { if(isExistingCategory(categoryName.toLowerCase())) { addCountToCategory(categoryName.toLowerCase()); } else { addCategory(categoryName.toLowerCase()); } } } } public static boolean isExistingCategory(String name) { /*for(int i=0; i<categoryList.size(); i++) { if(categoryList.get(i).getName().toLowerCase().equals(name.toLowerCase())) { return true; } } */ return false; } public static int getCategoryIndex(String name) { for(int i=0; i<categoryList.size(); i++) { if(categoryList.get(i).getName().toLowerCase().equals(name.toLowerCase())) { return i; } } return -1;//index not found } public static void addCountToCategory(String name) { int index = getCategoryIndex(name); if(index != -1) { categoryList.get(index).addCount(); } } public static void minusCountToCategory(String name) { int index = getCategoryIndex(name); if(index != -1) { categoryList.get(index).decreaseCount(); } } }
src/taskDo/CategoryList.java
package taskDo; import java.util.ArrayList; import Parser.ParsedResult; import commandFactory.CommandType; public class CategoryList { //Members private static ArrayList<Category> categoryList; //Constructor private CategoryList() { } //Accessor public static ArrayList<Category> getCategoryList() { if(categoryList == null) { categoryList = new ArrayList<Category>(); } return categoryList; } //Mutator public static boolean addCategory(String name) { categoryList.add(new Category(name)); return true; } public static boolean deleteCategory(String name) { for(int i=0; i<categoryList.size(); i++) { if(categoryList.get(i).getName().toLowerCase().equals(name.toLowerCase())) { categoryList.remove(i); return true; } } return false; } //Extra methods public static void updateCategoryList(CommandType command, String categoryName) { switch(command) { case ADD: if(CategoryList.isExistingCategory(categoryName)) { CategoryList.addCountToCategory(categoryName); } else { CategoryList.addCategory(categoryName); } break; case DELETE: if(categoryName != null && CategoryList.isExistingCategory(categoryName)) { CategoryList.minusCountToCategory(categoryName); } break; case UNDO: case COMPLETE: if(categoryName != null && CategoryList.isExistingCategory(categoryName)) { CategoryList.minusCountToCategory(categoryName); } break; } } public static boolean isExistingCategory(String name) { /*for(int i=0; i<categoryList.size(); i++) { if(categoryList.get(i).getName().toLowerCase().equals(name.toLowerCase())) { return true; } } */ return false; } public static int getCategoryIndex(String name) { for(int i=0; i<categoryList.size(); i++) { if(categoryList.get(i).getName().toLowerCase().equals(name.toLowerCase())) { return i; } } return -1;//index not found } public static void addCountToCategory(String name) { int index = getCategoryIndex(name); if(index != -1) { categoryList.get(index).addCount(); } } public static void minusCountToCategory(String name) { int index = getCategoryIndex(name); if(index != -1) { categoryList.get(index).decreaseCount(); } } }
CategoryList updates each time an command is carried out.
src/taskDo/CategoryList.java
CategoryList updates each time an command is carried out.
<ide><path>rc/taskDo/CategoryList.java <ide> <ide> import java.util.ArrayList; <ide> <del>import Parser.ParsedResult; <del> <del>import commandFactory.CommandType; <add>import commonClasses.StorageList; <ide> <ide> public class CategoryList { <ide> <ide> } <ide> <ide> //Extra methods <del> public static void updateCategoryList(CommandType command, String categoryName) { <del> <del> switch(command) { <del> <del> case ADD: <del> if(CategoryList.isExistingCategory(categoryName)) { <del> CategoryList.addCountToCategory(categoryName); <add> public static void updateCategoryList() { <add> <add> categoryList.clear(); <add> ArrayList<Task> updatedTask = StorageList.getInstance().getTaskList(); <add> <add> for(int i=0;i<updatedTask.size();i++) { <add> String categoryName = updatedTask.get(i).getCategory(); <add> if(categoryName != null) { <add> if(isExistingCategory(categoryName.toLowerCase())) { <add> addCountToCategory(categoryName.toLowerCase()); <ide> } else { <del> CategoryList.addCategory(categoryName); <add> addCategory(categoryName.toLowerCase()); <ide> } <del> break; <ide> <del> case DELETE: <del> if(categoryName != null && CategoryList.isExistingCategory(categoryName)) { <del> CategoryList.minusCountToCategory(categoryName); <del> } <del> break; <del> <del> case UNDO: <del> <del> case COMPLETE: <del> if(categoryName != null && CategoryList.isExistingCategory(categoryName)) { <del> CategoryList.minusCountToCategory(categoryName); <del> } <del> break; <add> } <ide> } <add> <ide> } <ide> <ide> public static boolean isExistingCategory(String name) {
Java
mit
555d15ac2b9025016ac36241f56a3e1d1464f8a7
0
CC007/KnowledgeSystem,CC007/KnowledgeSystem,CC007/KnowledgeSystem
/* * 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 com.github.cc007.knowledgesystem.utils; import com.github.cc007.knowledgesystem.model.knowledge.KnowledgeBase; import com.github.cc007.knowledgesystem.model.knowledge.KnowledgeOrigin; import com.github.cc007.knowledgesystem.model.knowledge.items.ChoiceSelectionItem; import com.github.cc007.knowledgesystem.model.knowledge.items.FloatingPointItem; import com.github.cc007.knowledgesystem.model.knowledge.items.MultipleChoiceSelectionItem; import com.github.cc007.knowledgesystem.model.rules.RuleBase; import com.github.cc007.knowledgesystem.utils.yml.YMLFile; import com.github.cc007.knowledgesystem.utils.yml.YMLNode; import com.github.cc007.knowledgesystem.utils.yml.YMLNodeList; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author annet */ public class YMLFileModelLoader extends FileModelLoader { public YMLFileModelLoader(String fileName) { super(fileName); } public void load(RuleBase ruleBase, KnowledgeBase knowledgeBase){ try { YMLFile knowledge = new YMLFile(fileName); YMLNode root = knowledge.getRootNode(); List<YMLNode> lists = root.getNodeList("lists").getNodes(); Map<String, List> listsMap = new HashMap<>(); for (YMLNode list : lists) { String name = list.getString("name"); List<String> options = list.getNodeList("options").getStrings(); listsMap.put(name, lists); } knowledgeBase.setItem(new ChoiceSelectionItem("leerling", jaNeeList, KnowledgeOrigin.CHOICESELECTION, false).setQuestion("Gaat het om een minderjarige die naar school gaat?")); name, type, question, options, tip List<YMLNode> questions = root.getNodeList("questions").getNodes(); for (YMLNode question : questions) { String name = question.getString("name"); String type = question.getString("type"); String questionText = question.getString("question"); String tip = question.getString("tip"); switch(type) { case "choiceSelection": String options = question.getString("options"); knowledgeBase.setItem(new ChoiceSelectionItem(name, listsMap.get(options), KnowledgeOrigin.CHOICESELECTION, false).setQuestion(questionText)); break; case "floatingPoint": //TODO case "multiChoiceSelection": String options = question.getString("options"); knowledgeBase.setItem(new MultipleChoiceSelectionItem(name, listsMap.get(options), KnowledgeOrigin.MULTICHOICESELECTION, false).setQuestion(questionText)); break; } } YMLNodeList goals = root.getNodeList("goals"); YMLNodeList rules = root.getNodeList("rules"); } catch (IOException ex) { Logger.getLogger(YMLFileModelLoader.class.getName()).log(Level.SEVERE, null, ex); } } }
src/main/java/com/github/cc007/knowledgesystem/utils/YMLFileModelLoader.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 com.github.cc007.knowledgesystem.utils; import java.io.File; /** * * @author annet */ public class YMLFileModelLoader extends FileModelLoader { public YMLFileModelLoader(File file) { super(file); } public YMLFileModelLoader(String fileName) { super(fileName); } }
Begin gemaakt YML parser
src/main/java/com/github/cc007/knowledgesystem/utils/YMLFileModelLoader.java
Begin gemaakt YML parser
<ide><path>rc/main/java/com/github/cc007/knowledgesystem/utils/YMLFileModelLoader.java <ide> */ <ide> package com.github.cc007.knowledgesystem.utils; <ide> <add>import com.github.cc007.knowledgesystem.model.knowledge.KnowledgeBase; <add>import com.github.cc007.knowledgesystem.model.knowledge.KnowledgeOrigin; <add>import com.github.cc007.knowledgesystem.model.knowledge.items.ChoiceSelectionItem; <add>import com.github.cc007.knowledgesystem.model.knowledge.items.FloatingPointItem; <add>import com.github.cc007.knowledgesystem.model.knowledge.items.MultipleChoiceSelectionItem; <add>import com.github.cc007.knowledgesystem.model.rules.RuleBase; <add>import com.github.cc007.knowledgesystem.utils.yml.YMLFile; <add>import com.github.cc007.knowledgesystem.utils.yml.YMLNode; <add>import com.github.cc007.knowledgesystem.utils.yml.YMLNodeList; <ide> import java.io.File; <add>import java.io.IOException; <add>import java.util.HashMap; <add>import java.util.List; <add>import java.util.Map; <add>import java.util.logging.Level; <add>import java.util.logging.Logger; <ide> <ide> /** <ide> * <ide> */ <ide> public class YMLFileModelLoader extends FileModelLoader { <ide> <del> public YMLFileModelLoader(File file) { <del> super(file); <add> public YMLFileModelLoader(String fileName) { <add> super(fileName); <add> <ide> } <ide> <del> public YMLFileModelLoader(String fileName) { <del> super(fileName); <add> public void load(RuleBase ruleBase, KnowledgeBase knowledgeBase){ <add> try { <add> YMLFile knowledge = new YMLFile(fileName); <add> YMLNode root = knowledge.getRootNode(); <add> List<YMLNode> lists = root.getNodeList("lists").getNodes(); <add> Map<String, List> listsMap = new HashMap<>(); <add> for (YMLNode list : lists) { <add> String name = list.getString("name"); <add> List<String> options = list.getNodeList("options").getStrings(); <add> listsMap.put(name, lists); <add> } <add> <add> knowledgeBase.setItem(new ChoiceSelectionItem("leerling", jaNeeList, KnowledgeOrigin.CHOICESELECTION, false).setQuestion("Gaat het om een minderjarige die naar school gaat?")); <add> name, type, question, options, tip <add> <add> <add> List<YMLNode> questions = root.getNodeList("questions").getNodes(); <add> for (YMLNode question : questions) { <add> String name = question.getString("name"); <add> String type = question.getString("type"); <add> String questionText = question.getString("question"); <add> <add> String tip = question.getString("tip"); <add> <add> switch(type) { <add> case "choiceSelection": String options = question.getString("options"); <add> knowledgeBase.setItem(new ChoiceSelectionItem(name, listsMap.get(options), KnowledgeOrigin.CHOICESELECTION, false).setQuestion(questionText)); <add> break; <add> case "floatingPoint": //TODO <add> case "multiChoiceSelection": String options = question.getString("options"); <add> knowledgeBase.setItem(new MultipleChoiceSelectionItem(name, listsMap.get(options), KnowledgeOrigin.MULTICHOICESELECTION, false).setQuestion(questionText)); <add> break; <add> <add> } <add> <add> } <add> <add> <add> YMLNodeList goals = root.getNodeList("goals"); <add> YMLNodeList rules = root.getNodeList("rules"); <add> <add> <add> <add> <add> <add> <add> <add> <add> <add> <add> } catch (IOException ex) { <add> Logger.getLogger(YMLFileModelLoader.class.getName()).log(Level.SEVERE, null, ex); <add> } <add> <ide> } <ide> <ide> }
Java
mit
error: pathspec '1-algorithm/13-leetcode/java/src/fundamentals/tree/lc235_lowestcommonancestorofabinarysearchtree/Solution.java' did not match any file(s) known to git
db9de64e7bab45e75c88c07ae187f75259c803f1
1
cdai/interview
package fundamentals.tree.lc235_lowestcommonancestorofabinarysearchtree; import fundamentals.tree.TreeNode; /** * Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. * According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w * as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” * For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. * Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. */ public class Solution { public static void main(String[] args) { TreeNode root = new TreeNode(2); root.right = new TreeNode(1); System.out.println(new Solution().lowestCommonAncestor(root, root, root.right).val); } public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null) { return null; } if (p.val > q.val) { TreeNode tmp = p; p = q; q = tmp; } if (p.val <= root.val && root.val <= q.val) { return root; } return (root.val > q.val) ? lowestCommonAncestor(root.left, p, q) : lowestCommonAncestor(root.right, p, q); // p.val > root.val } }
1-algorithm/13-leetcode/java/src/fundamentals/tree/lc235_lowestcommonancestorofabinarysearchtree/Solution.java
leetcode-235 lowest common ancestor of a binary search tree
1-algorithm/13-leetcode/java/src/fundamentals/tree/lc235_lowestcommonancestorofabinarysearchtree/Solution.java
leetcode-235 lowest common ancestor of a binary search tree
<ide><path>-algorithm/13-leetcode/java/src/fundamentals/tree/lc235_lowestcommonancestorofabinarysearchtree/Solution.java <add>package fundamentals.tree.lc235_lowestcommonancestorofabinarysearchtree; <add> <add>import fundamentals.tree.TreeNode; <add> <add>/** <add> * Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. <add> * According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w <add> * as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” <add> * For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. <add> * Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. <add> */ <add>public class Solution { <add> <add> public static void main(String[] args) { <add> TreeNode root = new TreeNode(2); <add> root.right = new TreeNode(1); <add> System.out.println(new Solution().lowestCommonAncestor(root, root, root.right).val); <add> } <add> <add> public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { <add> if (root == null) { <add> return null; <add> } <add> if (p.val > q.val) { <add> TreeNode tmp = p; <add> p = q; <add> q = tmp; <add> } <add> <add> if (p.val <= root.val && root.val <= q.val) { <add> return root; <add> } <add> return (root.val > q.val) <add> ? lowestCommonAncestor(root.left, p, q) <add> : lowestCommonAncestor(root.right, p, q); // p.val > root.val <add> } <add> <add>}
Java
apache-2.0
5bb0b2baa8b1b07dbea2608ba2b8bf7041d84690
0
mikosik/smooth-build,mikosik/smooth-build
package org.smoothbuild.lang.function.nativ; import static org.smoothbuild.util.ReflexiveUtils.isPublic; import static org.smoothbuild.util.ReflexiveUtils.isStatic; import java.lang.reflect.Method; import org.smoothbuild.lang.base.NativeApi; import org.smoothbuild.lang.base.SValue; import org.smoothbuild.lang.function.base.Signature; import org.smoothbuild.lang.function.nativ.err.MissingNameException; import org.smoothbuild.lang.function.nativ.err.NativeImplementationException; import org.smoothbuild.lang.function.nativ.err.NoSmoothFunctionException; import org.smoothbuild.lang.function.nativ.err.NonPublicSmoothFunctionException; import org.smoothbuild.lang.function.nativ.err.NonStaticSmoothFunctionException; import org.smoothbuild.lang.function.nativ.err.WrongParamsInSmoothFunctionException; import org.smoothbuild.lang.plugin.SmoothFunction; import org.smoothbuild.task.exec.NativeApiImpl; public class NativeFunctionFactory { public static NativeFunction<?> create(Class<?> klass, boolean builtin) throws NativeImplementationException { Method method = getExecuteMethod(klass); return createNativeFunction(method, builtin); } public static NativeFunction<?> createNativeFunction(Method method, boolean builtin) throws NativeImplementationException, MissingNameException { if (!isPublic(method)) { throw new NonPublicSmoothFunctionException(method); } if (!isStatic(method)) { throw new NonStaticSmoothFunctionException(method); } Class<?>[] paramTypes = method.getParameterTypes(); if (paramTypes.length != 2) { throw new WrongParamsInSmoothFunctionException(method); } Class<?> first = paramTypes[0]; if (!(first.equals(NativeApi.class) || (builtin && first.equals(NativeApiImpl.class)))) { throw new WrongParamsInSmoothFunctionException(method); } Class<?> paramsInterface = method.getParameterTypes()[1]; Signature<? extends SValue> signature = SignatureFactory.create(method, paramsInterface); return createNativeFunction(method, signature, paramsInterface); } private static <T extends SValue> NativeFunction<T> createNativeFunction(Method method, Signature<T> signature, Class<?> paramsInterface) throws NativeImplementationException, MissingNameException { /* * Cast is safe as T is return type of 'method'. */ @SuppressWarnings("unchecked") Invoker<T> invoker = (Invoker<T>) createInvoker(method, paramsInterface); return new NativeFunction<>(signature, invoker, isCacheable(method)); } private static Invoker<?> createInvoker(Method method, Class<?> paramsInterface) throws NativeImplementationException { ArgsCreator argsCreator = new ArgsCreator(paramsInterface); return new Invoker<>(method, argsCreator); } private static Method getExecuteMethod(Class<?> klass) throws NativeImplementationException { for (Method method : klass.getDeclaredMethods()) { if (method.isAnnotationPresent(SmoothFunction.class)) { return method; } } throw new NoSmoothFunctionException(klass); } private static boolean isCacheable(Method method) throws MissingNameException { SmoothFunction annotation = method.getAnnotation(SmoothFunction.class); if (annotation == null) { throw new MissingNameException(method); } return annotation.cacheable(); } }
src/java/org/smoothbuild/lang/function/nativ/NativeFunctionFactory.java
package org.smoothbuild.lang.function.nativ; import static org.smoothbuild.util.ReflexiveUtils.isPublic; import static org.smoothbuild.util.ReflexiveUtils.isStatic; import java.lang.reflect.Method; import org.smoothbuild.lang.base.NativeApi; import org.smoothbuild.lang.base.SValue; import org.smoothbuild.lang.function.base.Signature; import org.smoothbuild.lang.function.nativ.err.MissingNameException; import org.smoothbuild.lang.function.nativ.err.NativeImplementationException; import org.smoothbuild.lang.function.nativ.err.NoSmoothFunctionException; import org.smoothbuild.lang.function.nativ.err.NonPublicSmoothFunctionException; import org.smoothbuild.lang.function.nativ.err.NonStaticSmoothFunctionException; import org.smoothbuild.lang.function.nativ.err.WrongParamsInSmoothFunctionException; import org.smoothbuild.lang.plugin.SmoothFunction; import org.smoothbuild.task.exec.NativeApiImpl; public class NativeFunctionFactory { public static NativeFunction<?> create(Class<?> klass, boolean builtin) throws NativeImplementationException { Method method = getExecuteMethod(klass, builtin); Class<?> paramsInterface = method.getParameterTypes()[1]; Signature<? extends SValue> signature = SignatureFactory.create(method, paramsInterface); return createNativeFunction(method, signature, paramsInterface); } private static <T extends SValue> NativeFunction<T> createNativeFunction(Method method, Signature<T> signature, Class<?> paramsInterface) throws NativeImplementationException, MissingNameException { /* * Cast is safe as T is return type of 'method'. */ @SuppressWarnings("unchecked") Invoker<T> invoker = (Invoker<T>) createInvoker(method, paramsInterface); return new NativeFunction<>(signature, invoker, isCacheable(method)); } private static Invoker<?> createInvoker(Method method, Class<?> paramsInterface) throws NativeImplementationException { ArgsCreator argsCreator = new ArgsCreator(paramsInterface); return new Invoker<>(method, argsCreator); } private static Method getExecuteMethod(Class<?> klass, boolean builtin) throws NativeImplementationException { for (Method method : klass.getDeclaredMethods()) { if (method.isAnnotationPresent(SmoothFunction.class)) { if (!isPublic(method)) { throw new NonPublicSmoothFunctionException(method); } if (!isStatic(method)) { throw new NonStaticSmoothFunctionException(method); } Class<?>[] paramTypes = method.getParameterTypes(); if (paramTypes.length != 2) { throw new WrongParamsInSmoothFunctionException(method); } Class<?> first = paramTypes[0]; if (!(first.equals(NativeApi.class) || (builtin && first.equals(NativeApiImpl.class)))) { throw new WrongParamsInSmoothFunctionException(method); } return method; } } throw new NoSmoothFunctionException(klass); } private static boolean isCacheable(Method method) throws MissingNameException { SmoothFunction annotation = method.getAnnotation(SmoothFunction.class); if (annotation == null) { throw new MissingNameException(method); } return annotation.cacheable(); } }
refactored NativeFunctionFactory
src/java/org/smoothbuild/lang/function/nativ/NativeFunctionFactory.java
refactored NativeFunctionFactory
<ide><path>rc/java/org/smoothbuild/lang/function/nativ/NativeFunctionFactory.java <ide> public class NativeFunctionFactory { <ide> public static NativeFunction<?> create(Class<?> klass, boolean builtin) <ide> throws NativeImplementationException { <del> Method method = getExecuteMethod(klass, builtin); <add> Method method = getExecuteMethod(klass); <add> return createNativeFunction(method, builtin); <add> } <add> <add> public static NativeFunction<?> createNativeFunction(Method method, boolean builtin) <add> throws NativeImplementationException, MissingNameException { <add> if (!isPublic(method)) { <add> throw new NonPublicSmoothFunctionException(method); <add> } <add> if (!isStatic(method)) { <add> throw new NonStaticSmoothFunctionException(method); <add> } <add> Class<?>[] paramTypes = method.getParameterTypes(); <add> if (paramTypes.length != 2) { <add> throw new WrongParamsInSmoothFunctionException(method); <add> } <add> Class<?> first = paramTypes[0]; <add> if (!(first.equals(NativeApi.class) || (builtin && first.equals(NativeApiImpl.class)))) { <add> throw new WrongParamsInSmoothFunctionException(method); <add> } <add> <ide> Class<?> paramsInterface = method.getParameterTypes()[1]; <ide> Signature<? extends SValue> signature = SignatureFactory.create(method, paramsInterface); <del> <ide> return createNativeFunction(method, signature, paramsInterface); <ide> } <ide> <ide> return new Invoker<>(method, argsCreator); <ide> } <ide> <del> private static Method getExecuteMethod(Class<?> klass, boolean builtin) <del> throws NativeImplementationException { <add> private static Method getExecuteMethod(Class<?> klass) throws NativeImplementationException { <ide> for (Method method : klass.getDeclaredMethods()) { <ide> if (method.isAnnotationPresent(SmoothFunction.class)) { <del> if (!isPublic(method)) { <del> throw new NonPublicSmoothFunctionException(method); <del> } <del> if (!isStatic(method)) { <del> throw new NonStaticSmoothFunctionException(method); <del> } <del> Class<?>[] paramTypes = method.getParameterTypes(); <del> if (paramTypes.length != 2) { <del> throw new WrongParamsInSmoothFunctionException(method); <del> } <del> Class<?> first = paramTypes[0]; <del> if (!(first.equals(NativeApi.class) || (builtin && first.equals(NativeApiImpl.class)))) { <del> throw new WrongParamsInSmoothFunctionException(method); <del> } <del> <ide> return method; <ide> } <ide> }
Java
agpl-3.0
181b47e0ed1bf6324fd0234f042d5b2bc4f25f35
0
ProtocolSupport/ProtocolSupport,ridalarry/ProtocolSupport
package protocolsupport.protocol.storage; import java.net.InetAddress; import java.util.concurrent.TimeUnit; import org.bukkit.Bukkit; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import protocolsupport.utils.Utils; public class ThrottleTracker { private static final long time = Bukkit.getConnectionThrottle(); private static final Cache<InetAddress, Boolean> tracker = CacheBuilder.newBuilder() .concurrencyLevel(Utils.getRawJavaPropertyValue("io.netty.eventLoopThreads", Runtime.getRuntime().availableProcessors(), Utils.Converter.STRING_TO_INT)) .expireAfterWrite(time > 0 ? time : 1, TimeUnit.MILLISECONDS) .build(); public static boolean isEnabled() { return time > 0; } public static boolean throttle(InetAddress address) { boolean result = tracker.getIfPresent(address) != null; tracker.put(address, Boolean.TRUE); return result; } }
src/protocolsupport/protocol/storage/ThrottleTracker.java
package protocolsupport.protocol.storage; import java.net.InetAddress; import java.util.concurrent.TimeUnit; import org.bukkit.Bukkit; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import protocolsupport.utils.Utils; public class ThrottleTracker { private static final long time = Bukkit.getConnectionThrottle(); private static final Cache<InetAddress, Boolean> tracker = CacheBuilder.newBuilder() .concurrencyLevel(Utils.getRawJavaPropertyValue("io.netty.eventLoopThreads", Runtime.getRuntime().availableProcessors(), Utils.Converter.STRING_TO_INT)) .expireAfterWrite(time, TimeUnit.MILLISECONDS) .build(); public static boolean isEnabled() { return time > 0; } public static boolean throttle(InetAddress address) { boolean result = tracker.getIfPresent(address) != null; tracker.put(address, Boolean.TRUE); return result; } }
Fix throttle tracker
src/protocolsupport/protocol/storage/ThrottleTracker.java
Fix throttle tracker
<ide><path>rc/protocolsupport/protocol/storage/ThrottleTracker.java <ide> <ide> private static final Cache<InetAddress, Boolean> tracker = CacheBuilder.newBuilder() <ide> .concurrencyLevel(Utils.getRawJavaPropertyValue("io.netty.eventLoopThreads", Runtime.getRuntime().availableProcessors(), Utils.Converter.STRING_TO_INT)) <del> .expireAfterWrite(time, TimeUnit.MILLISECONDS) <add> .expireAfterWrite(time > 0 ? time : 1, TimeUnit.MILLISECONDS) <ide> .build(); <ide> <ide> public static boolean isEnabled() {
Java
apache-2.0
3084a24112c4eac8cdd50be5021fcef1bfb2275f
0
mglukhikh/intellij-community,asedunov/intellij-community,retomerz/intellij-community,clumsy/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,da1z/intellij-community,da1z/intellij-community,signed/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,clumsy/intellij-community,allotria/intellij-community,fitermay/intellij-community,apixandru/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,hurricup/intellij-community,hurricup/intellij-community,allotria/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,retomerz/intellij-community,xfournet/intellij-community,blademainer/intellij-community,da1z/intellij-community,allotria/intellij-community,fitermay/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,semonte/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,da1z/intellij-community,retomerz/intellij-community,signed/intellij-community,asedunov/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,allotria/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,fnouama/intellij-community,asedunov/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,allotria/intellij-community,apixandru/intellij-community,clumsy/intellij-community,semonte/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,xfournet/intellij-community,amith01994/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,clumsy/intellij-community,xfournet/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,allotria/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,da1z/intellij-community,fnouama/intellij-community,retomerz/intellij-community,ibinti/intellij-community,apixandru/intellij-community,allotria/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,jagguli/intellij-community,blademainer/intellij-community,xfournet/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,da1z/intellij-community,signed/intellij-community,fitermay/intellij-community,vladmm/intellij-community,da1z/intellij-community,FHannes/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,xfournet/intellij-community,fnouama/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,signed/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,FHannes/intellij-community,semonte/intellij-community,semonte/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,jagguli/intellij-community,amith01994/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,amith01994/intellij-community,jagguli/intellij-community,da1z/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,blademainer/intellij-community,clumsy/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,signed/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,amith01994/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,ibinti/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,clumsy/intellij-community,amith01994/intellij-community,fnouama/intellij-community,da1z/intellij-community,signed/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,vvv1559/intellij-community,semonte/intellij-community,fitermay/intellij-community,da1z/intellij-community,vladmm/intellij-community,asedunov/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,FHannes/intellij-community,clumsy/intellij-community,FHannes/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,xfournet/intellij-community,fnouama/intellij-community,da1z/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,FHannes/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,allotria/intellij-community,amith01994/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,blademainer/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,vladmm/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,retomerz/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,jagguli/intellij-community,kdwink/intellij-community,ibinti/intellij-community,kdwink/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,semonte/intellij-community,ibinti/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,fitermay/intellij-community,asedunov/intellij-community,signed/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,jagguli/intellij-community,hurricup/intellij-community,clumsy/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,ibinti/intellij-community,signed/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,amith01994/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.execution.actions; import com.intellij.execution.*; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.ConfigurationType; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Ref; import com.intellij.psi.PsiElement; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; /** * Supports creating run configurations from context (by right-clicking a code element in the source editor or the project view). Typically, * run configurations that can be created from context should extend the {@link com.intellij.execution.configurations.LocatableConfigurationBase} class. * * @since 13 * @author yole */ public abstract class RunConfigurationProducer<T extends RunConfiguration> { public static final ExtensionPointName<RunConfigurationProducer> EP_NAME = ExtensionPointName.create("com.intellij.runConfigurationProducer"); private static final Logger LOG = Logger.getInstance("#" + RunConfigurationProducer.class.getName()); @NotNull public static List<RunConfigurationProducer<?>> getProducers(@NotNull Project project) { RunConfigurationProducerService runConfigurationProducerService = RunConfigurationProducerService.getInstance(project); RunConfigurationProducer[] allProducers = Extensions.getExtensions(EP_NAME); List<RunConfigurationProducer<?>> result = ContainerUtil.newArrayListWithCapacity(allProducers.length); for (RunConfigurationProducer producer : allProducers) { if (!runConfigurationProducerService.isIgnored(producer)) { result.add(producer); } } return result; } private final ConfigurationFactory myConfigurationFactory; protected RunConfigurationProducer(final ConfigurationFactory configurationFactory) { myConfigurationFactory = configurationFactory; } protected RunConfigurationProducer(final ConfigurationType configurationType) { myConfigurationFactory = configurationType.getConfigurationFactories()[0]; } public ConfigurationFactory getConfigurationFactory() { return myConfigurationFactory; } public ConfigurationType getConfigurationType() { return myConfigurationFactory.getType(); } /** * Creates a run configuration from the context. * * @param context contains the information about a location in the source code. * @return a container with a prepared run configuration and the context element from which it was created, or null if the context is * not applicable to this run configuration producer. */ @Nullable public ConfigurationFromContext createConfigurationFromContext(ConfigurationContext context) { final RunnerAndConfigurationSettings settings = cloneTemplateConfiguration(context); try { if (!setupConfigurationFromContext((T)settings.getConfiguration(), context, new Ref<PsiElement>(context.getPsiLocation()))) { return null; } } catch (ClassCastException e) { LOG.error(myConfigurationFactory + " produced wrong type", e); return null; } return new ConfigurationFromContextImpl(this, settings, context.getPsiLocation()); } /** * Sets up a configuration based on the specified context. * * @param configuration a clone of the template run configuration of the specified type * @param context contains the information about a location in the source code. * @param sourceElement a reference to the source element for the run configuration (by default contains the element at caret, * can be updated by the producer to point to a higher-level element in the tree). * * @return true if the context is applicable to this run configuration producer, false if the context is not applicable and the * configuration should be discarded. */ protected abstract boolean setupConfigurationFromContext(T configuration, ConfigurationContext context, Ref<PsiElement> sourceElement); /** * Checks if the specified configuration was created from the specified context. * @param configuration a configuration instance. * @param context contains the information about a location in the source code. * @return true if this configuration was created from the specified context, false otherwise. */ public abstract boolean isConfigurationFromContext(T configuration, ConfigurationContext context); /** * When two configurations are created from the same context by two different producers, checks if the configuration created by * this producer should be discarded in favor of the other one. * * @param self a configuration created by this producer. * @param other a configuration created by another producer. * @return true if the configuration created by this producer is at least as good as the other one; false if this configuration * should be discarded and the other one should be used instead. * @see #shouldReplace(ConfigurationFromContext, ConfigurationFromContext) */ public boolean isPreferredConfiguration(ConfigurationFromContext self, ConfigurationFromContext other) { return true; } /** * When two configurations are created from the same context by two different producers, checks if the configuration created by * this producer should replace the other one, that is if the other one should be discarded. * * <p>This is the same relationship as {@link #isPreferredConfiguration(ConfigurationFromContext, ConfigurationFromContext)} but * specified from the "replacement" side. * * @param self a configuration created by this producer. * @param other a configuration created by another producer. * @return true if the other configuration should be discarded, false otherwise. * @see #isPreferredConfiguration(ConfigurationFromContext, ConfigurationFromContext) */ public boolean shouldReplace(ConfigurationFromContext self, ConfigurationFromContext other) { return false; } /** * Called before a configuration created from context by this producer is first executed. Can be used to show additional UI for * customizing the created configuration. * * @param configuration a configuration created by this producer. * @param context the context * @param startRunnable the runnable that needs to be called after additional customization is complete. */ public void onFirstRun(ConfigurationFromContext configuration, ConfigurationContext context, Runnable startRunnable) { startRunnable.run(); } /** * Searches the list of existing run configurations to find one created from this context. Returns one if found, or tries to create * a new configuration from this context if not found. * * @param context contains the information about a location in the source code. * @return a configuration (new or existing) matching the context, or null if the context is not applicable to this producer. */ @Nullable public ConfigurationFromContext findOrCreateConfigurationFromContext(ConfigurationContext context) { Location location = context.getLocation(); if (location == null) { return null; } ConfigurationFromContext fromContext = createConfigurationFromContext(context); if (fromContext != null) { final PsiElement psiElement = fromContext.getSourceElement(); final Location<PsiElement> _location = PsiLocation.fromPsiElement(psiElement, location.getModule()); if (_location != null) { // replace with existing configuration if any final RunManager runManager = RunManager.getInstance(context.getProject()); final ConfigurationType type = fromContext.getConfigurationType(); final List<RunnerAndConfigurationSettings> configurations = runManager.getConfigurationSettingsList(type); final RunnerAndConfigurationSettings settings = findExistingConfiguration(context); if (settings != null) { fromContext.setConfigurationSettings(settings); } else { final ArrayList<String> currentNames = new ArrayList<String>(); for (RunnerAndConfigurationSettings configurationSettings : configurations) { currentNames.add(configurationSettings.getName()); } RunConfiguration configuration = fromContext.getConfiguration(); String name = configuration.getName(); if (name == null) { LOG.error(configuration); name = "Unnamed"; } configuration.setName(RunManager.suggestUniqueName(name, currentNames)); } } } return fromContext; } /** * Searches the list of existing run configurations to find one created from this context. Returns one if found. * * @param context contains the information about a location in the source code. * @return an existing configuration matching the context, or null if no such configuration is found. */ @Nullable public RunnerAndConfigurationSettings findExistingConfiguration(ConfigurationContext context) { final RunManager runManager = RunManager.getInstance(context.getProject()); final List<RunnerAndConfigurationSettings> configurations = runManager.getConfigurationSettingsList(myConfigurationFactory.getType()); for (RunnerAndConfigurationSettings configurationSettings : configurations) { if (isConfigurationFromContext((T) configurationSettings.getConfiguration(), context)) { return configurationSettings; } } return null; } protected RunnerAndConfigurationSettings cloneTemplateConfiguration(@NotNull final ConfigurationContext context) { final RunConfiguration original = context.getOriginalConfiguration(myConfigurationFactory.getType()); if (original != null) { return RunManager.getInstance(context.getProject()).createConfiguration(original.clone(), myConfigurationFactory); } return RunManager.getInstance(context.getProject()).createRunConfiguration("", myConfigurationFactory); } @NotNull public static <T extends RunConfigurationProducer> T getInstance(Class<? extends T> aClass) { for (RunConfigurationProducer producer : Extensions.getExtensions(EP_NAME)) { if (aClass.isInstance(producer)) { return (T)producer; } } assert false : aClass; return null; } @Nullable public RunConfiguration createLightConfiguration(@NotNull final ConfigurationContext context) { RunConfiguration configuration = myConfigurationFactory.createTemplateConfiguration(context.getProject()); try { if (!setupConfigurationFromContext((T)configuration, context, new Ref<PsiElement>(context.getPsiLocation()))) { return null; } } catch (Exception e) { LOG.error(myConfigurationFactory + " produced wrong type", e); return null; } return configuration; } }
platform/lang-api/src/com/intellij/execution/actions/RunConfigurationProducer.java
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.execution.actions; import com.intellij.execution.*; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.ConfigurationType; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Ref; import com.intellij.psi.PsiElement; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; /** * Supports creating run configurations from context (by right-clicking a code element in the source editor or the project view). Typically, * run configurations that can be created from context should extend the {@link com.intellij.execution.configurations.LocatableConfigurationBase} class. * * @since 13 * @author yole */ public abstract class RunConfigurationProducer<T extends RunConfiguration> { public static final ExtensionPointName<RunConfigurationProducer> EP_NAME = ExtensionPointName.create("com.intellij.runConfigurationProducer"); private static final Logger LOG = Logger.getInstance("#" + RunConfigurationProducer.class.getName()); @NotNull public static List<RunConfigurationProducer<?>> getProducers(@NotNull Project project) { RunConfigurationProducerService runConfigurationProducerService = RunConfigurationProducerService.getInstance(project); RunConfigurationProducer[] allProducers = Extensions.getExtensions(EP_NAME); List<RunConfigurationProducer<?>> result = ContainerUtil.newArrayListWithCapacity(allProducers.length); for (RunConfigurationProducer producer : allProducers) { if (!runConfigurationProducerService.isIgnored(producer)) { result.add(producer); } } return result; } private final ConfigurationFactory myConfigurationFactory; protected RunConfigurationProducer(final ConfigurationFactory configurationFactory) { myConfigurationFactory = configurationFactory; } protected RunConfigurationProducer(final ConfigurationType configurationType) { myConfigurationFactory = configurationType.getConfigurationFactories()[0]; } public ConfigurationFactory getConfigurationFactory() { return myConfigurationFactory; } public ConfigurationType getConfigurationType() { return myConfigurationFactory.getType(); } /** * Creates a run configuration from the context. * * @param context contains the information about a location in the source code. * @return a container with a prepared run configuration and the context element from which it was created, or null if the context is * not applicable to this run configuration producer. */ @Nullable public ConfigurationFromContext createConfigurationFromContext(ConfigurationContext context) { final RunnerAndConfigurationSettings settings = cloneTemplateConfiguration(context); final Ref<PsiElement> locationRef = new Ref<PsiElement>(context.getPsiLocation()); T configuration = null; try { configuration = (T)settings.getConfiguration(); } catch (ClassCastException e) { LOG.error(myConfigurationFactory + " produced wrong type", e); return null; } if (!setupConfigurationFromContext(configuration, context, locationRef)) { return null; } return new ConfigurationFromContextImpl(this, settings, locationRef.get()); } /** * Sets up a configuration based on the specified context. * * @param configuration a clone of the template run configuration of the specified type * @param context contains the information about a location in the source code. * @param sourceElement a reference to the source element for the run configuration (by default contains the element at caret, * can be updated by the producer to point to a higher-level element in the tree). * * @return true if the context is applicable to this run configuration producer, false if the context is not applicable and the * configuration should be discarded. */ protected abstract boolean setupConfigurationFromContext(T configuration, ConfigurationContext context, Ref<PsiElement> sourceElement); /** * Checks if the specified configuration was created from the specified context. * @param configuration a configuration instance. * @param context contains the information about a location in the source code. * @return true if this configuration was created from the specified context, false otherwise. */ public abstract boolean isConfigurationFromContext(T configuration, ConfigurationContext context); /** * When two configurations are created from the same context by two different producers, checks if the configuration created by * this producer should be discarded in favor of the other one. * * @param self a configuration created by this producer. * @param other a configuration created by another producer. * @return true if the configuration created by this producer is at least as good as the other one; false if this configuration * should be discarded and the other one should be used instead. * @see #shouldReplace(ConfigurationFromContext, ConfigurationFromContext) */ public boolean isPreferredConfiguration(ConfigurationFromContext self, ConfigurationFromContext other) { return true; } /** * When two configurations are created from the same context by two different producers, checks if the configuration created by * this producer should replace the other one, that is if the other one should be discarded. * * <p>This is the same relationship as {@link #isPreferredConfiguration(ConfigurationFromContext, ConfigurationFromContext)} but * specified from the "replacement" side. * * @param self a configuration created by this producer. * @param other a configuration created by another producer. * @return true if the other configuration should be discarded, false otherwise. * @see #isPreferredConfiguration(ConfigurationFromContext, ConfigurationFromContext) */ public boolean shouldReplace(ConfigurationFromContext self, ConfigurationFromContext other) { return false; } /** * Called before a configuration created from context by this producer is first executed. Can be used to show additional UI for * customizing the created configuration. * * @param configuration a configuration created by this producer. * @param context the context * @param startRunnable the runnable that needs to be called after additional customization is complete. */ public void onFirstRun(ConfigurationFromContext configuration, ConfigurationContext context, Runnable startRunnable) { startRunnable.run(); } /** * Searches the list of existing run configurations to find one created from this context. Returns one if found, or tries to create * a new configuration from this context if not found. * * @param context contains the information about a location in the source code. * @return a configuration (new or existing) matching the context, or null if the context is not applicable to this producer. */ @Nullable public ConfigurationFromContext findOrCreateConfigurationFromContext(ConfigurationContext context) { Location location = context.getLocation(); if (location == null) { return null; } ConfigurationFromContext fromContext = createConfigurationFromContext(context); if (fromContext != null) { final PsiElement psiElement = fromContext.getSourceElement(); final Location<PsiElement> _location = PsiLocation.fromPsiElement(psiElement, location.getModule()); if (_location != null) { // replace with existing configuration if any final RunManager runManager = RunManager.getInstance(context.getProject()); final ConfigurationType type = fromContext.getConfigurationType(); final List<RunnerAndConfigurationSettings> configurations = runManager.getConfigurationSettingsList(type); final RunnerAndConfigurationSettings settings = findExistingConfiguration(context); if (settings != null) { fromContext.setConfigurationSettings(settings); } else { final ArrayList<String> currentNames = new ArrayList<String>(); for (RunnerAndConfigurationSettings configurationSettings : configurations) { currentNames.add(configurationSettings.getName()); } RunConfiguration configuration = fromContext.getConfiguration(); String name = configuration.getName(); if (name == null) { LOG.error(configuration); name = "Unnamed"; } configuration.setName(RunManager.suggestUniqueName(name, currentNames)); } } } return fromContext; } /** * Searches the list of existing run configurations to find one created from this context. Returns one if found. * * @param context contains the information about a location in the source code. * @return an existing configuration matching the context, or null if no such configuration is found. */ @Nullable public RunnerAndConfigurationSettings findExistingConfiguration(ConfigurationContext context) { final RunManager runManager = RunManager.getInstance(context.getProject()); final List<RunnerAndConfigurationSettings> configurations = runManager.getConfigurationSettingsList(myConfigurationFactory.getType()); for (RunnerAndConfigurationSettings configurationSettings : configurations) { if (isConfigurationFromContext((T) configurationSettings.getConfiguration(), context)) { return configurationSettings; } } return null; } protected RunnerAndConfigurationSettings cloneTemplateConfiguration(@NotNull final ConfigurationContext context) { final RunConfiguration original = context.getOriginalConfiguration(myConfigurationFactory.getType()); if (original != null) { return RunManager.getInstance(context.getProject()).createConfiguration(original.clone(), myConfigurationFactory); } return RunManager.getInstance(context.getProject()).createRunConfiguration("", myConfigurationFactory); } @NotNull public static <T extends RunConfigurationProducer> T getInstance(Class<? extends T> aClass) { for (RunConfigurationProducer producer : Extensions.getExtensions(EP_NAME)) { if (aClass.isInstance(producer)) { return (T)producer; } } assert false : aClass; return null; } @Nullable public RunConfiguration createLightConfiguration(@NotNull final ConfigurationContext context) { RunConfiguration configuration = myConfigurationFactory.createTemplateConfiguration(context.getProject()); if (!setupConfigurationFromContext((T)configuration, context, new Ref<PsiElement>(context.getPsiLocation()))) { return null; } return configuration; } }
better diagnostics for EA-72923 - CCE: AllInDirectoryConfigurationProducer.setupConfigurationFromContext
platform/lang-api/src/com/intellij/execution/actions/RunConfigurationProducer.java
better diagnostics for EA-72923 - CCE: AllInDirectoryConfigurationProducer.setupConfigurationFromContext
<ide><path>latform/lang-api/src/com/intellij/execution/actions/RunConfigurationProducer.java <ide> @Nullable <ide> public ConfigurationFromContext createConfigurationFromContext(ConfigurationContext context) { <ide> final RunnerAndConfigurationSettings settings = cloneTemplateConfiguration(context); <del> final Ref<PsiElement> locationRef = new Ref<PsiElement>(context.getPsiLocation()); <del> T configuration = null; <ide> try { <del> configuration = (T)settings.getConfiguration(); <add> if (!setupConfigurationFromContext((T)settings.getConfiguration(), context, new Ref<PsiElement>(context.getPsiLocation()))) { <add> return null; <add> } <ide> } <ide> catch (ClassCastException e) { <ide> LOG.error(myConfigurationFactory + " produced wrong type", e); <ide> return null; <ide> } <del> if (!setupConfigurationFromContext(configuration, context, locationRef)) { <del> return null; <del> } <del> return new ConfigurationFromContextImpl(this, settings, locationRef.get()); <add> return new ConfigurationFromContextImpl(this, settings, context.getPsiLocation()); <ide> } <ide> <ide> /** <ide> @Nullable <ide> public RunConfiguration createLightConfiguration(@NotNull final ConfigurationContext context) { <ide> RunConfiguration configuration = myConfigurationFactory.createTemplateConfiguration(context.getProject()); <del> if (!setupConfigurationFromContext((T)configuration, context, new Ref<PsiElement>(context.getPsiLocation()))) { <add> try { <add> if (!setupConfigurationFromContext((T)configuration, context, new Ref<PsiElement>(context.getPsiLocation()))) { <add> return null; <add> } <add> } <add> catch (Exception e) { <add> LOG.error(myConfigurationFactory + " produced wrong type", e); <ide> return null; <ide> } <ide> return configuration;
Java
apache-2.0
5042db166d575c50291bd7616a6a611cab14e3c7
0
jnidzwetzki/bboxdb,jnidzwetzki/scalephant,jnidzwetzki/scalephant,jnidzwetzki/bboxdb,jnidzwetzki/bboxdb
/******************************************************************************* * * Copyright (C) 2015-2017 the BBoxDB 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 org.bboxdb; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.atomic.AtomicInteger; import org.bboxdb.storage.entity.BoundingBox; import org.bboxdb.storage.entity.Tuple; import org.bboxdb.tools.converter.tuple.TupleBuilder; import org.bboxdb.tools.converter.tuple.TupleBuilderFactory; import org.bboxdb.util.TupleFile; import org.junit.Assert; import org.junit.Test; public class TestTupleBuilder { /** * The testline for TPC-H tests */ protected final static String TPCH_TEST_LINE = "3|29380|1883|4|2|2618.76|0.01|0.06|A|F|1993-12-04|1994-01-07|1994-01-01|NONE|TRUCK|y. fluffily pending d|"; /** * The testline for synthetic tests */ protected final static String SYNTHETIC_TEST_LINE = "51.47015078569419,58.26664175357267,49.11808592466023,52.72529828070016 e1k141dox9rayxo544y9"; /** * The testline for yellow taxi format tests */ protected final static String TAXI_TEST_LINE = "2,2016-01-01 00:00:00,2016-01-01 00:00:00,2,1.10,-73.990371704101563,40.734695434570313,1,N,-73.981842041015625,40.732406616210937,2,7.5,0.5,0.5,0,0,0.3,8.8"; /** * The line for geojson tests */ protected final static String GEO_JOSN_LINE = "{\"geometry\":{\"coordinates\":[52.4688608,13.3327994],\"type\":\"Point\"},\"id\":271247324,\"type\":\"Feature\",\"properties\":{\"natural\":\"tree\",\"leaf_cycle\":\"deciduous\",\"name\":\"Kaisereiche\",\"leaf_type\":\"broadleaved\",\"wikipedia\":\"de:Kaisereiche (Berlin)\"}}"; /** * Test the geo json tuple builder */ @Test public void testGeoJsonTupleBuilder() { final TupleBuilder tupleBuilder = TupleBuilderFactory.getBuilderForFormat( TupleBuilderFactory.Name.GEOJSON); final Tuple tuple = tupleBuilder.buildTuple("1", GEO_JOSN_LINE); Assert.assertTrue(tuple != null); Assert.assertEquals(Integer.toString(1), tuple.getKey()); final BoundingBox expectedBox = new BoundingBox(52.4688608, 52.4688608, 13.3327994, 13.3327994); Assert.assertEquals(expectedBox, tuple.getBoundingBox()); } /** * Test the yellow taxi range tuple builder * @throws ParseException */ @Test public void testYellowTaxiRangeTupleBuilder() throws ParseException { final TupleBuilder tupleBuilder = TupleBuilderFactory.getBuilderForFormat( TupleBuilderFactory.Name.YELLOWTAXI_RANGE); final Tuple tuple = tupleBuilder.buildTuple("1", TAXI_TEST_LINE); Assert.assertTrue(tuple != null); Assert.assertEquals(Integer.toString(1), tuple.getKey()); final SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss"); final Date dateLow = dateParser.parse("2016-01-01 00:00:00"); final Date dateHigh = dateParser.parse("2016-01-01 00:00:00"); final BoundingBox exptectedBox = new BoundingBox(-73.990371704101563, 40.734695434570313, -73.981842041015625, 40.732406616210937, (double) dateLow.getTime(), (double) dateHigh.getTime()); Assert.assertEquals(exptectedBox, tuple.getBoundingBox()); } /** * Test the yellow taxi range tuple builder * @throws ParseException */ @Test public void testYellowTaxiPointTupleBuilder() throws ParseException { final TupleBuilder tupleBuilder = TupleBuilderFactory.getBuilderForFormat( TupleBuilderFactory.Name.YELLOWTAXI_POINT); final Tuple tuple = tupleBuilder.buildTuple("1", TAXI_TEST_LINE); Assert.assertTrue(tuple != null); Assert.assertEquals(Integer.toString(1), tuple.getKey()); final SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss"); final Date dateLow = dateParser.parse("2016-01-01 00:00:00"); final BoundingBox exptectedBox = new BoundingBox(-73.990371704101563, 40.734695434570313, -73.990371704101563, 40.734695434570313, (double) dateLow.getTime(), (double) dateLow.getTime()); Assert.assertEquals(exptectedBox, tuple.getBoundingBox()); } /** * Test the tpch point tuple builder * @throws ParseException */ @Test public void testTPCHLineitemPointTupleBuilder() throws ParseException { final TupleBuilder tupleBuilder = TupleBuilderFactory.getBuilderForFormat( TupleBuilderFactory.Name.TPCH_LINEITEM_POINT); final Tuple tuple = tupleBuilder.buildTuple("1", TPCH_TEST_LINE); Assert.assertTrue(tuple != null); Assert.assertEquals(Integer.toString(1), tuple.getKey()); final SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-mm-dd"); final Date date = dateParser.parse("1993-12-04"); final double doubleTime = (double) date.getTime(); final BoundingBox exptectedBox = new BoundingBox(doubleTime, doubleTime); Assert.assertEquals(exptectedBox, tuple.getBoundingBox()); } /** * Test the tpch range tuple builder * @throws ParseException */ @Test public void testTPCHLineitemRangeTupleBuilder() throws ParseException { final TupleBuilder tupleBuilder = TupleBuilderFactory.getBuilderForFormat( TupleBuilderFactory.Name.TPCH_LINEITEM_RANGE); final Tuple tuple = tupleBuilder.buildTuple("1", TPCH_TEST_LINE); Assert.assertTrue(tuple != null); Assert.assertEquals(Integer.toString(1), tuple.getKey()); final SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-mm-dd"); final Date shipDateTime = dateParser.parse("1993-12-04"); final Date receiptDateTime = dateParser.parse("1994-01-01"); final double doubleShipDateTime = (double) shipDateTime.getTime(); final double doublereceiptDateTime = (double) receiptDateTime.getTime(); final BoundingBox exptectedBox = new BoundingBox(doubleShipDateTime, doublereceiptDateTime); Assert.assertEquals(exptectedBox, tuple.getBoundingBox()); } /** * Test the syntetic tuple builder * @throws ParseException */ @Test public void testSyntheticTupleBuilder() throws ParseException { final TupleBuilder tupleBuilder = TupleBuilderFactory.getBuilderForFormat( TupleBuilderFactory.Name.SYNTHETIC); final Tuple tuple = tupleBuilder.buildTuple("1", SYNTHETIC_TEST_LINE); Assert.assertTrue(tuple != null); Assert.assertEquals(Integer.toString(1), tuple.getKey()); final BoundingBox exptectedBox = new BoundingBox(51.47015078569419, 58.26664175357267, 49.11808592466023, 52.72529828070016); Assert.assertEquals(exptectedBox, tuple.getBoundingBox()); Assert.assertEquals("e1k141dox9rayxo544y9", new String(tuple.getDataBytes())); } /** * Test the tuple file builder - Process non existing file * @throws IOException */ @Test(expected=IOException.class) public void testTupleFile1() throws IOException { final File tempFile = File.createTempFile("temp",".txt"); tempFile.delete(); Assert.assertFalse(tempFile.exists()); final TupleFile tupleFile = new TupleFile(tempFile.getAbsolutePath(), TupleBuilderFactory.Name.GEOJSON); tupleFile.processFile(); } /** * Test the tuple file builder * @throws IOException */ @Test public void testTupleFile2() throws IOException { final File tempFile = File.createTempFile("temp",".txt"); tempFile.deleteOnExit(); // The reference tuple final TupleBuilder tupleBuilder = TupleBuilderFactory.getBuilderForFormat( TupleBuilderFactory.Name.GEOJSON); final Tuple tuple = tupleBuilder.buildTuple("1", GEO_JOSN_LINE); final BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile)); writer.write(GEO_JOSN_LINE); writer.write("\n"); writer.close(); final TupleFile tupleFile = new TupleFile(tempFile.getAbsolutePath(), TupleBuilderFactory.Name.GEOJSON); final AtomicInteger seenTuples = new AtomicInteger(0); tupleFile.addTupleListener(t -> { Assert.assertEquals(tuple.getKey(), t.getKey()); Assert.assertEquals(tuple.getBoundingBox(), t.getBoundingBox()); Assert.assertArrayEquals(tuple.getDataBytes(), t.getDataBytes()); seenTuples.incrementAndGet(); }); tupleFile.processFile(); Assert.assertEquals(1, seenTuples.get()); } }
src/test/java/org/bboxdb/TestTupleBuilder.java
/******************************************************************************* * * Copyright (C) 2015-2017 the BBoxDB 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 org.bboxdb; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.atomic.AtomicInteger; import org.bboxdb.storage.entity.BoundingBox; import org.bboxdb.storage.entity.Tuple; import org.bboxdb.tools.converter.tuple.TupleBuilder; import org.bboxdb.tools.converter.tuple.TupleBuilderFactory; import org.bboxdb.util.TupleFile; import org.junit.Assert; import org.junit.Test; public class TestTupleBuilder { /** * The testline for TPC-H tests */ protected final static String TPCH_TEST_LINE = "3|29380|1883|4|2|2618.76|0.01|0.06|A|F|1993-12-04|1994-01-07|1994-01-01|NONE|TRUCK|y. fluffily pending d|"; /** * The testline for synthetic tests */ protected final static String SYNTHETIC_TEST_LINE = "51.47015078569419,58.26664175357267,49.11808592466023,52.72529828070016 e1k141dox9rayxo544y9"; /** * The testline for yellow taxi format tests */ protected final static String TAXI_TEST_LINE = "2,2016-01-01 00:00:00,2016-01-01 00:00:00,2,1.10,-73.990371704101563,40.734695434570313,1,N,-73.981842041015625,40.732406616210937,2,7.5,0.5,0.5,0,0,0.3,8.8"; /** * The line for geojson tests */ protected final static String GEO_JOSN_LINE = "{\"geometry\":{\"coordinates\":[52.4688608,13.3327994],\"type\":\"Point\"},\"id\":271247324,\"type\":\"Feature\",\"properties\":{\"natural\":\"tree\",\"leaf_cycle\":\"deciduous\",\"name\":\"Kaisereiche\",\"leaf_type\":\"broadleaved\",\"wikipedia\":\"de:Kaisereiche (Berlin)\"}}"; /** * Test the geo json tuple builder */ @Test public void testGeoJsonTupleBuilder() { final TupleBuilder tupleBuilder = TupleBuilderFactory.getBuilderForFormat( TupleBuilderFactory.Name.GEOJSON); final Tuple tuple = tupleBuilder.buildTuple("1", GEO_JOSN_LINE); Assert.assertTrue(tuple != null); Assert.assertEquals(Integer.toString(1), tuple.getKey()); final BoundingBox expectedBox = new BoundingBox(52.4688608, 52.4688608, 13.3327994, 13.3327994); Assert.assertEquals(expectedBox, tuple.getBoundingBox()); } /** * Test the yellow taxi range tuple builder * @throws ParseException */ @Test public void testYellowTaxiRangeTupleBuilder() throws ParseException { final TupleBuilder tupleBuilder = TupleBuilderFactory.getBuilderForFormat( TupleBuilderFactory.Name.YELLOWTAXI_RANGE); final Tuple tuple = tupleBuilder.buildTuple("1", TAXI_TEST_LINE); Assert.assertTrue(tuple != null); Assert.assertEquals(Integer.toString(1), tuple.getKey()); final SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss"); final Date dateLow = dateParser.parse("2016-01-01 00:00:00"); final Date dateHigh = dateParser.parse("2016-01-01 00:00:00"); final BoundingBox exptectedBox = new BoundingBox(-73.990371704101563, 40.734695434570313, -73.981842041015625, 40.732406616210937, (double) dateLow.getTime(), (double) dateHigh.getTime()); Assert.assertEquals(exptectedBox, tuple.getBoundingBox()); } /** * Test the yellow taxi range tuple builder * @throws ParseException */ @Test public void testYellowTaxiPointTupleBuilder() throws ParseException { final TupleBuilder tupleBuilder = TupleBuilderFactory.getBuilderForFormat( TupleBuilderFactory.Name.YELLOWTAXI_POINT); final Tuple tuple = tupleBuilder.buildTuple("1", TAXI_TEST_LINE); Assert.assertTrue(tuple != null); Assert.assertEquals(Integer.toString(1), tuple.getKey()); final SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss"); final Date dateLow = dateParser.parse("2016-01-01 00:00:00"); final BoundingBox exptectedBox = new BoundingBox(-73.990371704101563, 40.734695434570313, -73.990371704101563, 40.734695434570313, (double) dateLow.getTime(), (double) dateLow.getTime()); Assert.assertEquals(exptectedBox, tuple.getBoundingBox()); } /** * Test the tpch point tuple builder * @throws ParseException */ @Test public void testTPCHLineitemPointTupleBuilder() throws ParseException { final TupleBuilder tupleBuilder = TupleBuilderFactory.getBuilderForFormat( TupleBuilderFactory.Name.TPCH_LINEITEM_POINT); final Tuple tuple = tupleBuilder.buildTuple("1", TPCH_TEST_LINE); Assert.assertTrue(tuple != null); Assert.assertEquals(Integer.toString(1), tuple.getKey()); final SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-mm-dd"); final Date date = dateParser.parse("1993-12-04"); final double doubleTime = (double) date.getTime(); final BoundingBox exptectedBox = new BoundingBox(doubleTime, doubleTime); Assert.assertEquals(exptectedBox, tuple.getBoundingBox()); } /** * Test the tpch range tuple builder * @throws ParseException */ @Test public void testTPCHLineitemRangeTupleBuilder() throws ParseException { final TupleBuilder tupleBuilder = TupleBuilderFactory.getBuilderForFormat( TupleBuilderFactory.Name.TPCH_LINEITEM_RANGE); final Tuple tuple = tupleBuilder.buildTuple("1", TPCH_TEST_LINE); Assert.assertTrue(tuple != null); Assert.assertEquals(Integer.toString(1), tuple.getKey()); final SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-mm-dd"); final Date shipDateTime = dateParser.parse("1993-12-04"); final Date receiptDateTime = dateParser.parse("1994-01-01"); final double doubleShipDateTime = (double) shipDateTime.getTime(); final double doublereceiptDateTime = (double) receiptDateTime.getTime(); final BoundingBox exptectedBox = new BoundingBox(doubleShipDateTime, doublereceiptDateTime); Assert.assertEquals(exptectedBox, tuple.getBoundingBox()); } /** * Test the syntetic tuple builder * @throws ParseException */ @Test public void testSyntheticTupleBuilder() throws ParseException { final TupleBuilder tupleBuilder = TupleBuilderFactory.getBuilderForFormat( TupleBuilderFactory.Name.SYNTHETIC); final Tuple tuple = tupleBuilder.buildTuple("1", SYNTHETIC_TEST_LINE); Assert.assertTrue(tuple != null); Assert.assertEquals(Integer.toString(1), tuple.getKey()); final BoundingBox exptectedBox = new BoundingBox(51.47015078569419, 58.26664175357267, 49.11808592466023, 52.72529828070016); Assert.assertEquals(exptectedBox, tuple.getBoundingBox()); Assert.assertEquals("e1k141dox9rayxo544y9", new String(tuple.getDataBytes())); } /** * Test the tuple file builder * @throws IOException */ @Test public void testTupleFile() throws IOException { final File tempFile = File.createTempFile("temp",".txt"); tempFile.deleteOnExit(); // The reference tuple final TupleBuilder tupleBuilder = TupleBuilderFactory.getBuilderForFormat( TupleBuilderFactory.Name.GEOJSON); final Tuple tuple = tupleBuilder.buildTuple("1", GEO_JOSN_LINE); final BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile)); writer.write(GEO_JOSN_LINE); writer.write("\n"); writer.close(); final TupleFile tupleFile = new TupleFile(tempFile.getAbsolutePath(), TupleBuilderFactory.Name.GEOJSON); final AtomicInteger seenTuples = new AtomicInteger(0); tupleFile.addTupleListener(t -> { Assert.assertEquals(tuple.getKey(), t.getKey()); Assert.assertEquals(tuple.getBoundingBox(), t.getBoundingBox()); Assert.assertArrayEquals(tuple.getDataBytes(), t.getDataBytes()); seenTuples.incrementAndGet(); }); tupleFile.processFile(); Assert.assertEquals(1, seenTuples.get()); } }
Added non existing file test
src/test/java/org/bboxdb/TestTupleBuilder.java
Added non existing file test
<ide><path>rc/test/java/org/bboxdb/TestTupleBuilder.java <ide> Assert.assertEquals("e1k141dox9rayxo544y9", new String(tuple.getDataBytes())); <ide> } <ide> <add> <add> /** <add> * Test the tuple file builder - Process non existing file <add> * @throws IOException <add> */ <add> @Test(expected=IOException.class) <add> public void testTupleFile1() throws IOException { <add> final File tempFile = File.createTempFile("temp",".txt"); <add> <add> tempFile.delete(); <add> Assert.assertFalse(tempFile.exists()); <add> <add> final TupleFile tupleFile = new TupleFile(tempFile.getAbsolutePath(), <add> TupleBuilderFactory.Name.GEOJSON); <add> <add> tupleFile.processFile(); <add> } <add> <ide> /** <ide> * Test the tuple file builder <ide> * @throws IOException <ide> */ <ide> @Test <del> public void testTupleFile() throws IOException { <add> public void testTupleFile2() throws IOException { <ide> final File tempFile = File.createTempFile("temp",".txt"); <ide> tempFile.deleteOnExit(); <ide>
Java
apache-2.0
77fbbac70b4d688be36199c104a1ba5a454d91cf
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.daemon.impl; import com.intellij.codeInsight.intention.impl.CachedIntentions; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class IntentionsUI { private final Project myProject; public static IntentionsUI getInstance(Project project) { return ServiceManager.getService(project, IntentionsUI.class); } public IntentionsUI(Project project) { myProject = project; } private volatile CachedIntentions myCachedIntentions = null; @NotNull public CachedIntentions getCachedIntentions(@Nullable Editor editor, @NotNull PsiFile file) { CachedIntentions cachedIntentions = myCachedIntentions; if (cachedIntentions != null && editor == cachedIntentions.getEditor() && file == cachedIntentions.getFile()) { return cachedIntentions; } else { CachedIntentions intentions = new CachedIntentions(myProject, file, editor); myCachedIntentions = intentions; return intentions; } } public void hide() { myCachedIntentions = null; doHide(); } public abstract void update(@NotNull CachedIntentions cachedIntentions, boolean actionsChanged); protected abstract void doHide(); }
platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/IntentionsUI.java
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.daemon.impl; import com.intellij.codeInsight.intention.impl.CachedIntentions; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class IntentionsUI { private final Project myProject; public static IntentionsUI getInstance(Project project) { return ServiceManager.getService(project, IntentionsUI.class); } public IntentionsUI(Project project) { myProject = project; } private volatile CachedIntentions myCachedIntentions = null; @NotNull public CachedIntentions getCachedIntentions(@Nullable Editor editor, @NotNull PsiFile file) { CachedIntentions cachedIntentions = myCachedIntentions; if (cachedIntentions != null && editor == myCachedIntentions.getEditor() && file == myCachedIntentions.getFile()) { return cachedIntentions; } else { CachedIntentions intentions = new CachedIntentions(myProject, file, editor); myCachedIntentions = intentions; return intentions; } } public void hide() { myCachedIntentions = null; doHide(); } public abstract void update(@NotNull CachedIntentions cachedIntentions, boolean actionsChanged); protected abstract void doHide(); }
fix NPE EA-118055
platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/IntentionsUI.java
fix NPE EA-118055
<ide><path>latform/lang-impl/src/com/intellij/codeInsight/daemon/impl/IntentionsUI.java <ide> @NotNull <ide> public CachedIntentions getCachedIntentions(@Nullable Editor editor, @NotNull PsiFile file) { <ide> CachedIntentions cachedIntentions = myCachedIntentions; <del> if (cachedIntentions != null && editor == myCachedIntentions.getEditor() && file == myCachedIntentions.getFile()) { <add> if (cachedIntentions != null && editor == cachedIntentions.getEditor() && file == cachedIntentions.getFile()) { <ide> return cachedIntentions; <ide> } else { <ide> CachedIntentions intentions = new CachedIntentions(myProject, file, editor);
Java
mit
d27f111dd4bf0fcc425df0cf9159e7bd1ccc98b3
0
Hypersonic/Starlorn
package edu.stuy.starlorn.entities; import edu.stuy.starlorn.upgrades.GunUpgrade; import java.io.IOException; import java.util.LinkedList; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.GL11; public class Ship extends Entity { protected LinkedList<GunUpgrade> _gunupgrades; protected int _baseDamage, _baseShotSpeed, _health, _fullCooldown, _cooldown, _cooldownRate, _movementSpeed; protected double _baseAim; //protected Texture _texture; public Ship() { super(); _gunupgrades = new LinkedList<GunUpgrade>(); _baseDamage = 1; _baseShotSpeed = 1; _health = 10; _baseAim = 0; //Aim up by default _cooldown = 10; _fullCooldown = _cooldown+1; _cooldownRate = 1; _movementSpeed = 1; /* try { _texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("res/spaceship.png")); } catch (IOException e) { e.printStackTrace(); } */ } public void draw() { render(); } public void render() { int x = 1; int y = 2; if (Keyboard.isKeyDown(Keyboard.KEY_UP)){ y = 1; _ycor--; } if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT)){ x = 2; _ycor++; } if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)){ y = 0; _ycor++; } if (Keyboard.isKeyDown(Keyboard.KEY_LEFT)){ x = 0; _xcor--; } } public void addUpgrade(GunUpgrade upgrade) { _gunupgrades.add(upgrade); } public boolean isHit(Bullet b) { return (b.getX() + b.getXvel() + b.getWidth() > _xcor + _xvel && b.getX() + b.getXvel() < _xcor + _width + _xvel && b.getY() + b.getYvel() + b.getHeight() > _ycor + _yvel && b.getY() + b.getYvel() < _ycor + _height + _yvel); } /* * Create the shots based on the available GunUpgrades */ public void shoot() { GunUpgrade topShot = _gunupgrades.get(0); int damage = _baseDamage; int shotSpeed = _baseShotSpeed; for (GunUpgrade up : _gunupgrades) { if (up.getNumShots() > topShot.getNumShots()) topShot = up; damage = up.getDamage(damage); shotSpeed = up.getShotSpeed(shotSpeed); } // Create new shots, based on dem vars int numShots = topShot.getNumShots(); for (int i = 0; i < numShots; i++) { Bullet b = new Bullet(_baseAim + topShot.getAimAngle(), damage, shotSpeed); b.setWorld(this.getWorld()); } } @Override public void step() { //Only cooldown if we're below the rate, otherwise the ship hasn't tried to shoot if (_fullCooldown <= _cooldown) { if (_fullCooldown < 0) { this.shoot(); _fullCooldown = _cooldown+1; } else { _fullCooldown -= _cooldownRate; } } super.step(); } }
src/entities/Ship.java
package edu.stuy.starlorn.entities; import edu.stuy.starlorn.upgrades.GunUpgrade; import java.io.IOException; import java.util.LinkedList; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.GL11; public class Ship extends Entity { protected LinkedList<GunUpgrade> _gunupgrades; protected int _baseDamage, _baseShotSpeed, _health, _fullCooldown, _cooldown, _cooldownRate, _movementSpeed; protected double _baseAim; //protected Texture _texture; public Ship() { super(); _gunupgrades = new LinkedList<GunUpgrade>(); _baseDamage = 1; _baseShotSpeed = 1; _health = 10; _baseAim = 0; //Aim up by default _cooldown = 10; _fullCooldown = _cooldown+1; _cooldownRate = 1; _movementSpeed = 1; /* try { _texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("res/spaceship.png")); } catch (IOException e) { e.printStackTrace(); } */ } public void draw() { render(); } public void render() { int x = 1; int y = 2; if (Keyboard.isKeyDown(Keyboard.KEY_UP)){ y = 1; _ycor--; } if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT)){ x = 2; _ycor++; } if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)){ y = 0; _ycor++; } if (Keyboard.isKeyDown(Keyboard.KEY_LEFT)){ x = 0; _xcor--; } } /* public void ihopethisworks(int tx, int ty) { Color.white.bind(); _texture.bind(); GL11.glBegin(GL11.GL_QUADS); GL11.glTexCoord2d(tx * 0.078125, ty * 0.078125); GL11.glVertex2d(_xcor, y); GL11.glTexCoord2d((tx + 1) * 0.078125, ty * 0.078125); GL11.glVertex2d(_xcor + 64, _ycor); GL11.glTexCoord2d((tx + 1) * 0.078125, (ty + 1) * 0.078125); GL11.glVertex2d(_xcor + 64, _ycor + 64); GL11.glTexCoord2d(tx * 0.078125, (ty + 1) * 0.078125); GL11.glVertex2d(_xcor, _ycor + 64); GL11.glEnd(); } */ public void addUpgrade(GunUpgrade upgrade) { _gunupgrades.add(upgrade); } public boolean isHit(Bullet b) { return (b.getX() + b.getXvel() + b.getWidth() > _xcor + _xvel && b.getX() + b.getXvel() < _xcor + _width + _xvel && b.getY() + b.getYvel() + b.getHeight() > _ycor + _yvel && b.getY() + b.getYvel() < _ycor + _height + _yvel); } /* * Create the shots based on the available GunUpgrades */ public void shoot() { GunUpgrade topShot = _gunupgrades.get(0); int damage = _baseDamage; int shotSpeed = _baseShotSpeed; for (GunUpgrade up : _gunupgrades) { if (up.getNumShots() > topShot.getNumShots()) topShot = up; damage = up.getDamage(damage); shotSpeed = up.getShotSpeed(shotSpeed); } // Create new shots, based on dem vars int numShots = topShot.getNumShots(); for (int i = 0; i < numShots; i++) { Bullet b = new Bullet(_baseAim + topShot.getAimAngle(), damage, shotSpeed); b.setWorld(this.getWorld()); } } @Override public void step() { //Only cooldown if we're below the rate, otherwise the ship hasn't tried to shoot if (_fullCooldown <= _cooldown) { if (_fullCooldown < 0) { this.shoot(); _fullCooldown = _cooldown+1; } else { _fullCooldown -= _cooldownRate; } } super.step(); } }
Remove GL stuff from Ship
src/entities/Ship.java
Remove GL stuff from Ship
<ide><path>rc/entities/Ship.java <ide> <ide> } <ide> <del> /* <del> public void ihopethisworks(int tx, int ty) { <del> Color.white.bind(); <del> <del> _texture.bind(); <del> <del> GL11.glBegin(GL11.GL_QUADS); <del> GL11.glTexCoord2d(tx * 0.078125, ty * 0.078125); <del> GL11.glVertex2d(_xcor, y); <del> GL11.glTexCoord2d((tx + 1) * 0.078125, ty * 0.078125); <del> GL11.glVertex2d(_xcor + 64, _ycor); <del> GL11.glTexCoord2d((tx + 1) * 0.078125, (ty + 1) * 0.078125); <del> GL11.glVertex2d(_xcor + 64, _ycor + 64); <del> GL11.glTexCoord2d(tx * 0.078125, (ty + 1) * 0.078125); <del> GL11.glVertex2d(_xcor, _ycor + 64); <del> GL11.glEnd(); <del> } <del> */ <ide> <ide> public void addUpgrade(GunUpgrade upgrade) { <ide> _gunupgrades.add(upgrade);
Java
bsd-3-clause
514a24a90c360e90bc0bc2e3e78977b0941c4a74
0
bmc/curn,songfj/curn,bmc/curn,songfj/curn,bmc/curn,songfj/curn,songfj/curn,bmc/curn,songfj/curn,bmc/curn
/*---------------------------------------------------------------------------*\ $Id$ --------------------------------------------------------------------------- This software is released under a Berkeley-style license: Copyright (c) 2004 Brian M. Clapper. All rights reserved. Redistribution and use in source and binary forms are permitted provided that: (1) source distributions retain this entire copyright notice and comment; and (2) modifications made to the software are prominently mentioned, and a copy of the original software (or a pointer to its location) are included. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Effectively, this means you can do what you want with the software except remove this notice or take advantage of the author's name. If you modify the software and redistribute your modified version, you must indicate that your version is a modification of the original, and you must provide either a pointer to or a copy of the original. \*---------------------------------------------------------------------------*/ package org.clapper.curn.parser; import org.clapper.curn.FeedInfo; import org.clapper.util.text.TextUtil; import org.clapper.util.text.HTMLUtil; import java.net.URL; import java.util.Collection; import java.util.Date; import java.util.Map; import java.util.HashMap; /** * This abstract class defines a simplified view of an RSS item, providing * only the methods necessary for <i>curn</i> to work. <i>curn</i> uses the * {@link RSSParserFactory} class to get a specific implementation of * <tt>RSSParser</tt>, which returns <tt>RSSChannel</tt>-conforming objects * that, in turn, return item objects that subclass <tt>RSSItem</tt>. This * strategy isolates the bulk of the code from the underlying RSS parser, * making it easier to substitute different parsers as more of them become * available. <tt>RSSItem</tt>. This strategy isolates the bulk of the code * from the underlying RSS parser, making it easier to substitute different * parsers as more of them become available. * * @see RSSParserFactory * @see RSSParser * @see RSSChannel * * @version <tt>$Revision$</tt> */ public abstract class RSSItem { /*----------------------------------------------------------------------*\ Constants \*----------------------------------------------------------------------*/ /** * Constant defining the pseudo-MIME type to use for default content. */ public static final String DEFAULT_CONTENT_TYPE = "*"; /*----------------------------------------------------------------------*\ Private Instance Data \*----------------------------------------------------------------------*/ private Map contentMap = new HashMap(); /*----------------------------------------------------------------------*\ Public Methods \*----------------------------------------------------------------------*/ /** * Get the item's content, if available. Some feed types (e.g., Atom) * support multiple content sections, each with its own MIME type; the * <tt>mimeType</tt> parameter specifies the caller's desired MIME * type. * * @param mimeType the desired MIME type * * @return the content (or the default content), or null if no content * of the desired MIME type is available */ public String getContent (String mimeType) { String result = null; result = (String) contentMap.get (mimeType); if (result == null) result = (String) contentMap.get (DEFAULT_CONTENT_TYPE); return result; } /** * Get the first content item that matches one of a list of MIME types. * * @param mimeTypes an array of MIME types to match, in order * * @return the first matching content string, or null if none was found. * Returns the default content (if set), if there's no exact * match. */ public final String getFirstContentOfType (String[] mimeTypes) { String result = null; for (int i = 0; i < mimeTypes.length; i++) { result = (String) contentMap.get (mimeTypes[i]); if (! TextUtil.stringIsEmpty (result)) break; } if (result == null) result = (String) contentMap.get (DEFAULT_CONTENT_TYPE); return result; } /** * Set the content for a specific MIME type. If the * <tt>isDefault</tt> flag is <tt>true</tt>, then this content * is served up as the default whenever content for a specific MIME type * is requested but isn't available. * * @param content the content string * @param mimeType the MIME type to associate with the content */ public void setContent (String content, String mimeType) { contentMap.put (mimeType, content); } /** * Utility method to get the summary to display for an * <tt>RSSItem</tt>. Consults the configuration data in the specified * {@link FeedInfo} object to determine whether to truncate the * summary, use the description (i.e., content) if the summary isn't * available, etc. Strips HTML by default. (Use the * {@link #getSummaryToDisplay(FeedInfo,String[],boolean) alternate version} * of this method to control the HTML-stripping behavior. * * @param feedInfo the corresponding feed's <tt>FeedInfo</tt> object * @param mimeTypes desired MIME types; used only if no summary is * available, and the content field should be used * * @return the summary string to use, or null if unavailable * * @see #getSummary * @see #getFirstContentOfType */ public String getSummaryToDisplay (FeedInfo feedInfo, String[] mimeTypes) { return getSummaryToDisplay (feedInfo, mimeTypes, true); } /** * Utility method to get the summary to display for an * <tt>RSSItem</tt>. Consults the configuration data in the specified * {@link FeedInfo} object to determine whether to truncate the * summary, use the description if the summary isn't available, etc. * Optionally strips HTML from the resulting string. * * @param feedInfo the corresponding feed's <tt>FeedInfo</tt> object * @param mimeTypes desired MIME types; used only if no summary is * available, and the content field should be used * @param stripHTML whether or not to strip HTML from the string * * @return the summary string to use, or null if unavailable * * @see #getSummary * @see #getFirstContentOfType */ public String getSummaryToDisplay (FeedInfo feedInfo, String[] mimeTypes, boolean stripHTML) { String summary = getSummary(); if (TextUtil.stringIsEmpty (summary)) summary = null; if ((summary == null) && (! feedInfo.summarizeOnly())) { assert (mimeTypes != null); summary = getFirstContentOfType (mimeTypes); if (TextUtil.stringIsEmpty (summary)) summary = null; } if (summary != null) { if (stripHTML) summary = HTMLUtil.textFromHTML (summary); int maxSize = feedInfo.getMaxSummarySize(); if (maxSize != FeedInfo.NO_MAX_SUMMARY_SIZE) summary = truncateSummary (summary, maxSize); } return summary; } /*----------------------------------------------------------------------*\ Public Abstract Methods \*----------------------------------------------------------------------*/ /** * Get the item's title * * @return the item's title, or null if there isn't one * * @see #setTitle */ public abstract String getTitle(); /** * Set the item's title * * @param newTitle the item's title, or null if there isn't one * * @see #getTitle */ public abstract void setTitle (String newTitle); /** * Get the item's published link (its URL). * * @return the URL, or null if not available */ public abstract URL getLink(); /** * Change the item's link (its URL) * * @param url the new link value */ public abstract void setLink (URL url); /** * Get the item's summary (also sometimes called the description or * synopsis). * * @return the summary, or null if not available * * @see #setSummary * @see #getSummaryToDisplay */ public abstract String getSummary(); /** * Set the item's summary (also sometimes called the description or * synopsis). * * @param newSummary the summary, or null if not available * * @see #getSummary */ public abstract void setSummary (String newSummary); /** * Get the item's author. * * @return the author, or null if not available * * @see #setAuthor */ public abstract String getAuthor(); /** * Set the item's author. * * @param newAuthor the author, or null if not available */ public abstract void setAuthor (String newAuthor); /** * Get the categories the item belongs to. * * @return a <tt>Collection</tt> of category strings (<tt>String</tt> * objects) or null if not applicable */ public abstract Collection getCategories(); /** * Get the item's publication date. * * @return the date, or null if not available */ public abstract Date getPublicationDate(); /** * Get the item's ID field, if any. * * @return the ID field, or null if not set */ public abstract String getID(); /*----------------------------------------------------------------------*\ Private Methods \*----------------------------------------------------------------------*/ /** * Truncate an RSS item's summary to a specified size. Truncates on * word boundary, if possible. * * @param summary the summary to truncate * @param maxSize the maximum size * * @return the truncated summary */ private String truncateSummary (String summary, int maxSize) { summary = summary.trim(); if (summary.length() > maxSize) { // Allow for ellipsis if (maxSize < 4) maxSize = 4; maxSize -= 4; int last = maxSize; char[] ch = summary.toCharArray(); int i = last; // If we're in the middle of a word, find the first hunk of // white space. while ((! Character.isWhitespace (ch[i])) && (i-- >= 0)) continue; // Next, get rid of trailing white space. while ((Character.isWhitespace (ch[i])) && (i-- >= 0)) continue; // Handle underflow. if (i >= 0) last = i; StringBuffer buf = new StringBuffer (summary.substring (0, last + 1)); buf.append (" ..."); summary = buf.toString(); } return summary; } }
src/org/clapper/curn/parser/RSSItem.java
/*---------------------------------------------------------------------------*\ $Id$ --------------------------------------------------------------------------- This software is released under a Berkeley-style license: Copyright (c) 2004 Brian M. Clapper. All rights reserved. Redistribution and use in source and binary forms are permitted provided that: (1) source distributions retain this entire copyright notice and comment; and (2) modifications made to the software are prominently mentioned, and a copy of the original software (or a pointer to its location) are included. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Effectively, this means you can do what you want with the software except remove this notice or take advantage of the author's name. If you modify the software and redistribute your modified version, you must indicate that your version is a modification of the original, and you must provide either a pointer to or a copy of the original. \*---------------------------------------------------------------------------*/ package org.clapper.curn.parser; import org.clapper.curn.FeedInfo; import org.clapper.util.text.TextUtil; import org.clapper.util.text.HTMLUtil; import java.net.URL; import java.util.Collection; import java.util.Date; import java.util.Map; import java.util.HashMap; /** * This abstract class defines a simplified view of an RSS item, providing * only the methods necessary for <i>curn</i> to work. <i>curn</i> uses the * {@link RSSParserFactory} class to get a specific implementation of * <tt>RSSParser</tt>, which returns <tt>RSSChannel</tt>-conforming objects * that, in turn, return item objects that subclass <tt>RSSItem</tt>. This * strategy isolates the bulk of the code from the underlying RSS parser, * making it easier to substitute different parsers as more of them become * available. <tt>RSSItem</tt>. This strategy isolates the bulk of the code * from the underlying RSS parser, making it easier to substitute different * parsers as more of them become available. * * @see RSSParserFactory * @see RSSParser * @see RSSChannel * * @version <tt>$Revision$</tt> */ public abstract class RSSItem { /*----------------------------------------------------------------------*\ Constants \*----------------------------------------------------------------------*/ /** * Constant defining the pseudo-MIME type to use for default content. */ public static final String DEFAULT_CONTENT_TYPE = "*"; /*----------------------------------------------------------------------*\ Private Instance Data \*----------------------------------------------------------------------*/ private Map contentMap = new HashMap(); /*----------------------------------------------------------------------*\ Public Methods \*----------------------------------------------------------------------*/ /** * Get the item's content, if available. Some feed types (e.g., Atom) * support multiple content sections, each with its own MIME type; the * <tt>mimeType</tt> parameter specifies the caller's desired MIME * type. * * @param mimeType the desired MIME type * * @return the content (or the default content), or null if no content * of the desired MIME type is available */ public String getContent (String mimeType) { String result = null; result = (String) contentMap.get (mimeType); if (result == null) result = (String) contentMap.get (DEFAULT_CONTENT_TYPE); return result; } /** * Get the first content item that matches one of a list of MIME types. * * @param mimeTypes an array of MIME types to match, in order * * @return the first matching content string, or null if none was found. * Returns the default content (if set), if there's no exact * match. */ public final String getFirstContentOfType (String[] mimeTypes) { String result = null; for (int i = 0; i < mimeTypes.length; i++) { result = (String) contentMap.get (mimeTypes[i]); if (! TextUtil.stringIsEmpty (result)) break; } if (result == null) result = (String) contentMap.get (DEFAULT_CONTENT_TYPE); return result; } /** * Set the content for a specific MIME type. If the * <tt>isDefault</tt> flag is <tt>true</tt>, then this content * is served up as the default whenever content for a specific MIME type * is requested but isn't available. * * @param content the content string * @param mimeType the MIME type to associate with the content */ public void setContent (String content, String mimeType) { contentMap.put (mimeType, content); } /** * Utility method to get the summary to display for an * <tt>RSSItem</tt>. Consults the configuration data in the specified * {@link FeedInfo} object to determine whether to truncate the * summary, use the description (i.e., content) if the summary isn't * available, etc. Strips HTML by default. (Use the * {@link #getItemSummary(FeedInfo,boolean) alternate version} of * this method to control the HTML-stripping behavior. * * @param feedInfo the corresponding feed's <tt>FeedInfo</tt> object * @param mimeTypes desired MIME types; used only if no summary is * available, and the content field should be used * * @return the summary string to use, or null if unavailable * * @see #getSummary * @see #getFirstContentOfType */ public String getSummaryToDisplay (FeedInfo feedInfo, String[] mimeTypes) { return getSummaryToDisplay (feedInfo, mimeTypes, true); } /** * Utility method to get the summary to display for an * <tt>RSSItem</tt>. Consults the configuration data in the specified * {@link FeedInfo} object to determine whether to truncate the * summary, use the description if the summary isn't available, etc. * Optionally strips HTML from the resulting string. * * @param feedInfo the corresponding feed's <tt>FeedInfo</tt> object * @param mimeTypes desired MIME types; used only if no summary is * available, and the content field should be used * @param stripHTML whether or not to strip HTML from the string * * @return the summary string to use, or null if unavailable * * @see #getSummary * @see #getFirstContentOfType */ public String getSummaryToDisplay (FeedInfo feedInfo, String[] mimeTypes, boolean stripHTML) { String summary = getSummary(); if (TextUtil.stringIsEmpty (summary)) summary = null; if ((summary == null) && (! feedInfo.summarizeOnly())) { assert (mimeTypes != null); summary = getFirstContentOfType (mimeTypes); if (TextUtil.stringIsEmpty (summary)) summary = null; } if (summary != null) { if (stripHTML) summary = HTMLUtil.textFromHTML (summary); int maxSize = feedInfo.getMaxSummarySize(); if (maxSize != FeedInfo.NO_MAX_SUMMARY_SIZE) summary = truncateSummary (summary, maxSize); } return summary; } /*----------------------------------------------------------------------*\ Public Abstract Methods \*----------------------------------------------------------------------*/ /** * Get the item's title * * @return the item's title, or null if there isn't one * * @see #setTitle */ public abstract String getTitle(); /** * Set the item's title * * @param newTitle the item's title, or null if there isn't one * * @see #getTitle */ public abstract void setTitle (String newTitle); /** * Get the item's published link (its URL). * * @return the URL, or null if not available */ public abstract URL getLink(); /** * Change the item's link (its URL) * * @param url the new link value */ public abstract void setLink (URL url); /** * Get the item's summary (also sometimes called the description or * synopsis). * * @return the summary, or null if not available * * @see #setSummary * @see #getSummaryToDisplay */ public abstract String getSummary(); /** * Set the item's summary (also sometimes called the description or * synopsis). * * @param newSummary the summary, or null if not available * * @see #getSummary */ public abstract void setSummary (String newSummary); /** * Get the item's author. * * @return the author, or null if not available * * @see #setAuthor */ public abstract String getAuthor(); /** * Set the item's author. * * @param newAuthor the author, or null if not available */ public abstract void setAuthor (String newAuthor); /** * Get the categories the item belongs to. * * @return a <tt>Collection</tt> of category strings (<tt>String</tt> * objects) or null if not applicable */ public abstract Collection getCategories(); /** * Get the item's publication date. * * @return the date, or null if not available */ public abstract Date getPublicationDate(); /** * Get the item's ID field, if any. * * @return the ID field, or null if not set */ public abstract String getID(); /*----------------------------------------------------------------------*\ Private Methods \*----------------------------------------------------------------------*/ /** * Truncate an RSS item's summary to a specified size. Truncates on * word boundary, if possible. * * @param summary the summary to truncate * @param maxSize the maximum size * * @return the truncated summary */ private String truncateSummary (String summary, int maxSize) { summary = summary.trim(); if (summary.length() > maxSize) { // Allow for ellipsis if (maxSize < 4) maxSize = 4; maxSize -= 4; int last = maxSize; char[] ch = summary.toCharArray(); int i = last; // If we're in the middle of a word, find the first hunk of // white space. while ((! Character.isWhitespace (ch[i])) && (i-- >= 0)) continue; // Next, get rid of trailing white space. while ((Character.isWhitespace (ch[i])) && (i-- >= 0)) continue; // Handle underflow. if (i >= 0) last = i; StringBuffer buf = new StringBuffer (summary.substring (0, last + 1)); buf.append (" ..."); summary = buf.toString(); } return summary; } }
Javadoc correction.
src/org/clapper/curn/parser/RSSItem.java
Javadoc correction.
<ide><path>rc/org/clapper/curn/parser/RSSItem.java <ide> * {@link FeedInfo} object to determine whether to truncate the <ide> * summary, use the description (i.e., content) if the summary isn't <ide> * available, etc. Strips HTML by default. (Use the <del> * {@link #getItemSummary(FeedInfo,boolean) alternate version} of <del> * this method to control the HTML-stripping behavior. <add> * {@link #getSummaryToDisplay(FeedInfo,String[],boolean) alternate version} <add> * of this method to control the HTML-stripping behavior. <ide> * <ide> * @param feedInfo the corresponding feed's <tt>FeedInfo</tt> object <ide> * @param mimeTypes desired MIME types; used only if no summary is
Java
epl-1.0
87c2f6df8509a8172da4827dcecf0ccbbb2f8897
0
OndraZizka/windup,windup/windup,lincolnthree/windup,OndraZizka/windup,d-s/windup,mbriskar/windup,Maarc/windup,jsight/windup,Ladicek/windup,mbriskar/windup,lincolnthree/windup,d-s/windup,jsight/windup,mareknovotny/windup,bradsdavis/windup,lincolnthree/windup,mareknovotny/windup,bradsdavis/windup,lincolnthree/windup,d-s/windup,Maarc/windup,bradsdavis/windup,Ladicek/windup,johnsteele/windup,sgilda/windup,mbriskar/windup,OndraZizka/windup,johnsteele/windup,johnsteele/windup,johnsteele/windup,mbriskar/windup,mareknovotny/windup,jsight/windup,Maarc/windup,windup/windup,OndraZizka/windup,sgilda/windup,mareknovotny/windup,sgilda/windup,Maarc/windup,Ladicek/windup,windup/windup,Ladicek/windup,windup/windup,sgilda/windup,d-s/windup,jsight/windup
package org.jboss.windup.config.operation.iteration; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import org.jboss.windup.config.GraphRewrite; import org.jboss.windup.config.graphsearch.GraphSearchConditionBuilderGremlin; import org.jboss.windup.config.operation.Iteration; import org.jboss.windup.config.selectables.VarStack; import org.jboss.windup.graph.GraphUtil; import org.jboss.windup.graph.model.WindupVertexFrame; import org.ocpsoft.common.util.Assert; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Predicate; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.gremlin.Tokens; import com.tinkerpop.gremlin.Tokens.T; import com.tinkerpop.pipes.Pipe; import com.tinkerpop.pipes.PipeFunction; import com.tinkerpop.pipes.branch.LoopPipe; import com.tinkerpop.pipes.transform.TransformPipe; import com.tinkerpop.pipes.util.structures.Pair; import com.tinkerpop.pipes.util.structures.Table; import com.tinkerpop.pipes.util.structures.Tree; import org.jboss.windup.config.operation.IterationRoot; /** * Gremlin Pipes adapter for Iteration.queryFor( ... ). */ public class GremlinPipesQueryImpl extends Iteration implements IterationQueryCriteria { private final IterationRoot root; private final GraphSearchConditionBuilderGremlin graphSearchConditionBuilderGremlin; private IterationPayloadManager payloadManager; public GremlinPipesQueryImpl(IterationRoot root, IterationPayloadManager manager) { this.root = root; this.setPayloadManager(manager); this.graphSearchConditionBuilderGremlin = new GraphSearchConditionBuilderGremlin(); } @Override public void setPayloadManager(IterationPayloadManager payloadManager) { Assert.notNull(payloadManager, "Payload manager must not be null."); this.payloadManager = payloadManager; } /** * @returns A SelectionManager which performs a Gremlin query. */ @Override public IterationSelectionManager getSelectionManager() { return new GremlinIterationSelectionManager(); } private class GremlinIterationSelectionManager implements IterationSelectionManager { @Override public Iterable<WindupVertexFrame> getFrames(GraphRewrite event, VarStack varStack) { List<Vertex> initialVertices = getInitialVertices( event, varStack ); // Perform the query and convert to frames. graphSearchConditionBuilderGremlin.setInitialVertices(initialVertices); Iterable<Vertex> v = graphSearchConditionBuilderGremlin.getResults(event); return GraphUtil.toVertexFrames(event.getGraphContext(), v); } /** * The initial vertices are those matched by previous query constructs. * Iteration.[initial vertices].queryFor().[gremlin pipe wrappers] */ private List<Vertex> getInitialVertices( GraphRewrite event, VarStack varStack ) { List<Vertex> initialVertices = new ArrayList<>(); Iterable<WindupVertexFrame> initialFrames = root.getSelectionManager().getFrames(event, varStack); // TODO: Doesn't the root SelectionManager have the same event and varStack? for (WindupVertexFrame frame : initialFrames) initialVertices.add(frame.asVertex()); return initialVertices; } } @Override public IterationPayloadManager getPayloadManager() { return payloadManager; } @Override public IterationQueryCriteria endQuery() { return this; } // <editor-fold defaultstate="collapsed" desc="Gremlin pipes wrapping methods."> public GremlinPipesQuery step(final PipeFunction function) { graphSearchConditionBuilderGremlin.step(function); return this; } public GremlinPipesQuery step(final Pipe<Vertex, Vertex> pipe) { graphSearchConditionBuilderGremlin.step(pipe); return this; } public GremlinPipesQuery copySplit(final Pipe<Vertex, Vertex>... pipes) { graphSearchConditionBuilderGremlin.copySplit(pipes); return this; } public GremlinPipesQuery exhaustMerge() { graphSearchConditionBuilderGremlin.exhaustMerge(); return this; } public GremlinPipesQuery fairMerge() { graphSearchConditionBuilderGremlin.fairMerge(); return this; } public GremlinPipesQuery ifThenElse(final PipeFunction<Vertex, Boolean> ifFunction, final PipeFunction<Vertex, Vertex> thenFunction, final PipeFunction<Vertex, Vertex> elseFunction) { graphSearchConditionBuilderGremlin.ifThenElse(ifFunction, thenFunction, elseFunction); return this; } public GremlinPipesQuery loop(final int numberedStep, final PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean> whileFunction) { graphSearchConditionBuilderGremlin.loop(numberedStep, whileFunction); return this; } public GremlinPipesQuery loop(final String namedStep, final PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean> whileFunction) { graphSearchConditionBuilderGremlin.loop(namedStep, whileFunction); return this; } @Deprecated @SuppressWarnings("deprecation") public GremlinPipesQuery loop(final int numberedStep, final PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean> whileFunction, final PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean> emitFunction) { graphSearchConditionBuilderGremlin.loop(numberedStep, whileFunction, emitFunction); return this; } public GremlinPipesQuery loop(final String namedStep, final PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean> whileFunction, final PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean> emitFunction) { graphSearchConditionBuilderGremlin.loop(namedStep, whileFunction, emitFunction); return this; } public GremlinPipesQuery and(final Pipe<Vertex, ?>... pipes) { graphSearchConditionBuilderGremlin.and(pipes); return this; } @Deprecated @SuppressWarnings("deprecation") public GremlinPipesQuery back(final int numberedStep) { graphSearchConditionBuilderGremlin.back(numberedStep); return this; } public GremlinPipesQuery back(final String namedStep) { graphSearchConditionBuilderGremlin.back(namedStep); return this; } public GremlinPipesQuery dedup() { graphSearchConditionBuilderGremlin.dedup(); return this; } public GremlinPipesQuery dedup(final PipeFunction<Vertex, ?> dedupFunction) { graphSearchConditionBuilderGremlin.dedup(dedupFunction); return this; } public GremlinPipesQuery except(final Collection<Vertex> collection) { graphSearchConditionBuilderGremlin.except(collection); return this; } public GremlinPipesQuery except(final String... namedSteps) { graphSearchConditionBuilderGremlin.except(namedSteps); return this; } public GremlinPipesQuery filter(final PipeFunction<Vertex, Boolean> filterFunction) { graphSearchConditionBuilderGremlin.filter(filterFunction); return this; } public GremlinPipesQuery or(final Pipe<Vertex, ?>... pipes) { graphSearchConditionBuilderGremlin.or(pipes); return this; } public GremlinPipesQuery random(final Double bias) { graphSearchConditionBuilderGremlin.random(bias); return this; } public GremlinPipesQuery range(final int low, final int high) { graphSearchConditionBuilderGremlin.range(low, high); return this; } public GremlinPipesQuery retain(final Collection<Vertex> collection) { graphSearchConditionBuilderGremlin.retain(collection); return this; } public GremlinPipesQuery retain(final String... namedSteps) { graphSearchConditionBuilderGremlin.retain(namedSteps); return this; } public GremlinPipesQuery simplePath() { graphSearchConditionBuilderGremlin.simplePath(); return this; } public GremlinPipesQuery has(final String key) { graphSearchConditionBuilderGremlin.has(key); return this; } public GremlinPipesQuery hasNot(final String key) { graphSearchConditionBuilderGremlin.hasNot(key); return this; } public GremlinPipesQuery has(final String key, final Object value) { graphSearchConditionBuilderGremlin.has(key, value); return this; } public GremlinPipesQuery has(final String key, final Tokens.T compareToken, final Object value) { graphSearchConditionBuilderGremlin.has(key, compareToken, value); return this; } public GremlinPipesQuery has(final String key, final Predicate predicate, final Object value) { graphSearchConditionBuilderGremlin.has(key, predicate, value); return this; } public GremlinPipesQuery hasNot(final String key, final Object value) { graphSearchConditionBuilderGremlin.hasNot(key, value); return this; } public GremlinPipesQuery interval(final String key, final Comparable startValue, final Comparable endValue) { graphSearchConditionBuilderGremlin.interval(key, startValue, endValue); return this; } public GremlinPipesQuery gather() { graphSearchConditionBuilderGremlin.gather(); return this; } public GremlinPipesQuery gather(final PipeFunction<List, ?> function) { graphSearchConditionBuilderGremlin.gather(function); return this; } public GremlinPipesQuery _() { graphSearchConditionBuilderGremlin._(); return this; } public GremlinPipesQuery memoize(final String namedStep) { graphSearchConditionBuilderGremlin.memoize(namedStep); return this; } @Deprecated @SuppressWarnings("deprecation") public GremlinPipesQuery memoize(final int numberedStep) { graphSearchConditionBuilderGremlin.memoize(numberedStep); return this; } public GremlinPipesQuery memoize(final String namedStep, final Map map) { graphSearchConditionBuilderGremlin.memoize(namedStep, map); return this; } @Deprecated @SuppressWarnings("deprecation") public GremlinPipesQuery memoize(final int numberedStep, final Map map) { graphSearchConditionBuilderGremlin.memoize(numberedStep, map); return this; } public GremlinPipesQuery order() { graphSearchConditionBuilderGremlin.order(); return this; } public GremlinPipesQuery order(TransformPipe.Order order) { graphSearchConditionBuilderGremlin.order(order); return this; } public GremlinPipesQuery order(final PipeFunction<Pair<Vertex, Vertex>, Integer> compareFunction) { graphSearchConditionBuilderGremlin.order(compareFunction); return this; } public GremlinPipesQuery path(final PipeFunction... pathFunctions) { graphSearchConditionBuilderGremlin.path(pathFunctions); return this; } public GremlinPipesQuery scatter() { graphSearchConditionBuilderGremlin.scatter(); return this; } public GremlinPipesQuery select(final Collection<String> stepNames, final PipeFunction... columnFunctions) { graphSearchConditionBuilderGremlin.select(stepNames, columnFunctions); return this; } public GremlinPipesQuery select(final PipeFunction... columnFunctions) { graphSearchConditionBuilderGremlin.select(columnFunctions); return this; } public GremlinPipesQuery select() { graphSearchConditionBuilderGremlin.select(); return this; } public GremlinPipesQuery shuffle() { graphSearchConditionBuilderGremlin.shuffle(); return this; } public GremlinPipesQuery cap() { graphSearchConditionBuilderGremlin.cap(); return this; } public GremlinPipesQuery orderMap(TransformPipe.Order order) { graphSearchConditionBuilderGremlin.orderMap(order); return this; } public GremlinPipesQuery orderMap(PipeFunction<Pair<Map.Entry, Map.Entry>, Integer> compareFunction) { graphSearchConditionBuilderGremlin.orderMap(compareFunction); return this; } public GremlinPipesQuery transform(final PipeFunction<Vertex, T> function) { graphSearchConditionBuilderGremlin.transform(function); return this; } public GremlinPipesQuery bothE(final String... labels) { graphSearchConditionBuilderGremlin.bothE(labels); return this; } public GremlinPipesQuery bothE(final int branchFactor, final String... labels) { graphSearchConditionBuilderGremlin.bothE(branchFactor, labels); return this; } public GremlinPipesQuery both(final String... labels) { graphSearchConditionBuilderGremlin.both(labels); return this; } public GremlinPipesQuery both(final int branchFactor, final String... labels) { graphSearchConditionBuilderGremlin.both(branchFactor, labels); return this; } public GremlinPipesQuery bothV() { graphSearchConditionBuilderGremlin.bothV(); return this; } public GremlinPipesQuery idEdge(final Graph graph) { graphSearchConditionBuilderGremlin.idEdge(graph); return this; } public GremlinPipesQuery id() { graphSearchConditionBuilderGremlin.id(); return this; } public GremlinPipesQuery idVertex(final Graph graph) { graphSearchConditionBuilderGremlin.idVertex(graph); return this; } public GremlinPipesQuery inE(final String... labels) { graphSearchConditionBuilderGremlin.inE(labels); return this; } public GremlinPipesQuery inE(final int branchFactor, final String... labels) { graphSearchConditionBuilderGremlin.inE(branchFactor, labels); return this; } public GremlinPipesQuery in(final String... labels) { graphSearchConditionBuilderGremlin.in(labels); return this; } public GremlinPipesQuery in(final int branchFactor, final String... labels) { graphSearchConditionBuilderGremlin.in(branchFactor, labels); return this; } public GremlinPipesQuery inV() { graphSearchConditionBuilderGremlin.inV(); return this; } public GremlinPipesQuery label() { graphSearchConditionBuilderGremlin.label(); return this; } public GremlinPipesQuery outE(final String... labels) { graphSearchConditionBuilderGremlin.outE(labels); return this; } public GremlinPipesQuery outE(final int branchFactor, final String... labels) { graphSearchConditionBuilderGremlin.outE(branchFactor, labels); return this; } public GremlinPipesQuery out(final String... labels) { graphSearchConditionBuilderGremlin.out(labels); return this; } public GremlinPipesQuery out(final int branchFactor, final String... labels) { graphSearchConditionBuilderGremlin.out(branchFactor, labels); return this; } public GremlinPipesQuery outV() { graphSearchConditionBuilderGremlin.outV(); return this; } public GremlinPipesQuery map(final String... keys) { graphSearchConditionBuilderGremlin.map(keys); return this; } public GremlinPipesQuery property(final String key) { graphSearchConditionBuilderGremlin.property(key); return this; } public GremlinPipesQuery aggregate() { graphSearchConditionBuilderGremlin.aggregate(); return this; } public GremlinPipesQuery aggregate(final Collection<Vertex> aggregate) { graphSearchConditionBuilderGremlin.aggregate(aggregate); return this; } public GremlinPipesQuery aggregate(final Collection aggregate, final PipeFunction<Vertex, ?> aggregateFunction) { graphSearchConditionBuilderGremlin.aggregate(aggregate, aggregateFunction); return this; } public GremlinPipesQuery aggregate(final PipeFunction<Vertex, ?> aggregateFunction) { graphSearchConditionBuilderGremlin.aggregate(aggregateFunction); return this; } @Deprecated @SuppressWarnings("deprecation") public GremlinPipesQuery optional(final int numberedStep) { graphSearchConditionBuilderGremlin.optional(numberedStep); return this; } public GremlinPipesQuery optional(final String namedStep) { graphSearchConditionBuilderGremlin.optional(namedStep); return this; } public GremlinPipesQuery groupBy(final Map<?, List<?>> map, final PipeFunction keyFunction, final PipeFunction valueFunction) { graphSearchConditionBuilderGremlin.groupBy(map, keyFunction, valueFunction); return this; } public GremlinPipesQuery groupBy(final PipeFunction keyFunction, final PipeFunction valueFunction) { graphSearchConditionBuilderGremlin.groupBy(keyFunction, valueFunction); return this; } public GremlinPipesQuery groupBy(final Map reduceMap, final PipeFunction keyFunction, final PipeFunction valueFunction, final PipeFunction reduceFunction) { graphSearchConditionBuilderGremlin.groupBy(reduceMap, keyFunction, valueFunction, reduceFunction); return this; } public GremlinPipesQuery groupBy(final PipeFunction keyFunction, final PipeFunction valueFunction, final PipeFunction reduceFunction) { graphSearchConditionBuilderGremlin.groupBy(keyFunction, valueFunction, reduceFunction); return this; } public GremlinPipesQuery groupCount(final Map<?, Number> map, final PipeFunction keyFunction, final PipeFunction<Pair<?, Number>, Number> valueFunction) { graphSearchConditionBuilderGremlin.groupCount(map, keyFunction, valueFunction); return this; } public GremlinPipesQuery groupCount(final PipeFunction keyFunction, final PipeFunction<Pair<?, Number>, Number> valueFunction) { graphSearchConditionBuilderGremlin.groupCount(keyFunction, valueFunction); return this; } public GremlinPipesQuery groupCount(final Map<?, Number> map, final PipeFunction keyFunction) { graphSearchConditionBuilderGremlin.groupCount(map, keyFunction); return this; } public GremlinPipesQuery groupCount(final PipeFunction keyFunction) { graphSearchConditionBuilderGremlin.groupCount(keyFunction); return this; } public GremlinPipesQuery groupCount(final Map<?, Number> map) { graphSearchConditionBuilderGremlin.groupCount(map); return this; } public GremlinPipesQuery groupCount() { graphSearchConditionBuilderGremlin.groupCount(); return this; } public GremlinPipesQuery sideEffect(final PipeFunction<Vertex, ?> sideEffectFunction) { graphSearchConditionBuilderGremlin.sideEffect(sideEffectFunction); return this; } public GremlinPipesQuery store(final Collection<Vertex> storage) { graphSearchConditionBuilderGremlin.store(storage); return this; } public GremlinPipesQuery store(final Collection storage, final PipeFunction<Vertex, ?> storageFunction) { graphSearchConditionBuilderGremlin.store(storage, storageFunction); return this; } public GremlinPipesQuery store() { graphSearchConditionBuilderGremlin.store(); return this; } public GremlinPipesQuery store(final PipeFunction<Vertex, ?> storageFunction) { graphSearchConditionBuilderGremlin.store(storageFunction); return this; } public GremlinPipesQuery table(final Table table, final Collection<String> stepNames, final PipeFunction... columnFunctions) { graphSearchConditionBuilderGremlin.table(table, stepNames, columnFunctions); return this; } public GremlinPipesQuery table(final Table table, final PipeFunction... columnFunctions) { graphSearchConditionBuilderGremlin.table(table, columnFunctions); return this; } public GremlinPipesQuery table(final PipeFunction... columnFunctions) { graphSearchConditionBuilderGremlin.table(columnFunctions); return this; } public GremlinPipesQuery table(final Table table) { graphSearchConditionBuilderGremlin.table(table); return this; } public GremlinPipesQuery table() { graphSearchConditionBuilderGremlin.table(); return this; } public GremlinPipesQuery tree(final Tree tree, final PipeFunction... branchFunctions) { graphSearchConditionBuilderGremlin.tree(tree, branchFunctions); return this; } public GremlinPipesQuery tree(final PipeFunction... branchFunctions) { graphSearchConditionBuilderGremlin.tree(branchFunctions); return this; } public GremlinPipesQuery linkOut(final String label, final String namedStep) { graphSearchConditionBuilderGremlin.linkOut(label, namedStep); return this; } public GremlinPipesQuery linkIn(final String label, final String namedStep) { graphSearchConditionBuilderGremlin.linkIn(label, namedStep); return this; } public GremlinPipesQuery linkBoth(final String label, final String namedStep) { graphSearchConditionBuilderGremlin.linkBoth(label, namedStep); return this; } public GremlinPipesQuery linkOut(final String label, final Vertex other) { graphSearchConditionBuilderGremlin.linkOut(label, other); return this; } public GremlinPipesQuery linkIn(final String label, final Vertex other) { graphSearchConditionBuilderGremlin.linkIn(label, other); return this; } public GremlinPipesQuery linkBoth(final String label, final Vertex other) { graphSearchConditionBuilderGremlin.linkBoth(label, other); return this; } public GremlinPipesQuery as(final String name) { graphSearchConditionBuilderGremlin.as(name); return this; } public GremlinPipesQuery enablePath() { graphSearchConditionBuilderGremlin.enablePath(); return this; } public GremlinPipesQuery cast(Class<Vertex> end) { graphSearchConditionBuilderGremlin.cast(end); return this; } }
config/api/src/main/java/org/jboss/windup/config/operation/iteration/GremlinPipesQueryImpl.java
package org.jboss.windup.config.operation.iteration; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import org.jboss.windup.config.GraphRewrite; import org.jboss.windup.config.graphsearch.GraphSearchConditionBuilderGremlin; import org.jboss.windup.config.operation.Iteration; import org.jboss.windup.config.selectables.VarStack; import org.jboss.windup.graph.GraphUtil; import org.jboss.windup.graph.model.WindupVertexFrame; import org.ocpsoft.common.util.Assert; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Predicate; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.gremlin.Tokens; import com.tinkerpop.gremlin.Tokens.T; import com.tinkerpop.pipes.Pipe; import com.tinkerpop.pipes.PipeFunction; import com.tinkerpop.pipes.branch.LoopPipe; import com.tinkerpop.pipes.transform.TransformPipe; import com.tinkerpop.pipes.util.structures.Pair; import com.tinkerpop.pipes.util.structures.Table; import com.tinkerpop.pipes.util.structures.Tree; import org.jboss.windup.config.operation.IterationRoot; /** * Gremlin Pipes adapter for Iteration.queryFor( ... ). */ public class GremlinPipesQueryImpl extends Iteration implements IterationQueryCriteria { private final IterationRoot root; private final GraphSearchConditionBuilderGremlin graphSearchConditionBuilderGremlin; private IterationPayloadManager payloadManager; public GremlinPipesQueryImpl(IterationRoot root, IterationPayloadManager manager) { this.root = root; this.setPayloadManager(manager); this.graphSearchConditionBuilderGremlin = new GraphSearchConditionBuilderGremlin(); } @Override public void setPayloadManager(IterationPayloadManager payloadManager) { Assert.notNull(payloadManager, "Payload manager must not be null."); this.payloadManager = payloadManager; } /** * @returns A SelectionManager which performs a Gremlin query. */ @Override public IterationSelectionManager getSelectionManager() { return new GremlinIterationSelectionManager(); } private class GremlinIterationSelectionManager implements IterationSelectionManager { @Override public Iterable<WindupVertexFrame> getFrames(GraphRewrite event, VarStack varStack) { // The initial vertices are those matched by previous query constructs. // Iteration.[initial vertices].queryFor().[gremlin pipe wrappers] List<Vertex> initialVertices = new ArrayList<>(); // TODO: Doesn't the root SelectionManager have the same event and varStack? Iterable<WindupVertexFrame> initialFrames = root.getSelectionManager().getFrames(event, varStack); for (WindupVertexFrame frame : initialFrames) { initialVertices.add(frame.asVertex()); } // Perform the query and convert to frames. graphSearchConditionBuilderGremlin.setInitialVertices(initialVertices); Iterable<Vertex> v = graphSearchConditionBuilderGremlin.getResults(event); return GraphUtil.toVertexFrames(event.getGraphContext(), v); } } @Override public IterationPayloadManager getPayloadManager() { return payloadManager; } @Override public IterationQueryCriteria endQuery() { return this; } // <editor-fold defaultstate="collapsed" desc="Gremlin pipes wrapping methods."> public GremlinPipesQuery step(final PipeFunction function) { graphSearchConditionBuilderGremlin.step(function); return this; } public GremlinPipesQuery step(final Pipe<Vertex, Vertex> pipe) { graphSearchConditionBuilderGremlin.step(pipe); return this; } public GremlinPipesQuery copySplit(final Pipe<Vertex, Vertex>... pipes) { graphSearchConditionBuilderGremlin.copySplit(pipes); return this; } public GremlinPipesQuery exhaustMerge() { graphSearchConditionBuilderGremlin.exhaustMerge(); return this; } public GremlinPipesQuery fairMerge() { graphSearchConditionBuilderGremlin.fairMerge(); return this; } public GremlinPipesQuery ifThenElse(final PipeFunction<Vertex, Boolean> ifFunction, final PipeFunction<Vertex, Vertex> thenFunction, final PipeFunction<Vertex, Vertex> elseFunction) { graphSearchConditionBuilderGremlin.ifThenElse(ifFunction, thenFunction, elseFunction); return this; } public GremlinPipesQuery loop(final int numberedStep, final PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean> whileFunction) { graphSearchConditionBuilderGremlin.loop(numberedStep, whileFunction); return this; } public GremlinPipesQuery loop(final String namedStep, final PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean> whileFunction) { graphSearchConditionBuilderGremlin.loop(namedStep, whileFunction); return this; } @Deprecated @SuppressWarnings("deprecation") public GremlinPipesQuery loop(final int numberedStep, final PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean> whileFunction, final PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean> emitFunction) { graphSearchConditionBuilderGremlin.loop(numberedStep, whileFunction, emitFunction); return this; } public GremlinPipesQuery loop(final String namedStep, final PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean> whileFunction, final PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean> emitFunction) { graphSearchConditionBuilderGremlin.loop(namedStep, whileFunction, emitFunction); return this; } public GremlinPipesQuery and(final Pipe<Vertex, ?>... pipes) { graphSearchConditionBuilderGremlin.and(pipes); return this; } @Deprecated @SuppressWarnings("deprecation") public GremlinPipesQuery back(final int numberedStep) { graphSearchConditionBuilderGremlin.back(numberedStep); return this; } public GremlinPipesQuery back(final String namedStep) { graphSearchConditionBuilderGremlin.back(namedStep); return this; } public GremlinPipesQuery dedup() { graphSearchConditionBuilderGremlin.dedup(); return this; } public GremlinPipesQuery dedup(final PipeFunction<Vertex, ?> dedupFunction) { graphSearchConditionBuilderGremlin.dedup(dedupFunction); return this; } public GremlinPipesQuery except(final Collection<Vertex> collection) { graphSearchConditionBuilderGremlin.except(collection); return this; } public GremlinPipesQuery except(final String... namedSteps) { graphSearchConditionBuilderGremlin.except(namedSteps); return this; } public GremlinPipesQuery filter(final PipeFunction<Vertex, Boolean> filterFunction) { graphSearchConditionBuilderGremlin.filter(filterFunction); return this; } public GremlinPipesQuery or(final Pipe<Vertex, ?>... pipes) { graphSearchConditionBuilderGremlin.or(pipes); return this; } public GremlinPipesQuery random(final Double bias) { graphSearchConditionBuilderGremlin.random(bias); return this; } public GremlinPipesQuery range(final int low, final int high) { graphSearchConditionBuilderGremlin.range(low, high); return this; } public GremlinPipesQuery retain(final Collection<Vertex> collection) { graphSearchConditionBuilderGremlin.retain(collection); return this; } public GremlinPipesQuery retain(final String... namedSteps) { graphSearchConditionBuilderGremlin.retain(namedSteps); return this; } public GremlinPipesQuery simplePath() { graphSearchConditionBuilderGremlin.simplePath(); return this; } public GremlinPipesQuery has(final String key) { graphSearchConditionBuilderGremlin.has(key); return this; } public GremlinPipesQuery hasNot(final String key) { graphSearchConditionBuilderGremlin.hasNot(key); return this; } public GremlinPipesQuery has(final String key, final Object value) { graphSearchConditionBuilderGremlin.has(key, value); return this; } public GremlinPipesQuery has(final String key, final Tokens.T compareToken, final Object value) { graphSearchConditionBuilderGremlin.has(key, compareToken, value); return this; } public GremlinPipesQuery has(final String key, final Predicate predicate, final Object value) { graphSearchConditionBuilderGremlin.has(key, predicate, value); return this; } public GremlinPipesQuery hasNot(final String key, final Object value) { graphSearchConditionBuilderGremlin.hasNot(key, value); return this; } public GremlinPipesQuery interval(final String key, final Comparable startValue, final Comparable endValue) { graphSearchConditionBuilderGremlin.interval(key, startValue, endValue); return this; } public GremlinPipesQuery gather() { graphSearchConditionBuilderGremlin.gather(); return this; } public GremlinPipesQuery gather(final PipeFunction<List, ?> function) { graphSearchConditionBuilderGremlin.gather(function); return this; } public GremlinPipesQuery _() { graphSearchConditionBuilderGremlin._(); return this; } public GremlinPipesQuery memoize(final String namedStep) { graphSearchConditionBuilderGremlin.memoize(namedStep); return this; } @Deprecated @SuppressWarnings("deprecation") public GremlinPipesQuery memoize(final int numberedStep) { graphSearchConditionBuilderGremlin.memoize(numberedStep); return this; } public GremlinPipesQuery memoize(final String namedStep, final Map map) { graphSearchConditionBuilderGremlin.memoize(namedStep, map); return this; } @Deprecated @SuppressWarnings("deprecation") public GremlinPipesQuery memoize(final int numberedStep, final Map map) { graphSearchConditionBuilderGremlin.memoize(numberedStep, map); return this; } public GremlinPipesQuery order() { graphSearchConditionBuilderGremlin.order(); return this; } public GremlinPipesQuery order(TransformPipe.Order order) { graphSearchConditionBuilderGremlin.order(order); return this; } public GremlinPipesQuery order(final PipeFunction<Pair<Vertex, Vertex>, Integer> compareFunction) { graphSearchConditionBuilderGremlin.order(compareFunction); return this; } public GremlinPipesQuery path(final PipeFunction... pathFunctions) { graphSearchConditionBuilderGremlin.path(pathFunctions); return this; } public GremlinPipesQuery scatter() { graphSearchConditionBuilderGremlin.scatter(); return this; } public GremlinPipesQuery select(final Collection<String> stepNames, final PipeFunction... columnFunctions) { graphSearchConditionBuilderGremlin.select(stepNames, columnFunctions); return this; } public GremlinPipesQuery select(final PipeFunction... columnFunctions) { graphSearchConditionBuilderGremlin.select(columnFunctions); return this; } public GremlinPipesQuery select() { graphSearchConditionBuilderGremlin.select(); return this; } public GremlinPipesQuery shuffle() { graphSearchConditionBuilderGremlin.shuffle(); return this; } public GremlinPipesQuery cap() { graphSearchConditionBuilderGremlin.cap(); return this; } public GremlinPipesQuery orderMap(TransformPipe.Order order) { graphSearchConditionBuilderGremlin.orderMap(order); return this; } public GremlinPipesQuery orderMap(PipeFunction<Pair<Map.Entry, Map.Entry>, Integer> compareFunction) { graphSearchConditionBuilderGremlin.orderMap(compareFunction); return this; } public GremlinPipesQuery transform(final PipeFunction<Vertex, T> function) { graphSearchConditionBuilderGremlin.transform(function); return this; } public GremlinPipesQuery bothE(final String... labels) { graphSearchConditionBuilderGremlin.bothE(labels); return this; } public GremlinPipesQuery bothE(final int branchFactor, final String... labels) { graphSearchConditionBuilderGremlin.bothE(branchFactor, labels); return this; } public GremlinPipesQuery both(final String... labels) { graphSearchConditionBuilderGremlin.both(labels); return this; } public GremlinPipesQuery both(final int branchFactor, final String... labels) { graphSearchConditionBuilderGremlin.both(branchFactor, labels); return this; } public GremlinPipesQuery bothV() { graphSearchConditionBuilderGremlin.bothV(); return this; } public GremlinPipesQuery idEdge(final Graph graph) { graphSearchConditionBuilderGremlin.idEdge(graph); return this; } public GremlinPipesQuery id() { graphSearchConditionBuilderGremlin.id(); return this; } public GremlinPipesQuery idVertex(final Graph graph) { graphSearchConditionBuilderGremlin.idVertex(graph); return this; } public GremlinPipesQuery inE(final String... labels) { graphSearchConditionBuilderGremlin.inE(labels); return this; } public GremlinPipesQuery inE(final int branchFactor, final String... labels) { graphSearchConditionBuilderGremlin.inE(branchFactor, labels); return this; } public GremlinPipesQuery in(final String... labels) { graphSearchConditionBuilderGremlin.in(labels); return this; } public GremlinPipesQuery in(final int branchFactor, final String... labels) { graphSearchConditionBuilderGremlin.in(branchFactor, labels); return this; } public GremlinPipesQuery inV() { graphSearchConditionBuilderGremlin.inV(); return this; } public GremlinPipesQuery label() { graphSearchConditionBuilderGremlin.label(); return this; } public GremlinPipesQuery outE(final String... labels) { graphSearchConditionBuilderGremlin.outE(labels); return this; } public GremlinPipesQuery outE(final int branchFactor, final String... labels) { graphSearchConditionBuilderGremlin.outE(branchFactor, labels); return this; } public GremlinPipesQuery out(final String... labels) { graphSearchConditionBuilderGremlin.out(labels); return this; } public GremlinPipesQuery out(final int branchFactor, final String... labels) { graphSearchConditionBuilderGremlin.out(branchFactor, labels); return this; } public GremlinPipesQuery outV() { graphSearchConditionBuilderGremlin.outV(); return this; } public GremlinPipesQuery map(final String... keys) { graphSearchConditionBuilderGremlin.map(keys); return this; } public GremlinPipesQuery property(final String key) { graphSearchConditionBuilderGremlin.property(key); return this; } public GremlinPipesQuery aggregate() { graphSearchConditionBuilderGremlin.aggregate(); return this; } public GremlinPipesQuery aggregate(final Collection<Vertex> aggregate) { graphSearchConditionBuilderGremlin.aggregate(aggregate); return this; } public GremlinPipesQuery aggregate(final Collection aggregate, final PipeFunction<Vertex, ?> aggregateFunction) { graphSearchConditionBuilderGremlin.aggregate(aggregate, aggregateFunction); return this; } public GremlinPipesQuery aggregate(final PipeFunction<Vertex, ?> aggregateFunction) { graphSearchConditionBuilderGremlin.aggregate(aggregateFunction); return this; } @Deprecated @SuppressWarnings("deprecation") public GremlinPipesQuery optional(final int numberedStep) { graphSearchConditionBuilderGremlin.optional(numberedStep); return this; } public GremlinPipesQuery optional(final String namedStep) { graphSearchConditionBuilderGremlin.optional(namedStep); return this; } public GremlinPipesQuery groupBy(final Map<?, List<?>> map, final PipeFunction keyFunction, final PipeFunction valueFunction) { graphSearchConditionBuilderGremlin.groupBy(map, keyFunction, valueFunction); return this; } public GremlinPipesQuery groupBy(final PipeFunction keyFunction, final PipeFunction valueFunction) { graphSearchConditionBuilderGremlin.groupBy(keyFunction, valueFunction); return this; } public GremlinPipesQuery groupBy(final Map reduceMap, final PipeFunction keyFunction, final PipeFunction valueFunction, final PipeFunction reduceFunction) { graphSearchConditionBuilderGremlin.groupBy(reduceMap, keyFunction, valueFunction, reduceFunction); return this; } public GremlinPipesQuery groupBy(final PipeFunction keyFunction, final PipeFunction valueFunction, final PipeFunction reduceFunction) { graphSearchConditionBuilderGremlin.groupBy(keyFunction, valueFunction, reduceFunction); return this; } public GremlinPipesQuery groupCount(final Map<?, Number> map, final PipeFunction keyFunction, final PipeFunction<Pair<?, Number>, Number> valueFunction) { graphSearchConditionBuilderGremlin.groupCount(map, keyFunction, valueFunction); return this; } public GremlinPipesQuery groupCount(final PipeFunction keyFunction, final PipeFunction<Pair<?, Number>, Number> valueFunction) { graphSearchConditionBuilderGremlin.groupCount(keyFunction, valueFunction); return this; } public GremlinPipesQuery groupCount(final Map<?, Number> map, final PipeFunction keyFunction) { graphSearchConditionBuilderGremlin.groupCount(map, keyFunction); return this; } public GremlinPipesQuery groupCount(final PipeFunction keyFunction) { graphSearchConditionBuilderGremlin.groupCount(keyFunction); return this; } public GremlinPipesQuery groupCount(final Map<?, Number> map) { graphSearchConditionBuilderGremlin.groupCount(map); return this; } public GremlinPipesQuery groupCount() { graphSearchConditionBuilderGremlin.groupCount(); return this; } public GremlinPipesQuery sideEffect(final PipeFunction<Vertex, ?> sideEffectFunction) { graphSearchConditionBuilderGremlin.sideEffect(sideEffectFunction); return this; } public GremlinPipesQuery store(final Collection<Vertex> storage) { graphSearchConditionBuilderGremlin.store(storage); return this; } public GremlinPipesQuery store(final Collection storage, final PipeFunction<Vertex, ?> storageFunction) { graphSearchConditionBuilderGremlin.store(storage, storageFunction); return this; } public GremlinPipesQuery store() { graphSearchConditionBuilderGremlin.store(); return this; } public GremlinPipesQuery store(final PipeFunction<Vertex, ?> storageFunction) { graphSearchConditionBuilderGremlin.store(storageFunction); return this; } public GremlinPipesQuery table(final Table table, final Collection<String> stepNames, final PipeFunction... columnFunctions) { graphSearchConditionBuilderGremlin.table(table, stepNames, columnFunctions); return this; } public GremlinPipesQuery table(final Table table, final PipeFunction... columnFunctions) { graphSearchConditionBuilderGremlin.table(table, columnFunctions); return this; } public GremlinPipesQuery table(final PipeFunction... columnFunctions) { graphSearchConditionBuilderGremlin.table(columnFunctions); return this; } public GremlinPipesQuery table(final Table table) { graphSearchConditionBuilderGremlin.table(table); return this; } public GremlinPipesQuery table() { graphSearchConditionBuilderGremlin.table(); return this; } public GremlinPipesQuery tree(final Tree tree, final PipeFunction... branchFunctions) { graphSearchConditionBuilderGremlin.tree(tree, branchFunctions); return this; } public GremlinPipesQuery tree(final PipeFunction... branchFunctions) { graphSearchConditionBuilderGremlin.tree(branchFunctions); return this; } public GremlinPipesQuery linkOut(final String label, final String namedStep) { graphSearchConditionBuilderGremlin.linkOut(label, namedStep); return this; } public GremlinPipesQuery linkIn(final String label, final String namedStep) { graphSearchConditionBuilderGremlin.linkIn(label, namedStep); return this; } public GremlinPipesQuery linkBoth(final String label, final String namedStep) { graphSearchConditionBuilderGremlin.linkBoth(label, namedStep); return this; } public GremlinPipesQuery linkOut(final String label, final Vertex other) { graphSearchConditionBuilderGremlin.linkOut(label, other); return this; } public GremlinPipesQuery linkIn(final String label, final Vertex other) { graphSearchConditionBuilderGremlin.linkIn(label, other); return this; } public GremlinPipesQuery linkBoth(final String label, final Vertex other) { graphSearchConditionBuilderGremlin.linkBoth(label, other); return this; } public GremlinPipesQuery as(final String name) { graphSearchConditionBuilderGremlin.as(name); return this; } public GremlinPipesQuery enablePath() { graphSearchConditionBuilderGremlin.enablePath(); return this; } public GremlinPipesQuery cast(Class<Vertex> end) { graphSearchConditionBuilderGremlin.cast(end); return this; } }
getInitialVertices()
config/api/src/main/java/org/jboss/windup/config/operation/iteration/GremlinPipesQueryImpl.java
getInitialVertices()
<ide><path>onfig/api/src/main/java/org/jboss/windup/config/operation/iteration/GremlinPipesQueryImpl.java <ide> @Override <ide> public Iterable<WindupVertexFrame> getFrames(GraphRewrite event, VarStack varStack) <ide> { <del> // The initial vertices are those matched by previous query constructs. <del> // Iteration.[initial vertices].queryFor().[gremlin pipe wrappers] <del> List<Vertex> initialVertices = new ArrayList<>(); <del> // TODO: Doesn't the root SelectionManager have the same event and varStack? <del> Iterable<WindupVertexFrame> initialFrames = root.getSelectionManager().getFrames(event, varStack); <del> for (WindupVertexFrame frame : initialFrames) <del> { <del> initialVertices.add(frame.asVertex()); <del> } <add> List<Vertex> initialVertices = getInitialVertices( event, varStack ); <ide> <ide> // Perform the query and convert to frames. <ide> graphSearchConditionBuilderGremlin.setInitialVertices(initialVertices); <ide> Iterable<Vertex> v = graphSearchConditionBuilderGremlin.getResults(event); <ide> return GraphUtil.toVertexFrames(event.getGraphContext(), v); <ide> } <del> <add> <add> /** <add> * The initial vertices are those matched by previous query constructs. <add> * Iteration.[initial vertices].queryFor().[gremlin pipe wrappers] <add> */ <add> private List<Vertex> getInitialVertices( GraphRewrite event, VarStack varStack ) { <add> List<Vertex> initialVertices = new ArrayList<>(); <add> Iterable<WindupVertexFrame> initialFrames = root.getSelectionManager().getFrames(event, varStack); <add> // TODO: Doesn't the root SelectionManager have the same event and varStack? <add> for (WindupVertexFrame frame : initialFrames) <add> initialVertices.add(frame.asVertex()); <add> return initialVertices; <add> } <ide> } <ide> <ide> @Override
Java
mit
b4cafed8d03baf9afdbc0ee5e299a4f9f6e546ca
0
gravitylow/Updater,r-clancy/Updater
/* * Updater for Bukkit. * * This class provides the means to safely and easily update a plugin, or check to see if it is updated using dev.bukkit.org */ package net.gravitydevelopment.updater; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.Plugin; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; /** * Check dev.bukkit.org to find updates for a given plugin, and download the updates if needed. * <p/> * <b>VERY, VERY IMPORTANT</b>: Because there are no standards for adding auto-update toggles in your plugin's config, this system provides NO CHECK WITH YOUR CONFIG to make sure the user has allowed auto-updating. * <br> * It is a <b>BUKKIT POLICY</b> that you include a boolean value in your config that prevents the auto-updater from running <b>AT ALL</b>. * <br> * If you fail to include this option in your config, your plugin will be <b>REJECTED</b> when you attempt to submit it to dev.bukkit.org. * <p/> * An example of a good configuration option would be something similar to 'auto-update: true' - if this value is set to false you may NOT run the auto-updater. * <br> * If you are unsure about these rules, please read the plugin submission guidelines: http://goo.gl/8iU5l * * @author Gravity */ public class Updater { private Plugin plugin; private UpdateType type; private String versionTitle; private String versionLink; private long totalSize; // Holds the total size of the file private int sizeLine; // Used for detecting file size private int multiplier; // Used for determining when to broadcast download updates private boolean announce; // Whether to announce file downloads private URL url; // Connecting to RSS private File file; // The plugin's file private Thread thread; // Updater thread private int id = -1; // Project's Curse ID private String apiKey = null; // BukkitDev ServerMods API key private static final String TITLE_VALUE = "name"; // Gets remote file's title private static final String LINK_VALUE = "downloadUrl"; // Gets remote file's download link private static final String QUERY = "/servermods/files?projectIds="; // Path to GET private static final String HOST = "https://api.curseforge.com"; // Slugs will be appended to this to get to the project's RSS feed private String[] noUpdateTag = {"-DEV", "-PRE", "-SNAPSHOT"}; // If the version number contains one of these, don't update. private static final int BYTE_SIZE = 1024; // Used for downloading files private YamlConfiguration config; // Config file private String updateFolder = YamlConfiguration.loadConfiguration(new File("bukkit.yml")).getString("settings.update-folder"); // The folder that downloads will be placed in private Updater.UpdateResult result = Updater.UpdateResult.SUCCESS; // Used for determining the outcome of the update process /** * Gives the dev the result of the update process. Can be obtained by called getResult(). */ public enum UpdateResult { /** * The updater found an update, and has readied it to be loaded the next time the server restarts/reloads. */ SUCCESS, /** * The updater did not find an update, and nothing was downloaded. */ NO_UPDATE, /** * The server administrator has disabled the updating system */ DISABLED, /** * The updater found an update, but was unable to download it. */ FAIL_DOWNLOAD, /** * For some reason, the updater was unable to contact dev.bukkit.org to download the file. */ FAIL_DBO, /** * When running the version check, the file on DBO did not contain the a version in the format 'vVersion' such as 'v1.0'. */ FAIL_NOVERSION, /** * The id provided by the plugin running the updater was invalid and doesn't exist on DBO. */ FAIL_BADID, /** * The server administrator has improperly configured their API key in the configuration */ FAIL_APIKEY, /** * The updater found an update, but because of the UpdateType being set to NO_DOWNLOAD, it wasn't downloaded. */ UPDATE_AVAILABLE } /** * Allows the dev to specify the type of update that will be run. */ public enum UpdateType { /** * Run a version check, and then if the file is out of date, download the newest version. */ DEFAULT, /** * Don't run a version check, just find the latest update and download it. */ NO_VERSION_CHECK, /** * Get information about the version and the download size, but don't actually download anything. */ NO_DOWNLOAD } /** * Initialize the updater * * @param plugin The plugin that is checking for an update. * @param id The dev.bukkit.org id of the project * @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class. * @param type Specify the type of update this will be. See {@link UpdateType} * @param announce True if the program should announce the progress of new updates in console */ public Updater(Plugin plugin, int id, File file, UpdateType type, boolean announce) { this.plugin = plugin; this.type = type; this.announce = announce; this.file = file; this.id = id; File pluginFile = plugin.getDataFolder().getParentFile(); File updaterFile = new File(pluginFile, "Updater"); File updaterConfigFile = new File(updaterFile, "config.yml"); if (!updaterFile.exists()) { updaterFile.mkdir(); } if (!updaterConfigFile.exists()) { try { updaterConfigFile.createNewFile(); } catch (IOException e) { plugin.getLogger().severe("The updater could not create a configuration in " + updaterFile.getAbsolutePath()); e.printStackTrace(); } } config = YamlConfiguration.loadConfiguration(updaterConfigFile); config.addDefault("api-key", "PUT_API_KEY_HERE"); config.addDefault("disable", false); if (config.get("api-key", null) == null) { config.options().copyDefaults(true); try { config.save(updaterConfigFile); } catch (IOException e) { plugin.getLogger().severe("The updater could not save the configuration in " + updaterFile.getAbsolutePath()); e.printStackTrace(); } } if (config.getBoolean("disable")) { result = UpdateResult.DISABLED; return; } String key = config.getString("api-key"); if (key.equalsIgnoreCase("PUT_API_KEY_HERE") || key.equals("")) { key = null; } apiKey = key; try { url = new URL(HOST + QUERY + id); } catch (MalformedURLException e) { plugin.getLogger().severe("The project ID provided for updating, " + id + " is invalid."); result = UpdateResult.FAIL_BADID; e.printStackTrace(); } thread = new Thread(new UpdateRunnable()); thread.start(); } /** * Get the result of the update process. */ public Updater.UpdateResult getResult() { waitForThread(); return result; } /** * Get the total bytes of the file (can only be used after running a version check or a normal run). */ public long getFileSize() { waitForThread(); return totalSize; } /** * Get the version string latest file avaliable online. */ public String getLatestVersionString() { waitForThread(); return versionTitle; } /** * As the result of Updater output depends on the thread's completion, it is necessary to wait for the thread to finish * before allowing anyone to check the result. */ public void waitForThread() { if (thread != null && thread.isAlive()) { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * Save an update from dev.bukkit.org into the server's update folder. */ private void saveFile(File folder, String file, String u) { if (!folder.exists()) { folder.mkdir(); } BufferedInputStream in = null; FileOutputStream fout = null; try { // Download the file URL url = new URL(u); int fileLength = url.openConnection().getContentLength(); in = new BufferedInputStream(url.openStream()); fout = new FileOutputStream(folder.getAbsolutePath() + "/" + file); byte[] data = new byte[BYTE_SIZE]; int count; if (announce) plugin.getLogger().info("About to download a new update: " + versionTitle); long downloaded = 0; while ((count = in.read(data, 0, BYTE_SIZE)) != -1) { downloaded += count; fout.write(data, 0, count); int percent = (int) (downloaded * 100 / fileLength); if (announce & (percent % 10 == 0)) { plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes."); } } //Just a quick check to make sure we didn't leave any files from last time... for (File xFile : new File("plugins/" + updateFolder).listFiles()) { if (xFile.getName().endsWith(".zip")) { xFile.delete(); } } // Check to see if it's a zip file, if it is, unzip it. File dFile = new File(folder.getAbsolutePath() + "/" + file); if (dFile.getName().endsWith(".zip")) { // Unzip unzip(dFile.getCanonicalPath()); } if (announce) plugin.getLogger().info("Finished updating."); } catch (Exception ex) { plugin.getLogger().warning("The auto-updater tried to download a new update, but was unsuccessful."); result = Updater.UpdateResult.FAIL_DOWNLOAD; } finally { try { if (in != null) { in.close(); } if (fout != null) { fout.close(); } } catch (Exception ex) { } } } /** * Part of Zip-File-Extractor, modified by H31IX for use with Bukkit */ private void unzip(String file) { try { File fSourceZip = new File(file); String zipPath = file.substring(0, file.length() - 4); ZipFile zipFile = new ZipFile(fSourceZip); Enumeration<? extends ZipEntry> e = zipFile.entries(); while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); File destinationFilePath = new File(zipPath, entry.getName()); destinationFilePath.getParentFile().mkdirs(); if (entry.isDirectory()) { continue; } else { BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); int b; byte buffer[] = new byte[BYTE_SIZE]; FileOutputStream fos = new FileOutputStream(destinationFilePath); BufferedOutputStream bos = new BufferedOutputStream(fos, BYTE_SIZE); while ((b = bis.read(buffer, 0, BYTE_SIZE)) != -1) { bos.write(buffer, 0, b); } bos.flush(); bos.close(); bis.close(); String name = destinationFilePath.getName(); if (name.endsWith(".jar") && pluginFile(name)) { destinationFilePath.renameTo(new File("plugins/" + updateFolder + "/" + name)); } } entry = null; destinationFilePath = null; } e = null; zipFile.close(); zipFile = null; // Move any plugin data folders that were included to the right place, Bukkit won't do this for us. for (File dFile : new File(zipPath).listFiles()) { if (dFile.isDirectory()) { if (pluginFile(dFile.getName())) { File oFile = new File("plugins/" + dFile.getName()); // Get current dir File[] contents = oFile.listFiles(); // List of existing files in the current dir for (File cFile : dFile.listFiles()) // Loop through all the files in the new dir { boolean found = false; for (File xFile : contents) // Loop through contents to see if it exists { if (xFile.getName().equals(cFile.getName())) { found = true; break; } } if (!found) { // Move the new file into the current dir cFile.renameTo(new File(oFile.getCanonicalFile() + "/" + cFile.getName())); } else { // This file already exists, so we don't need it anymore. cFile.delete(); } } } } dFile.delete(); } new File(zipPath).delete(); fSourceZip.delete(); } catch (IOException ex) { plugin.getLogger().warning("The auto-updater tried to unzip a new update file, but was unsuccessful."); result = Updater.UpdateResult.FAIL_DOWNLOAD; ex.printStackTrace(); } new File(file).delete(); } /** * Check if the name of a jar is one of the plugins currently installed, used for extracting the correct files out of a zip. */ public boolean pluginFile(String name) { for (File file : new File("plugins").listFiles()) { if (file.getName().equals(name)) { return true; } } return false; } /** * Check to see if the program should continue by evaluation whether the plugin is already updated, or shouldn't be updated */ private boolean versionCheck(String title) { if (type != UpdateType.NO_VERSION_CHECK) { String version = plugin.getDescription().getVersion(); if (title.split(" v").length == 2) { String remoteVersion = title.split(" v")[1].split(" ")[0]; // Get the newest file's version number int remVer = -1, curVer = 0; try { remVer = calVer(remoteVersion); curVer = calVer(version); } catch (NumberFormatException nfe) { remVer = -1; } if (hasTag(version) || version.equalsIgnoreCase(remoteVersion) || curVer >= remVer) { // We already have the latest version, or this build is tagged for no-update result = Updater.UpdateResult.NO_UPDATE; return false; } } else { // The file's name did not contain the string 'vVersion' plugin.getLogger().warning("The author of this plugin (" + plugin.getDescription().getAuthors().get(0) + ") has misconfigured their Auto Update system"); plugin.getLogger().warning("Files uploaded to BukkitDev should contain the version number, seperated from the name by a 'v', such as PluginName v1.0"); plugin.getLogger().warning("Please notify the author of this error."); result = Updater.UpdateResult.FAIL_NOVERSION; return false; } } return true; } /** * Used to calculate the version string as an Integer */ private Integer calVer(String s) throws NumberFormatException { if (s.contains(".")) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { Character c = s.charAt(i); if (Character.isLetterOrDigit(c)) { sb.append(c); } } return Integer.parseInt(sb.toString()); } return Integer.parseInt(s); } /** * Evaluate whether the version number is marked showing that it should not be updated by this program */ private boolean hasTag(String version) { for (String string : noUpdateTag) { if (version.contains(string)) { return true; } } return false; } public boolean read() { try { URLConnection conn = url.openConnection(); conn.setConnectTimeout(5000); if (apiKey != null) { conn.addRequestProperty("X-API-Key", apiKey); } conn.addRequestProperty("User-Agent", "Updater (by Gravity)"); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = reader.readLine(); JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() == 0) { plugin.getLogger().warning("The updater could not find any files for the project id " + id); result = UpdateResult.FAIL_BADID; return false; } versionTitle = (String) ((JSONObject) array.get(array.size() - 1)).get(TITLE_VALUE); versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(LINK_VALUE); return true; } catch (IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { plugin.getLogger().warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); plugin.getLogger().warning("Please double-check your configuration to ensure it is correct."); result = UpdateResult.FAIL_APIKEY; } else { plugin.getLogger().warning("The updater could not contact dev.bukkit.org for updating."); plugin.getLogger().warning("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); result = UpdateResult.FAIL_DBO; } e.printStackTrace(); return false; } } private class UpdateRunnable implements Runnable { public void run() { if (url != null) { // Obtain the results of the project's file feed if (read()) { if (versionCheck(versionTitle)) { if (versionLink != null && type != UpdateType.NO_DOWNLOAD) { String name = file.getName(); // If it's a zip file, it shouldn't be downloaded as the plugin's name if (versionLink.endsWith(".zip")) { String[] split = versionLink.split("/"); name = split[split.length - 1]; } saveFile(new File("plugins/" + updateFolder), name, versionLink); } else { result = UpdateResult.UPDATE_AVAILABLE; } } } } } } }
src/net/gravitydevelopment/updater/Updater.java
/* * Updater for Bukkit. * * This class provides the means to safely and easily update a plugin, or check to see if it is updated using dev.bukkit.org */ package net.gravitydevelopment.updater; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.Plugin; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; /** * Check dev.bukkit.org to find updates for a given plugin, and download the updates if needed. * <p/> * <b>VERY, VERY IMPORTANT</b>: Because there are no standards for adding auto-update toggles in your plugin's config, this system provides NO CHECK WITH YOUR CONFIG to make sure the user has allowed auto-updating. * <br> * It is a <b>BUKKIT POLICY</b> that you include a boolean value in your config that prevents the auto-updater from running <b>AT ALL</b>. * <br> * If you fail to include this option in your config, your plugin will be <b>REJECTED</b> when you attempt to submit it to dev.bukkit.org. * <p/> * An example of a good configuration option would be something similar to 'auto-update: true' - if this value is set to false you may NOT run the auto-updater. * <br> * If you are unsure about these rules, please read the plugin submission guidelines: http://goo.gl/8iU5l * * @author Gravity */ public class Updater { private Plugin plugin; private UpdateType type; private String versionTitle; private String versionLink; private long totalSize; // Holds the total size of the file private int sizeLine; // Used for detecting file size private int multiplier; // Used for determining when to broadcast download updates private boolean announce; // Whether to announce file downloads private URL url; // Connecting to RSS private File file; // The plugin's file private Thread thread; // Updater thread private int id = -1; // Project's Curse ID private String apiKey = null; // BukkitDev ServerMods API key private static final String TITLE_VALUE = "name"; // Gets remote file's title private static final String LINK_VALUE = "downloadUrl"; // Gets remote file's download link private static final String QUERY = "/servermods/files?projectIds="; // Path to GET private static final String HOST = "https://api.curseforge.com"; // Slugs will be appended to this to get to the project's RSS feed private String[] noUpdateTag = {"-DEV", "-PRE", "-SNAPSHOT"}; // If the version number contains one of these, don't update. private static final int BYTE_SIZE = 1024; // Used for downloading files private YamlConfiguration config; // Config file private String updateFolder = YamlConfiguration.loadConfiguration(new File("bukkit.yml")).getString("settings.update-folder"); // The folder that downloads will be placed in private Updater.UpdateResult result = Updater.UpdateResult.SUCCESS; // Used for determining the outcome of the update process /** * Gives the dev the result of the update process. Can be obtained by called getResult(). */ public enum UpdateResult { /** * The updater found an update, and has readied it to be loaded the next time the server restarts/reloads. */ SUCCESS, /** * The updater did not find an update, and nothing was downloaded. */ NO_UPDATE, /** * The server administrator has disabled the updating system */ DISABLED, /** * The updater found an update, but was unable to download it. */ FAIL_DOWNLOAD, /** * For some reason, the updater was unable to contact dev.bukkit.org to download the file. */ FAIL_DBO, /** * When running the version check, the file on DBO did not contain the a version in the format 'vVersion' such as 'v1.0'. */ FAIL_NOVERSION, /** * The id provided by the plugin running the updater was invalid and doesn't exist on DBO. */ FAIL_BADID, /** * The server administrator has not, or has improperly configured their API key in the configuration */ FAIL_APIKEY, /** * The updater found an update, but because of the UpdateType being set to NO_DOWNLOAD, it wasn't downloaded. */ UPDATE_AVAILABLE } /** * Allows the dev to specify the type of update that will be run. */ public enum UpdateType { /** * Run a version check, and then if the file is out of date, download the newest version. */ DEFAULT, /** * Don't run a version check, just find the latest update and download it. */ NO_VERSION_CHECK, /** * Get information about the version and the download size, but don't actually download anything. */ NO_DOWNLOAD } /** * Initialize the updater * * @param plugin The plugin that is checking for an update. * @param id The dev.bukkit.org id of the project * @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class. * @param type Specify the type of update this will be. See {@link UpdateType} * @param announce True if the program should announce the progress of new updates in console */ public Updater(Plugin plugin, int id, File file, UpdateType type, boolean announce) { this.plugin = plugin; this.type = type; this.announce = announce; this.file = file; this.id = id; File pluginFile = plugin.getDataFolder().getParentFile(); File updaterFile = new File(pluginFile, "Updater"); File updaterConfigFile = new File(updaterFile, "config.yml"); if(!updaterFile.exists()) { updaterFile.mkdir(); } if(!updaterConfigFile.exists()) { try { updaterConfigFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } config = YamlConfiguration.loadConfiguration(updaterConfigFile); config.addDefault("api-key", "PUT_API_KEY_HERE"); config.addDefault("disable", false); if(config.get("api-key", null) == null) { config.options().copyDefaults(true); try { config.save(updaterConfigFile); } catch (IOException e) { e.printStackTrace(); } } if(config.getBoolean("disable")) { result = UpdateResult.DISABLED; return; } String key = config.getString("api-key"); if(key.equalsIgnoreCase("PUT_API_KEY_HERE") || key.equals("")) { key = null; } apiKey = key; try { url = new URL(HOST + QUERY + id); } catch (MalformedURLException e) { e.printStackTrace(); } thread = new Thread(new UpdateRunnable()); thread.start(); } /** * Get the result of the update process. */ public Updater.UpdateResult getResult() { waitForThread(); return result; } /** * Get the total bytes of the file (can only be used after running a version check or a normal run). */ public long getFileSize() { waitForThread(); return totalSize; } /** * Get the version string latest file avaliable online. */ public String getLatestVersionString() { waitForThread(); return versionTitle; } /** * As the result of Updater output depends on the thread's completion, it is necessary to wait for the thread to finish * before alloowing anyone to check the result. */ public void waitForThread() { if (thread != null && thread.isAlive()) { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * Save an update from dev.bukkit.org into the server's update folder. */ private void saveFile(File folder, String file, String u) { if (!folder.exists()) { folder.mkdir(); } BufferedInputStream in = null; FileOutputStream fout = null; try { // Download the file URL url = new URL(u); int fileLength = url.openConnection().getContentLength(); in = new BufferedInputStream(url.openStream()); fout = new FileOutputStream(folder.getAbsolutePath() + "/" + file); byte[] data = new byte[BYTE_SIZE]; int count; if (announce) plugin.getLogger().info("About to download a new update: " + versionTitle); long downloaded = 0; while ((count = in.read(data, 0, BYTE_SIZE)) != -1) { downloaded += count; fout.write(data, 0, count); int percent = (int) (downloaded * 100 / fileLength); if (announce & (percent % 10 == 0)) { plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes."); } } //Just a quick check to make sure we didn't leave any files from last time... for (File xFile : new File("plugins/" + updateFolder).listFiles()) { if (xFile.getName().endsWith(".zip")) { xFile.delete(); } } // Check to see if it's a zip file, if it is, unzip it. File dFile = new File(folder.getAbsolutePath() + "/" + file); if (dFile.getName().endsWith(".zip")) { // Unzip unzip(dFile.getCanonicalPath()); } if (announce) plugin.getLogger().info("Finished updating."); } catch (Exception ex) { plugin.getLogger().warning("The auto-updater tried to download a new update, but was unsuccessful."); result = Updater.UpdateResult.FAIL_DOWNLOAD; } finally { try { if (in != null) { in.close(); } if (fout != null) { fout.close(); } } catch (Exception ex) { } } } /** * Part of Zip-File-Extractor, modified by H31IX for use with Bukkit */ private void unzip(String file) { try { File fSourceZip = new File(file); String zipPath = file.substring(0, file.length() - 4); ZipFile zipFile = new ZipFile(fSourceZip); Enumeration<? extends ZipEntry> e = zipFile.entries(); while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); File destinationFilePath = new File(zipPath, entry.getName()); destinationFilePath.getParentFile().mkdirs(); if (entry.isDirectory()) { continue; } else { BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); int b; byte buffer[] = new byte[BYTE_SIZE]; FileOutputStream fos = new FileOutputStream(destinationFilePath); BufferedOutputStream bos = new BufferedOutputStream(fos, BYTE_SIZE); while ((b = bis.read(buffer, 0, BYTE_SIZE)) != -1) { bos.write(buffer, 0, b); } bos.flush(); bos.close(); bis.close(); String name = destinationFilePath.getName(); if (name.endsWith(".jar") && pluginFile(name)) { destinationFilePath.renameTo(new File("plugins/" + updateFolder + "/" + name)); } } entry = null; destinationFilePath = null; } e = null; zipFile.close(); zipFile = null; // Move any plugin data folders that were included to the right place, Bukkit won't do this for us. for (File dFile : new File(zipPath).listFiles()) { if (dFile.isDirectory()) { if (pluginFile(dFile.getName())) { File oFile = new File("plugins/" + dFile.getName()); // Get current dir File[] contents = oFile.listFiles(); // List of existing files in the current dir for (File cFile : dFile.listFiles()) // Loop through all the files in the new dir { boolean found = false; for (File xFile : contents) // Loop through contents to see if it exists { if (xFile.getName().equals(cFile.getName())) { found = true; break; } } if (!found) { // Move the new file into the current dir cFile.renameTo(new File(oFile.getCanonicalFile() + "/" + cFile.getName())); } else { // This file already exists, so we don't need it anymore. cFile.delete(); } } } } dFile.delete(); } new File(zipPath).delete(); fSourceZip.delete(); } catch (IOException ex) { ex.printStackTrace(); plugin.getLogger().warning("The auto-updater tried to unzip a new update file, but was unsuccessful."); result = Updater.UpdateResult.FAIL_DOWNLOAD; } new File(file).delete(); } /** * Check if the name of a jar is one of the plugins currently installed, used for extracting the correct files out of a zip. */ public boolean pluginFile(String name) { for (File file : new File("plugins").listFiles()) { if (file.getName().equals(name)) { return true; } } return false; } /** * Obtain the direct download file url from the file's page. */ private String getFile(String link) { String download = null; try { // Open a connection to the page URL url = new URL(link); URLConnection urlConn = url.openConnection(); InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream()); BufferedReader buff = new BufferedReader(inStream); int counter = 0; String line; while ((line = buff.readLine()) != null) { counter++; // Search for the download link if (line.contains("<li class=\"user-action user-action-download\">")) { // Get the raw link download = line.split("<a href=\"")[1].split("\">Download</a>")[0]; } // Search for size else if (line.contains("<dt>Size</dt>")) { sizeLine = counter + 1; } else if (counter == sizeLine) { String size = line.replaceAll("<dd>", "").replaceAll("</dd>", ""); multiplier = size.contains("MiB") ? 1048576 : 1024; size = size.replace(" KiB", "").replace(" MiB", ""); totalSize = (long) (Double.parseDouble(size) * multiplier); } } urlConn = null; inStream = null; buff.close(); buff = null; } catch (Exception ex) { ex.printStackTrace(); plugin.getLogger().warning("The auto-updater tried to contact dev.bukkit.org, but was unsuccessful."); result = Updater.UpdateResult.FAIL_DBO; return null; } return download; } /** * Check to see if the program should continue by evaluation whether the plugin is already updated, or shouldn't be updated */ private boolean versionCheck(String title) { if (type != UpdateType.NO_VERSION_CHECK) { String version = plugin.getDescription().getVersion(); if (title.split(" v").length == 2) { String remoteVersion = title.split(" v")[1].split(" ")[0]; // Get the newest file's version number int remVer = -1, curVer = 0; try { remVer = calVer(remoteVersion); curVer = calVer(version); } catch (NumberFormatException nfe) { remVer = -1; } if (hasTag(version) || version.equalsIgnoreCase(remoteVersion) || curVer >= remVer) { // We already have the latest version, or this build is tagged for no-update result = Updater.UpdateResult.NO_UPDATE; return false; } } else { // The file's name did not contain the string 'vVersion' plugin.getLogger().warning("The author of this plugin (" + plugin.getDescription().getAuthors().get(0) + ") has misconfigured their Auto Update system"); plugin.getLogger().warning("Files uploaded to BukkitDev should contain the version number, seperated from the name by a 'v', such as PluginName v1.0"); plugin.getLogger().warning("Please notify the author of this error."); result = Updater.UpdateResult.FAIL_NOVERSION; return false; } } return true; } /** * Used to calculate the version string as an Integer */ private Integer calVer(String s) throws NumberFormatException { if (s.contains(".")) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { Character c = s.charAt(i); if (Character.isLetterOrDigit(c)) { sb.append(c); } } return Integer.parseInt(sb.toString()); } return Integer.parseInt(s); } /** * Evaluate whether the version number is marked showing that it should not be updated by this program */ private boolean hasTag(String version) { for (String string : noUpdateTag) { if (version.contains(string)) { return true; } } return false; } public void read() { try { URLConnection conn = url.openConnection(); if(apiKey != null) { conn.addRequestProperty("X-API-Key", apiKey); } conn.addRequestProperty("User-Agent", "Updater (by Gravity)"); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = reader.readLine(); JSONArray array = (JSONArray) JSONValue.parse(response); versionTitle = (String) ((JSONObject) array.get(array.size() - 1)).get(TITLE_VALUE); versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(LINK_VALUE); } catch (IOException e) { plugin.getLogger().warning("dev.bukkit.org cannot be reached for update polling with the API key configured in plugins/Updater/config.yml"); plugin.getLogger().warning("If this is the first time you are seeing this error and have not recently changed your configuration, dev.bukkit.org may be temporarily unreachable."); result = UpdateResult.FAIL_APIKEY; e.printStackTrace(); } } private class UpdateRunnable implements Runnable { public void run() { if (url != null) { // Obtain the results of the project's file feed read(); if (versionCheck(versionTitle)) { String fileLink = getFile(versionLink); if (fileLink != null && type != UpdateType.NO_DOWNLOAD) { String name = file.getName(); // If it's a zip file, it shouldn't be downloaded as the plugin's name if (fileLink.endsWith(".zip")) { String[] split = fileLink.split("/"); name = split[split.length - 1]; } saveFile(new File("plugins/" + updateFolder), name, fileLink); } else { result = UpdateResult.UPDATE_AVAILABLE; } } } } } }
Better error handling and removal of old code
src/net/gravitydevelopment/updater/Updater.java
Better error handling and removal of old code
<ide><path>rc/net/gravitydevelopment/updater/Updater.java <ide> */ <ide> FAIL_BADID, <ide> /** <del> * The server administrator has not, or has improperly configured their API key in the configuration <add> * The server administrator has improperly configured their API key in the configuration <ide> */ <ide> FAIL_APIKEY, <ide> /** <ide> File updaterFile = new File(pluginFile, "Updater"); <ide> File updaterConfigFile = new File(updaterFile, "config.yml"); <ide> <del> if(!updaterFile.exists()) { <add> if (!updaterFile.exists()) { <ide> updaterFile.mkdir(); <ide> } <del> if(!updaterConfigFile.exists()) { <add> if (!updaterConfigFile.exists()) { <ide> try { <ide> updaterConfigFile.createNewFile(); <ide> } catch (IOException e) { <add> plugin.getLogger().severe("The updater could not create a configuration in " + updaterFile.getAbsolutePath()); <ide> e.printStackTrace(); <ide> } <ide> } <ide> config.addDefault("api-key", "PUT_API_KEY_HERE"); <ide> config.addDefault("disable", false); <ide> <del> if(config.get("api-key", null) == null) { <add> if (config.get("api-key", null) == null) { <ide> config.options().copyDefaults(true); <ide> try { <ide> config.save(updaterConfigFile); <ide> } catch (IOException e) { <add> plugin.getLogger().severe("The updater could not save the configuration in " + updaterFile.getAbsolutePath()); <ide> e.printStackTrace(); <ide> } <ide> } <ide> <del> if(config.getBoolean("disable")) { <add> if (config.getBoolean("disable")) { <ide> result = UpdateResult.DISABLED; <ide> return; <ide> } <ide> <ide> String key = config.getString("api-key"); <del> if(key.equalsIgnoreCase("PUT_API_KEY_HERE") || key.equals("")) { <add> if (key.equalsIgnoreCase("PUT_API_KEY_HERE") || key.equals("")) { <ide> key = null; <ide> } <ide> <ide> try { <ide> url = new URL(HOST + QUERY + id); <ide> } catch (MalformedURLException e) { <add> plugin.getLogger().severe("The project ID provided for updating, " + id + " is invalid."); <add> result = UpdateResult.FAIL_BADID; <ide> e.printStackTrace(); <ide> } <ide> <ide> <ide> /** <ide> * As the result of Updater output depends on the thread's completion, it is necessary to wait for the thread to finish <del> * before alloowing anyone to check the result. <add> * before allowing anyone to check the result. <ide> */ <ide> public void waitForThread() { <ide> if (thread != null && thread.isAlive()) { <ide> new File(zipPath).delete(); <ide> fSourceZip.delete(); <ide> } catch (IOException ex) { <del> ex.printStackTrace(); <ide> plugin.getLogger().warning("The auto-updater tried to unzip a new update file, but was unsuccessful."); <ide> result = Updater.UpdateResult.FAIL_DOWNLOAD; <add> ex.printStackTrace(); <ide> } <ide> new File(file).delete(); <ide> } <ide> } <ide> } <ide> return false; <del> } <del> <del> /** <del> * Obtain the direct download file url from the file's page. <del> */ <del> private String getFile(String link) { <del> String download = null; <del> try { <del> // Open a connection to the page <del> URL url = new URL(link); <del> URLConnection urlConn = url.openConnection(); <del> InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream()); <del> BufferedReader buff = new BufferedReader(inStream); <del> <del> int counter = 0; <del> String line; <del> while ((line = buff.readLine()) != null) { <del> counter++; <del> // Search for the download link <del> if (line.contains("<li class=\"user-action user-action-download\">")) { <del> // Get the raw link <del> download = line.split("<a href=\"")[1].split("\">Download</a>")[0]; <del> } <del> // Search for size <del> else if (line.contains("<dt>Size</dt>")) { <del> sizeLine = counter + 1; <del> } else if (counter == sizeLine) { <del> String size = line.replaceAll("<dd>", "").replaceAll("</dd>", ""); <del> multiplier = size.contains("MiB") ? 1048576 : 1024; <del> size = size.replace(" KiB", "").replace(" MiB", ""); <del> totalSize = (long) (Double.parseDouble(size) * multiplier); <del> } <del> } <del> urlConn = null; <del> inStream = null; <del> buff.close(); <del> buff = null; <del> } catch (Exception ex) { <del> ex.printStackTrace(); <del> plugin.getLogger().warning("The auto-updater tried to contact dev.bukkit.org, but was unsuccessful."); <del> result = Updater.UpdateResult.FAIL_DBO; <del> return null; <del> } <del> return download; <ide> } <ide> <ide> /** <ide> return false; <ide> } <ide> <del> public void read() { <add> public boolean read() { <ide> try { <ide> URLConnection conn = url.openConnection(); <del> if(apiKey != null) { <add> conn.setConnectTimeout(5000); <add> <add> if (apiKey != null) { <ide> conn.addRequestProperty("X-API-Key", apiKey); <ide> } <ide> conn.addRequestProperty("User-Agent", "Updater (by Gravity)"); <ide> String response = reader.readLine(); <ide> <ide> JSONArray array = (JSONArray) JSONValue.parse(response); <add> <add> if (array.size() == 0) { <add> plugin.getLogger().warning("The updater could not find any files for the project id " + id); <add> result = UpdateResult.FAIL_BADID; <add> return false; <add> } <add> <ide> versionTitle = (String) ((JSONObject) array.get(array.size() - 1)).get(TITLE_VALUE); <ide> versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(LINK_VALUE); <add> <add> return true; <ide> } catch (IOException e) { <del> plugin.getLogger().warning("dev.bukkit.org cannot be reached for update polling with the API key configured in plugins/Updater/config.yml"); <del> plugin.getLogger().warning("If this is the first time you are seeing this error and have not recently changed your configuration, dev.bukkit.org may be temporarily unreachable."); <del> result = UpdateResult.FAIL_APIKEY; <add> if (e.getMessage().contains("HTTP response code: 403")) { <add> plugin.getLogger().warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); <add> plugin.getLogger().warning("Please double-check your configuration to ensure it is correct."); <add> result = UpdateResult.FAIL_APIKEY; <add> } else { <add> plugin.getLogger().warning("The updater could not contact dev.bukkit.org for updating."); <add> plugin.getLogger().warning("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); <add> result = UpdateResult.FAIL_DBO; <add> } <ide> e.printStackTrace(); <add> return false; <ide> } <ide> } <ide> <ide> public void run() { <ide> if (url != null) { <ide> // Obtain the results of the project's file feed <del> read(); <del> if (versionCheck(versionTitle)) { <del> String fileLink = getFile(versionLink); <del> if (fileLink != null && type != UpdateType.NO_DOWNLOAD) { <del> String name = file.getName(); <del> // If it's a zip file, it shouldn't be downloaded as the plugin's name <del> if (fileLink.endsWith(".zip")) { <del> String[] split = fileLink.split("/"); <del> name = split[split.length - 1]; <add> if (read()) { <add> if (versionCheck(versionTitle)) { <add> if (versionLink != null && type != UpdateType.NO_DOWNLOAD) { <add> String name = file.getName(); <add> // If it's a zip file, it shouldn't be downloaded as the plugin's name <add> if (versionLink.endsWith(".zip")) { <add> String[] split = versionLink.split("/"); <add> name = split[split.length - 1]; <add> } <add> saveFile(new File("plugins/" + updateFolder), name, versionLink); <add> } else { <add> result = UpdateResult.UPDATE_AVAILABLE; <ide> } <del> saveFile(new File("plugins/" + updateFolder), name, fileLink); <del> } else { <del> result = UpdateResult.UPDATE_AVAILABLE; <ide> } <ide> } <ide> }
JavaScript
mit
51b3ecd1293c6d29bdc2412ebfe3cb44f241d974
0
NRGI/rp-org-frontend,NRGI/rp-org-frontend
var Source = require('mongoose').model('Source'), Country = require('mongoose').model('Country'), Commodity = require('mongoose').model('Commodity'), CompanyGroup = require('mongoose').model('CompanyGroup'), Company = require('mongoose').model('Company'), Project = require('mongoose').model('Project'), Site = require('mongoose').model('Site'), Link = require('mongoose').model('Link'), Contract = require('mongoose').model('Contract'), Concession = require('mongoose').model('Concession'), Production = require('mongoose').model('Production'), Transfer = require('mongoose').model('Transfer'), ObjectId = require('mongoose').Types.ObjectId, util = require('util'), async = require('async'), csv = require('csv'), request = require('request'), moment = require('moment'); exports.processData = function(link, callback) { var report = ""; var keytoend = link.substr(link.indexOf("/d/") + 3, link.length); var key = keytoend.substr(0, keytoend.indexOf("/")); report += `Using link ${link}\n`; if (key.length != 44) { report += "Could not detect a valid spreadsheet key in URL\n"; callback("Failed", report); return; } else { report += `Using GS key ${key}\n`; } var feedurl = `https://spreadsheets.google.com/feeds/worksheets/${key}/public/full?alt=json`; var sheets = new Object; request({ url: feedurl, json: true }, function (error, response, body) { if (!error && response.statusCode === 200) { var numSheets = body.feed.entry.length; var mainTitle = body.feed.title.$t; var numProcessed = 0; for (var i=0; i<body.feed.entry.length; i++) { for (var j=0; j<body.feed.entry[i].link.length; j++) { if (body.feed.entry[i].link[j].type == "text/csv") { report += `Getting data from sheet "${body.feed.entry[i].title.$t}"...\n`; request({ url: body.feed.entry[i].link[j].href }, (function (i, error, response, sbody) { if (error) { report += `${body.feed.entry[i].title.$t}: Could not retrieve sheet\n`; callback("Failed", report); return; } csv.parse(sbody, {trim: true}, function(err, rowdata){ if (error) { report += `${skey}: Could not parse sheet\n`; callback("Failed", report); return; } var item = new Object; var cd = response.headers['content-disposition']; item.title = body.feed.entry[i].title.$t; item.link = response.request.uri.href; item.data = rowdata; report += `${item.title}: Stored ${rowdata.length} rows\n`; sheets[item.title] = item; numProcessed++; if (numProcessed == numSheets) { parseData(sheets, report, callback); } }); }).bind(null, i)); } } } } else { report += "Could not get information from GSheets feed - is the sheet shared?\n" callback("Failed", report); return; } }); } function parseGsDate(input) { /* In general format should appear as DD/MM/YYYY or empty but sometimes GS has it as a date internally */ var result; if (!input || input == "") return null; else result = moment(input, "DD/MM/YYYY").format(); //Hope for the best if (result == "Invalid date") return input; else return result; } //Data needed for inter-entity reference var sources, countries, commodities, companies, projects; var makeNewSource = function(flagDuplicate, newRow, duplicateId) { newRow[7] = parseGsDate(newRow[7]); newRow[8] = parseGsDate(newRow[8]); var source = { source_name: newRow[0], source_type: newRow[2], //TODO: unnecessary? /* TODO? source_type_id: String, */ source_url: newRow[4], source_url_type: newRow[5], //TODO: unnecessary? /* TODO? source_url_type_id: String, */ source_archive_url: newRow[6], source_notes: newRow[9], source_date: newRow[7], retrieve_date: newRow[8] /* TODO create_author:, */ } if (flagDuplicate) { source.possible_duplicate = true; source.duplicate = duplicateId } return source; } var makeNewCommodity = function(newRow) { var commodity = { commodity_name: newRow[9], commodity_type: newRow[8].toLowerCase().replace(/ /g, "_") } return commodity; } var makeNewCompanyGroup = function(newRow) { var returnObj = {obj: null, link: null}; var companyg = { company_group_name: newRow[7] }; if (newRow[0] != "") { if (sources[newRow[0]]) { //Must be here due to lookups in sheet companyg.company_group_record_established = sources[newRow[0]]._id; } else return false; //error } returnObj.obj = companyg; //console.log("new company group: " + util.inspect(returnObj)); return returnObj; } var makeNewCompany = function(newRow) { var returnObj = {obj: null, link: null}; var company = { company_name: newRow[3] }; if (newRow[5] != "") { company.open_corporates_id = newRow[5]; } if (newRow[2] != "") { //TODO: This is not very helpful for the end user if (!countries[newRow[2]]) { console.log("SERIOUS ERROR: Missing country in the DB"); return false; } company.country_of_incorporation = [{country: countries[newRow[2]]._id}]; //Fact } if (newRow[6] != "") { company.company_website = {string: newRow[6]}; //Fact, will have comp. id added later } if (newRow[0] != "") { if (sources[newRow[0]]) { //Must be here due to lookups in sheet company.company_established_source = sources[newRow[0]]._id; } else return false; //error } if (newRow[7] != "") { //TODO: Also should check aliases in each object returnObj.link = {company_group: company_groups[newRow[8]]._id}; } returnObj.obj = company; return returnObj; } var makeNewProject = function(newRow) { var project = { proj_name: newRow[1], }; return project; } var updateProjectFacts = function(doc, row, report) { var fact; //Update status and commodity if (row[9] != "") { var notfound = true; if (doc.proj_commodity) { for (fact of doc.proj_commodity) { //No need to check if commodity exists as commodities are taken from here //TODO: In general, do we want to store multiple sources for the same truth? [from GS] if (commodities[row[9]]._id == fact.commodity._id) { notfound = false; report.add(`Project commodity ${row[9]} already exists in project, not adding\n`); break; } } } else doc.proj_commodity = []; if (notfound) { //Commodity must be here, as based on this sheet //Don't push but add, existing values will not be removed doc.proj_commodity = [{commodity: commodities[row[9]]._id, source: sources[row[0]]._id}]; report.add(`Project commodity ${row[9]} added to project\n`); } } else if (doc.proj_commodity) delete doc.proj_commodity; //Don't push if (row[10] != "") { var notfound = true; if (doc.proj_status) { for (fact of doc.proj_status) { if (row[10] == fact.string) { notfound = false; report.add(`Project status ${row[10]} already exists in project, not adding\n`); break; } } } else doc.proj_status = []; if (notfound) { //Don't push but add, existing values will not be removed doc.proj_status = [{string: row[10].toLowerCase(), date: parseGsDate(row[11]), source: sources[row[0]]._id}]; report.add(`Project status ${row[10]} added to project\n`); } } else if (doc.proj_status) delete doc.proj_status; //Don't push //TODO... projects with mulitple countries, really? if (row[5] != "") { var notfound = true; if (doc.proj_country) { //TODO: project without a country??? for (fact of doc.proj_country) { if (countries[row[5]]._id == fact.country._id) { notfound = false; report.add(`Project country ${row[5]} already exists in project, not adding\n`); break; } } } else doc.proj_country = []; if (notfound) { //Don't push but add, existing values will not be removed doc.proj_country = [{country: countries[row[5]]._id, source: sources[row[0]]._id}]; report.add(`Project country ${row[5]} added to project\n`); } } else if (doc.proj_country) delete doc.proj_country; //Don't push return doc; } var makeNewSite = function(newRow) { var site = { site_name: newRow[2], site_established_source: sources[newRow[0]]._id, site_country: [{country: countries[newRow[5]]._id, source: sources[newRow[0]]._id}] //TODO: How in the world can there multiple versions of country } if (newRow[3] != "") site.site_address = [{string: newRow[3], source: sources[newRow[0]]._id}]; //TODO FIELD INFO field: Boolean // if (newRow[6] != "") site.site_coordinates = [{loc: [parseFloat(newRow[6]), parseFloat(newRow[7])], source: sources[newRow[0]]._id}]; return site; } var makeNewProduction = function(newRow) { var production = { production_commodity: commodities[newRow[8]]._id, production_year: parseInt(newRow[5]), //production_project: projects[newRow[3]]._id, source: sources[newRow[0]]._id } if (newRow[7] != "") { production.production_unit = newRow[7]; } if (newRow[6] != "") { production.production_volume = newRow[6].replace(/,/g, ""); } if (newRow[9] != "") { production.production_price = newRow[9].replace(/,/g, ""); } if (newRow[10] != "") { production.production_price_per_unit = newRow[10]; } return production; } var makeNewTransfer = function(newRow, transfer_audit_type) { //TODO: This is not very helpful for the end user if (!countries[newRow[2]]) { console.log("SERIOUS ERROR: Missing country in the DB"); return false; } var transfer = { source: sources[newRow[0]]._id, transfer_country: countries[newRow[2]]._id, transfer_audit_type: transfer_audit_type }; if (newRow[3] != "") { transfer.transfer_company = companies[newRow[3]]._id; } if (newRow[4] != "") { transfer.transfer_line_item = newRow[4]; } if (newRow[5] != "") { transfer.transfer_level = "project"; //transfer.transfer_project = projects[newRow[5]]._id; } else { transfer.transfer_level = "country"; } if (transfer_audit_type == "government_receipt") { transfer.transfer_year = parseInt(newRow[13]); transfer.transfer_type = newRow[17]; transfer.transfer_unit = newRow[19]; transfer.transfer_value = newRow[21].replace(/,/g, ""); if (newRow[20] != "") transfer.transfer_accounting_basis = newRow[20]; if (newRow[15] != "") transfer.transfer_gov_entity = newRow[15]; if (newRow[16] != "") transfer.transfer_gov_entity_id = newRow[16]; } else if (transfer_audit_type == "company_payment") { transfer.transfer_audit_type = "company_payment"; transfer.transfer_year = parseInt(newRow[6]); transfer.transfer_type = newRow[5]; transfer.transfer_unit = newRow[7]; transfer.transfer_value = newRow[9].replace(/,/g, ""); if (newRow[8] != "") transfer.transfer_accounting_basis = newRow[8]; } else return false; return transfer; } //TODO: This needs some more work, specifically which properties to compare equalDocs = function(masterDoc, newDoc) { for (property in newDoc) { if (masterDoc[property]) { if (newDoc[property] != masterDoc[property]) { return false; } } else return false; } return true; } processGenericRow = function(report, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { if ((row[rowIndex] == "") || (row[rowIndex][0] == "#")) { report.add(entityName + ": Empty row or label.\n"); return callback(null); //Do nothing } var finderObj = {}; finderObj[modelKey] = row[rowIndex]; model.findOne( finderObj, function(err, doc) { if (err) { report.add(`Encountered an error (${err}) while querying the DB. Aborting.\n`); return callback(`Failed: ${report.report}`); } else if (doc) { report.add(`${entityName} ${row[rowIndex]} already exists in the DB (name match), not adding\n`); destObj[row[rowIndex]] = doc; return callback(null); } else { model.create( makerFunction(row), function(err, createdModel) { if (err) { report.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); return callback(`Failed: ${report.report}`); } report.add(`Added ${entityName} ${row[rowIndex]} to the DB.\n`); destObj[row[rowIndex]] = createdModel; return callback(null); } ); } } ); } //This handles companies and company groups //Not the maker function returns an object with a sub-object processCompanyRow = function(companiesReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { if ((row[rowIndex] == "") || (row[rowIndex][0] == "#")) { companiesReport.add(entityName + ": Empty row or label.\n"); return callback(null); //Do nothing } //Check against name and aliases //TODO - may need some sort of sophisticated duplicate detection here var queryEntry1 = {}; queryEntry1[modelKey] = row[rowIndex]; var queryEntry2 = {}; queryEntry2[modelKey+'_aliases.alias'] = row[rowIndex]; //TODO!!! Cannot be searched this way (no pre-population) model.findOne( {$or: [ queryEntry1, queryEntry2 ]}, function(err, doc) { var testAndCreateLink = function(skipTest, link, company_id) { var createLink = function() { link.entities = ['company', 'company_group']; Link.create(link, function(err, nlmodel) { if (err) { companiesReport.add(`Encountered an error (${err}) adding link to DB. Aborting.\n`); return callback(`Failed: ${companiesReport.report}`); } else { companiesReport.add(`Created link\n`); return callback(null); } }); }; if (!skipTest) { link.company = company_id; Link.findOne( link, function (err, lmodel) { if (err) { companiesReport.add(`Encountered an error (${err}) while querying DB. Aborting.\n`); return callback(`Failed: ${companiesReport.report}`); } else if (lmodel) { companiesReport.add(`Link already exists in the DB, not adding\n`); return callback(null); } else { createLink(); } } ); } else createLink(); } if (err) { companiesReport.add(`Encountered an error (${err}) while querying the DB. Aborting.\n`); return callback(`Failed: ${companiesReport.report}`); } else if (doc) { destObj[row[rowIndex]] = doc; companiesReport.add(`${entityName} ${row[rowIndex]} already exists in the DB (name or alias match), not adding. Checking for link creation need.\n`); var testObj = makerFunction(row); if (testObj && testObj.link) { testAndCreateLink(false, testObj.link, doc._id); } else { companiesReport.add(`No link to make\n`); return callback(null); } } else { var newObj = makerFunction(row); if (!newObj) { companiesReport.add(`Invalid data in row: ${row}. Aborting.\n`); return callback(`Failed: ${companiesReport.report}`); } model.create( newObj.obj, function(err, cmodel) { if (err) { companiesReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); return callback(`Failed: ${companiesReport.report}`); } companiesReport.add(`Added ${entityName} ${row[rowIndex]} to the DB.\n`); destObj[row[rowIndex]] = cmodel; if (newObj.link) { testAndCreateLink(true, newObj.link, cmodel._id); } else return callback(null); } ); } } ); }; function parseData(sheets, report, finalcallback) { async.waterfall([ parseBasis, parseCompanyGroups, parseCompanies, parseProjects, parseConcessionsAndContracts, parseProduction, parseTransfers, parseReserves ], function (err, report) { if (err) { console.log("PARSE: Got an error\n"); return finalcallback("Failed", report) } finalcallback("Success", report); } ); ; function parseEntity(reportSoFar, sheetname, dropRowsStart, dropRowsEnd, entityObj, processRow, entityName, rowIndex, model, modelKey, rowMaker, callback) { var intReport = { report: reportSoFar, //Relevant for the series waterfall - report gets passed along add: function(text) { this.report += text; } } //Drop first X, last Y rows var data = sheets[sheetname].data.slice(dropRowsStart, (sheets[sheetname].data.length - dropRowsEnd)); //TODO: for some cases parallel is OK: differentiate async.eachSeries(data, processRow.bind(null, intReport, entityObj, entityName, rowIndex, model, modelKey, rowMaker), function (err) { //"A callback which is called when all iteratee functions have finished, or an error occurs." if (err) { return callback(err, intReport.report); //Giving up } callback(null, intReport.report); //All good }); } function parseBasis(callback) { var basisReport = report + "Processing basis info\n"; async.parallel([ parseSources, parseCountries, parseCommodities ], (function (err, resultsarray) { console.log("PARSE BASIS: Finished parallel tasks OR got an error"); for (var r=0; r<resultsarray.length; r++) { if (!resultsarray[r]) { basisReport += "** NO RESULT **\n"; } else basisReport += resultsarray[r]; } if (err) { console.log("PARSE BASIS: Got an error"); basisReport += `Processing of basis info caused an error: ${err}\n`; return callback(`Processing of basis info caused an error: ${err}\n`, basisReport); } console.log("Finished parse basis"); callback(null, basisReport); })); function parseCountries(callback) { //Complete country list is in the DB var creport = "Getting countries from database...\n"; countries = new Object; Country.find({}, function (err, cresult) { if (err) { creport += `Got an error: ${err}`; callback(err, creport); } else { creport += `Found ${cresult.length} countries`; var ctry; for (ctry of cresult) { countries[ctry.iso2] = ctry; } callback(null, creport); } }); } function parseCommodities(callback) { //TODO: In some sheets only a group is named... commodities = new Object; //The list of commodities of relevance for this dataset is taken from the location/status/commodity list parseEntity("", '5. Project location, status, commodity', 3, 0, commodities, processGenericRow, "Commodity", 9, Commodity, "commodity_name", makeNewCommodity, callback); } function parseSources(callback) { var processSourceRow = function(sourcesReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { if ((row[0] == "") || (row[0] == "#source")) { sourcesReport.add("Sources: Empty row or label.\n"); return callback(null); //Do nothing } //TODO: Find OLDEST (use that for comparison instead of some other duplicate - important where we create duplicates) //TODO - may need some sort of sophisticated duplicate detection here Source.findOne( {source_url: row[4].toLowerCase()}, function(err, doc) { if (err) { sourcesReport.add(`Encountered an error while querying the DB: ${err}. Aborting.\n`); return callback(`Failed: ${sourcesReport.report}`); } else if (doc) { sourcesReport.add(`Source ${row[0]} already exists in the DB (url match), checking content\n`); if (equalDocs(doc, makeNewSource(false, row))) { sourcesReport.add(`Source ${row[0]} already exists in the DB (url match), not adding\n`); sources[row[0]] = doc; return callback(null); } else { sourcesReport.add(`Source ${row[0]} already exists in the DB (url match),flagging as duplicate\n`); Source.create( makeNewSource(true, row, doc._id), function(err, model) { if (err) { sourcesReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); return callback(`Failed: ${sourcesReport.report}`); } sources[row[0]] = model; return callback(null); } ); } } else { Source.findOne( {source_name: row[0]}, (function(err, doc) { if (err) { sourcesReport.add(`Encountered an error while querying the DB: ${err}. Aborting.\n`); return callback(`Failed: ${sourcesReport.report}`); } else if (doc) { sourcesReport.add(`Source ${row[0]} already exists in the DB (name match), will flag as possible duplicate\n`); Source.create( makeNewSource(true, row, doc._id), (function(err, model) { if (err) { sourcesReport.add(`Encountered an error while creating a source in the DB: ${err}. Aborting.\n`); return callback(`Failed: ${sourcesReport.report}`); } sources[row[0]] = model; return callback(null); }) ); } else { sourcesReport.add(`Source ${row[0]} not found in the DB, creating\n`); Source.create( makeNewSource(false, row), (function(err, model) { if (err) { sourcesReport.add(`Encountered an error while creating a source in the DB: ${err}. Aborting.\n`); return callback(`Failed: ${sourcesReport.report}`); } sources[row[0]] = model; return callback(null); }) ); } }) ); } } ); }; sources = new Object; //TODO - refactor processSourceRow to use generic row or similar? parseEntity("", '2. Source List', 3, 0, sources, processSourceRow, "Source", 0, Source, "source_name", makeNewSource, callback); } } function parseCompanyGroups(result, callback) { company_groups = new Object; parseEntity(result, '6. Companies and Groups', 3, 0, company_groups, processCompanyRow, "CompanyGroup", 7, CompanyGroup, "company_group_name", makeNewCompanyGroup, callback); } function parseCompanies(result, callback) { companies = new Object; parseEntity(result, '6. Companies and Groups', 3, 0, companies, processCompanyRow, "Company", 3, Company, "company_name", makeNewCompany, callback); } //TODO: make more generic, entity names etc. function createSiteProjectLink (siteId, projectId, report, lcallback) { Link.create({project: projectId, site: siteId, entities: ['project', 'site']}, function (err, nlmodel) { if (err) { report.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); return lcallback(`Failed: ${report.report}`); } else { report.add(`Linked site to project in the DB.\n`); return lcallback(null); //Final step, no return value } } ); } function parseProjects(result, callback) { var processProjectRow = function(projectsReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { if ((row[rowIndex] == "") || (row[1] == "#project")) { projectsReport.add("Projects: Empty row or label.\n"); return callback(null); //Do nothing } function updateOrCreateProject(projDoc, wcallback) { var doc_id = null; if (!projDoc) { projDoc = makeNewProject(row); } else { doc_id = projDoc._id; projDoc = projDoc.toObject(); delete projDoc._id; //Don't send id back in to Mongo delete projDoc.__v; //https://github.com/Automattic/mongoose/issues/1933 } final_doc = updateProjectFacts(projDoc, row, projectsReport); if (!final_doc) { projectsReport.add(`Invalid data in row: ${row}. Aborting.\n`); return wcallback(`Failed: ${projectsReport.report}`); } //console.log("Sent:\n" + util.inspect(final_doc)); if (!doc_id) doc_id = new ObjectId; Project.findByIdAndUpdate( doc_id, final_doc, {setDefaultsOnInsert: true, upsert: true, new: true}, function(err, model) { if (err) { //console.log(err); projectsReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); return wcallback(`Failed: ${projectsReport.report}`); } //console.log("Returned\n: " + model) projectsReport.add(`Added or updated project ${row[rowIndex]} to the DB.\n`); projects[row[rowIndex]] = model; return wcallback(null, model); //Continue to site stuff } ); } function createSiteAndLink(projDoc, wcallback) { if (row[2] != "") { Site.findOne( {$or: [ {site_name: row[2]}, {"site_aliases.alias": row[2]} //TODO: FIX POPULATE ETC.? ]}, function (err, sitemodel) { if (err) { projectsReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); return wcallback(`Failed: ${projectsReport.report}`); } else if (sitemodel) { //Site already exists - check for link, could be missing if site is from another project var found = false; Link.find({project: projDoc._id, site: sitemodel._id}, function (err, sitelinkmodel) { if (err) { projectsReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); return wcallback(`Failed: ${projectsReport.report}`); } else if (sitelinkmodel) { projectsReport.add(`Link to ${row[2]} already exists in the DB, not adding\n`); return wcallback(null); } else { createSiteProjectLink(sitemodel._id, projDoc._id, projectsReport, wcallback); } } ); } else { //Site doesn't exist - create and link Site.create( makeNewSite(row), function (err, newsitemodel) { if (err) { projectsReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); return wcallback(`Failed: ${projectsReport.report}`); } else { createSiteProjectLink(newsitemodel._id, projDoc._id, projectsReport, wcallback); } } ); } } ); } else { //Nothing more to do projectsReport.add(`No site info in row\n`); return wcallback(null); } } //Projects - check against name and aliases //TODO - may need some sort of sophisticated duplicate detection here Project.findOne( {$or: [ {proj_name: row[rowIndex]}, {"proj_aliases.alias": row[rowIndex]} //TODO: FIX POPULATE ETC.? ]}, function(err, doc) { //console.log(doc); if (err) { projectsReport.add(`Encountered an error (${err}) while querying the DB. Aborting.\n`); return callback(`Failed: ${projectsReport.report}`); } else if (doc) { //Project already exists, row might represent a new site projectsReport.add(`Project ${row[rowIndex]} already exists in the DB (name or alias match), not adding but updating facts and checking for new sites\n`); projects[row[rowIndex]] = doc; //Basis data is always the same, OK if this gets called multiple times async.waterfall( //Waterfall because we want to be able to cope with a result or error being returned [updateOrCreateProject.bind(null, doc), createSiteAndLink], //Gets proj. id passed as result function (err, result) { if (err) { return callback(`Failed: ${projectsReport.report}`); } else { //All done return callback(null); } } ); } else { projectsReport.add(`Project ${row[rowIndex]} not found, creating.\n`); async.waterfall( //Waterfall because we want to be able to cope with a result or error being returned [updateOrCreateProject.bind(null, null), //Proj = null = create it please createSiteAndLink], //Gets proj. id passed as result function (err, result) { if (err) { return callback(`Failed: ${projectsReport.report}`); } else { //All done return callback(null); } } ); } } ); }; projects = new Object; parseEntity(result, '5. Project location, status, commodity', 3, 0, projects, processProjectRow, "Project", 1, Project, "proj_name", makeNewProject, callback); } function parseConcessionsAndContracts(result, callback) { //First linked companies var processCandCRowCompanies = function(row, callback) { var compReport = ""; if (row[2] != "") { if (!companies[row[2]] || !projects[row[1]] || !sources[row[0]] ) { compReport += (`Invalid data in row: ${row}. Aborting.\n`); return callback(`Failed: ${compReport}`); } Link.findOne( { company: companies[row[2]]._id, project: projects[row[1]]._id }, function(err, doc) { if (err) { compReport += (`Encountered an error (${err}) while querying the DB. Aborting.\n`); return callback(`Failed: ${compReport}`); } else if (doc) { compReport += (`Company ${row[2]} is already linked with project ${row[1]}, not adding\n`); return callback(null, compReport); } else { var newCompanyLink = { company: companies[row[2]]._id, project: projects[row[1]]._id, source: sources[row[0]]._id, entities:['company','project'] }; Link.create( newCompanyLink, function(err, model) { if (err) { compReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); return callback(`Failed: ${compReport}`); } compReport += (`Linked company ${row[2]} with project ${row[1]} in the DB.\n`); return callback(null, compReport); } ); } } ); } else return callback(null, "No company found in row\n"); }; //Linked contracts - all based on ID (for API look up) var processCandCRowContracts = function(row, callback) { var contReport = ""; if (row[7] != "") { Contract.findOne({ contract_id: row[7] }, function(err, doc) { if (err) { contReport += (`Encountered an error (${err}) while querying the DB. Aborting.\n`); return callback(`Failed: ${contReport}`); } else if (doc) { //Found contract, now see if its linked contReport += (`Contract ${row[7]} exists, checking for link\n`); Link.findOne( { contract: doc._id, project: projects[row[1]]._id }, function(err, ldoc) { if (err) { contReport += (`Encountered an error (${err}) while querying the DB. Aborting.\n`); return callback(`Failed: ${contReport}`); } else if (ldoc) { contReport += (`Contract ${row[7]} is already linked with project ${row[1]}, not adding\n`); return callback(null, contReport); } else { var newContractLink = { contract: doc._id, project: projects[row[1]]._id, source: sources[row[0]]._id, entities:['contract','project'] }; Link.create( newContractLink, function(err, model) { if (err) { contReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); return callback(`Failed: ${contReport}`); } contReport += (`Linked contract ${row[7]} with project ${row[1]} in the DB.\n`); return callback(null, contReport); } ); } }); } else { //No contract, create and link var newContract = { contract_id: row[7] }; Contract.create( newContract, function(err, cmodel) { if (err) { contReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); return callback(`Failed: ${contReport}`); } contReport += (`Created contract ${row[7]}.\n`); //Now create Link var newContractLink = { contract: cmodel._id, project: projects[row[1]]._id, source: sources[row[0]]._id, entities:['contract','project'] }; Link.create( newContractLink, function(err, model) { if (err) { contReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); return callback(`Failed: ${contReport}`); } contReport += (`Linked contract ${row[7]} with project ${row[1]} in the DB.\n`); return callback(null, contReport); } ); } ); } } ); } else return callback(null, "No contract found in row\n"); }; //Then linked concessions var processCandCRowConcessions = function(row, callback) { var concReport = ""; if (row[8] != "") { Concession.findOne( {$or: [ {concession_name: row[8]}, {"concession_aliases.alias": row[8]} //TODO, alias population ] }, function(err, doc) { if (err) { concReport += (`Encountered an error (${err}) while querying the DB. Aborting.\n`); return callback(`Failed: ${concReport}`); } else if (doc) { //Found concession, now see if its linked concReport += (`Contract ${row[8]} exists, checking for link\n`); Link.findOne( { concession: doc._id, project: projects[row[1]]._id }, function(err, ldoc) { if (err) { concReport += (`Encountered an error (${err}) while querying the DB. Aborting.\n`); return callback(`Failed: ${concReport}`); } else if (ldoc) { concReport += (`Concession ${row[8]} is already linked with project ${row[1]}, not adding\n`); return callback(null, concReport); } else { var newConcessionLink = { concession: doc._id, project: projects[row[1]]._id, source: sources[row[0]]._id, entities:['concession','project'] }; Link.create( newConcessionLink, function(err, model) { if (err) { concReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); return callback(`Failed: ${concReport}`); } concReport += (`Linked concession ${row[8]} with project ${row[1]} in the DB.\n`); return callback(null, concReport); } ); } }); } else { //No concession, create and link var newConcession = { concession_name: row[8], concession_established_source: sources[row[0]]._id }; if (row[10] != "") { newConcession.concession_country = {country: countries[row[10]]._id, source: sources[row[0]]._id} } Concession.create( newConcession, function(err, cmodel) { if (err) { concReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); return callback(`Failed: ${concReport}`); } concReport += (`Created concession ${row[8]}.\n`); //Now create Link var newConcessionLink = { concession: cmodel._id, project: projects[row[1]]._id, source: sources[row[0]]._id, entities:['concession','project'] }; Link.create( newConcessionLink, function(err, model) { if (err) { concReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); return callback(`Failed: ${concReport}`); } concReport += (`Linked concession ${row[8]} with project ${row[1]} in the DB.\n`); return callback(null, concReport); } ); } ); } } ); } else return callback(null, "No concession found in row\n"); }; var processCandCRow = function(candcReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { if ((row[0] == "#source") || ((row[2] == "") && (row[7] == "") && (row[8] == ""))) { candcReport.add("Concessions and Contracts: Empty row or label.\n"); return callback(null); //Do nothing } if (!sources[row[0]] ) { candcReport.add(`Invalid source in row: ${row}. Aborting.\n`); return callback(`Failed: ${candcReport.report}`); } async.parallel([ processCandCRowCompanies.bind(null, row), processCandCRowContracts.bind(null, row), processCandCRowConcessions.bind(null, row) ], function (err, resultsarray) { for (var r=0; r<resultsarray.length; r++) { if (!resultsarray[r]) { candcReport.add("** NO RESULT **\n"); } else candcReport.add(resultsarray[r]); } if (err) { candcReport.add(`Processing of company/contract/concessions caused an error: ${err}\n`); return callback(`Processing of company/contract/concession caused an error: ${err}\n`, candcReport.report); } return callback(null); } ); } parseEntity(result, '7. Contracts, concessions and companies', 4, 0, null, processCandCRow, null, null, null, null, null, callback); } //TODO: This is definitely a candidate for bringing into genericrow with custom query function parseProduction(result, callback) { var processProductionRow = function(prodReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { //This serves 2 purposes, check for blank rows and skip rows with no value if ((row[6] == "") || (row[0] == "#source")) { prodReport.add("Productions: Empty row or label, or no volume data.\n"); return callback(null); //Do nothing } //TODO: Currently hard req. for project. Country and Company seem to be optional and unused. //thereby data can only be grabbed via project therefore req. project! if (/*(row[2] == "") || !countries[row[2]] || */(row[3] == "") || !sources[row[0]] || (row[8] == "") || !commodities[row[8]] || (row[5] == "") ) { prodReport += (`Invalid or missing data in row: ${row}. Aborting.\n`); return callback(`Failed: ${prodReport}`); } //Here we depend on links, use controller //Production - match (ideally) by (country???) + project (if present???) + year + commodity //BUT (TODO) there is currently no easy way of grabbing country & project Production.findOne( { production_commodity: commodities[row[8]]._id, production_year: parseInt(row[5]), }, function(err, doc) { if (err) { prodReport.add(`Encountered an error (${err}) while querying the DB. Aborting.\n`); return callback(`Failed: ${prodReport.report}`); } else if (doc) { prodReport.add(`Production ${row[3]}/${row[8]}/${row[5]} already exists in the DB, not adding\n`); return callback(null); } else { var newProduction = makeNewProduction(row); Production.create( newProduction, function(err, model) { if (err) { prodReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); return callback(`Failed: ${prodReport.report}`); } //TODO: Link Production<->Project, (Production<->Country ???) //As productions can only exist with a project (TODO: check), go ahead and create the link Link.create( {project: projects[row[3]]._id, production: model._id, entities: ['project', 'production']}, function name(err, lmodel) { if (err) { prodReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); return callback(`Failed: ${prodReport.report}`); } else { prodReport.add(`Added production ${row[3]}/${row[8]}/${row[5]} to the DB and linked to project.\n`); return callback(null); } } ); } ); } } ); }; parseEntity(result, '8. Production', 3, 0, null, processProductionRow, null, null, null, null, null, callback); } function parseTransfers(result, callback) { var processTransferRow = function(transReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { //This serves 2 purposes, check for blank row${util.inspect(query)s and skip rows with no value if (((row[21] == "") && (row[9] == "")) || (row[0] == "#source")) { transReport.add("Transfers: Empty row or label, or no volume data.\n"); return callback(null); //Do nothing } //This, in turn is a little harsh to abort of payment type is missing, but it does make for an invalid row if ((row[5] == "") || !projects[row[5]] || !sources[row[0]] || !countries[row[2]] || (row[17] == "") ) { transReport += (`Invalid or missing data in row: ${row}. Aborting.\n`); return callback(`Failed: ${transReport}`); } //Transfer - many possible ways to match //Determine if payment or receipt var transfer_audit_type = ""; if (row[21] != "") { transfer_audit_type = "government_receipt" transfer_type = "receipt"; } else if (row[9] != "") { transfer_audit_type = "company_payment"; transfer_type = "payment"; } else returnInvalid(); //TODO: How to match without projects in the transfers any more? var query = {transfer_country: countries[row[2]]._id, transfer_audit_type: transfer_audit_type}; if (row[5] != "") { //query.transfer_project = projects[row[5]]._id; query.transfer_level = "project"; } else query.transfer_level = "country"; if (row[3] != "") { query.transfer_company = companies[row[3]]._id; } if (transfer_type == "payment") { query.transfer_year = parseInt(row[6]); query.transfer_type = row[8]; } else { query.transfer_year = parseInt(row[13]); query.transfer_type = row[17]; if (row[15] != "") { query.transfer_gov_entity = row[15]; } if (row[16] != "") { query.transfer_gov_entity_id = row[16]; } } Transfer.findOne( query, function(err, doc) { if (err) { transReport.add(`Encountered an error (${err}) while querying the DB. Aborting.\n`); return callback(`Failed: ${transReport.report}`); } else if (doc) { transReport.add(`Transfer (${util.inspect(query)}) already exists in the DB, not adding\n`); return callback(null); } else { var newTransfer = makeNewTransfer(row, transfer_audit_type); if (!newTransfer) { transReport += (`Invalid or missing data in row: ${row}. Aborting.\n`); return callback(`Failed: ${transReport}`); } Transfer.create( newTransfer, function(err, model) { if (err) { transReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); return callback(`Failed: ${transReport.report}`); } //TODO: Link Transfer<->Project, (Transfer<->Company ???) //Can't find the transfer without a project (if there is one), so go ahead and create it without checks if (row[5] != "") { Link.create( {project: projects[row[5]]._id, transfer: model._id, entities: ['project', 'transfer']}, function name(err, lmodel) { if (err) { transReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); return callback(`Failed: ${transReport.report}`); } else { transReport.add(`Added transfer (${util.inspect(query)}) with project link to the DB.\n`); return callback(null); } } ); } else { transReport.add(`Added transfer (${util.inspect(query)}) to the DB without project link.\n`); return callback(null); } } ); } } ); }; parseEntity(result, '10. Payments and receipts', 3, 0, null, processTransferRow, null, null, null, null, null, callback); } function parseReserves(result, callback) { result += "Reserves IGNORED\n"; callback(null, result); } }
server/dataprocessing/googlesheets.js
//var Source = require('mongoose').model('Source'), // Country = require('mongoose').model('Country'), // Commodity = require('mongoose').model('Commodity'), // CompanyGroup = require('mongoose').model('CompanyGroup'), // Company = require('mongoose').model('Company'), // Project = require('mongoose').model('Project'), // Site = require('mongoose').model('Site'), // Link = require('mongoose').model('Link'), // Contract = require('mongoose').model('Contract'), // Concession = require('mongoose').model('Concession'), // Production = require('mongoose').model('Production'), // Transfer = require('mongoose').model('Transfer'), // ObjectId = require('mongoose').Types.ObjectId, // util = require('util'), // async = require('async'), // csv = require('csv'), // request = require('request'), // moment = require('moment'); // //exports.processData = function(link, callback) { // var report = ""; // var keytoend = link.substr(link.indexOf("/d/") + 3, link.length); // var key = keytoend.substr(0, keytoend.indexOf("/")); // report += `Using link ${link}\n`; // if (key.length != 44) { // report += "Could not detect a valid spreadsheet key in URL\n"; // callback("Failed", report); // return; // } // else { // report += `Using GS key ${key}\n`; // } // var feedurl = `https://spreadsheets.google.com/feeds/worksheets/${key}/public/full?alt=json`; // var sheets = new Object; // // request({ // url: feedurl, // json: true // }, function (error, response, body) { // if (!error && response.statusCode === 200) { // var numSheets = body.feed.entry.length; // var mainTitle = body.feed.title.$t; // var numProcessed = 0; // for (var i=0; i<body.feed.entry.length; i++) { // for (var j=0; j<body.feed.entry[i].link.length; j++) { // if (body.feed.entry[i].link[j].type == "text/csv") { // report += `Getting data from sheet "${body.feed.entry[i].title.$t}"...\n`; // request({ // url: body.feed.entry[i].link[j].href // }, (function (i, error, response, sbody) { // if (error) { // report += `${body.feed.entry[i].title.$t}: Could not retrieve sheet\n`; // callback("Failed", report); // return; // } // csv.parse(sbody, {trim: true}, function(err, rowdata){ // if (error) { // report += `${skey}: Could not parse sheet\n`; // callback("Failed", report); // return; // } // var item = new Object; // var cd = response.headers['content-disposition']; // // item.title = body.feed.entry[i].title.$t; // item.link = response.request.uri.href; // item.data = rowdata; // report += `${item.title}: Stored ${rowdata.length} rows\n`; // sheets[item.title] = item; // numProcessed++; // if (numProcessed == numSheets) { // parseData(sheets, report, callback); // } // }); // }).bind(null, i)); // } // } // } // } // else { // report += "Could not get information from GSheets feed - is the sheet shared?\n" // callback("Failed", report); // return; // } // }); //} // //function parseGsDate(input) { // /* In general format should appear as DD/MM/YYYY or empty but sometimes GS has it as a date internally */ // var result; // if (!input || input == "") return null; // else result = moment(input, "DD/MM/YYYY").format(); // //Hope for the best // if (result == "Invalid date") return input; // else return result; //} // ////Data needed for inter-entity reference //var sources, countries, commodities, companies, projects; // //var makeNewSource = function(flagDuplicate, newRow, duplicateId) { // newRow[7] = parseGsDate(newRow[7]); // newRow[8] = parseGsDate(newRow[8]); // // var source = { // source_name: newRow[0], // source_type: newRow[2], //TODO: unnecessary? // /* TODO? source_type_id: String, */ // source_url: newRow[4], // source_url_type: newRow[5], //TODO: unnecessary? // /* TODO? source_url_type_id: String, */ // source_archive_url: newRow[6], // source_notes: newRow[9], // source_date: newRow[7], // retrieve_date: newRow[8] // /* TODO create_author:, */ // } // if (flagDuplicate) { // source.possible_duplicate = true; // source.duplicate = duplicateId // } // return source; //} // //var makeNewCommodity = function(newRow) { // var commodity = { // commodity_name: newRow[9], // commodity_type: newRow[8].toLowerCase().replace(/ /g, "_") // } // return commodity; //} // //var makeNewCompanyGroup = function(newRow) { // var returnObj = {obj: null, link: null}; // var companyg = { // company_group_name: newRow[7] // }; // // if (newRow[0] != "") { // if (sources[newRow[0]]) { //Must be here due to lookups in sheet // companyg.company_group_record_established = sources[newRow[0]]._id; // } // else return false; //error // } // returnObj.obj = companyg; // //console.log("new company group: " + util.inspect(returnObj)); // return returnObj; //} // //var makeNewCompany = function(newRow) { // var returnObj = {obj: null, link: null}; // var company = { // company_name: newRow[3] // }; // // if (newRow[5] != "") { // company.open_corporates_id = newRow[5]; // } // if (newRow[2] != "") { // //TODO: This is not very helpful for the end user // if (!countries[newRow[2]]) { // console.log("SERIOUS ERROR: Missing country in the DB"); // return false; // } // company.country_of_incorporation = [{country: countries[newRow[2]]._id}]; //Fact // } // if (newRow[6] != "") { // company.company_website = {string: newRow[6]}; //Fact, will have comp. id added later // } // if (newRow[0] != "") { // if (sources[newRow[0]]) { //Must be here due to lookups in sheet // company.company_established_source = sources[newRow[0]]._id; // } // else return false; //error // } // // if (newRow[7] != "") { // //TODO: Also should check aliases in each object // returnObj.link = {company_group: company_groups[newRow[8]]._id}; // } // // returnObj.obj = company; // return returnObj; //} // //var makeNewProject = function(newRow) { // var project = { // proj_name: newRow[1], // }; // return project; //} // //var updateProjectFacts = function(doc, row, report) //{ // var fact; // //Update status and commodity // if (row[9] != "") { // var notfound = true; // if (doc.proj_commodity) { // for (fact of doc.proj_commodity) { // //No need to check if commodity exists as commodities are taken from here // //TODO: In general, do we want to store multiple sources for the same truth? [from GS] // if (commodities[row[9]]._id == fact.commodity._id) { // notfound = false; // report.add(`Project commodity ${row[9]} already exists in project, not adding\n`); // break; // } // } // } // else doc.proj_commodity = []; // if (notfound) { //Commodity must be here, as based on this sheet // //Don't push but add, existing values will not be removed // doc.proj_commodity = [{commodity: commodities[row[9]]._id, source: sources[row[0]]._id}]; // report.add(`Project commodity ${row[9]} added to project\n`); // } // } // else if (doc.proj_commodity) delete doc.proj_commodity; //Don't push // // if (row[10] != "") { // var notfound = true; // if (doc.proj_status) { // for (fact of doc.proj_status) { // if (row[10] == fact.string) { // notfound = false; // report.add(`Project status ${row[10]} already exists in project, not adding\n`); // break; // } // } // } // else doc.proj_status = []; // if (notfound) { // //Don't push but add, existing values will not be removed // doc.proj_status = [{string: row[10].toLowerCase(), date: parseGsDate(row[11]), source: sources[row[0]]._id}]; // report.add(`Project status ${row[10]} added to project\n`); // } // } // else if (doc.proj_status) delete doc.proj_status; //Don't push // // //TODO... projects with mulitple countries, really? // if (row[5] != "") { // var notfound = true; // if (doc.proj_country) { //TODO: project without a country??? // for (fact of doc.proj_country) { // if (countries[row[5]]._id == fact.country._id) { // notfound = false; // report.add(`Project country ${row[5]} already exists in project, not adding\n`); // break; // } // } // } // else doc.proj_country = []; // if (notfound) { // //Don't push but add, existing values will not be removed // doc.proj_country = [{country: countries[row[5]]._id, source: sources[row[0]]._id}]; // report.add(`Project country ${row[5]} added to project\n`); // } // } // else if (doc.proj_country) delete doc.proj_country; //Don't push // return doc; //} // //var makeNewSite = function(newRow) { // var site = { // site_name: newRow[2], // site_established_source: sources[newRow[0]]._id, // site_country: [{country: countries[newRow[5]]._id, source: sources[newRow[0]]._id}] //TODO: How in the world can there multiple versions of country // } // if (newRow[3] != "") site.site_address = [{string: newRow[3], source: sources[newRow[0]]._id}]; // //TODO FIELD INFO field: Boolean // // if (newRow[6] != "") site.site_coordinates = [{loc: [parseFloat(newRow[6]), parseFloat(newRow[7])], source: sources[newRow[0]]._id}]; // return site; //} // //var makeNewProduction = function(newRow) { // var production = { // production_commodity: commodities[newRow[8]]._id, // production_year: parseInt(newRow[5]), // //production_project: projects[newRow[3]]._id, // source: sources[newRow[0]]._id // } // // if (newRow[7] != "") { // production.production_unit = newRow[7]; // } // if (newRow[6] != "") { // production.production_volume = newRow[6].replace(/,/g, ""); // } // if (newRow[9] != "") { // production.production_price = newRow[9].replace(/,/g, ""); // } // if (newRow[10] != "") { // production.production_price_per_unit = newRow[10]; // } // // return production; //} // //var makeNewTransfer = function(newRow, transfer_audit_type) { // //TODO: This is not very helpful for the end user // if (!countries[newRow[2]]) { // console.log("SERIOUS ERROR: Missing country in the DB"); // return false; // } // // var transfer = { // source: sources[newRow[0]]._id, // transfer_country: countries[newRow[2]]._id, // transfer_audit_type: transfer_audit_type // }; // // if (newRow[3] != "") { // transfer.transfer_company = companies[newRow[3]]._id; // } // // if (newRow[4] != "") { // transfer.transfer_line_item = newRow[4]; // } // // if (newRow[5] != "") { // transfer.transfer_level = "project"; // //transfer.transfer_project = projects[newRow[5]]._id; // } // else { // transfer.transfer_level = "country"; // } // // if (transfer_audit_type == "government_receipt") { // transfer.transfer_year = parseInt(newRow[13]); // transfer.transfer_type = newRow[17]; // transfer.transfer_unit = newRow[19]; // transfer.transfer_value = newRow[21].replace(/,/g, ""); // if (newRow[20] != "") transfer.transfer_accounting_basis = newRow[20]; // if (newRow[15] != "") transfer.transfer_gov_entity = newRow[15]; // if (newRow[16] != "") transfer.transfer_gov_entity_id = newRow[16]; // } // else if (transfer_audit_type == "company_payment") { // transfer.transfer_audit_type = "company_payment"; // transfer.transfer_year = parseInt(newRow[6]); // transfer.transfer_type = newRow[5]; // transfer.transfer_unit = newRow[7]; // transfer.transfer_value = newRow[9].replace(/,/g, ""); // if (newRow[8] != "") transfer.transfer_accounting_basis = newRow[8]; // } // else return false; // // return transfer; //} // ////TODO: This needs some more work, specifically which properties to compare //equalDocs = function(masterDoc, newDoc) { // for (property in newDoc) { // if (masterDoc[property]) { // if (newDoc[property] != masterDoc[property]) { // return false; // } // } // else return false; // } // return true; //} // //processGenericRow = function(report, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { // if ((row[rowIndex] == "") || (row[rowIndex][0] == "#")) { // report.add(entityName + ": Empty row or label.\n"); // return callback(null); //Do nothing // } // var finderObj = {}; // finderObj[modelKey] = row[rowIndex]; // model.findOne( // finderObj, // function(err, doc) { // if (err) { // report.add(`Encountered an error (${err}) while querying the DB. Aborting.\n`); // return callback(`Failed: ${report.report}`); // } // else if (doc) { // report.add(`${entityName} ${row[rowIndex]} already exists in the DB (name match), not adding\n`); // destObj[row[rowIndex]] = doc; // return callback(null); // } // else { // model.create( // makerFunction(row), // function(err, createdModel) { // if (err) { // report.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); // return callback(`Failed: ${report.report}`); // } // report.add(`Added ${entityName} ${row[rowIndex]} to the DB.\n`); // destObj[row[rowIndex]] = createdModel; // return callback(null); // } // ); // } // } // ); //} // ////This handles companies and company groups ////Not the maker function returns an object with a sub-object //processCompanyRow = function(companiesReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { // if ((row[rowIndex] == "") || (row[rowIndex][0] == "#")) { // companiesReport.add(entityName + ": Empty row or label.\n"); // return callback(null); //Do nothing // } // //Check against name and aliases // //TODO - may need some sort of sophisticated duplicate detection here // var queryEntry1 = {}; // queryEntry1[modelKey] = row[rowIndex]; // var queryEntry2 = {}; // queryEntry2[modelKey+'_aliases.alias'] = row[rowIndex]; //TODO!!! Cannot be searched this way (no pre-population) // // model.findOne( // {$or: [ // queryEntry1, // queryEntry2 // ]}, // function(err, doc) { // var testAndCreateLink = function(skipTest, link, company_id) { // var createLink = function() { // link.entities = ['company', 'company_group']; // Link.create(link, function(err, nlmodel) { // if (err) { // companiesReport.add(`Encountered an error (${err}) adding link to DB. Aborting.\n`); // return callback(`Failed: ${companiesReport.report}`); // } // else { // companiesReport.add(`Created link\n`); // return callback(null); // } // }); // }; // if (!skipTest) { // link.company = company_id; // Link.findOne( // link, // function (err, lmodel) { // if (err) { // companiesReport.add(`Encountered an error (${err}) while querying DB. Aborting.\n`); // return callback(`Failed: ${companiesReport.report}`); // } // else if (lmodel) { // companiesReport.add(`Link already exists in the DB, not adding\n`); // return callback(null); // } // else { // createLink(); // } // } // ); // } // else createLink(); // } // if (err) { // companiesReport.add(`Encountered an error (${err}) while querying the DB. Aborting.\n`); // return callback(`Failed: ${companiesReport.report}`); // } // else if (doc) { // destObj[row[rowIndex]] = doc; // companiesReport.add(`${entityName} ${row[rowIndex]} already exists in the DB (name or alias match), not adding. Checking for link creation need.\n`); // var testObj = makerFunction(row); // if (testObj && testObj.link) { // testAndCreateLink(false, testObj.link, doc._id); // } // else { // companiesReport.add(`No link to make\n`); // return callback(null); // } // } // else { // var newObj = makerFunction(row); // if (!newObj) { // companiesReport.add(`Invalid data in row: ${row}. Aborting.\n`); // return callback(`Failed: ${companiesReport.report}`); // } // model.create( // newObj.obj, // function(err, cmodel) { // if (err) { // companiesReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); // return callback(`Failed: ${companiesReport.report}`); // } // companiesReport.add(`Added ${entityName} ${row[rowIndex]} to the DB.\n`); // destObj[row[rowIndex]] = cmodel; // if (newObj.link) { // testAndCreateLink(true, newObj.link, cmodel._id); // } // else return callback(null); // } // ); // } // } // ); //}; // //function parseData(sheets, report, finalcallback) { // async.waterfall([ // parseBasis, // parseCompanyGroups, // parseCompanies, // parseProjects, // parseConcessionsAndContracts, // parseProduction, // parseTransfers, // parseReserves // ], function (err, report) { // if (err) { // console.log("PARSE: Got an error\n"); // return finalcallback("Failed", report) // } // finalcallback("Success", report); // } // ); // // ; // // function parseEntity(reportSoFar, sheetname, dropRowsStart, dropRowsEnd, entityObj, processRow, entityName, rowIndex, model, modelKey, rowMaker, callback) { // var intReport = { // report: reportSoFar, //Relevant for the series waterfall - report gets passed along // add: function(text) { // this.report += text; // } // } // //Drop first X, last Y rows // var data = sheets[sheetname].data.slice(dropRowsStart, (sheets[sheetname].data.length - dropRowsEnd)); // //TODO: for some cases parallel is OK: differentiate // async.eachSeries(data, processRow.bind(null, intReport, entityObj, entityName, rowIndex, model, modelKey, rowMaker), function (err) { //"A callback which is called when all iteratee functions have finished, or an error occurs." // if (err) { // return callback(err, intReport.report); //Giving up // } // callback(null, intReport.report); //All good // }); // } // // function parseBasis(callback) { // var basisReport = report + "Processing basis info\n"; // // async.parallel([ // parseSources, // parseCountries, // parseCommodities // ], (function (err, resultsarray) { // console.log("PARSE BASIS: Finished parallel tasks OR got an error"); // for (var r=0; r<resultsarray.length; r++) { // if (!resultsarray[r]) { // basisReport += "** NO RESULT **\n"; // } // else basisReport += resultsarray[r]; // } // if (err) { // console.log("PARSE BASIS: Got an error"); // basisReport += `Processing of basis info caused an error: ${err}\n`; // return callback(`Processing of basis info caused an error: ${err}\n`, basisReport); // } // console.log("Finished parse basis"); // callback(null, basisReport); // })); // // function parseCountries(callback) { // //Complete country list is in the DB // var creport = "Getting countries from database...\n"; // countries = new Object; // Country.find({}, function (err, cresult) { // if (err) { // creport += `Got an error: ${err}`; // callback(err, creport); // } // else { // creport += `Found ${cresult.length} countries`; // var ctry; // for (ctry of cresult) { // countries[ctry.iso2] = ctry; // } // callback(null, creport); // } // }); // } // // function parseCommodities(callback) { // //TODO: In some sheets only a group is named... // commodities = new Object; // //The list of commodities of relevance for this dataset is taken from the location/status/commodity list // parseEntity("", '5. Project location, status, commodity', 3, 0, commodities, processGenericRow, "Commodity", 9, Commodity, "commodity_name", makeNewCommodity, callback); // } // // function parseSources(callback) { // var processSourceRow = function(sourcesReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { // if ((row[0] == "") || (row[0] == "#source")) { // sourcesReport.add("Sources: Empty row or label.\n"); // return callback(null); //Do nothing // } // //TODO: Find OLDEST (use that for comparison instead of some other duplicate - important where we create duplicates) // //TODO - may need some sort of sophisticated duplicate detection here // Source.findOne( // {source_url: row[4].toLowerCase()}, // function(err, doc) { // if (err) { // sourcesReport.add(`Encountered an error while querying the DB: ${err}. Aborting.\n`); // return callback(`Failed: ${sourcesReport.report}`); // } // else if (doc) { // sourcesReport.add(`Source ${row[0]} already exists in the DB (url match), checking content\n`); // if (equalDocs(doc, makeNewSource(false, row))) { // sourcesReport.add(`Source ${row[0]} already exists in the DB (url match), not adding\n`); // sources[row[0]] = doc; // return callback(null); // } // else { // sourcesReport.add(`Source ${row[0]} already exists in the DB (url match),flagging as duplicate\n`); // Source.create( // makeNewSource(true, row, doc._id), // function(err, model) { // if (err) { // sourcesReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); // return callback(`Failed: ${sourcesReport.report}`); // } // sources[row[0]] = model; // return callback(null); // } // ); // } // } // else { // Source.findOne( // {source_name: row[0]}, // (function(err, doc) { // if (err) { // sourcesReport.add(`Encountered an error while querying the DB: ${err}. Aborting.\n`); // return callback(`Failed: ${sourcesReport.report}`); // } // else if (doc) { // sourcesReport.add(`Source ${row[0]} already exists in the DB (name match), will flag as possible duplicate\n`); // Source.create( // makeNewSource(true, row, doc._id), // (function(err, model) { // if (err) { // sourcesReport.add(`Encountered an error while creating a source in the DB: ${err}. Aborting.\n`); // return callback(`Failed: ${sourcesReport.report}`); // } // sources[row[0]] = model; // return callback(null); // }) // ); // } // else { // sourcesReport.add(`Source ${row[0]} not found in the DB, creating\n`); // Source.create( // makeNewSource(false, row), // (function(err, model) { // if (err) { // sourcesReport.add(`Encountered an error while creating a source in the DB: ${err}. Aborting.\n`); // return callback(`Failed: ${sourcesReport.report}`); // } // sources[row[0]] = model; // return callback(null); // }) // ); // } // }) // ); // } // } // ); // }; // sources = new Object; // //TODO - refactor processSourceRow to use generic row or similar? // parseEntity("", '2. Source List', 3, 0, sources, processSourceRow, "Source", 0, Source, "source_name", makeNewSource, callback); // } // // } // // function parseCompanyGroups(result, callback) { // company_groups = new Object; // parseEntity(result, '6. Companies and Groups', 3, 0, company_groups, processCompanyRow, "CompanyGroup", 7, CompanyGroup, "company_group_name", makeNewCompanyGroup, callback); // } // // function parseCompanies(result, callback) { // companies = new Object; // parseEntity(result, '6. Companies and Groups', 3, 0, companies, processCompanyRow, "Company", 3, Company, "company_name", makeNewCompany, callback); // } // // //TODO: make more generic, entity names etc. // function createSiteProjectLink (siteId, projectId, report, lcallback) { // Link.create({project: projectId, site: siteId, entities: ['project', 'site']}, // function (err, nlmodel) { // if (err) { // report.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); // return lcallback(`Failed: ${report.report}`); // } // else { // report.add(`Linked site to project in the DB.\n`); // return lcallback(null); //Final step, no return value // } // } // ); // } // // function parseProjects(result, callback) { // var processProjectRow = function(projectsReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { // if ((row[rowIndex] == "") || (row[1] == "#project")) { // projectsReport.add("Projects: Empty row or label.\n"); // return callback(null); //Do nothing // } // // function updateOrCreateProject(projDoc, wcallback) { // var doc_id = null; // // if (!projDoc) { // projDoc = makeNewProject(row); // } // else { // doc_id = projDoc._id; // projDoc = projDoc.toObject(); // delete projDoc._id; //Don't send id back in to Mongo // delete projDoc.__v; //https://github.com/Automattic/mongoose/issues/1933 // } // // final_doc = updateProjectFacts(projDoc, row, projectsReport); // // if (!final_doc) { // projectsReport.add(`Invalid data in row: ${row}. Aborting.\n`); // return wcallback(`Failed: ${projectsReport.report}`); // } // // //console.log("Sent:\n" + util.inspect(final_doc)); // // if (!doc_id) doc_id = new ObjectId; // Project.findByIdAndUpdate( // doc_id, // final_doc, // {setDefaultsOnInsert: true, upsert: true, new: true}, // function(err, model) { // if (err) { // //console.log(err); // projectsReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); // return wcallback(`Failed: ${projectsReport.report}`); // } // //console.log("Returned\n: " + model) // projectsReport.add(`Added or updated project ${row[rowIndex]} to the DB.\n`); // projects[row[rowIndex]] = model; // return wcallback(null, model); //Continue to site stuff // } // ); // } // // function createSiteAndLink(projDoc, wcallback) { // if (row[2] != "") { // Site.findOne( // {$or: [ // {site_name: row[2]}, // {"site_aliases.alias": row[2]} //TODO: FIX POPULATE ETC.? // ]}, // function (err, sitemodel) { // if (err) { // projectsReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); // return wcallback(`Failed: ${projectsReport.report}`); // } // else if (sitemodel) { // //Site already exists - check for link, could be missing if site is from another project // var found = false; // Link.find({project: projDoc._id, site: sitemodel._id}, // function (err, sitelinkmodel) { // if (err) { // projectsReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); // return wcallback(`Failed: ${projectsReport.report}`); // } // else if (sitelinkmodel) { // projectsReport.add(`Link to ${row[2]} already exists in the DB, not adding\n`); // return wcallback(null); // } // else { // createSiteProjectLink(sitemodel._id, projDoc._id, projectsReport, wcallback); // } // } // ); // } // else { //Site doesn't exist - create and link // Site.create( // makeNewSite(row), // function (err, newsitemodel) { // if (err) { // projectsReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); // return wcallback(`Failed: ${projectsReport.report}`); // } // else { // createSiteProjectLink(newsitemodel._id, projDoc._id, projectsReport, wcallback); // } // } // ); // } // } // ); // } // else { //Nothing more to do // projectsReport.add(`No site info in row\n`); // return wcallback(null); // } // } // // //Projects - check against name and aliases // //TODO - may need some sort of sophisticated duplicate detection here // Project.findOne( // {$or: [ // {proj_name: row[rowIndex]}, // {"proj_aliases.alias": row[rowIndex]} //TODO: FIX POPULATE ETC.? // ]}, // function(err, doc) { // //console.log(doc); // if (err) { // projectsReport.add(`Encountered an error (${err}) while querying the DB. Aborting.\n`); // return callback(`Failed: ${projectsReport.report}`); // } // else if (doc) { //Project already exists, row might represent a new site // projectsReport.add(`Project ${row[rowIndex]} already exists in the DB (name or alias match), not adding but updating facts and checking for new sites\n`); // projects[row[rowIndex]] = doc; //Basis data is always the same, OK if this gets called multiple times // async.waterfall( //Waterfall because we want to be able to cope with a result or error being returned // [updateOrCreateProject.bind(null, doc), // createSiteAndLink], //Gets proj. id passed as result // function (err, result) { // if (err) { // return callback(`Failed: ${projectsReport.report}`); // } // else { // //All done // return callback(null); // } // } // ); // } // else { // projectsReport.add(`Project ${row[rowIndex]} not found, creating.\n`); // async.waterfall( //Waterfall because we want to be able to cope with a result or error being returned // [updateOrCreateProject.bind(null, null), //Proj = null = create it please // createSiteAndLink], //Gets proj. id passed as result // function (err, result) { // if (err) { // return callback(`Failed: ${projectsReport.report}`); // } // else { // //All done // return callback(null); // } // } // ); // } // } // ); // }; // projects = new Object; // parseEntity(result, '5. Project location, status, commodity', 3, 0, projects, processProjectRow, "Project", 1, Project, "proj_name", makeNewProject, callback); // } // // function parseConcessionsAndContracts(result, callback) { // //First linked companies // var processCandCRowCompanies = function(row, callback) { // var compReport = ""; // if (row[2] != "") { // if (!companies[row[2]] || !projects[row[1]] || !sources[row[0]] ) { // compReport += (`Invalid data in row: ${row}. Aborting.\n`); // return callback(`Failed: ${compReport}`); // } // Link.findOne( // { // company: companies[row[2]]._id, // project: projects[row[1]]._id // }, // function(err, doc) { // if (err) { // compReport += (`Encountered an error (${err}) while querying the DB. Aborting.\n`); // return callback(`Failed: ${compReport}`); // } // else if (doc) { // compReport += (`Company ${row[2]} is already linked with project ${row[1]}, not adding\n`); // return callback(null, compReport); // } // else { // var newCompanyLink = { // company: companies[row[2]]._id, // project: projects[row[1]]._id, // source: sources[row[0]]._id, // entities:['company','project'] // }; // Link.create( // newCompanyLink, // function(err, model) { // if (err) { // compReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); // return callback(`Failed: ${compReport}`); // } // compReport += (`Linked company ${row[2]} with project ${row[1]} in the DB.\n`); // return callback(null, compReport); // } // ); // } // } // ); // } // else return callback(null, "No company found in row\n"); // }; // //Linked contracts - all based on ID (for API look up) // var processCandCRowContracts = function(row, callback) { // var contReport = ""; // if (row[7] != "") { // Contract.findOne({ // contract_id: row[7] // }, // function(err, doc) { // if (err) { // contReport += (`Encountered an error (${err}) while querying the DB. Aborting.\n`); // return callback(`Failed: ${contReport}`); // } // else if (doc) { //Found contract, now see if its linked // contReport += (`Contract ${row[7]} exists, checking for link\n`); // Link.findOne( // { // contract: doc._id, // project: projects[row[1]]._id // }, // function(err, ldoc) { // if (err) { // contReport += (`Encountered an error (${err}) while querying the DB. Aborting.\n`); // return callback(`Failed: ${contReport}`); // } // else if (ldoc) { // contReport += (`Contract ${row[7]} is already linked with project ${row[1]}, not adding\n`); // return callback(null, contReport); // } // else { // var newContractLink = { // contract: doc._id, // project: projects[row[1]]._id, // source: sources[row[0]]._id, // entities:['contract','project'] // }; // Link.create( // newContractLink, // function(err, model) { // if (err) { // contReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); // return callback(`Failed: ${contReport}`); // } // contReport += (`Linked contract ${row[7]} with project ${row[1]} in the DB.\n`); // return callback(null, contReport); // } // ); // } // }); // } // else { //No contract, create and link // var newContract = { // contract_id: row[7] // }; // Contract.create( // newContract, // function(err, cmodel) { // if (err) { // contReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); // return callback(`Failed: ${contReport}`); // } // contReport += (`Created contract ${row[7]}.\n`); // //Now create Link // var newContractLink = { // contract: cmodel._id, // project: projects[row[1]]._id, // source: sources[row[0]]._id, // entities:['contract','project'] // }; // Link.create( // newContractLink, // function(err, model) { // if (err) { // contReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); // return callback(`Failed: ${contReport}`); // } // contReport += (`Linked contract ${row[7]} with project ${row[1]} in the DB.\n`); // return callback(null, contReport); // } // ); // } // ); // } // } // ); // } // else return callback(null, "No contract found in row\n"); // }; // //Then linked concessions // var processCandCRowConcessions = function(row, callback) { // var concReport = ""; // if (row[8] != "") { // Concession.findOne( // {$or: [ // {concession_name: row[8]}, // {"concession_aliases.alias": row[8]} //TODO, alias population // ] // }, // function(err, doc) { // if (err) { // concReport += (`Encountered an error (${err}) while querying the DB. Aborting.\n`); // return callback(`Failed: ${concReport}`); // } // else if (doc) { //Found concession, now see if its linked // concReport += (`Contract ${row[8]} exists, checking for link\n`); // Link.findOne( // { // concession: doc._id, // project: projects[row[1]]._id // }, // function(err, ldoc) { // if (err) { // concReport += (`Encountered an error (${err}) while querying the DB. Aborting.\n`); // return callback(`Failed: ${concReport}`); // } // else if (ldoc) { // concReport += (`Concession ${row[8]} is already linked with project ${row[1]}, not adding\n`); // return callback(null, concReport); // } // else { // var newConcessionLink = { // concession: doc._id, // project: projects[row[1]]._id, // source: sources[row[0]]._id, // entities:['concession','project'] // }; // Link.create( // newConcessionLink, // function(err, model) { // if (err) { // concReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); // return callback(`Failed: ${concReport}`); // } // concReport += (`Linked concession ${row[8]} with project ${row[1]} in the DB.\n`); // return callback(null, concReport); // } // ); // } // }); // } // else { //No concession, create and link // var newConcession = { // concession_name: row[8], // concession_established_source: sources[row[0]]._id // }; // if (row[10] != "") { // newConcession.concession_country = {country: countries[row[10]]._id, source: sources[row[0]]._id} // } // Concession.create( // newConcession, // function(err, cmodel) { // if (err) { // concReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); // return callback(`Failed: ${concReport}`); // } // concReport += (`Created concession ${row[8]}.\n`); // //Now create Link // var newConcessionLink = { // concession: cmodel._id, // project: projects[row[1]]._id, // source: sources[row[0]]._id, // entities:['concession','project'] // }; // Link.create( // newConcessionLink, // function(err, model) { // if (err) { // concReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); // return callback(`Failed: ${concReport}`); // } // concReport += (`Linked concession ${row[8]} with project ${row[1]} in the DB.\n`); // return callback(null, concReport); // } // ); // } // ); // } // } // ); // } // else return callback(null, "No concession found in row\n"); // }; // // var processCandCRow = function(candcReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { // if ((row[0] == "#source") || ((row[2] == "") && (row[7] == "") && (row[8] == ""))) { // candcReport.add("Concessions and Contracts: Empty row or label.\n"); // return callback(null); //Do nothing // } // if (!sources[row[0]] ) { // candcReport.add(`Invalid source in row: ${row}. Aborting.\n`); // return callback(`Failed: ${candcReport.report}`); // } // async.parallel([ // processCandCRowCompanies.bind(null, row), // processCandCRowContracts.bind(null, row), // processCandCRowConcessions.bind(null, row) // ], // function (err, resultsarray) { // for (var r=0; r<resultsarray.length; r++) { // if (!resultsarray[r]) { // candcReport.add("** NO RESULT **\n"); // } // else candcReport.add(resultsarray[r]); // } // if (err) { // candcReport.add(`Processing of company/contract/concessions caused an error: ${err}\n`); // return callback(`Processing of company/contract/concession caused an error: ${err}\n`, candcReport.report); // } // return callback(null); // } // ); // } // parseEntity(result, '7. Contracts, concessions and companies', 4, 0, null, processCandCRow, null, null, null, null, null, callback); // } // // //TODO: This is definitely a candidate for bringing into genericrow with custom query // function parseProduction(result, callback) { // var processProductionRow = function(prodReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { // //This serves 2 purposes, check for blank rows and skip rows with no value // if ((row[6] == "") || (row[0] == "#source")) { // prodReport.add("Productions: Empty row or label, or no volume data.\n"); // return callback(null); //Do nothing // } // //TODO: Currently hard req. for project. Country and Company seem to be optional and unused. // //thereby data can only be grabbed via project therefore req. project! // if (/*(row[2] == "") || !countries[row[2]] || */(row[3] == "") || !sources[row[0]] || (row[8] == "") || !commodities[row[8]] || (row[5] == "") ) { // prodReport += (`Invalid or missing data in row: ${row}. Aborting.\n`); // return callback(`Failed: ${prodReport}`); // } // //Here we depend on links, use controller // // //Production - match (ideally) by (country???) + project (if present???) + year + commodity // //BUT (TODO) there is currently no easy way of grabbing country & project // Production.findOne( // { // production_commodity: commodities[row[8]]._id, // production_year: parseInt(row[5]), // }, // function(err, doc) { // if (err) { // prodReport.add(`Encountered an error (${err}) while querying the DB. Aborting.\n`); // return callback(`Failed: ${prodReport.report}`); // } // else if (doc) { // prodReport.add(`Production ${row[3]}/${row[8]}/${row[5]} already exists in the DB, not adding\n`); // return callback(null); // } // else { // var newProduction = makeNewProduction(row); // Production.create( // newProduction, // function(err, model) { // if (err) { // prodReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); // return callback(`Failed: ${prodReport.report}`); // } // //TODO: Link Production<->Project, (Production<->Country ???) // //As productions can only exist with a project (TODO: check), go ahead and create the link // Link.create( // {project: projects[row[3]]._id, production: model._id, entities: ['project', 'production']}, // function name(err, lmodel) { // if (err) { // prodReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); // return callback(`Failed: ${prodReport.report}`); // } // else { // prodReport.add(`Added production ${row[3]}/${row[8]}/${row[5]} to the DB and linked to project.\n`); // return callback(null); // } // } // ); // } // ); // } // } // ); // }; // parseEntity(result, '8. Production', 3, 0, null, processProductionRow, null, null, null, null, null, callback); // } // // function parseTransfers(result, callback) { // var processTransferRow = function(transReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { // //This serves 2 purposes, check for blank row${util.inspect(query)s and skip rows with no value // if (((row[21] == "") && (row[9] == "")) || (row[0] == "#source")) { // transReport.add("Transfers: Empty row or label, or no volume data.\n"); // return callback(null); //Do nothing // } // //This, in turn is a little harsh to abort of payment type is missing, but it does make for an invalid row // if ((row[5] == "") || !projects[row[5]] || !sources[row[0]] || !countries[row[2]] || (row[17] == "") ) { // transReport += (`Invalid or missing data in row: ${row}. Aborting.\n`); // return callback(`Failed: ${transReport}`); // } // //Transfer - many possible ways to match // //Determine if payment or receipt // var transfer_audit_type = ""; // if (row[21] != "") { // transfer_audit_type = "government_receipt" // transfer_type = "receipt"; // } // else if (row[9] != "") { // transfer_audit_type = "company_payment"; // transfer_type = "payment"; // } // else returnInvalid(); // // //TODO: How to match without projects in the transfers any more? // var query = {transfer_country: countries[row[2]]._id, transfer_audit_type: transfer_audit_type}; // if (row[5] != "") { // //query.transfer_project = projects[row[5]]._id; // query.transfer_level = "project"; // } // else query.transfer_level = "country"; // // if (row[3] != "") { // query.transfer_company = companies[row[3]]._id; // } // // if (transfer_type == "payment") { // query.transfer_year = parseInt(row[6]); // query.transfer_type = row[8]; // } // else { // query.transfer_year = parseInt(row[13]); // query.transfer_type = row[17]; // if (row[15] != "") { // query.transfer_gov_entity = row[15]; // } // if (row[16] != "") { // query.transfer_gov_entity_id = row[16]; // } // } // // Transfer.findOne( // query, // function(err, doc) { // if (err) { // transReport.add(`Encountered an error (${err}) while querying the DB. Aborting.\n`); // return callback(`Failed: ${transReport.report}`); // } // else if (doc) { // transReport.add(`Transfer (${util.inspect(query)}) already exists in the DB, not adding\n`); // return callback(null); // } // else { // var newTransfer = makeNewTransfer(row, transfer_audit_type); // if (!newTransfer) { // transReport += (`Invalid or missing data in row: ${row}. Aborting.\n`); // return callback(`Failed: ${transReport}`); // } // Transfer.create( // newTransfer, // function(err, model) { // if (err) { // transReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); // return callback(`Failed: ${transReport.report}`); // } // //TODO: Link Transfer<->Project, (Transfer<->Company ???) // //Can't find the transfer without a project (if there is one), so go ahead and create it without checks // if (row[5] != "") { // Link.create( // {project: projects[row[5]]._id, transfer: model._id, entities: ['project', 'transfer']}, // function name(err, lmodel) { // if (err) { // transReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); // return callback(`Failed: ${transReport.report}`); // } // else { // transReport.add(`Added transfer (${util.inspect(query)}) with project link to the DB.\n`); // return callback(null); // } // } // ); // } // else { // transReport.add(`Added transfer (${util.inspect(query)}) to the DB without project link.\n`); // return callback(null); // } // } // ); // } // } // ); // }; // parseEntity(result, '10. Payments and receipts', 3, 0, null, processTransferRow, null, null, null, null, null, callback); // } // // function parseReserves(result, callback) { // result += "Reserves IGNORED\n"; // callback(null, result); // } //}
Minor user auth for ETL, proper recording of actions, less console output
server/dataprocessing/googlesheets.js
Minor user auth for ETL, proper recording of actions, less console output
<ide><path>erver/dataprocessing/googlesheets.js <del>//var Source = require('mongoose').model('Source'), <del>// Country = require('mongoose').model('Country'), <del>// Commodity = require('mongoose').model('Commodity'), <del>// CompanyGroup = require('mongoose').model('CompanyGroup'), <del>// Company = require('mongoose').model('Company'), <del>// Project = require('mongoose').model('Project'), <del>// Site = require('mongoose').model('Site'), <del>// Link = require('mongoose').model('Link'), <del>// Contract = require('mongoose').model('Contract'), <del>// Concession = require('mongoose').model('Concession'), <del>// Production = require('mongoose').model('Production'), <del>// Transfer = require('mongoose').model('Transfer'), <del>// ObjectId = require('mongoose').Types.ObjectId, <del>// util = require('util'), <del>// async = require('async'), <del>// csv = require('csv'), <del>// request = require('request'), <del>// moment = require('moment'); <del>// <del>//exports.processData = function(link, callback) { <del>// var report = ""; <del>// var keytoend = link.substr(link.indexOf("/d/") + 3, link.length); <del>// var key = keytoend.substr(0, keytoend.indexOf("/")); <del>// report += `Using link ${link}\n`; <del>// if (key.length != 44) { <del>// report += "Could not detect a valid spreadsheet key in URL\n"; <del>// callback("Failed", report); <del>// return; <del>// } <del>// else { <del>// report += `Using GS key ${key}\n`; <del>// } <del>// var feedurl = `https://spreadsheets.google.com/feeds/worksheets/${key}/public/full?alt=json`; <del>// var sheets = new Object; <del>// <del>// request({ <del>// url: feedurl, <del>// json: true <del>// }, function (error, response, body) { <del>// if (!error && response.statusCode === 200) { <del>// var numSheets = body.feed.entry.length; <del>// var mainTitle = body.feed.title.$t; <del>// var numProcessed = 0; <del>// for (var i=0; i<body.feed.entry.length; i++) { <del>// for (var j=0; j<body.feed.entry[i].link.length; j++) { <del>// if (body.feed.entry[i].link[j].type == "text/csv") { <del>// report += `Getting data from sheet "${body.feed.entry[i].title.$t}"...\n`; <del>// request({ <del>// url: body.feed.entry[i].link[j].href <del>// }, (function (i, error, response, sbody) { <del>// if (error) { <del>// report += `${body.feed.entry[i].title.$t}: Could not retrieve sheet\n`; <del>// callback("Failed", report); <del>// return; <del>// } <del>// csv.parse(sbody, {trim: true}, function(err, rowdata){ <del>// if (error) { <del>// report += `${skey}: Could not parse sheet\n`; <del>// callback("Failed", report); <del>// return; <del>// } <del>// var item = new Object; <del>// var cd = response.headers['content-disposition']; <del>// <del>// item.title = body.feed.entry[i].title.$t; <del>// item.link = response.request.uri.href; <del>// item.data = rowdata; <del>// report += `${item.title}: Stored ${rowdata.length} rows\n`; <del>// sheets[item.title] = item; <del>// numProcessed++; <del>// if (numProcessed == numSheets) { <del>// parseData(sheets, report, callback); <del>// } <del>// }); <del>// }).bind(null, i)); <del>// } <del>// } <del>// } <del>// } <del>// else { <del>// report += "Could not get information from GSheets feed - is the sheet shared?\n" <del>// callback("Failed", report); <del>// return; <del>// } <del>// }); <del>//} <del>// <del>//function parseGsDate(input) { <del>// /* In general format should appear as DD/MM/YYYY or empty but sometimes GS has it as a date internally */ <del>// var result; <del>// if (!input || input == "") return null; <del>// else result = moment(input, "DD/MM/YYYY").format(); <del>// //Hope for the best <del>// if (result == "Invalid date") return input; <del>// else return result; <del>//} <del>// <del>////Data needed for inter-entity reference <del>//var sources, countries, commodities, companies, projects; <del>// <del>//var makeNewSource = function(flagDuplicate, newRow, duplicateId) { <del>// newRow[7] = parseGsDate(newRow[7]); <del>// newRow[8] = parseGsDate(newRow[8]); <del>// <del>// var source = { <del>// source_name: newRow[0], <del>// source_type: newRow[2], //TODO: unnecessary? <del>// /* TODO? source_type_id: String, */ <del>// source_url: newRow[4], <del>// source_url_type: newRow[5], //TODO: unnecessary? <del>// /* TODO? source_url_type_id: String, */ <del>// source_archive_url: newRow[6], <del>// source_notes: newRow[9], <del>// source_date: newRow[7], <del>// retrieve_date: newRow[8] <del>// /* TODO create_author:, */ <del>// } <del>// if (flagDuplicate) { <del>// source.possible_duplicate = true; <del>// source.duplicate = duplicateId <del>// } <del>// return source; <del>//} <del>// <del>//var makeNewCommodity = function(newRow) { <del>// var commodity = { <del>// commodity_name: newRow[9], <del>// commodity_type: newRow[8].toLowerCase().replace(/ /g, "_") <del>// } <del>// return commodity; <del>//} <del>// <del>//var makeNewCompanyGroup = function(newRow) { <del>// var returnObj = {obj: null, link: null}; <del>// var companyg = { <del>// company_group_name: newRow[7] <del>// }; <del>// <del>// if (newRow[0] != "") { <del>// if (sources[newRow[0]]) { //Must be here due to lookups in sheet <del>// companyg.company_group_record_established = sources[newRow[0]]._id; <del>// } <del>// else return false; //error <del>// } <del>// returnObj.obj = companyg; <del>// //console.log("new company group: " + util.inspect(returnObj)); <del>// return returnObj; <del>//} <del>// <del>//var makeNewCompany = function(newRow) { <del>// var returnObj = {obj: null, link: null}; <del>// var company = { <del>// company_name: newRow[3] <del>// }; <del>// <del>// if (newRow[5] != "") { <del>// company.open_corporates_id = newRow[5]; <del>// } <del>// if (newRow[2] != "") { <del>// //TODO: This is not very helpful for the end user <del>// if (!countries[newRow[2]]) { <del>// console.log("SERIOUS ERROR: Missing country in the DB"); <del>// return false; <del>// } <del>// company.country_of_incorporation = [{country: countries[newRow[2]]._id}]; //Fact <del>// } <del>// if (newRow[6] != "") { <del>// company.company_website = {string: newRow[6]}; //Fact, will have comp. id added later <del>// } <del>// if (newRow[0] != "") { <del>// if (sources[newRow[0]]) { //Must be here due to lookups in sheet <del>// company.company_established_source = sources[newRow[0]]._id; <del>// } <del>// else return false; //error <del>// } <del>// <del>// if (newRow[7] != "") { <del>// //TODO: Also should check aliases in each object <del>// returnObj.link = {company_group: company_groups[newRow[8]]._id}; <del>// } <del>// <del>// returnObj.obj = company; <del>// return returnObj; <del>//} <del>// <del>//var makeNewProject = function(newRow) { <del>// var project = { <del>// proj_name: newRow[1], <del>// }; <del>// return project; <del>//} <del>// <del>//var updateProjectFacts = function(doc, row, report) <del>//{ <del>// var fact; <del>// //Update status and commodity <del>// if (row[9] != "") { <del>// var notfound = true; <del>// if (doc.proj_commodity) { <del>// for (fact of doc.proj_commodity) { <del>// //No need to check if commodity exists as commodities are taken from here <del>// //TODO: In general, do we want to store multiple sources for the same truth? [from GS] <del>// if (commodities[row[9]]._id == fact.commodity._id) { <del>// notfound = false; <del>// report.add(`Project commodity ${row[9]} already exists in project, not adding\n`); <del>// break; <del>// } <del>// } <del>// } <del>// else doc.proj_commodity = []; <del>// if (notfound) { //Commodity must be here, as based on this sheet <del>// //Don't push but add, existing values will not be removed <del>// doc.proj_commodity = [{commodity: commodities[row[9]]._id, source: sources[row[0]]._id}]; <del>// report.add(`Project commodity ${row[9]} added to project\n`); <del>// } <del>// } <del>// else if (doc.proj_commodity) delete doc.proj_commodity; //Don't push <del>// <del>// if (row[10] != "") { <del>// var notfound = true; <del>// if (doc.proj_status) { <del>// for (fact of doc.proj_status) { <del>// if (row[10] == fact.string) { <del>// notfound = false; <del>// report.add(`Project status ${row[10]} already exists in project, not adding\n`); <del>// break; <del>// } <del>// } <del>// } <del>// else doc.proj_status = []; <del>// if (notfound) { <del>// //Don't push but add, existing values will not be removed <del>// doc.proj_status = [{string: row[10].toLowerCase(), date: parseGsDate(row[11]), source: sources[row[0]]._id}]; <del>// report.add(`Project status ${row[10]} added to project\n`); <del>// } <del>// } <del>// else if (doc.proj_status) delete doc.proj_status; //Don't push <del>// <del>// //TODO... projects with mulitple countries, really? <del>// if (row[5] != "") { <del>// var notfound = true; <del>// if (doc.proj_country) { //TODO: project without a country??? <del>// for (fact of doc.proj_country) { <del>// if (countries[row[5]]._id == fact.country._id) { <del>// notfound = false; <del>// report.add(`Project country ${row[5]} already exists in project, not adding\n`); <del>// break; <del>// } <del>// } <del>// } <del>// else doc.proj_country = []; <del>// if (notfound) { <del>// //Don't push but add, existing values will not be removed <del>// doc.proj_country = [{country: countries[row[5]]._id, source: sources[row[0]]._id}]; <del>// report.add(`Project country ${row[5]} added to project\n`); <del>// } <del>// } <del>// else if (doc.proj_country) delete doc.proj_country; //Don't push <del>// return doc; <del>//} <del>// <del>//var makeNewSite = function(newRow) { <del>// var site = { <del>// site_name: newRow[2], <del>// site_established_source: sources[newRow[0]]._id, <del>// site_country: [{country: countries[newRow[5]]._id, source: sources[newRow[0]]._id}] //TODO: How in the world can there multiple versions of country <del>// } <del>// if (newRow[3] != "") site.site_address = [{string: newRow[3], source: sources[newRow[0]]._id}]; <del>// //TODO FIELD INFO field: Boolean // <del>// if (newRow[6] != "") site.site_coordinates = [{loc: [parseFloat(newRow[6]), parseFloat(newRow[7])], source: sources[newRow[0]]._id}]; <del>// return site; <del>//} <del>// <del>//var makeNewProduction = function(newRow) { <del>// var production = { <del>// production_commodity: commodities[newRow[8]]._id, <del>// production_year: parseInt(newRow[5]), <del>// //production_project: projects[newRow[3]]._id, <del>// source: sources[newRow[0]]._id <del>// } <del>// <del>// if (newRow[7] != "") { <del>// production.production_unit = newRow[7]; <del>// } <del>// if (newRow[6] != "") { <del>// production.production_volume = newRow[6].replace(/,/g, ""); <del>// } <del>// if (newRow[9] != "") { <del>// production.production_price = newRow[9].replace(/,/g, ""); <del>// } <del>// if (newRow[10] != "") { <del>// production.production_price_per_unit = newRow[10]; <del>// } <del>// <del>// return production; <del>//} <del>// <del>//var makeNewTransfer = function(newRow, transfer_audit_type) { <del>// //TODO: This is not very helpful for the end user <del>// if (!countries[newRow[2]]) { <del>// console.log("SERIOUS ERROR: Missing country in the DB"); <del>// return false; <del>// } <del>// <del>// var transfer = { <del>// source: sources[newRow[0]]._id, <del>// transfer_country: countries[newRow[2]]._id, <del>// transfer_audit_type: transfer_audit_type <del>// }; <del>// <del>// if (newRow[3] != "") { <del>// transfer.transfer_company = companies[newRow[3]]._id; <del>// } <del>// <del>// if (newRow[4] != "") { <del>// transfer.transfer_line_item = newRow[4]; <del>// } <del>// <del>// if (newRow[5] != "") { <del>// transfer.transfer_level = "project"; <del>// //transfer.transfer_project = projects[newRow[5]]._id; <del>// } <del>// else { <del>// transfer.transfer_level = "country"; <del>// } <del>// <del>// if (transfer_audit_type == "government_receipt") { <del>// transfer.transfer_year = parseInt(newRow[13]); <del>// transfer.transfer_type = newRow[17]; <del>// transfer.transfer_unit = newRow[19]; <del>// transfer.transfer_value = newRow[21].replace(/,/g, ""); <del>// if (newRow[20] != "") transfer.transfer_accounting_basis = newRow[20]; <del>// if (newRow[15] != "") transfer.transfer_gov_entity = newRow[15]; <del>// if (newRow[16] != "") transfer.transfer_gov_entity_id = newRow[16]; <del>// } <del>// else if (transfer_audit_type == "company_payment") { <del>// transfer.transfer_audit_type = "company_payment"; <del>// transfer.transfer_year = parseInt(newRow[6]); <del>// transfer.transfer_type = newRow[5]; <del>// transfer.transfer_unit = newRow[7]; <del>// transfer.transfer_value = newRow[9].replace(/,/g, ""); <del>// if (newRow[8] != "") transfer.transfer_accounting_basis = newRow[8]; <del>// } <del>// else return false; <del>// <del>// return transfer; <del>//} <del>// <del>////TODO: This needs some more work, specifically which properties to compare <del>//equalDocs = function(masterDoc, newDoc) { <del>// for (property in newDoc) { <del>// if (masterDoc[property]) { <del>// if (newDoc[property] != masterDoc[property]) { <del>// return false; <del>// } <del>// } <del>// else return false; <del>// } <del>// return true; <del>//} <del>// <del>//processGenericRow = function(report, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { <del>// if ((row[rowIndex] == "") || (row[rowIndex][0] == "#")) { <del>// report.add(entityName + ": Empty row or label.\n"); <del>// return callback(null); //Do nothing <del>// } <del>// var finderObj = {}; <del>// finderObj[modelKey] = row[rowIndex]; <del>// model.findOne( <del>// finderObj, <del>// function(err, doc) { <del>// if (err) { <del>// report.add(`Encountered an error (${err}) while querying the DB. Aborting.\n`); <del>// return callback(`Failed: ${report.report}`); <del>// } <del>// else if (doc) { <del>// report.add(`${entityName} ${row[rowIndex]} already exists in the DB (name match), not adding\n`); <del>// destObj[row[rowIndex]] = doc; <del>// return callback(null); <del>// } <del>// else { <del>// model.create( <del>// makerFunction(row), <del>// function(err, createdModel) { <del>// if (err) { <del>// report.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <del>// return callback(`Failed: ${report.report}`); <del>// } <del>// report.add(`Added ${entityName} ${row[rowIndex]} to the DB.\n`); <del>// destObj[row[rowIndex]] = createdModel; <del>// return callback(null); <del>// } <del>// ); <del>// } <del>// } <del>// ); <del>//} <del>// <del>////This handles companies and company groups <del>////Not the maker function returns an object with a sub-object <del>//processCompanyRow = function(companiesReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { <del>// if ((row[rowIndex] == "") || (row[rowIndex][0] == "#")) { <del>// companiesReport.add(entityName + ": Empty row or label.\n"); <del>// return callback(null); //Do nothing <del>// } <del>// //Check against name and aliases <del>// //TODO - may need some sort of sophisticated duplicate detection here <del>// var queryEntry1 = {}; <del>// queryEntry1[modelKey] = row[rowIndex]; <del>// var queryEntry2 = {}; <del>// queryEntry2[modelKey+'_aliases.alias'] = row[rowIndex]; //TODO!!! Cannot be searched this way (no pre-population) <del>// <del>// model.findOne( <del>// {$or: [ <del>// queryEntry1, <del>// queryEntry2 <del>// ]}, <del>// function(err, doc) { <del>// var testAndCreateLink = function(skipTest, link, company_id) { <del>// var createLink = function() { <del>// link.entities = ['company', 'company_group']; <del>// Link.create(link, function(err, nlmodel) { <del>// if (err) { <del>// companiesReport.add(`Encountered an error (${err}) adding link to DB. Aborting.\n`); <del>// return callback(`Failed: ${companiesReport.report}`); <del>// } <del>// else { <del>// companiesReport.add(`Created link\n`); <del>// return callback(null); <del>// } <del>// }); <del>// }; <del>// if (!skipTest) { <del>// link.company = company_id; <del>// Link.findOne( <del>// link, <del>// function (err, lmodel) { <del>// if (err) { <del>// companiesReport.add(`Encountered an error (${err}) while querying DB. Aborting.\n`); <del>// return callback(`Failed: ${companiesReport.report}`); <del>// } <del>// else if (lmodel) { <del>// companiesReport.add(`Link already exists in the DB, not adding\n`); <del>// return callback(null); <del>// } <del>// else { <del>// createLink(); <del>// } <del>// } <del>// ); <del>// } <del>// else createLink(); <del>// } <del>// if (err) { <del>// companiesReport.add(`Encountered an error (${err}) while querying the DB. Aborting.\n`); <del>// return callback(`Failed: ${companiesReport.report}`); <del>// } <del>// else if (doc) { <del>// destObj[row[rowIndex]] = doc; <del>// companiesReport.add(`${entityName} ${row[rowIndex]} already exists in the DB (name or alias match), not adding. Checking for link creation need.\n`); <del>// var testObj = makerFunction(row); <del>// if (testObj && testObj.link) { <del>// testAndCreateLink(false, testObj.link, doc._id); <del>// } <del>// else { <del>// companiesReport.add(`No link to make\n`); <del>// return callback(null); <del>// } <del>// } <del>// else { <del>// var newObj = makerFunction(row); <del>// if (!newObj) { <del>// companiesReport.add(`Invalid data in row: ${row}. Aborting.\n`); <del>// return callback(`Failed: ${companiesReport.report}`); <del>// } <del>// model.create( <del>// newObj.obj, <del>// function(err, cmodel) { <del>// if (err) { <del>// companiesReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <del>// return callback(`Failed: ${companiesReport.report}`); <del>// } <del>// companiesReport.add(`Added ${entityName} ${row[rowIndex]} to the DB.\n`); <del>// destObj[row[rowIndex]] = cmodel; <del>// if (newObj.link) { <del>// testAndCreateLink(true, newObj.link, cmodel._id); <del>// } <del>// else return callback(null); <del>// } <del>// ); <del>// } <del>// } <del>// ); <del>//}; <del>// <del>//function parseData(sheets, report, finalcallback) { <del>// async.waterfall([ <del>// parseBasis, <del>// parseCompanyGroups, <del>// parseCompanies, <del>// parseProjects, <del>// parseConcessionsAndContracts, <del>// parseProduction, <del>// parseTransfers, <del>// parseReserves <del>// ], function (err, report) { <del>// if (err) { <del>// console.log("PARSE: Got an error\n"); <del>// return finalcallback("Failed", report) <del>// } <del>// finalcallback("Success", report); <del>// } <del>// ); <del>// <del>// ; <del>// <del>// function parseEntity(reportSoFar, sheetname, dropRowsStart, dropRowsEnd, entityObj, processRow, entityName, rowIndex, model, modelKey, rowMaker, callback) { <del>// var intReport = { <del>// report: reportSoFar, //Relevant for the series waterfall - report gets passed along <del>// add: function(text) { <del>// this.report += text; <del>// } <del>// } <del>// //Drop first X, last Y rows <del>// var data = sheets[sheetname].data.slice(dropRowsStart, (sheets[sheetname].data.length - dropRowsEnd)); <del>// //TODO: for some cases parallel is OK: differentiate <del>// async.eachSeries(data, processRow.bind(null, intReport, entityObj, entityName, rowIndex, model, modelKey, rowMaker), function (err) { //"A callback which is called when all iteratee functions have finished, or an error occurs." <del>// if (err) { <del>// return callback(err, intReport.report); //Giving up <del>// } <del>// callback(null, intReport.report); //All good <del>// }); <del>// } <del>// <del>// function parseBasis(callback) { <del>// var basisReport = report + "Processing basis info\n"; <del>// <del>// async.parallel([ <del>// parseSources, <del>// parseCountries, <del>// parseCommodities <del>// ], (function (err, resultsarray) { <del>// console.log("PARSE BASIS: Finished parallel tasks OR got an error"); <del>// for (var r=0; r<resultsarray.length; r++) { <del>// if (!resultsarray[r]) { <del>// basisReport += "** NO RESULT **\n"; <del>// } <del>// else basisReport += resultsarray[r]; <del>// } <del>// if (err) { <del>// console.log("PARSE BASIS: Got an error"); <del>// basisReport += `Processing of basis info caused an error: ${err}\n`; <del>// return callback(`Processing of basis info caused an error: ${err}\n`, basisReport); <del>// } <del>// console.log("Finished parse basis"); <del>// callback(null, basisReport); <del>// })); <del>// <del>// function parseCountries(callback) { <del>// //Complete country list is in the DB <del>// var creport = "Getting countries from database...\n"; <del>// countries = new Object; <del>// Country.find({}, function (err, cresult) { <del>// if (err) { <del>// creport += `Got an error: ${err}`; <del>// callback(err, creport); <del>// } <del>// else { <del>// creport += `Found ${cresult.length} countries`; <del>// var ctry; <del>// for (ctry of cresult) { <del>// countries[ctry.iso2] = ctry; <del>// } <del>// callback(null, creport); <del>// } <del>// }); <del>// } <del>// <del>// function parseCommodities(callback) { <del>// //TODO: In some sheets only a group is named... <del>// commodities = new Object; <del>// //The list of commodities of relevance for this dataset is taken from the location/status/commodity list <del>// parseEntity("", '5. Project location, status, commodity', 3, 0, commodities, processGenericRow, "Commodity", 9, Commodity, "commodity_name", makeNewCommodity, callback); <del>// } <del>// <del>// function parseSources(callback) { <del>// var processSourceRow = function(sourcesReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { <del>// if ((row[0] == "") || (row[0] == "#source")) { <del>// sourcesReport.add("Sources: Empty row or label.\n"); <del>// return callback(null); //Do nothing <del>// } <del>// //TODO: Find OLDEST (use that for comparison instead of some other duplicate - important where we create duplicates) <del>// //TODO - may need some sort of sophisticated duplicate detection here <del>// Source.findOne( <del>// {source_url: row[4].toLowerCase()}, <del>// function(err, doc) { <del>// if (err) { <del>// sourcesReport.add(`Encountered an error while querying the DB: ${err}. Aborting.\n`); <del>// return callback(`Failed: ${sourcesReport.report}`); <del>// } <del>// else if (doc) { <del>// sourcesReport.add(`Source ${row[0]} already exists in the DB (url match), checking content\n`); <del>// if (equalDocs(doc, makeNewSource(false, row))) { <del>// sourcesReport.add(`Source ${row[0]} already exists in the DB (url match), not adding\n`); <del>// sources[row[0]] = doc; <del>// return callback(null); <del>// } <del>// else { <del>// sourcesReport.add(`Source ${row[0]} already exists in the DB (url match),flagging as duplicate\n`); <del>// Source.create( <del>// makeNewSource(true, row, doc._id), <del>// function(err, model) { <del>// if (err) { <del>// sourcesReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <del>// return callback(`Failed: ${sourcesReport.report}`); <del>// } <del>// sources[row[0]] = model; <del>// return callback(null); <del>// } <del>// ); <del>// } <del>// } <del>// else { <del>// Source.findOne( <del>// {source_name: row[0]}, <del>// (function(err, doc) { <del>// if (err) { <del>// sourcesReport.add(`Encountered an error while querying the DB: ${err}. Aborting.\n`); <del>// return callback(`Failed: ${sourcesReport.report}`); <del>// } <del>// else if (doc) { <del>// sourcesReport.add(`Source ${row[0]} already exists in the DB (name match), will flag as possible duplicate\n`); <del>// Source.create( <del>// makeNewSource(true, row, doc._id), <del>// (function(err, model) { <del>// if (err) { <del>// sourcesReport.add(`Encountered an error while creating a source in the DB: ${err}. Aborting.\n`); <del>// return callback(`Failed: ${sourcesReport.report}`); <del>// } <del>// sources[row[0]] = model; <del>// return callback(null); <del>// }) <del>// ); <del>// } <del>// else { <del>// sourcesReport.add(`Source ${row[0]} not found in the DB, creating\n`); <del>// Source.create( <del>// makeNewSource(false, row), <del>// (function(err, model) { <del>// if (err) { <del>// sourcesReport.add(`Encountered an error while creating a source in the DB: ${err}. Aborting.\n`); <del>// return callback(`Failed: ${sourcesReport.report}`); <del>// } <del>// sources[row[0]] = model; <del>// return callback(null); <del>// }) <del>// ); <del>// } <del>// }) <del>// ); <del>// } <del>// } <del>// ); <del>// }; <del>// sources = new Object; <del>// //TODO - refactor processSourceRow to use generic row or similar? <del>// parseEntity("", '2. Source List', 3, 0, sources, processSourceRow, "Source", 0, Source, "source_name", makeNewSource, callback); <del>// } <del>// <del>// } <del>// <del>// function parseCompanyGroups(result, callback) { <del>// company_groups = new Object; <del>// parseEntity(result, '6. Companies and Groups', 3, 0, company_groups, processCompanyRow, "CompanyGroup", 7, CompanyGroup, "company_group_name", makeNewCompanyGroup, callback); <del>// } <del>// <del>// function parseCompanies(result, callback) { <del>// companies = new Object; <del>// parseEntity(result, '6. Companies and Groups', 3, 0, companies, processCompanyRow, "Company", 3, Company, "company_name", makeNewCompany, callback); <del>// } <del>// <del>// //TODO: make more generic, entity names etc. <del>// function createSiteProjectLink (siteId, projectId, report, lcallback) { <del>// Link.create({project: projectId, site: siteId, entities: ['project', 'site']}, <del>// function (err, nlmodel) { <del>// if (err) { <del>// report.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <del>// return lcallback(`Failed: ${report.report}`); <del>// } <del>// else { <del>// report.add(`Linked site to project in the DB.\n`); <del>// return lcallback(null); //Final step, no return value <del>// } <del>// } <del>// ); <del>// } <del>// <del>// function parseProjects(result, callback) { <del>// var processProjectRow = function(projectsReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { <del>// if ((row[rowIndex] == "") || (row[1] == "#project")) { <del>// projectsReport.add("Projects: Empty row or label.\n"); <del>// return callback(null); //Do nothing <del>// } <del>// <del>// function updateOrCreateProject(projDoc, wcallback) { <del>// var doc_id = null; <del>// <del>// if (!projDoc) { <del>// projDoc = makeNewProject(row); <del>// } <del>// else { <del>// doc_id = projDoc._id; <del>// projDoc = projDoc.toObject(); <del>// delete projDoc._id; //Don't send id back in to Mongo <del>// delete projDoc.__v; //https://github.com/Automattic/mongoose/issues/1933 <del>// } <del>// <del>// final_doc = updateProjectFacts(projDoc, row, projectsReport); <del>// <del>// if (!final_doc) { <del>// projectsReport.add(`Invalid data in row: ${row}. Aborting.\n`); <del>// return wcallback(`Failed: ${projectsReport.report}`); <del>// } <del>// <del>// //console.log("Sent:\n" + util.inspect(final_doc)); <del>// <del>// if (!doc_id) doc_id = new ObjectId; <del>// Project.findByIdAndUpdate( <del>// doc_id, <del>// final_doc, <del>// {setDefaultsOnInsert: true, upsert: true, new: true}, <del>// function(err, model) { <del>// if (err) { <del>// //console.log(err); <del>// projectsReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <del>// return wcallback(`Failed: ${projectsReport.report}`); <del>// } <del>// //console.log("Returned\n: " + model) <del>// projectsReport.add(`Added or updated project ${row[rowIndex]} to the DB.\n`); <del>// projects[row[rowIndex]] = model; <del>// return wcallback(null, model); //Continue to site stuff <del>// } <del>// ); <del>// } <del>// <del>// function createSiteAndLink(projDoc, wcallback) { <del>// if (row[2] != "") { <del>// Site.findOne( <del>// {$or: [ <del>// {site_name: row[2]}, <del>// {"site_aliases.alias": row[2]} //TODO: FIX POPULATE ETC.? <del>// ]}, <del>// function (err, sitemodel) { <del>// if (err) { <del>// projectsReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <del>// return wcallback(`Failed: ${projectsReport.report}`); <del>// } <del>// else if (sitemodel) { <del>// //Site already exists - check for link, could be missing if site is from another project <del>// var found = false; <del>// Link.find({project: projDoc._id, site: sitemodel._id}, <del>// function (err, sitelinkmodel) { <del>// if (err) { <del>// projectsReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <del>// return wcallback(`Failed: ${projectsReport.report}`); <del>// } <del>// else if (sitelinkmodel) { <del>// projectsReport.add(`Link to ${row[2]} already exists in the DB, not adding\n`); <del>// return wcallback(null); <del>// } <del>// else { <del>// createSiteProjectLink(sitemodel._id, projDoc._id, projectsReport, wcallback); <del>// } <del>// } <del>// ); <del>// } <del>// else { //Site doesn't exist - create and link <del>// Site.create( <del>// makeNewSite(row), <del>// function (err, newsitemodel) { <del>// if (err) { <del>// projectsReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <del>// return wcallback(`Failed: ${projectsReport.report}`); <del>// } <del>// else { <del>// createSiteProjectLink(newsitemodel._id, projDoc._id, projectsReport, wcallback); <del>// } <del>// } <del>// ); <del>// } <del>// } <del>// ); <del>// } <del>// else { //Nothing more to do <del>// projectsReport.add(`No site info in row\n`); <del>// return wcallback(null); <del>// } <del>// } <del>// <del>// //Projects - check against name and aliases <del>// //TODO - may need some sort of sophisticated duplicate detection here <del>// Project.findOne( <del>// {$or: [ <del>// {proj_name: row[rowIndex]}, <del>// {"proj_aliases.alias": row[rowIndex]} //TODO: FIX POPULATE ETC.? <del>// ]}, <del>// function(err, doc) { <del>// //console.log(doc); <del>// if (err) { <del>// projectsReport.add(`Encountered an error (${err}) while querying the DB. Aborting.\n`); <del>// return callback(`Failed: ${projectsReport.report}`); <del>// } <del>// else if (doc) { //Project already exists, row might represent a new site <del>// projectsReport.add(`Project ${row[rowIndex]} already exists in the DB (name or alias match), not adding but updating facts and checking for new sites\n`); <del>// projects[row[rowIndex]] = doc; //Basis data is always the same, OK if this gets called multiple times <del>// async.waterfall( //Waterfall because we want to be able to cope with a result or error being returned <del>// [updateOrCreateProject.bind(null, doc), <del>// createSiteAndLink], //Gets proj. id passed as result <del>// function (err, result) { <del>// if (err) { <del>// return callback(`Failed: ${projectsReport.report}`); <del>// } <del>// else { <del>// //All done <del>// return callback(null); <del>// } <del>// } <del>// ); <del>// } <del>// else { <del>// projectsReport.add(`Project ${row[rowIndex]} not found, creating.\n`); <del>// async.waterfall( //Waterfall because we want to be able to cope with a result or error being returned <del>// [updateOrCreateProject.bind(null, null), //Proj = null = create it please <del>// createSiteAndLink], //Gets proj. id passed as result <del>// function (err, result) { <del>// if (err) { <del>// return callback(`Failed: ${projectsReport.report}`); <del>// } <del>// else { <del>// //All done <del>// return callback(null); <del>// } <del>// } <del>// ); <del>// } <del>// } <del>// ); <del>// }; <del>// projects = new Object; <del>// parseEntity(result, '5. Project location, status, commodity', 3, 0, projects, processProjectRow, "Project", 1, Project, "proj_name", makeNewProject, callback); <del>// } <del>// <del>// function parseConcessionsAndContracts(result, callback) { <del>// //First linked companies <del>// var processCandCRowCompanies = function(row, callback) { <del>// var compReport = ""; <del>// if (row[2] != "") { <del>// if (!companies[row[2]] || !projects[row[1]] || !sources[row[0]] ) { <del>// compReport += (`Invalid data in row: ${row}. Aborting.\n`); <del>// return callback(`Failed: ${compReport}`); <del>// } <del>// Link.findOne( <del>// { <del>// company: companies[row[2]]._id, <del>// project: projects[row[1]]._id <del>// }, <del>// function(err, doc) { <del>// if (err) { <del>// compReport += (`Encountered an error (${err}) while querying the DB. Aborting.\n`); <del>// return callback(`Failed: ${compReport}`); <del>// } <del>// else if (doc) { <del>// compReport += (`Company ${row[2]} is already linked with project ${row[1]}, not adding\n`); <del>// return callback(null, compReport); <del>// } <del>// else { <del>// var newCompanyLink = { <del>// company: companies[row[2]]._id, <del>// project: projects[row[1]]._id, <del>// source: sources[row[0]]._id, <del>// entities:['company','project'] <del>// }; <del>// Link.create( <del>// newCompanyLink, <del>// function(err, model) { <del>// if (err) { <del>// compReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); <del>// return callback(`Failed: ${compReport}`); <del>// } <del>// compReport += (`Linked company ${row[2]} with project ${row[1]} in the DB.\n`); <del>// return callback(null, compReport); <del>// } <del>// ); <del>// } <del>// } <del>// ); <del>// } <del>// else return callback(null, "No company found in row\n"); <del>// }; <del>// //Linked contracts - all based on ID (for API look up) <del>// var processCandCRowContracts = function(row, callback) { <del>// var contReport = ""; <del>// if (row[7] != "") { <del>// Contract.findOne({ <del>// contract_id: row[7] <del>// }, <del>// function(err, doc) { <del>// if (err) { <del>// contReport += (`Encountered an error (${err}) while querying the DB. Aborting.\n`); <del>// return callback(`Failed: ${contReport}`); <del>// } <del>// else if (doc) { //Found contract, now see if its linked <del>// contReport += (`Contract ${row[7]} exists, checking for link\n`); <del>// Link.findOne( <del>// { <del>// contract: doc._id, <del>// project: projects[row[1]]._id <del>// }, <del>// function(err, ldoc) { <del>// if (err) { <del>// contReport += (`Encountered an error (${err}) while querying the DB. Aborting.\n`); <del>// return callback(`Failed: ${contReport}`); <del>// } <del>// else if (ldoc) { <del>// contReport += (`Contract ${row[7]} is already linked with project ${row[1]}, not adding\n`); <del>// return callback(null, contReport); <del>// } <del>// else { <del>// var newContractLink = { <del>// contract: doc._id, <del>// project: projects[row[1]]._id, <del>// source: sources[row[0]]._id, <del>// entities:['contract','project'] <del>// }; <del>// Link.create( <del>// newContractLink, <del>// function(err, model) { <del>// if (err) { <del>// contReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); <del>// return callback(`Failed: ${contReport}`); <del>// } <del>// contReport += (`Linked contract ${row[7]} with project ${row[1]} in the DB.\n`); <del>// return callback(null, contReport); <del>// } <del>// ); <del>// } <del>// }); <del>// } <del>// else { //No contract, create and link <del>// var newContract = { <del>// contract_id: row[7] <del>// }; <del>// Contract.create( <del>// newContract, <del>// function(err, cmodel) { <del>// if (err) { <del>// contReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); <del>// return callback(`Failed: ${contReport}`); <del>// } <del>// contReport += (`Created contract ${row[7]}.\n`); <del>// //Now create Link <del>// var newContractLink = { <del>// contract: cmodel._id, <del>// project: projects[row[1]]._id, <del>// source: sources[row[0]]._id, <del>// entities:['contract','project'] <del>// }; <del>// Link.create( <del>// newContractLink, <del>// function(err, model) { <del>// if (err) { <del>// contReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); <del>// return callback(`Failed: ${contReport}`); <del>// } <del>// contReport += (`Linked contract ${row[7]} with project ${row[1]} in the DB.\n`); <del>// return callback(null, contReport); <del>// } <del>// ); <del>// } <del>// ); <del>// } <del>// } <del>// ); <del>// } <del>// else return callback(null, "No contract found in row\n"); <del>// }; <del>// //Then linked concessions <del>// var processCandCRowConcessions = function(row, callback) { <del>// var concReport = ""; <del>// if (row[8] != "") { <del>// Concession.findOne( <del>// {$or: [ <del>// {concession_name: row[8]}, <del>// {"concession_aliases.alias": row[8]} //TODO, alias population <del>// ] <del>// }, <del>// function(err, doc) { <del>// if (err) { <del>// concReport += (`Encountered an error (${err}) while querying the DB. Aborting.\n`); <del>// return callback(`Failed: ${concReport}`); <del>// } <del>// else if (doc) { //Found concession, now see if its linked <del>// concReport += (`Contract ${row[8]} exists, checking for link\n`); <del>// Link.findOne( <del>// { <del>// concession: doc._id, <del>// project: projects[row[1]]._id <del>// }, <del>// function(err, ldoc) { <del>// if (err) { <del>// concReport += (`Encountered an error (${err}) while querying the DB. Aborting.\n`); <del>// return callback(`Failed: ${concReport}`); <del>// } <del>// else if (ldoc) { <del>// concReport += (`Concession ${row[8]} is already linked with project ${row[1]}, not adding\n`); <del>// return callback(null, concReport); <del>// } <del>// else { <del>// var newConcessionLink = { <del>// concession: doc._id, <del>// project: projects[row[1]]._id, <del>// source: sources[row[0]]._id, <del>// entities:['concession','project'] <del>// }; <del>// Link.create( <del>// newConcessionLink, <del>// function(err, model) { <del>// if (err) { <del>// concReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); <del>// return callback(`Failed: ${concReport}`); <del>// } <del>// concReport += (`Linked concession ${row[8]} with project ${row[1]} in the DB.\n`); <del>// return callback(null, concReport); <del>// } <del>// ); <del>// } <del>// }); <del>// } <del>// else { //No concession, create and link <del>// var newConcession = { <del>// concession_name: row[8], <del>// concession_established_source: sources[row[0]]._id <del>// }; <del>// if (row[10] != "") { <del>// newConcession.concession_country = {country: countries[row[10]]._id, source: sources[row[0]]._id} <del>// } <del>// Concession.create( <del>// newConcession, <del>// function(err, cmodel) { <del>// if (err) { <del>// concReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); <del>// return callback(`Failed: ${concReport}`); <del>// } <del>// concReport += (`Created concession ${row[8]}.\n`); <del>// //Now create Link <del>// var newConcessionLink = { <del>// concession: cmodel._id, <del>// project: projects[row[1]]._id, <del>// source: sources[row[0]]._id, <del>// entities:['concession','project'] <del>// }; <del>// Link.create( <del>// newConcessionLink, <del>// function(err, model) { <del>// if (err) { <del>// concReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); <del>// return callback(`Failed: ${concReport}`); <del>// } <del>// concReport += (`Linked concession ${row[8]} with project ${row[1]} in the DB.\n`); <del>// return callback(null, concReport); <del>// } <del>// ); <del>// } <del>// ); <del>// } <del>// } <del>// ); <del>// } <del>// else return callback(null, "No concession found in row\n"); <del>// }; <del>// <del>// var processCandCRow = function(candcReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { <del>// if ((row[0] == "#source") || ((row[2] == "") && (row[7] == "") && (row[8] == ""))) { <del>// candcReport.add("Concessions and Contracts: Empty row or label.\n"); <del>// return callback(null); //Do nothing <del>// } <del>// if (!sources[row[0]] ) { <del>// candcReport.add(`Invalid source in row: ${row}. Aborting.\n`); <del>// return callback(`Failed: ${candcReport.report}`); <del>// } <del>// async.parallel([ <del>// processCandCRowCompanies.bind(null, row), <del>// processCandCRowContracts.bind(null, row), <del>// processCandCRowConcessions.bind(null, row) <del>// ], <del>// function (err, resultsarray) { <del>// for (var r=0; r<resultsarray.length; r++) { <del>// if (!resultsarray[r]) { <del>// candcReport.add("** NO RESULT **\n"); <del>// } <del>// else candcReport.add(resultsarray[r]); <del>// } <del>// if (err) { <del>// candcReport.add(`Processing of company/contract/concessions caused an error: ${err}\n`); <del>// return callback(`Processing of company/contract/concession caused an error: ${err}\n`, candcReport.report); <del>// } <del>// return callback(null); <del>// } <del>// ); <del>// } <del>// parseEntity(result, '7. Contracts, concessions and companies', 4, 0, null, processCandCRow, null, null, null, null, null, callback); <del>// } <del>// <del>// //TODO: This is definitely a candidate for bringing into genericrow with custom query <del>// function parseProduction(result, callback) { <del>// var processProductionRow = function(prodReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { <del>// //This serves 2 purposes, check for blank rows and skip rows with no value <del>// if ((row[6] == "") || (row[0] == "#source")) { <del>// prodReport.add("Productions: Empty row or label, or no volume data.\n"); <del>// return callback(null); //Do nothing <del>// } <del>// //TODO: Currently hard req. for project. Country and Company seem to be optional and unused. <del>// //thereby data can only be grabbed via project therefore req. project! <del>// if (/*(row[2] == "") || !countries[row[2]] || */(row[3] == "") || !sources[row[0]] || (row[8] == "") || !commodities[row[8]] || (row[5] == "") ) { <del>// prodReport += (`Invalid or missing data in row: ${row}. Aborting.\n`); <del>// return callback(`Failed: ${prodReport}`); <del>// } <del>// //Here we depend on links, use controller <del>// <del>// //Production - match (ideally) by (country???) + project (if present???) + year + commodity <del>// //BUT (TODO) there is currently no easy way of grabbing country & project <del>// Production.findOne( <del>// { <del>// production_commodity: commodities[row[8]]._id, <del>// production_year: parseInt(row[5]), <del>// }, <del>// function(err, doc) { <del>// if (err) { <del>// prodReport.add(`Encountered an error (${err}) while querying the DB. Aborting.\n`); <del>// return callback(`Failed: ${prodReport.report}`); <del>// } <del>// else if (doc) { <del>// prodReport.add(`Production ${row[3]}/${row[8]}/${row[5]} already exists in the DB, not adding\n`); <del>// return callback(null); <del>// } <del>// else { <del>// var newProduction = makeNewProduction(row); <del>// Production.create( <del>// newProduction, <del>// function(err, model) { <del>// if (err) { <del>// prodReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <del>// return callback(`Failed: ${prodReport.report}`); <del>// } <del>// //TODO: Link Production<->Project, (Production<->Country ???) <del>// //As productions can only exist with a project (TODO: check), go ahead and create the link <del>// Link.create( <del>// {project: projects[row[3]]._id, production: model._id, entities: ['project', 'production']}, <del>// function name(err, lmodel) { <del>// if (err) { <del>// prodReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <del>// return callback(`Failed: ${prodReport.report}`); <del>// } <del>// else { <del>// prodReport.add(`Added production ${row[3]}/${row[8]}/${row[5]} to the DB and linked to project.\n`); <del>// return callback(null); <del>// } <del>// } <del>// ); <del>// } <del>// ); <del>// } <del>// } <del>// ); <del>// }; <del>// parseEntity(result, '8. Production', 3, 0, null, processProductionRow, null, null, null, null, null, callback); <del>// } <del>// <del>// function parseTransfers(result, callback) { <del>// var processTransferRow = function(transReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { <del>// //This serves 2 purposes, check for blank row${util.inspect(query)s and skip rows with no value <del>// if (((row[21] == "") && (row[9] == "")) || (row[0] == "#source")) { <del>// transReport.add("Transfers: Empty row or label, or no volume data.\n"); <del>// return callback(null); //Do nothing <del>// } <del>// //This, in turn is a little harsh to abort of payment type is missing, but it does make for an invalid row <del>// if ((row[5] == "") || !projects[row[5]] || !sources[row[0]] || !countries[row[2]] || (row[17] == "") ) { <del>// transReport += (`Invalid or missing data in row: ${row}. Aborting.\n`); <del>// return callback(`Failed: ${transReport}`); <del>// } <del>// //Transfer - many possible ways to match <del>// //Determine if payment or receipt <del>// var transfer_audit_type = ""; <del>// if (row[21] != "") { <del>// transfer_audit_type = "government_receipt" <del>// transfer_type = "receipt"; <del>// } <del>// else if (row[9] != "") { <del>// transfer_audit_type = "company_payment"; <del>// transfer_type = "payment"; <del>// } <del>// else returnInvalid(); <del>// <del>// //TODO: How to match without projects in the transfers any more? <del>// var query = {transfer_country: countries[row[2]]._id, transfer_audit_type: transfer_audit_type}; <del>// if (row[5] != "") { <del>// //query.transfer_project = projects[row[5]]._id; <del>// query.transfer_level = "project"; <del>// } <del>// else query.transfer_level = "country"; <del>// <del>// if (row[3] != "") { <del>// query.transfer_company = companies[row[3]]._id; <del>// } <del>// <del>// if (transfer_type == "payment") { <del>// query.transfer_year = parseInt(row[6]); <del>// query.transfer_type = row[8]; <del>// } <del>// else { <del>// query.transfer_year = parseInt(row[13]); <del>// query.transfer_type = row[17]; <del>// if (row[15] != "") { <del>// query.transfer_gov_entity = row[15]; <del>// } <del>// if (row[16] != "") { <del>// query.transfer_gov_entity_id = row[16]; <del>// } <del>// } <del>// <del>// Transfer.findOne( <del>// query, <del>// function(err, doc) { <del>// if (err) { <del>// transReport.add(`Encountered an error (${err}) while querying the DB. Aborting.\n`); <del>// return callback(`Failed: ${transReport.report}`); <del>// } <del>// else if (doc) { <del>// transReport.add(`Transfer (${util.inspect(query)}) already exists in the DB, not adding\n`); <del>// return callback(null); <del>// } <del>// else { <del>// var newTransfer = makeNewTransfer(row, transfer_audit_type); <del>// if (!newTransfer) { <del>// transReport += (`Invalid or missing data in row: ${row}. Aborting.\n`); <del>// return callback(`Failed: ${transReport}`); <del>// } <del>// Transfer.create( <del>// newTransfer, <del>// function(err, model) { <del>// if (err) { <del>// transReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <del>// return callback(`Failed: ${transReport.report}`); <del>// } <del>// //TODO: Link Transfer<->Project, (Transfer<->Company ???) <del>// //Can't find the transfer without a project (if there is one), so go ahead and create it without checks <del>// if (row[5] != "") { <del>// Link.create( <del>// {project: projects[row[5]]._id, transfer: model._id, entities: ['project', 'transfer']}, <del>// function name(err, lmodel) { <del>// if (err) { <del>// transReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <del>// return callback(`Failed: ${transReport.report}`); <del>// } <del>// else { <del>// transReport.add(`Added transfer (${util.inspect(query)}) with project link to the DB.\n`); <del>// return callback(null); <del>// } <del>// } <del>// ); <del>// } <del>// else { <del>// transReport.add(`Added transfer (${util.inspect(query)}) to the DB without project link.\n`); <del>// return callback(null); <del>// } <del>// } <del>// ); <del>// } <del>// } <del>// ); <del>// }; <del>// parseEntity(result, '10. Payments and receipts', 3, 0, null, processTransferRow, null, null, null, null, null, callback); <del>// } <del>// <del>// function parseReserves(result, callback) { <del>// result += "Reserves IGNORED\n"; <del>// callback(null, result); <del>// } <del>//} <add>var Source = require('mongoose').model('Source'), <add> Country = require('mongoose').model('Country'), <add> Commodity = require('mongoose').model('Commodity'), <add> CompanyGroup = require('mongoose').model('CompanyGroup'), <add> Company = require('mongoose').model('Company'), <add> Project = require('mongoose').model('Project'), <add> Site = require('mongoose').model('Site'), <add> Link = require('mongoose').model('Link'), <add> Contract = require('mongoose').model('Contract'), <add> Concession = require('mongoose').model('Concession'), <add> Production = require('mongoose').model('Production'), <add> Transfer = require('mongoose').model('Transfer'), <add> ObjectId = require('mongoose').Types.ObjectId, <add> util = require('util'), <add> async = require('async'), <add> csv = require('csv'), <add> request = require('request'), <add> moment = require('moment'); <add> <add>exports.processData = function(link, callback) { <add> var report = ""; <add> var keytoend = link.substr(link.indexOf("/d/") + 3, link.length); <add> var key = keytoend.substr(0, keytoend.indexOf("/")); <add> report += `Using link ${link}\n`; <add> if (key.length != 44) { <add> report += "Could not detect a valid spreadsheet key in URL\n"; <add> callback("Failed", report); <add> return; <add> } <add> else { <add> report += `Using GS key ${key}\n`; <add> } <add> var feedurl = `https://spreadsheets.google.com/feeds/worksheets/${key}/public/full?alt=json`; <add> var sheets = new Object; <add> <add> request({ <add> url: feedurl, <add> json: true <add> }, function (error, response, body) { <add> if (!error && response.statusCode === 200) { <add> var numSheets = body.feed.entry.length; <add> var mainTitle = body.feed.title.$t; <add> var numProcessed = 0; <add> for (var i=0; i<body.feed.entry.length; i++) { <add> for (var j=0; j<body.feed.entry[i].link.length; j++) { <add> if (body.feed.entry[i].link[j].type == "text/csv") { <add> report += `Getting data from sheet "${body.feed.entry[i].title.$t}"...\n`; <add> request({ <add> url: body.feed.entry[i].link[j].href <add> }, (function (i, error, response, sbody) { <add> if (error) { <add> report += `${body.feed.entry[i].title.$t}: Could not retrieve sheet\n`; <add> callback("Failed", report); <add> return; <add> } <add> csv.parse(sbody, {trim: true}, function(err, rowdata){ <add> if (error) { <add> report += `${skey}: Could not parse sheet\n`; <add> callback("Failed", report); <add> return; <add> } <add> var item = new Object; <add> var cd = response.headers['content-disposition']; <add> <add> item.title = body.feed.entry[i].title.$t; <add> item.link = response.request.uri.href; <add> item.data = rowdata; <add> report += `${item.title}: Stored ${rowdata.length} rows\n`; <add> sheets[item.title] = item; <add> numProcessed++; <add> if (numProcessed == numSheets) { <add> parseData(sheets, report, callback); <add> } <add> }); <add> }).bind(null, i)); <add> } <add> } <add> } <add> } <add> else { <add> report += "Could not get information from GSheets feed - is the sheet shared?\n" <add> callback("Failed", report); <add> return; <add> } <add> }); <add>} <add> <add>function parseGsDate(input) { <add> /* In general format should appear as DD/MM/YYYY or empty but sometimes GS has it as a date internally */ <add> var result; <add> if (!input || input == "") return null; <add> else result = moment(input, "DD/MM/YYYY").format(); <add> //Hope for the best <add> if (result == "Invalid date") return input; <add> else return result; <add>} <add> <add>//Data needed for inter-entity reference <add>var sources, countries, commodities, companies, projects; <add> <add>var makeNewSource = function(flagDuplicate, newRow, duplicateId) { <add> newRow[7] = parseGsDate(newRow[7]); <add> newRow[8] = parseGsDate(newRow[8]); <add> <add> var source = { <add> source_name: newRow[0], <add> source_type: newRow[2], //TODO: unnecessary? <add> /* TODO? source_type_id: String, */ <add> source_url: newRow[4], <add> source_url_type: newRow[5], //TODO: unnecessary? <add> /* TODO? source_url_type_id: String, */ <add> source_archive_url: newRow[6], <add> source_notes: newRow[9], <add> source_date: newRow[7], <add> retrieve_date: newRow[8] <add> /* TODO create_author:, */ <add> } <add> if (flagDuplicate) { <add> source.possible_duplicate = true; <add> source.duplicate = duplicateId <add> } <add> return source; <add>} <add> <add>var makeNewCommodity = function(newRow) { <add> var commodity = { <add> commodity_name: newRow[9], <add> commodity_type: newRow[8].toLowerCase().replace(/ /g, "_") <add> } <add> return commodity; <add>} <add> <add>var makeNewCompanyGroup = function(newRow) { <add> var returnObj = {obj: null, link: null}; <add> var companyg = { <add> company_group_name: newRow[7] <add> }; <add> <add> if (newRow[0] != "") { <add> if (sources[newRow[0]]) { //Must be here due to lookups in sheet <add> companyg.company_group_record_established = sources[newRow[0]]._id; <add> } <add> else return false; //error <add> } <add> returnObj.obj = companyg; <add> //console.log("new company group: " + util.inspect(returnObj)); <add> return returnObj; <add>} <add> <add>var makeNewCompany = function(newRow) { <add> var returnObj = {obj: null, link: null}; <add> var company = { <add> company_name: newRow[3] <add> }; <add> <add> if (newRow[5] != "") { <add> company.open_corporates_id = newRow[5]; <add> } <add> if (newRow[2] != "") { <add> //TODO: This is not very helpful for the end user <add> if (!countries[newRow[2]]) { <add> console.log("SERIOUS ERROR: Missing country in the DB"); <add> return false; <add> } <add> company.country_of_incorporation = [{country: countries[newRow[2]]._id}]; //Fact <add> } <add> if (newRow[6] != "") { <add> company.company_website = {string: newRow[6]}; //Fact, will have comp. id added later <add> } <add> if (newRow[0] != "") { <add> if (sources[newRow[0]]) { //Must be here due to lookups in sheet <add> company.company_established_source = sources[newRow[0]]._id; <add> } <add> else return false; //error <add> } <add> <add> if (newRow[7] != "") { <add> //TODO: Also should check aliases in each object <add> returnObj.link = {company_group: company_groups[newRow[8]]._id}; <add> } <add> <add> returnObj.obj = company; <add> return returnObj; <add>} <add> <add>var makeNewProject = function(newRow) { <add> var project = { <add> proj_name: newRow[1], <add> }; <add> return project; <add>} <add> <add>var updateProjectFacts = function(doc, row, report) <add>{ <add> var fact; <add> //Update status and commodity <add> if (row[9] != "") { <add> var notfound = true; <add> if (doc.proj_commodity) { <add> for (fact of doc.proj_commodity) { <add> //No need to check if commodity exists as commodities are taken from here <add> //TODO: In general, do we want to store multiple sources for the same truth? [from GS] <add> if (commodities[row[9]]._id == fact.commodity._id) { <add> notfound = false; <add> report.add(`Project commodity ${row[9]} already exists in project, not adding\n`); <add> break; <add> } <add> } <add> } <add> else doc.proj_commodity = []; <add> if (notfound) { //Commodity must be here, as based on this sheet <add> //Don't push but add, existing values will not be removed <add> doc.proj_commodity = [{commodity: commodities[row[9]]._id, source: sources[row[0]]._id}]; <add> report.add(`Project commodity ${row[9]} added to project\n`); <add> } <add> } <add> else if (doc.proj_commodity) delete doc.proj_commodity; //Don't push <add> <add> if (row[10] != "") { <add> var notfound = true; <add> if (doc.proj_status) { <add> for (fact of doc.proj_status) { <add> if (row[10] == fact.string) { <add> notfound = false; <add> report.add(`Project status ${row[10]} already exists in project, not adding\n`); <add> break; <add> } <add> } <add> } <add> else doc.proj_status = []; <add> if (notfound) { <add> //Don't push but add, existing values will not be removed <add> doc.proj_status = [{string: row[10].toLowerCase(), date: parseGsDate(row[11]), source: sources[row[0]]._id}]; <add> report.add(`Project status ${row[10]} added to project\n`); <add> } <add> } <add> else if (doc.proj_status) delete doc.proj_status; //Don't push <add> <add> //TODO... projects with mulitple countries, really? <add> if (row[5] != "") { <add> var notfound = true; <add> if (doc.proj_country) { //TODO: project without a country??? <add> for (fact of doc.proj_country) { <add> if (countries[row[5]]._id == fact.country._id) { <add> notfound = false; <add> report.add(`Project country ${row[5]} already exists in project, not adding\n`); <add> break; <add> } <add> } <add> } <add> else doc.proj_country = []; <add> if (notfound) { <add> //Don't push but add, existing values will not be removed <add> doc.proj_country = [{country: countries[row[5]]._id, source: sources[row[0]]._id}]; <add> report.add(`Project country ${row[5]} added to project\n`); <add> } <add> } <add> else if (doc.proj_country) delete doc.proj_country; //Don't push <add> return doc; <add>} <add> <add>var makeNewSite = function(newRow) { <add> var site = { <add> site_name: newRow[2], <add> site_established_source: sources[newRow[0]]._id, <add> site_country: [{country: countries[newRow[5]]._id, source: sources[newRow[0]]._id}] //TODO: How in the world can there multiple versions of country <add> } <add> if (newRow[3] != "") site.site_address = [{string: newRow[3], source: sources[newRow[0]]._id}]; <add> //TODO FIELD INFO field: Boolean // <add> if (newRow[6] != "") site.site_coordinates = [{loc: [parseFloat(newRow[6]), parseFloat(newRow[7])], source: sources[newRow[0]]._id}]; <add> return site; <add>} <add> <add>var makeNewProduction = function(newRow) { <add> var production = { <add> production_commodity: commodities[newRow[8]]._id, <add> production_year: parseInt(newRow[5]), <add> //production_project: projects[newRow[3]]._id, <add> source: sources[newRow[0]]._id <add> } <add> <add> if (newRow[7] != "") { <add> production.production_unit = newRow[7]; <add> } <add> if (newRow[6] != "") { <add> production.production_volume = newRow[6].replace(/,/g, ""); <add> } <add> if (newRow[9] != "") { <add> production.production_price = newRow[9].replace(/,/g, ""); <add> } <add> if (newRow[10] != "") { <add> production.production_price_per_unit = newRow[10]; <add> } <add> <add> return production; <add>} <add> <add>var makeNewTransfer = function(newRow, transfer_audit_type) { <add> //TODO: This is not very helpful for the end user <add> if (!countries[newRow[2]]) { <add> console.log("SERIOUS ERROR: Missing country in the DB"); <add> return false; <add> } <add> <add> var transfer = { <add> source: sources[newRow[0]]._id, <add> transfer_country: countries[newRow[2]]._id, <add> transfer_audit_type: transfer_audit_type <add> }; <add> <add> if (newRow[3] != "") { <add> transfer.transfer_company = companies[newRow[3]]._id; <add> } <add> <add> if (newRow[4] != "") { <add> transfer.transfer_line_item = newRow[4]; <add> } <add> <add> if (newRow[5] != "") { <add> transfer.transfer_level = "project"; <add> //transfer.transfer_project = projects[newRow[5]]._id; <add> } <add> else { <add> transfer.transfer_level = "country"; <add> } <add> <add> if (transfer_audit_type == "government_receipt") { <add> transfer.transfer_year = parseInt(newRow[13]); <add> transfer.transfer_type = newRow[17]; <add> transfer.transfer_unit = newRow[19]; <add> transfer.transfer_value = newRow[21].replace(/,/g, ""); <add> if (newRow[20] != "") transfer.transfer_accounting_basis = newRow[20]; <add> if (newRow[15] != "") transfer.transfer_gov_entity = newRow[15]; <add> if (newRow[16] != "") transfer.transfer_gov_entity_id = newRow[16]; <add> } <add> else if (transfer_audit_type == "company_payment") { <add> transfer.transfer_audit_type = "company_payment"; <add> transfer.transfer_year = parseInt(newRow[6]); <add> transfer.transfer_type = newRow[5]; <add> transfer.transfer_unit = newRow[7]; <add> transfer.transfer_value = newRow[9].replace(/,/g, ""); <add> if (newRow[8] != "") transfer.transfer_accounting_basis = newRow[8]; <add> } <add> else return false; <add> <add> return transfer; <add>} <add> <add>//TODO: This needs some more work, specifically which properties to compare <add>equalDocs = function(masterDoc, newDoc) { <add> for (property in newDoc) { <add> if (masterDoc[property]) { <add> if (newDoc[property] != masterDoc[property]) { <add> return false; <add> } <add> } <add> else return false; <add> } <add> return true; <add>} <add> <add>processGenericRow = function(report, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { <add> if ((row[rowIndex] == "") || (row[rowIndex][0] == "#")) { <add> report.add(entityName + ": Empty row or label.\n"); <add> return callback(null); //Do nothing <add> } <add> var finderObj = {}; <add> finderObj[modelKey] = row[rowIndex]; <add> model.findOne( <add> finderObj, <add> function(err, doc) { <add> if (err) { <add> report.add(`Encountered an error (${err}) while querying the DB. Aborting.\n`); <add> return callback(`Failed: ${report.report}`); <add> } <add> else if (doc) { <add> report.add(`${entityName} ${row[rowIndex]} already exists in the DB (name match), not adding\n`); <add> destObj[row[rowIndex]] = doc; <add> return callback(null); <add> } <add> else { <add> model.create( <add> makerFunction(row), <add> function(err, createdModel) { <add> if (err) { <add> report.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <add> return callback(`Failed: ${report.report}`); <add> } <add> report.add(`Added ${entityName} ${row[rowIndex]} to the DB.\n`); <add> destObj[row[rowIndex]] = createdModel; <add> return callback(null); <add> } <add> ); <add> } <add> } <add> ); <add> } <add> <add>//This handles companies and company groups <add>//Not the maker function returns an object with a sub-object <add>processCompanyRow = function(companiesReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { <add> if ((row[rowIndex] == "") || (row[rowIndex][0] == "#")) { <add> companiesReport.add(entityName + ": Empty row or label.\n"); <add> return callback(null); //Do nothing <add> } <add> //Check against name and aliases <add> //TODO - may need some sort of sophisticated duplicate detection here <add> var queryEntry1 = {}; <add> queryEntry1[modelKey] = row[rowIndex]; <add> var queryEntry2 = {}; <add> queryEntry2[modelKey+'_aliases.alias'] = row[rowIndex]; //TODO!!! Cannot be searched this way (no pre-population) <add> <add> model.findOne( <add> {$or: [ <add> queryEntry1, <add> queryEntry2 <add> ]}, <add> function(err, doc) { <add> var testAndCreateLink = function(skipTest, link, company_id) { <add> var createLink = function() { <add> link.entities = ['company', 'company_group']; <add> Link.create(link, function(err, nlmodel) { <add> if (err) { <add> companiesReport.add(`Encountered an error (${err}) adding link to DB. Aborting.\n`); <add> return callback(`Failed: ${companiesReport.report}`); <add> } <add> else { <add> companiesReport.add(`Created link\n`); <add> return callback(null); <add> } <add> }); <add> }; <add> if (!skipTest) { <add> link.company = company_id; <add> Link.findOne( <add> link, <add> function (err, lmodel) { <add> if (err) { <add> companiesReport.add(`Encountered an error (${err}) while querying DB. Aborting.\n`); <add> return callback(`Failed: ${companiesReport.report}`); <add> } <add> else if (lmodel) { <add> companiesReport.add(`Link already exists in the DB, not adding\n`); <add> return callback(null); <add> } <add> else { <add> createLink(); <add> } <add> } <add> ); <add> } <add> else createLink(); <add> } <add> if (err) { <add> companiesReport.add(`Encountered an error (${err}) while querying the DB. Aborting.\n`); <add> return callback(`Failed: ${companiesReport.report}`); <add> } <add> else if (doc) { <add> destObj[row[rowIndex]] = doc; <add> companiesReport.add(`${entityName} ${row[rowIndex]} already exists in the DB (name or alias match), not adding. Checking for link creation need.\n`); <add> var testObj = makerFunction(row); <add> if (testObj && testObj.link) { <add> testAndCreateLink(false, testObj.link, doc._id); <add> } <add> else { <add> companiesReport.add(`No link to make\n`); <add> return callback(null); <add> } <add> } <add> else { <add> var newObj = makerFunction(row); <add> if (!newObj) { <add> companiesReport.add(`Invalid data in row: ${row}. Aborting.\n`); <add> return callback(`Failed: ${companiesReport.report}`); <add> } <add> model.create( <add> newObj.obj, <add> function(err, cmodel) { <add> if (err) { <add> companiesReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <add> return callback(`Failed: ${companiesReport.report}`); <add> } <add> companiesReport.add(`Added ${entityName} ${row[rowIndex]} to the DB.\n`); <add> destObj[row[rowIndex]] = cmodel; <add> if (newObj.link) { <add> testAndCreateLink(true, newObj.link, cmodel._id); <add> } <add> else return callback(null); <add> } <add> ); <add> } <add> } <add> ); <add>}; <add> <add>function parseData(sheets, report, finalcallback) { <add> async.waterfall([ <add> parseBasis, <add> parseCompanyGroups, <add> parseCompanies, <add> parseProjects, <add> parseConcessionsAndContracts, <add> parseProduction, <add> parseTransfers, <add> parseReserves <add> ], function (err, report) { <add> if (err) { <add> console.log("PARSE: Got an error\n"); <add> return finalcallback("Failed", report) <add> } <add> finalcallback("Success", report); <add> } <add> ); <add> <add> ; <add> <add> function parseEntity(reportSoFar, sheetname, dropRowsStart, dropRowsEnd, entityObj, processRow, entityName, rowIndex, model, modelKey, rowMaker, callback) { <add> var intReport = { <add> report: reportSoFar, //Relevant for the series waterfall - report gets passed along <add> add: function(text) { <add> this.report += text; <add> } <add> } <add> //Drop first X, last Y rows <add> var data = sheets[sheetname].data.slice(dropRowsStart, (sheets[sheetname].data.length - dropRowsEnd)); <add> //TODO: for some cases parallel is OK: differentiate <add> async.eachSeries(data, processRow.bind(null, intReport, entityObj, entityName, rowIndex, model, modelKey, rowMaker), function (err) { //"A callback which is called when all iteratee functions have finished, or an error occurs." <add> if (err) { <add> return callback(err, intReport.report); //Giving up <add> } <add> callback(null, intReport.report); //All good <add> }); <add> } <add> <add> function parseBasis(callback) { <add> var basisReport = report + "Processing basis info\n"; <add> <add> async.parallel([ <add> parseSources, <add> parseCountries, <add> parseCommodities <add> ], (function (err, resultsarray) { <add> console.log("PARSE BASIS: Finished parallel tasks OR got an error"); <add> for (var r=0; r<resultsarray.length; r++) { <add> if (!resultsarray[r]) { <add> basisReport += "** NO RESULT **\n"; <add> } <add> else basisReport += resultsarray[r]; <add> } <add> if (err) { <add> console.log("PARSE BASIS: Got an error"); <add> basisReport += `Processing of basis info caused an error: ${err}\n`; <add> return callback(`Processing of basis info caused an error: ${err}\n`, basisReport); <add> } <add> console.log("Finished parse basis"); <add> callback(null, basisReport); <add> })); <add> <add> function parseCountries(callback) { <add> //Complete country list is in the DB <add> var creport = "Getting countries from database...\n"; <add> countries = new Object; <add> Country.find({}, function (err, cresult) { <add> if (err) { <add> creport += `Got an error: ${err}`; <add> callback(err, creport); <add> } <add> else { <add> creport += `Found ${cresult.length} countries`; <add> var ctry; <add> for (ctry of cresult) { <add> countries[ctry.iso2] = ctry; <add> } <add> callback(null, creport); <add> } <add> }); <add> } <add> <add> function parseCommodities(callback) { <add> //TODO: In some sheets only a group is named... <add> commodities = new Object; <add> //The list of commodities of relevance for this dataset is taken from the location/status/commodity list <add> parseEntity("", '5. Project location, status, commodity', 3, 0, commodities, processGenericRow, "Commodity", 9, Commodity, "commodity_name", makeNewCommodity, callback); <add> } <add> <add> function parseSources(callback) { <add> var processSourceRow = function(sourcesReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { <add> if ((row[0] == "") || (row[0] == "#source")) { <add> sourcesReport.add("Sources: Empty row or label.\n"); <add> return callback(null); //Do nothing <add> } <add> //TODO: Find OLDEST (use that for comparison instead of some other duplicate - important where we create duplicates) <add> //TODO - may need some sort of sophisticated duplicate detection here <add> Source.findOne( <add> {source_url: row[4].toLowerCase()}, <add> function(err, doc) { <add> if (err) { <add> sourcesReport.add(`Encountered an error while querying the DB: ${err}. Aborting.\n`); <add> return callback(`Failed: ${sourcesReport.report}`); <add> } <add> else if (doc) { <add> sourcesReport.add(`Source ${row[0]} already exists in the DB (url match), checking content\n`); <add> if (equalDocs(doc, makeNewSource(false, row))) { <add> sourcesReport.add(`Source ${row[0]} already exists in the DB (url match), not adding\n`); <add> sources[row[0]] = doc; <add> return callback(null); <add> } <add> else { <add> sourcesReport.add(`Source ${row[0]} already exists in the DB (url match),flagging as duplicate\n`); <add> Source.create( <add> makeNewSource(true, row, doc._id), <add> function(err, model) { <add> if (err) { <add> sourcesReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <add> return callback(`Failed: ${sourcesReport.report}`); <add> } <add> sources[row[0]] = model; <add> return callback(null); <add> } <add> ); <add> } <add> } <add> else { <add> Source.findOne( <add> {source_name: row[0]}, <add> (function(err, doc) { <add> if (err) { <add> sourcesReport.add(`Encountered an error while querying the DB: ${err}. Aborting.\n`); <add> return callback(`Failed: ${sourcesReport.report}`); <add> } <add> else if (doc) { <add> sourcesReport.add(`Source ${row[0]} already exists in the DB (name match), will flag as possible duplicate\n`); <add> Source.create( <add> makeNewSource(true, row, doc._id), <add> (function(err, model) { <add> if (err) { <add> sourcesReport.add(`Encountered an error while creating a source in the DB: ${err}. Aborting.\n`); <add> return callback(`Failed: ${sourcesReport.report}`); <add> } <add> sources[row[0]] = model; <add> return callback(null); <add> }) <add> ); <add> } <add> else { <add> sourcesReport.add(`Source ${row[0]} not found in the DB, creating\n`); <add> Source.create( <add> makeNewSource(false, row), <add> (function(err, model) { <add> if (err) { <add> sourcesReport.add(`Encountered an error while creating a source in the DB: ${err}. Aborting.\n`); <add> return callback(`Failed: ${sourcesReport.report}`); <add> } <add> sources[row[0]] = model; <add> return callback(null); <add> }) <add> ); <add> } <add> }) <add> ); <add> } <add> } <add> ); <add> }; <add> sources = new Object; <add> //TODO - refactor processSourceRow to use generic row or similar? <add> parseEntity("", '2. Source List', 3, 0, sources, processSourceRow, "Source", 0, Source, "source_name", makeNewSource, callback); <add> } <add> <add> } <add> <add> function parseCompanyGroups(result, callback) { <add> company_groups = new Object; <add> parseEntity(result, '6. Companies and Groups', 3, 0, company_groups, processCompanyRow, "CompanyGroup", 7, CompanyGroup, "company_group_name", makeNewCompanyGroup, callback); <add> } <add> <add> function parseCompanies(result, callback) { <add> companies = new Object; <add> parseEntity(result, '6. Companies and Groups', 3, 0, companies, processCompanyRow, "Company", 3, Company, "company_name", makeNewCompany, callback); <add> } <add> <add> //TODO: make more generic, entity names etc. <add> function createSiteProjectLink (siteId, projectId, report, lcallback) { <add> Link.create({project: projectId, site: siteId, entities: ['project', 'site']}, <add> function (err, nlmodel) { <add> if (err) { <add> report.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <add> return lcallback(`Failed: ${report.report}`); <add> } <add> else { <add> report.add(`Linked site to project in the DB.\n`); <add> return lcallback(null); //Final step, no return value <add> } <add> } <add> ); <add> } <add> <add> function parseProjects(result, callback) { <add> var processProjectRow = function(projectsReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { <add> if ((row[rowIndex] == "") || (row[1] == "#project")) { <add> projectsReport.add("Projects: Empty row or label.\n"); <add> return callback(null); //Do nothing <add> } <add> <add> function updateOrCreateProject(projDoc, wcallback) { <add> var doc_id = null; <add> <add> if (!projDoc) { <add> projDoc = makeNewProject(row); <add> } <add> else { <add> doc_id = projDoc._id; <add> projDoc = projDoc.toObject(); <add> delete projDoc._id; //Don't send id back in to Mongo <add> delete projDoc.__v; //https://github.com/Automattic/mongoose/issues/1933 <add> } <add> <add> final_doc = updateProjectFacts(projDoc, row, projectsReport); <add> <add> if (!final_doc) { <add> projectsReport.add(`Invalid data in row: ${row}. Aborting.\n`); <add> return wcallback(`Failed: ${projectsReport.report}`); <add> } <add> <add> //console.log("Sent:\n" + util.inspect(final_doc)); <add> <add> if (!doc_id) doc_id = new ObjectId; <add> Project.findByIdAndUpdate( <add> doc_id, <add> final_doc, <add> {setDefaultsOnInsert: true, upsert: true, new: true}, <add> function(err, model) { <add> if (err) { <add> //console.log(err); <add> projectsReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <add> return wcallback(`Failed: ${projectsReport.report}`); <add> } <add> //console.log("Returned\n: " + model) <add> projectsReport.add(`Added or updated project ${row[rowIndex]} to the DB.\n`); <add> projects[row[rowIndex]] = model; <add> return wcallback(null, model); //Continue to site stuff <add> } <add> ); <add> } <add> <add> function createSiteAndLink(projDoc, wcallback) { <add> if (row[2] != "") { <add> Site.findOne( <add> {$or: [ <add> {site_name: row[2]}, <add> {"site_aliases.alias": row[2]} //TODO: FIX POPULATE ETC.? <add> ]}, <add> function (err, sitemodel) { <add> if (err) { <add> projectsReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <add> return wcallback(`Failed: ${projectsReport.report}`); <add> } <add> else if (sitemodel) { <add> //Site already exists - check for link, could be missing if site is from another project <add> var found = false; <add> Link.find({project: projDoc._id, site: sitemodel._id}, <add> function (err, sitelinkmodel) { <add> if (err) { <add> projectsReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <add> return wcallback(`Failed: ${projectsReport.report}`); <add> } <add> else if (sitelinkmodel) { <add> projectsReport.add(`Link to ${row[2]} already exists in the DB, not adding\n`); <add> return wcallback(null); <add> } <add> else { <add> createSiteProjectLink(sitemodel._id, projDoc._id, projectsReport, wcallback); <add> } <add> } <add> ); <add> } <add> else { //Site doesn't exist - create and link <add> Site.create( <add> makeNewSite(row), <add> function (err, newsitemodel) { <add> if (err) { <add> projectsReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <add> return wcallback(`Failed: ${projectsReport.report}`); <add> } <add> else { <add> createSiteProjectLink(newsitemodel._id, projDoc._id, projectsReport, wcallback); <add> } <add> } <add> ); <add> } <add> } <add> ); <add> } <add> else { //Nothing more to do <add> projectsReport.add(`No site info in row\n`); <add> return wcallback(null); <add> } <add> } <add> <add> //Projects - check against name and aliases <add> //TODO - may need some sort of sophisticated duplicate detection here <add> Project.findOne( <add> {$or: [ <add> {proj_name: row[rowIndex]}, <add> {"proj_aliases.alias": row[rowIndex]} //TODO: FIX POPULATE ETC.? <add> ]}, <add> function(err, doc) { <add> //console.log(doc); <add> if (err) { <add> projectsReport.add(`Encountered an error (${err}) while querying the DB. Aborting.\n`); <add> return callback(`Failed: ${projectsReport.report}`); <add> } <add> else if (doc) { //Project already exists, row might represent a new site <add> projectsReport.add(`Project ${row[rowIndex]} already exists in the DB (name or alias match), not adding but updating facts and checking for new sites\n`); <add> projects[row[rowIndex]] = doc; //Basis data is always the same, OK if this gets called multiple times <add> async.waterfall( //Waterfall because we want to be able to cope with a result or error being returned <add> [updateOrCreateProject.bind(null, doc), <add> createSiteAndLink], //Gets proj. id passed as result <add> function (err, result) { <add> if (err) { <add> return callback(`Failed: ${projectsReport.report}`); <add> } <add> else { <add> //All done <add> return callback(null); <add> } <add> } <add> ); <add> } <add> else { <add> projectsReport.add(`Project ${row[rowIndex]} not found, creating.\n`); <add> async.waterfall( //Waterfall because we want to be able to cope with a result or error being returned <add> [updateOrCreateProject.bind(null, null), //Proj = null = create it please <add> createSiteAndLink], //Gets proj. id passed as result <add> function (err, result) { <add> if (err) { <add> return callback(`Failed: ${projectsReport.report}`); <add> } <add> else { <add> //All done <add> return callback(null); <add> } <add> } <add> ); <add> } <add> } <add> ); <add> }; <add> projects = new Object; <add> parseEntity(result, '5. Project location, status, commodity', 3, 0, projects, processProjectRow, "Project", 1, Project, "proj_name", makeNewProject, callback); <add> } <add> <add> function parseConcessionsAndContracts(result, callback) { <add> //First linked companies <add> var processCandCRowCompanies = function(row, callback) { <add> var compReport = ""; <add> if (row[2] != "") { <add> if (!companies[row[2]] || !projects[row[1]] || !sources[row[0]] ) { <add> compReport += (`Invalid data in row: ${row}. Aborting.\n`); <add> return callback(`Failed: ${compReport}`); <add> } <add> Link.findOne( <add> { <add> company: companies[row[2]]._id, <add> project: projects[row[1]]._id <add> }, <add> function(err, doc) { <add> if (err) { <add> compReport += (`Encountered an error (${err}) while querying the DB. Aborting.\n`); <add> return callback(`Failed: ${compReport}`); <add> } <add> else if (doc) { <add> compReport += (`Company ${row[2]} is already linked with project ${row[1]}, not adding\n`); <add> return callback(null, compReport); <add> } <add> else { <add> var newCompanyLink = { <add> company: companies[row[2]]._id, <add> project: projects[row[1]]._id, <add> source: sources[row[0]]._id, <add> entities:['company','project'] <add> }; <add> Link.create( <add> newCompanyLink, <add> function(err, model) { <add> if (err) { <add> compReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); <add> return callback(`Failed: ${compReport}`); <add> } <add> compReport += (`Linked company ${row[2]} with project ${row[1]} in the DB.\n`); <add> return callback(null, compReport); <add> } <add> ); <add> } <add> } <add> ); <add> } <add> else return callback(null, "No company found in row\n"); <add> }; <add> //Linked contracts - all based on ID (for API look up) <add> var processCandCRowContracts = function(row, callback) { <add> var contReport = ""; <add> if (row[7] != "") { <add> Contract.findOne({ <add> contract_id: row[7] <add> }, <add> function(err, doc) { <add> if (err) { <add> contReport += (`Encountered an error (${err}) while querying the DB. Aborting.\n`); <add> return callback(`Failed: ${contReport}`); <add> } <add> else if (doc) { //Found contract, now see if its linked <add> contReport += (`Contract ${row[7]} exists, checking for link\n`); <add> Link.findOne( <add> { <add> contract: doc._id, <add> project: projects[row[1]]._id <add> }, <add> function(err, ldoc) { <add> if (err) { <add> contReport += (`Encountered an error (${err}) while querying the DB. Aborting.\n`); <add> return callback(`Failed: ${contReport}`); <add> } <add> else if (ldoc) { <add> contReport += (`Contract ${row[7]} is already linked with project ${row[1]}, not adding\n`); <add> return callback(null, contReport); <add> } <add> else { <add> var newContractLink = { <add> contract: doc._id, <add> project: projects[row[1]]._id, <add> source: sources[row[0]]._id, <add> entities:['contract','project'] <add> }; <add> Link.create( <add> newContractLink, <add> function(err, model) { <add> if (err) { <add> contReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); <add> return callback(`Failed: ${contReport}`); <add> } <add> contReport += (`Linked contract ${row[7]} with project ${row[1]} in the DB.\n`); <add> return callback(null, contReport); <add> } <add> ); <add> } <add> }); <add> } <add> else { //No contract, create and link <add> var newContract = { <add> contract_id: row[7] <add> }; <add> Contract.create( <add> newContract, <add> function(err, cmodel) { <add> if (err) { <add> contReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); <add> return callback(`Failed: ${contReport}`); <add> } <add> contReport += (`Created contract ${row[7]}.\n`); <add> //Now create Link <add> var newContractLink = { <add> contract: cmodel._id, <add> project: projects[row[1]]._id, <add> source: sources[row[0]]._id, <add> entities:['contract','project'] <add> }; <add> Link.create( <add> newContractLink, <add> function(err, model) { <add> if (err) { <add> contReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); <add> return callback(`Failed: ${contReport}`); <add> } <add> contReport += (`Linked contract ${row[7]} with project ${row[1]} in the DB.\n`); <add> return callback(null, contReport); <add> } <add> ); <add> } <add> ); <add> } <add> } <add> ); <add> } <add> else return callback(null, "No contract found in row\n"); <add> }; <add> //Then linked concessions <add> var processCandCRowConcessions = function(row, callback) { <add> var concReport = ""; <add> if (row[8] != "") { <add> Concession.findOne( <add> {$or: [ <add> {concession_name: row[8]}, <add> {"concession_aliases.alias": row[8]} //TODO, alias population <add> ] <add> }, <add> function(err, doc) { <add> if (err) { <add> concReport += (`Encountered an error (${err}) while querying the DB. Aborting.\n`); <add> return callback(`Failed: ${concReport}`); <add> } <add> else if (doc) { //Found concession, now see if its linked <add> concReport += (`Contract ${row[8]} exists, checking for link\n`); <add> Link.findOne( <add> { <add> concession: doc._id, <add> project: projects[row[1]]._id <add> }, <add> function(err, ldoc) { <add> if (err) { <add> concReport += (`Encountered an error (${err}) while querying the DB. Aborting.\n`); <add> return callback(`Failed: ${concReport}`); <add> } <add> else if (ldoc) { <add> concReport += (`Concession ${row[8]} is already linked with project ${row[1]}, not adding\n`); <add> return callback(null, concReport); <add> } <add> else { <add> var newConcessionLink = { <add> concession: doc._id, <add> project: projects[row[1]]._id, <add> source: sources[row[0]]._id, <add> entities:['concession','project'] <add> }; <add> Link.create( <add> newConcessionLink, <add> function(err, model) { <add> if (err) { <add> concReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); <add> return callback(`Failed: ${concReport}`); <add> } <add> concReport += (`Linked concession ${row[8]} with project ${row[1]} in the DB.\n`); <add> return callback(null, concReport); <add> } <add> ); <add> } <add> }); <add> } <add> else { //No concession, create and link <add> var newConcession = { <add> concession_name: row[8], <add> concession_established_source: sources[row[0]]._id <add> }; <add> if (row[10] != "") { <add> newConcession.concession_country = {country: countries[row[10]]._id, source: sources[row[0]]._id} <add> } <add> Concession.create( <add> newConcession, <add> function(err, cmodel) { <add> if (err) { <add> concReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); <add> return callback(`Failed: ${concReport}`); <add> } <add> concReport += (`Created concession ${row[8]}.\n`); <add> //Now create Link <add> var newConcessionLink = { <add> concession: cmodel._id, <add> project: projects[row[1]]._id, <add> source: sources[row[0]]._id, <add> entities:['concession','project'] <add> }; <add> Link.create( <add> newConcessionLink, <add> function(err, model) { <add> if (err) { <add> concReport += (`Encountered an error while updating the DB: ${err}. Aborting.\n`); <add> return callback(`Failed: ${concReport}`); <add> } <add> concReport += (`Linked concession ${row[8]} with project ${row[1]} in the DB.\n`); <add> return callback(null, concReport); <add> } <add> ); <add> } <add> ); <add> } <add> } <add> ); <add> } <add> else return callback(null, "No concession found in row\n"); <add> }; <add> <add> var processCandCRow = function(candcReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { <add> if ((row[0] == "#source") || ((row[2] == "") && (row[7] == "") && (row[8] == ""))) { <add> candcReport.add("Concessions and Contracts: Empty row or label.\n"); <add> return callback(null); //Do nothing <add> } <add> if (!sources[row[0]] ) { <add> candcReport.add(`Invalid source in row: ${row}. Aborting.\n`); <add> return callback(`Failed: ${candcReport.report}`); <add> } <add> async.parallel([ <add> processCandCRowCompanies.bind(null, row), <add> processCandCRowContracts.bind(null, row), <add> processCandCRowConcessions.bind(null, row) <add> ], <add> function (err, resultsarray) { <add> for (var r=0; r<resultsarray.length; r++) { <add> if (!resultsarray[r]) { <add> candcReport.add("** NO RESULT **\n"); <add> } <add> else candcReport.add(resultsarray[r]); <add> } <add> if (err) { <add> candcReport.add(`Processing of company/contract/concessions caused an error: ${err}\n`); <add> return callback(`Processing of company/contract/concession caused an error: ${err}\n`, candcReport.report); <add> } <add> return callback(null); <add> } <add> ); <add> } <add> parseEntity(result, '7. Contracts, concessions and companies', 4, 0, null, processCandCRow, null, null, null, null, null, callback); <add> } <add> <add> //TODO: This is definitely a candidate for bringing into genericrow with custom query <add> function parseProduction(result, callback) { <add> var processProductionRow = function(prodReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { <add> //This serves 2 purposes, check for blank rows and skip rows with no value <add> if ((row[6] == "") || (row[0] == "#source")) { <add> prodReport.add("Productions: Empty row or label, or no volume data.\n"); <add> return callback(null); //Do nothing <add> } <add> //TODO: Currently hard req. for project. Country and Company seem to be optional and unused. <add> //thereby data can only be grabbed via project therefore req. project! <add> if (/*(row[2] == "") || !countries[row[2]] || */(row[3] == "") || !sources[row[0]] || (row[8] == "") || !commodities[row[8]] || (row[5] == "") ) { <add> prodReport += (`Invalid or missing data in row: ${row}. Aborting.\n`); <add> return callback(`Failed: ${prodReport}`); <add> } <add> //Here we depend on links, use controller <add> <add> //Production - match (ideally) by (country???) + project (if present???) + year + commodity <add> //BUT (TODO) there is currently no easy way of grabbing country & project <add> Production.findOne( <add> { <add> production_commodity: commodities[row[8]]._id, <add> production_year: parseInt(row[5]), <add> }, <add> function(err, doc) { <add> if (err) { <add> prodReport.add(`Encountered an error (${err}) while querying the DB. Aborting.\n`); <add> return callback(`Failed: ${prodReport.report}`); <add> } <add> else if (doc) { <add> prodReport.add(`Production ${row[3]}/${row[8]}/${row[5]} already exists in the DB, not adding\n`); <add> return callback(null); <add> } <add> else { <add> var newProduction = makeNewProduction(row); <add> Production.create( <add> newProduction, <add> function(err, model) { <add> if (err) { <add> prodReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <add> return callback(`Failed: ${prodReport.report}`); <add> } <add> //TODO: Link Production<->Project, (Production<->Country ???) <add> //As productions can only exist with a project (TODO: check), go ahead and create the link <add> Link.create( <add> {project: projects[row[3]]._id, production: model._id, entities: ['project', 'production']}, <add> function name(err, lmodel) { <add> if (err) { <add> prodReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <add> return callback(`Failed: ${prodReport.report}`); <add> } <add> else { <add> prodReport.add(`Added production ${row[3]}/${row[8]}/${row[5]} to the DB and linked to project.\n`); <add> return callback(null); <add> } <add> } <add> ); <add> } <add> ); <add> } <add> } <add> ); <add> }; <add> parseEntity(result, '8. Production', 3, 0, null, processProductionRow, null, null, null, null, null, callback); <add> } <add> <add> function parseTransfers(result, callback) { <add> var processTransferRow = function(transReport, destObj, entityName, rowIndex, model, modelKey, makerFunction, row, callback) { <add> //This serves 2 purposes, check for blank row${util.inspect(query)s and skip rows with no value <add> if (((row[21] == "") && (row[9] == "")) || (row[0] == "#source")) { <add> transReport.add("Transfers: Empty row or label, or no volume data.\n"); <add> return callback(null); //Do nothing <add> } <add> //This, in turn is a little harsh to abort of payment type is missing, but it does make for an invalid row <add> if ((row[5] == "") || !projects[row[5]] || !sources[row[0]] || !countries[row[2]] || (row[17] == "") ) { <add> transReport += (`Invalid or missing data in row: ${row}. Aborting.\n`); <add> return callback(`Failed: ${transReport}`); <add> } <add> //Transfer - many possible ways to match <add> //Determine if payment or receipt <add> var transfer_audit_type = ""; <add> if (row[21] != "") { <add> transfer_audit_type = "government_receipt" <add> transfer_type = "receipt"; <add> } <add> else if (row[9] != "") { <add> transfer_audit_type = "company_payment"; <add> transfer_type = "payment"; <add> } <add> else returnInvalid(); <add> <add> //TODO: How to match without projects in the transfers any more? <add> var query = {transfer_country: countries[row[2]]._id, transfer_audit_type: transfer_audit_type}; <add> if (row[5] != "") { <add> //query.transfer_project = projects[row[5]]._id; <add> query.transfer_level = "project"; <add> } <add> else query.transfer_level = "country"; <add> <add> if (row[3] != "") { <add> query.transfer_company = companies[row[3]]._id; <add> } <add> <add> if (transfer_type == "payment") { <add> query.transfer_year = parseInt(row[6]); <add> query.transfer_type = row[8]; <add> } <add> else { <add> query.transfer_year = parseInt(row[13]); <add> query.transfer_type = row[17]; <add> if (row[15] != "") { <add> query.transfer_gov_entity = row[15]; <add> } <add> if (row[16] != "") { <add> query.transfer_gov_entity_id = row[16]; <add> } <add> } <add> <add> Transfer.findOne( <add> query, <add> function(err, doc) { <add> if (err) { <add> transReport.add(`Encountered an error (${err}) while querying the DB. Aborting.\n`); <add> return callback(`Failed: ${transReport.report}`); <add> } <add> else if (doc) { <add> transReport.add(`Transfer (${util.inspect(query)}) already exists in the DB, not adding\n`); <add> return callback(null); <add> } <add> else { <add> var newTransfer = makeNewTransfer(row, transfer_audit_type); <add> if (!newTransfer) { <add> transReport += (`Invalid or missing data in row: ${row}. Aborting.\n`); <add> return callback(`Failed: ${transReport}`); <add> } <add> Transfer.create( <add> newTransfer, <add> function(err, model) { <add> if (err) { <add> transReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <add> return callback(`Failed: ${transReport.report}`); <add> } <add> //TODO: Link Transfer<->Project, (Transfer<->Company ???) <add> //Can't find the transfer without a project (if there is one), so go ahead and create it without checks <add> if (row[5] != "") { <add> Link.create( <add> {project: projects[row[5]]._id, transfer: model._id, entities: ['project', 'transfer']}, <add> function name(err, lmodel) { <add> if (err) { <add> transReport.add(`Encountered an error while updating the DB: ${err}. Aborting.\n`); <add> return callback(`Failed: ${transReport.report}`); <add> } <add> else { <add> transReport.add(`Added transfer (${util.inspect(query)}) with project link to the DB.\n`); <add> return callback(null); <add> } <add> } <add> ); <add> } <add> else { <add> transReport.add(`Added transfer (${util.inspect(query)}) to the DB without project link.\n`); <add> return callback(null); <add> } <add> } <add> ); <add> } <add> } <add> ); <add> }; <add> parseEntity(result, '10. Payments and receipts', 3, 0, null, processTransferRow, null, null, null, null, null, callback); <add> } <add> <add> function parseReserves(result, callback) { <add> result += "Reserves IGNORED\n"; <add> callback(null, result); <add> } <add>}
JavaScript
agpl-3.0
55fd7bd576bf613f14588d69ecdfe53aef4171d5
0
mitechie/juju-gui,mitechie/juju-gui,mitechie/juju-gui,mitechie/juju-gui
/* This file is part of the Juju GUI, which lets users view and manage Juju environments within a graphical interface (https://launchpad.net/juju-gui). Copyright (C) 2012-2013 Canonical Ltd. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. */ 'use strict'; /** * Provide the main App class, based on the YUI App framework. Also provide * the routing definitions, which map the request paths to the top-level * views defined by the App class. * * @module app */ // Create a global for debug console access to YUI context. var yui; // eslint-disable-line no-unused-vars YUI.add('juju-gui', function(Y) { // Assign the global for console access. yui = Y; var juju = Y.namespace('juju'), models = Y.namespace('juju.models'), views = Y.namespace('juju.views'), widgets = Y.namespace('juju.widgets'), d3 = Y.namespace('d3'); /** * The main app class. * * @class App */ var extensions = [ widgets.AutodeployExtension, Y.juju.Cookies, Y.juju.AppRenderer, Y.juju.GhostDeployer ]; var JujuGUI = Y.Base.create('juju-gui', Y.App, extensions, { /** * Views * * The views encapsulate the functionality blocks that output * the GUI pages. The "parent" attribute defines the hierarchy. * * @attribute views */ views: { environment: { type: 'juju.views.environment', preserve: true } }, /* * Declarative keybindings on the window object. * * Prefix supported are: * C - Control * A - Alt * S - Shift * * Followed by a lowercase letter. For example * * A-s is the 'Alt + s' keybinding. * * This maps to an object which has the following behavior. * * target: {String} CSS selector of one element * focus: {Boolean} Focus the element. * toggle: {Boolean} Toggle element visibility. * fire: {String} Event to fire when triggered. (XXX: Target is topology) * condition: {Function} returns Boolean, should method be added to * keybindings. * callback: {Function} Taking (event, target). * help: {String} Help text to display in popup. * label: {String} The label to display in the help text. Defaults to the * specified keybinding. * * All are optional. */ keybindings: { 'A-s': { target: '#charm-search-field', focus: true, help: 'Select the charm Search', label: 'Alt + s' }, '/': { target: '.header-search__input', focus: true, help: 'Select the charm Search' }, 'S-1': { callback: function() { this._clearShortcutsModal(); if (document.getElementById('modal-gui-settings'). children.length > 0) { this._clearSettingsModal(); } else { this._displaySettingsModal(); } }, help: 'GUI Settings', label: 'Shift + !' }, 'S-/': { callback: function() { this._clearSettingsModal(); if (document.getElementById('modal-shortcuts'). children.length > 0) { this._clearShortcutsModal(); } else { this._displayShortcutsModal(); } }, help: 'Display this help', label: 'Shift + ?' }, 'S-+': { fire: 'topo.zoom_in', help: 'Zoom In', label: 'Shift + "+"' }, 'S--': { fire: 'topo.zoom_out', help: 'Zoom Out', label: 'Shift + -' }, 'S-0': { fire: 'topo.panToCenter', help: 'Center the model overview', label: 'Shift + 0' }, 'esc': { fire: 'topo.clearState', callback: function() { this._clearSettingsModal(); this._clearShortcutsModal(); }, help: 'Cancel current action', label: 'Esc' }, 'S-d': { callback: function(evt) { views.utils.exportEnvironmentFile(this.db); }, help: 'Export the model', label: 'Shift + d' } }, /** * Activate the keyboard listeners. Only called by the main index.html, * not by the tests' one. * * @method activateHotkeys */ activateHotkeys: function() { var key_map = { '1': 49, '/': 191, '?': 63, '+': 187, '-': 189, enter: 13, esc: 27, backspace: 8, tab: 9, pageup: 33, pagedown: 34}; var code_map = {}; Object.keys(key_map).forEach(k => { const v = key_map[k]; code_map[v] = k; }); this._keybindings = document.addEventListener('keydown', evt => { // Normalize key-code // This gets triggered by different types of elements some YUI some // React. So try and use the native tagName property first, if that // fails then fall back to ReactDOM.findDOMNode(). var tagName = evt.target.tagName; var contentEditable = evt.target.contentEditable; var currentKey; if (code_map[evt.keyCode]) { currentKey = code_map[evt.which]; } else { currentKey = String.fromCharCode(evt.which).toLowerCase(); } if (!tagName) { tagName = ReactDOM.findDOMNode(evt.target).tagName; } if (!contentEditable) { contentEditable = ReactDOM.findDOMNode(evt.target).contentEditable; } // Don't ignore esc in the search box. if (currentKey === 'esc' && evt.target.className === 'header-search__input') { // Remove the focus from the search box. evt.target.blur(); // Target filtering, we want to listen on window // but not honor hotkeys when focused on // text oriented input fields. } else if (['INPUT', 'TEXTAREA'].indexOf(tagName) !== -1 || contentEditable === 'true') { return; } var symbolic = []; if (evt.ctrlKey) { symbolic.push('C');} if (evt.altKey) { symbolic.push('A');} if (evt.shiftKey) { symbolic.push('S');} symbolic.push(currentKey); var trigger = symbolic.join('-'); var spec = this.keybindings[trigger]; if (spec) { if (spec.condition && !spec.condition.call(this)) { // Note that when a condition check fails, // the event still propagates. return; } var target = document.querySelector(spec.target); if (target) { if (spec.toggle) { if (target.classList.contains('hidden')) { target.classList.remove('hidden'); } else { target.classList.add('hidden'); } } if (spec.focus) { target.focus(); } } if (spec.callback) { spec.callback.call(this, evt, target); } // HACK w/o context/view restriction but right direction if (spec.fire) { document.dispatchEvent(new Event(spec.fire)); } // If we handled the event nothing else has to. evt.stopPropagation(); } }); }, /** Return the current model unique identifier. @method _getModelUUID @return {String} The model UUID. */ _getModelUUID: function() { return this.get('modelUUID') || (window.juju_config && window.juju_config.jujuEnvUUID); }, /** * @method initializer * @param {Object} cfg Application configuration data. */ initializer: function(cfg) { // If no cfg is passed in, use a default empty object so we don't blow up // getting at things. cfg = cfg || {}; // If this flag is true, start the application with the console activated. var consoleEnabled = this.get('consoleEnabled'); // Concession to testing, they need muck with console, we cannot as well. if (window.mochaPhantomJS === undefined) { if (consoleEnabled) { consoleManager.native(); } else { consoleManager.noop(); } } /** Reference to the juju.Cookies instance. @property cookieHandler @type {juju.Cookies} @default null */ this.cookieHandler = null; this.renderEnvironment = true; // When a user drags a file over the browser we show notifications which // are drop targets to illustrate what they can do with their selected // file. This array keeps track of those masks and their respective // handlers with a { mask: mask, handlers: handlers } format. this.dragNotifications = []; /** The object used for storing a mapping of previously visited user paths to the type of entity (model, store). e.g. /u/spinach/ghost would map to store. @property userPaths @type {Map} */ this.userPaths = new Map(); // Track anonymous mode. This value will be set to true when anonymous // navigation is allowed, in essence when a GISF anonymous user is being // modeling on a new canvas. this.anonymousMode = false; const config = window.juju_config || {}; config.interactiveLogin = this.get('interactiveLogin'); // Set up a client side database to store state. this.db = new models.Database(); // Create a user store to track authentication details. const userCfg = { externalAuth: this.get('auth'), expiration: window.sessionStorage.getItem('expirationDatetime') }; this.user = this.get('user') || new window.jujugui.User(userCfg); // Instantiate a macaroon bakery, which is used to handle the macaroon // acquisition over HTTP. const webHandler = new Y.juju.environments.web.WebHandler(); const stateGetter = () => { return this.state.current; }; const cookieSetter = (value, callback) => { this.get('charmstore').setAuthCookie(value, callback); }; this.bakery = Y.juju.bakeryutils.newBakery( config, this.user, stateGetter, cookieSetter, webHandler); // Create and set up a new instance of the charmstore. this._setupCharmstore(config, window.jujulib.charmstore); // Create and set up a new instance of the bundleservice. this._setupBundleservice(window.jujulib.bundleservice); // Set up a new modelController instance. this.modelController = new juju.ModelController({ db: this.db, charmstore: this.get('charmstore') }); let environments = juju.environments; // This is wrapped to be called twice. // The early return (at line 478) would state from being set (originally // at line 514). const setUpStateWrapper = function() { // If there is no protocol in the baseURL then prefix the origin when // creating state. let baseURL = cfg.baseUrl; if (baseURL.indexOf('://') < 0) { baseURL = `${window.location.origin}${baseURL}`; } this.state = this._setupState(baseURL); }.bind(this); // Create an environment facade to interact with. // Allow "env" as an attribute/option to ease testing. var env = this.get('env'); if (env) { setUpStateWrapper(); this._init(cfg, env, this.get('controllerAPI')); return; } var ecs = new juju.EnvironmentChangeSet({db: this.db}); this.renderDeploymentBarListener = this._renderDeploymentBar.bind(this); document.addEventListener( 'ecs.changeSetModified', this.renderDeploymentBarListener); document.addEventListener( 'ecs.currentCommitFinished', this.renderDeploymentBarListener); if (this.get('gisf')) { document.body.classList.add('u-is-beta'); } this.defaultPageTitle = 'Juju GUI'; let modelOptions = { user: this.user, ecs: ecs, conn: this.get('conn'), jujuCoreVersion: this.get('jujuCoreVersion'), bundleService: this.get('bundleService') }; let controllerOptions = Object.assign({}, modelOptions); modelOptions.webHandler = new environments.web.WebHandler(); const modelAPI = new environments.GoEnvironment(modelOptions); const controllerAPI = new Y.juju.ControllerAPI(controllerOptions); // For analytics to work we need to set it up before state is set up. // Relies on controllerAPI, is used by state this.sendAnalytics = juju.sendAnalyticsFactory( controllerAPI, window.dataLayer ); setUpStateWrapper(); this.defaultPageTitle = 'Juju GUI'; this._init(cfg, modelAPI, controllerAPI); }, /** Complete the application initialization. @method _init @param {Object} cfg Application configuration data. @param {Object} modelAPI The environment instance. @param {Object} controllerAPI The controller api instance. */ _init: function(cfg, modelAPI, controllerAPI) { // Store the initial model UUID. const modelUUID = this._getModelUUID(); this.set('modelUUID', modelUUID); const controllerCreds = this.user.controller; this.env = modelAPI; // Generate the application state then see if we have to disambiguate // the user portion of the state. const pathState = this.state.generateState(window.location.href, false); let entityPromise = null; if (!pathState.error && pathState.state.user) { // If we have a user component to the state then it is ambiguous. // disambiguate the user state by checking if the user fragment // represents a charm store entity. entityPromise = this._fetchEntityFromUserState(pathState.state.user); } this.controllerAPI = this.setUpControllerAPI( controllerAPI, controllerCreds.user, controllerCreds.password, controllerCreds.macaroons, entityPromise); const getBundleChanges = this.controllerAPI.getBundleChanges.bind( this.controllerAPI); // Create Romulus API client instances. this._setupRomulusServices(window.juju_config, window.jujulib); // Set the modelAPI in the model controller here so // that we know that it's been setup. this.modelController.set('env', this.env); // Create a Bundle Importer instance. this.bundleImporter = new Y.juju.BundleImporter({ db: this.db, modelAPI: this.env, getBundleChanges: getBundleChanges, makeEntityModel: Y.juju.makeEntityModel, charmstore: this.get('charmstore'), hideDragOverNotification: this._hideDragOverNotification.bind(this) }); // Create the ACL object. this.acl = new Y.juju.generateAcl(this.controllerAPI, this.env); this.changesUtils = window.juju.utils.ChangesUtils; this.relationUtils = window.juju.utils.RelationUtils; // Listen for window unloads and trigger the unloadWindow function. window.onbeforeunload = views.utils.unloadWindow.bind(this); // When the environment name becomes available, display it. this.env.after('environmentNameChange', this.onEnvironmentNameChange, this); this.env.after('defaultSeriesChange', this.onDefaultSeriesChange, this); // Once we know about MAAS server, update the header accordingly. let maasServer = this.env.get('maasServer'); if (!maasServer && this.controllerAPI) { maasServer = this.controllerAPI.get('maasServer'); } if (maasServer) { this._displayMaasLink(maasServer); } else { if (this.controllerAPI) { this.controllerAPI.once('maasServerChange', this._onMaasServer, this); } this.env.once('maasServerChange', this._onMaasServer, this); } // Feed environment changes directly into the database. this.onDeltaBound = this.db.onDelta.bind(this.db); document.addEventListener('delta', this.onDeltaBound); // Handlers for adding and removing services to the service list. this.endpointsController = new juju.EndpointsController({ db: this.db, modelController: this.modelController }); this.endpointsController.bind(); // Stash the location object so that tests can override it. this.location = window.location; // When the connection resets, reset the db, re-login (a delta will // arrive with successful authentication), and redispatch. this.env.after('connectedChange', evt => { this._renderProviderLogo(); if (!evt.newVal) { // The model is not connected, do nothing waiting for a reconnection. console.log('model disconnected'); return; } console.log('model connected'); this.env.userIsAuthenticated = false; // Attempt to log in if we already have credentials available. const credentials = this.user.model; if (credentials.areAvailable) { this.loginToAPIs(null, !!credentials.macaroons, [this.env]); return; } }); // If the database updates, redraw the view (distinct from model updates). // TODO: bound views will automatically update this on individual models. this.bound_on_database_changed = this.on_database_changed.bind(this); document.addEventListener('update', this.bound_on_database_changed); // Watch specific things, (add units), remove db.update above // Note: This hides under the flag as tests don't properly clean // up sometimes and this binding creates spooky interaction // at a distance and strange failures. this.db.machines.after( ['add', 'remove', '*:change'], this.on_database_changed, this); this.db.services.after( ['add', 'remove', '*:change'], this.on_database_changed, this); this.db.relations.after( ['add', 'remove', '*:change'], this.on_database_changed, this); this.db.environment.after( ['add', 'remove', '*:change'], this.on_database_changed, this); this.db.units.after( ['add', 'remove', '*:change'], this.on_database_changed, this); this.db.notifications.after('add', this._renderNotifications, this); // When someone wants a charm to be deployed they fire an event and we // show the charm panel to configure/deploy the service. this._onInitiateDeploy = evt => { this.deployService(evt.detail.charm, evt.detail.ghostAttributes); }; document.addEventListener('initiateDeploy', this._onInitiateDeploy); this._boundAppDragOverHandler = this._appDragOverHandler.bind(this); // These are manually detached in the destructor. ['dragenter', 'dragover', 'dragleave'].forEach((eventName) => { document.addEventListener( eventName, this._boundAppDragOverHandler); }); // In Juju >= 2 we connect to the controller and then to the model. this.controllerAPI.connect(); this.state.bootstrap(); }, /** Sends the discharge token via POST to the storefront. This is used when the GUI is operating in GISF mode, allowing a shared login between the GUI and the storefront. @method _sendGISFPostBack */ _sendGISFPostBack: function() { const dischargeToken = this.user.getMacaroon('identity'); if (!dischargeToken) { console.error('no discharge token in local storage after login'); return; } console.log('sending discharge token to storefront'); const content = 'discharge-token=' + dischargeToken; const webhandler = new Y.juju.environments.web.WebHandler(); webhandler.sendPostRequest( '/_login', {'Content-Type': 'application/x-www-form-urlencoded'}, content); }, /** Auto log the user into the charm store as part of the login process when the GUI operates in a GISF context. */ _ensureLoggedIntoCharmstore: function() { if (!this.user.getMacaroon('charmstore')) { this.get('charmstore').getMacaroon((err, macaroon) => { if (err) { console.error(err); return; } this.storeUser('charmstore', true); console.log('logged into charmstore'); }); } }, /** Creates the second instance of the WebSocket for communication with the Juju controller if it's necessary. A username and password must be supplied if you're connecting to a standalone Juju controller and not to one which requires macaroon authentication. @method setUpControllerAPI @param {Object} controllerAPI Instance of the GoEnvironment class. @param {String} user The username if not using macaroons. @param {String} password The password if not using macaroons. @param {Array} macaroons A list of macaroons that the user has saved. @param {Promise} entityPromise A promise with the entity if any. @return {environments.GoEnvironment} An instance of the environment class with the necessary events attached and values set. Or undefined if we're in a legacy juju model and no controllerAPI instance was supplied. */ setUpControllerAPI: function( controllerAPI, user, password, macaroons, entityPromise) { this.user.controller = { user, password, macaroons }; this.controllerLoginHandler = evt => { const state = this.state; const current = this.state.current; this.anonymousMode = false; if (evt.detail && evt.detail.err) { this._renderLogin(evt.detail.err); return; } this._renderUserMenu(); console.log('successfully logged into controller'); // If the GUI is embedded in storefront, we need to share login // data with the storefront backend and ensure we're already // logged into the charmstore. if (this.get('gisf')) { this._sendGISFPostBack(); this._ensureLoggedIntoCharmstore(); } // If state has a `next` property then that overrides all defaults. const specialState = current.special; const next = specialState && specialState.next; const dd = specialState && specialState.dd; if (state.current.root === 'login') { if (dd) { console.log('initiating direct deploy'); this.maskVisibility(false); this._directDeploy(dd); return; } else if (next) { // There should never be a `next` state if we aren't on login but // adding the state login check here just to be sure. console.log('redirecting to "next" state', next); const {error, state: newState} = state.generateState(next, false); if (error === null) { // The root at this point will be 'login' and because the `next` // url may not explicitly define a new root path we have to set it // to null to clear 'login' from the url. if (!newState.root) { newState.root = null; } newState.special = null; this.maskVisibility(false); state.changeState(newState); return; } console.error('error redirecting to previous state', error); return; } } // If the user is connected to a model then the modelList will be // fetched by the modelswitcher component. if (this.env.get('modelUUID')) { return; } const modelUUID = this._getModelUUID(); if (modelUUID && !current.profile && current.root !== 'store') { // A model uuid was defined in the config so attempt to connect to it. this._listAndSwitchModel(null, modelUUID); } else if (entityPromise !== null) { this._disambiguateUserState(entityPromise); } else { // Drop into disconnected mode and show the profile but only if there // is no state defined in root or store. If there is a state defined // either of those then we want to let that dispatcher handle the // routing. this.maskVisibility(false); const isLogin = current.root === 'login'; const previousState = state.previous; const previousRoot = previousState && previousState.root || null; // If there was a previous root before the login then redirect to that // otherwise go to the profile. let newState = { // We don't want to redirect to the previous root if it was the // login page. profile: previousRoot && previousRoot !== 'login' ? null : current.profile, root: isLogin ? previousRoot : current.root }; // If the current root is 'login' after logging into the controller, // and there is no root, no store and no profile defined then we // want to render the users profile. if ( !current.store && !newState.profile && newState.root !== 'account' && (isLogin || !current.root) && this.get('gisf') ) { newState.profile = this.user.displayName; } state.changeState(newState); } }; document.addEventListener('login', this.controllerLoginHandler); controllerAPI.after('connectedChange', evt => { if (!evt.newVal) { // The controller is not connected, do nothing waiting for a // reconnection. console.log('controller disconnected'); return; } console.log('controller connected'); const creds = this.user.controller; const gisf = this.get('gisf'); const currentState = this.state.current; const rootState = currentState ? currentState.root : null; // If an anonymous GISF user lands on the GUI at /new then don't // attempt to log into the controller. if (( !creds.areAvailable && gisf && rootState === 'new' ) || ( this.anonymousMode && rootState !== 'login' )) { this.anonymousMode = true; console.log('now in anonymous mode'); this.maskVisibility(false); return; } if (!creds.areAvailable || // When using direct deploy when a user is not logged in it will // navigate to show the login if we do not have this state check. (currentState.special && currentState.special.dd)) { this._displayLogin(); return; } // If macaroons are available or if we have an external token from // Keystone, then proceed with the macaroons based authentication. if (creds.macaroons || creds.areExternal) { this.loginToAPIs(null, true, [this.controllerAPI]); return; } // The traditional user/password authentication does not make sense if // the GUI is embedded in the storefront. if (!gisf) { this.loginToAPIs(null, false, [this.controllerAPI]); } }); controllerAPI.set('socket_url', this.createSocketURL(this.get('controllerSocketTemplate'))); return controllerAPI; }, /** Handles logging into both the env and controller api WebSockets. @method loginToAPIs @param {Object} credentials The credentials for the controller APIs. @param {Boolean} useMacaroons Whether to use macaroon based auth (macaraq) or simple username/password auth. @param {Array} apis The apis instances that we should be logging into. Defaults to [this.controllerAPI, this.env]. */ loginToAPIs: function( credentials, useMacaroons, apis=[this.controllerAPI, this.env]) { if (useMacaroons) { apis.forEach(api => { // The api may be unset if the current Juju does not support it. if (api && api.get('connected')) { console.log(`logging into ${api.name} with macaroons`); api.loginWithMacaroon( this.bakery, this._apiLoginHandler.bind(this, api)); } }); return; } apis.forEach(api => { // The api may be unset if the current Juju does not support it. if (!api) { return; } // Ensure the credentials are set, if available. if (credentials && api.name === 'model-api') { this.user.model = credentials; } else if (credentials) { this.user.controller = credentials; } if (api.get('connected')) { console.log(`logging into ${api.name} with user and password`); api.login(); } }); }, /** Callback handler for the API loginWithMacaroon method which handles the "redirection required" error message. @method _apiLoginHandler @param {Object} api The API that the user is attempting to log into. ex) this.env or this.controllerAPI @param {String} err The login error message, if any. */ _apiLoginHandler: function(api, err) { if (this.state.current.root === 'login') { this.state.changeState({root: null}); } if (!err) { return; } if (!views.utils.isRedirectError(err)) { // There is nothing to do in this case, and the user is already // prompted with the error in the login view. console.log(`cannot log into ${api.name}: ${err}`); return; } // If the error is that redirection is required then we have to // make a request to get the appropriate model connection information. console.log(`redirection required for loggin into ${api.name}`); api.redirectInfo((err, servers) => { if (err) { this.db.notifications.add({ title: 'Unable to log into Juju', message: err, level: 'error' }); return; } // Loop through the available servers and find the public IP. const hosts = servers[0]; const publicHosts = hosts.filter(host => host.scope === 'public'); if (!publicHosts.length) { this.db.notifications.add({ title: 'Model connection error', message: 'Cannot find a public host for connecting to the model', level: 'error' }); console.error('no public hosts found: ' + JSON.stringify(servers)); return; } const publicHost = publicHosts[0]; // Switch to the redirected model. // Make sure we keep the change set by not clearing the db when // creating a model with change set (last param false). this.switchEnv(this.createSocketURL( this.get('socketTemplate'), this.get('modelUUID'), publicHost.value, publicHost.port), null, null, null, true, false); }); }, /** Renders the login component. @method _renderLogin @param {String} err Possible authentication error, or null if no error message must be displayed. */ _renderLogin: function(err) { document.getElementById('loading-message').style.display = 'none'; // XXX j.c.sackett 2017-01-30 Right now USSO link is using // loginToController, while loginToAPIs is used by the login form. // We want to use loginToAPIs everywhere since it handles more. const loginToController = this.controllerAPI.loginWithMacaroon.bind( this.controllerAPI, this.bakery); const controllerIsConnected = () => { return this.controllerAPI && this.controllerAPI.get('connected'); }; ReactDOM.render( <window.juju.components.Login controllerIsConnected={controllerIsConnected} errorMessage={err} gisf={this.get('gisf')} loginToAPIs={this.loginToAPIs.bind(this)} loginToController={loginToController} />, document.getElementById('login-container')); }, /** Renders the Log out component or log in link depending on the environment the GUI is executing in. */ _renderUserMenu: function() { const controllerAPI = this.controllerAPI; const linkContainerId = 'profile-link-container'; const linkContainer = document.getElementById(linkContainerId); if (!linkContainer) { console.error(`no linkContainerId: ${linkContainerId}`); return; } const charmstore = this.get('charmstore'); const bakery = this.bakery; const USSOLoginLink = (<window.juju.components.USSOLoginLink displayType={'text'} loginToController={controllerAPI.loginWithMacaroon.bind( controllerAPI, bakery)} />); const LogoutLink = (<window.juju.components.Logout logout={this.logout.bind(this)} clearCookie={bakery.storage.clear.bind(bakery.storage)} gisfLogout={window.juju_config.gisfLogout || ''} gisf={window.juju_config.gisf || false} charmstoreLogoutUrl={charmstore.getLogoutUrl()} getUser={this.getUser.bind(this, 'charmstore')} clearUser={this.clearUser.bind(this, 'charmstore')} // If the charmbrowser is open then don't show the logout link. visible={!this.state.current.store} locationAssign={window.location.assign.bind(window.location)} />); const navigateUserProfile = () => { const username = this.user.displayName; if (!username) { return; } views.utils.showProfile( this.env && this.env.get('ecs'), this.state.changeState.bind(this.state), username); }; const navigateUserAccount = () => { const username = this.user.displayName; if (!username) { return; } views.utils.showAccount( this.env && this.env.get('ecs'), this.state.changeState.bind(this.state)); }; ReactDOM.render(<window.juju.components.UserMenu controllerAPI={controllerAPI} LogoutLink={LogoutLink} navigateUserAccount={navigateUserAccount} navigateUserProfile={navigateUserProfile} USSOLoginLink={USSOLoginLink} />, linkContainer); }, /** Renders the user profile component. @method _renderUserProfile @param {Object} state - The app state. @param {Function} next - Call to continue dispatching. */ _renderUserProfile: function(state, next) { // XXX Jeff - 1-2-2016 - Because of a bug in the state system the profile // view renders itself and then makes requests to identity before the // controller is setup and the user has successfully logged in. As a // temporary workaround we will just prevent rendering the profile until // the controller is connected. // XXX frankban: it seems that the profile is rendered even when the // profile is not included in the state. const guiState = state.gui || {}; if ( guiState.deploy !== undefined || !state.profile || !this.controllerAPI.get('connected') || !this.controllerAPI.userIsAuthenticated ) { return; } // XXX Jeff - 18-11-2016 - This profile gets rendered before the // controller has completed connecting and logging in when in gisf. The // proper fix is to queue up the RPC calls but due to time constraints // we're setting up this handler to simply re-render the profile when // the controller is properly connected. const facadesExist = !!this.controllerAPI.get('facades'); if (!facadesExist) { const handler = this.controllerAPI.after('facadesChange', e => { if (e.newVal) { this._renderUserProfile(state, next); handler.detach(); } }); } const charmstore = this.get('charmstore'); const utils = views.utils; const currentModel = this.get('modelUUID'); // When going to the profile view, we are theoretically no longer // connected to any model. Setting the current model identifier to null // also allows switching to the same model from the profile view. this.set('modelUUID', null); // NOTE: we need to clone this.get('users') below; passing in without // cloning breaks React's ability to distinguish between this.props and // nextProps on the lifecycle methods. ReactDOM.render( <window.juju.components.UserProfile acl={this.acl} addNotification= {this.db.notifications.add.bind(this.db.notifications)} charmstore={charmstore} currentModel={currentModel} d3={d3} facadesExist={facadesExist} listBudgets={this.plans.listBudgets.bind(this.plans)} listModelsWithInfo={ this.controllerAPI.listModelsWithInfo.bind(this.controllerAPI)} getKpiMetrics={this.plans.getKpiMetrics.bind(this.plans)} changeState={this.state.changeState.bind(this.state)} destroyModels={ this.controllerAPI.destroyModels.bind(this.controllerAPI)} getAgreements={this.terms.getAgreements.bind(this.terms)} getDiagramURL={charmstore.getDiagramURL.bind(charmstore)} interactiveLogin={this.get('interactiveLogin')} pluralize={utils.pluralize.bind(this)} setPageTitle={this.setPageTitle} staticURL={window.juju_config.staticURL} storeUser={this.storeUser.bind(this)} switchModel={utils.switchModel.bind(this, this.env)} userInfo={this._getUserInfo(state)} />, document.getElementById('top-page-container')); }, /** Generate a user info object. @param {Object} state - The application state. */ _getUserInfo: function(state) { const username = state.profile || this.user.displayName || ''; const userInfo = { external: username, isCurrent: false, profile: username }; if (userInfo.profile === this.user.displayName) { userInfo.isCurrent = true; // This is the current user, and might be a local one. Use the // authenticated charm store user as the external (USSO) name. const users = this.get('users') || {}; userInfo.external = users.charmstore ? users.charmstore.user : null; } return userInfo; }, /** The cleanup dispatcher for the user profile path. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _clearUserProfile: function(state, next) { ReactDOM.unmountComponentAtNode( document.getElementById('top-page-container')); next(); }, /** Renders the ISV profile component. @method _renderISVProfile */ _renderISVProfile: function() { ReactDOM.render( <window.juju.components.ISVProfile d3={d3} />, document.getElementById('top-page-container')); // The model name should not be visible when viewing the profile. this._renderBreadcrumb({ showEnvSwitcher: false }); }, /** Renders the account component. @method _renderAccount @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _renderAccount: function(state, next) { const controllerAPI = this.controllerAPI; if (!controllerAPI || !controllerAPI.userIsAuthenticated) { // If the controller isn't ready yet then don't render anything. return; } // When going to the account view, we are theoretically no longer // connected to any model. this.set('modelUUID', null); ReactDOM.render( <window.juju.components.Account acl={this.acl} addAddress={ this.payment && this.payment.addAddress.bind(this.payment)} addBillingAddress={ this.payment && this.payment.addBillingAddress.bind(this.payment)} addNotification={ this.db.notifications.add.bind(this.db.notifications)} controllerIsReady={this._controllerIsReady.bind(this)} createCardElement={ this.stripe && this.stripe.createCardElement.bind(this.stripe)} createPaymentMethod={ this.payment && this.payment.createPaymentMethod.bind(this.payment)} createToken={this.stripe && this.stripe.createToken.bind(this.stripe)} createUser={ this.payment && this.payment.createUser.bind(this.payment)} generateCloudCredentialName={views.utils.generateCloudCredentialName} getUser={this.payment && this.payment.getUser.bind(this.payment)} getCharges={ this.payment && this.payment.getCharges.bind(this.payment)} getCloudCredentialNames={ controllerAPI.getCloudCredentialNames.bind(controllerAPI)} getCloudProviderDetails={views.utils.getCloudProviderDetails.bind( views.utils)} getCountries={ this.payment && this.payment.getCountries.bind(this.payment)} getReceipt={ this.payment && this.payment.getReceipt.bind(this.payment)} listClouds={controllerAPI.listClouds.bind(controllerAPI)} removeAddress={ this.payment && this.payment.removeAddress.bind(this.payment)} removeBillingAddress={ this.payment && this.payment.removeBillingAddress.bind( this.payment)} removePaymentMethod={ this.payment && this.payment.removePaymentMethod.bind(this.payment)} revokeCloudCredential={ controllerAPI.revokeCloudCredential.bind(controllerAPI)} sendAnalytics={this.sendAnalytics} showPay={window.juju_config.payFlag || false} updateCloudCredential={ controllerAPI.updateCloudCredential.bind(controllerAPI)} updateAddress={ this.payment && this.payment.updateAddress.bind(this.payment)} updateBillingAddress={ this.payment && this.payment.updateBillingAddress.bind( this.payment)} updatePaymentMethod={ this.payment && this.payment.updatePaymentMethod.bind(this.payment)} user={this.user.controller.user} userInfo={this._getUserInfo(state)} validateForm={views.utils.validateForm.bind(views.utils)} />, document.getElementById('top-page-container')); next(); }, /** The cleanup dispatcher for the account path. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _clearAccount: function(state, next) { ReactDOM.unmountComponentAtNode( document.getElementById('top-page-container')); next(); }, /** Renders the Environment Size Display component to the page in the designated element. @method _renderEnvSizeDisplay @param {Integer} serviceCount The serviceCount to display. @param {Integer} machineCount The machineCount to display. */ _renderEnvSizeDisplay: function(serviceCount=0, machineCount=0) { ReactDOM.render( <window.juju.components.EnvSizeDisplay appState={this.state} machineCount={machineCount} pluralize={views.utils.pluralize.bind(this)} serviceCount={serviceCount} />, document.getElementById('env-size-display-container')); }, /** Renders the Header Search component to the page in the designated element. @method _renderHeaderSearch */ _renderHeaderSearch: function() { ReactDOM.render( <window.juju.components.HeaderSearch appState={this.state} />, document.getElementById('header-search-container')); }, _renderHeaderHelp: function() { ReactDOM.render( <window.juju.components.HeaderHelp appState={this.state} gisf={this.get('gisf')} displayShortcutsModal={this._displayShortcutsModal.bind(this)} user={this.user} />, document.getElementById('header-help')); }, _renderHeaderLogo: function() { const userName = this.user.displayName; const gisf = this.get('gisf'); const homePath = gisf ? '/' : this.state.generatePath({profile: userName}); const showProfile = () => this.state.changeState({ profile: userName, model: null, store: null, root: null, search: null, account: null, user: null }); ReactDOM.render( <window.juju.components.HeaderLogo gisf={gisf} homePath={homePath} showProfile={showProfile} />, document.getElementById('header-logo')); }, /** Renders the notification component to the page in the designated element. @method _renderNotifications */ _renderNotifications: function(e) { var notification = null; if (e && e.details) { notification = e.details[0].model.getAttrs(); } ReactDOM.render( <window.juju.components.NotificationList notification={notification}/>, document.getElementById('notifications-container')); }, /** Renders the Deployment component to the page in the designated element. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _renderDeployment: function(state, next) { const env = this.env; const db = this.db; const connected = this.env.get('connected'); const modelName = env.get('environmentName') || 'mymodel'; const utils = views.utils; const ecs = env.get('ecs'); const currentChangeSet = ecs.getCurrentChangeSet(); const deployState = state.gui.deploy; const ddData = deployState ? JSON.parse(deployState) : null; if (Object.keys(currentChangeSet).length === 0 && !ddData) { // If there are no changes then close the deployment flow. This is to // prevent showing the deployment flow if the user clicks back in the // browser or navigates directly to the url. This changeState needs to // happen in app.js, not the component otherwise it will have to try and // interrupt the mount to unmount the component. this.state.changeState({ gui: { deploy: null } }); return; } const changesUtils = this.changesUtils; const controllerAPI = this.controllerAPI; const services = db.services; // Auto place the units. This is probably not the best UX, but is required // to display the machines in the deployment flow. this._autoPlaceUnits(); let cloud = env.get('providerType'); if (cloud) { cloud = { cloudType: cloud, name: env.get('cloud') }; } const getUserName = () => { return this.user.username; }; const loginToController = controllerAPI.loginWithMacaroon.bind( controllerAPI, this.bakery); const charmstore = this.get('charmstore'); const isLoggedIn = () => this.controllerAPI.userIsAuthenticated; ReactDOM.render( <window.juju.components.DeploymentFlow acl={this.acl} addAgreement={this.terms.addAgreement.bind(this.terms)} addNotification={db.notifications.add.bind(db.notifications)} applications={services.toArray()} charmstore={charmstore} changesFilterByParent={ changesUtils.filterByParent.bind(changesUtils, currentChangeSet)} changeState={this.state.changeState.bind(this.state)} cloud={cloud} controllerIsReady={this._controllerIsReady.bind(this)} createToken={this.stripe && this.stripe.createToken.bind(this.stripe)} createCardElement={ this.stripe && this.stripe.createCardElement.bind(this.stripe)} createUser={ this.payment && this.payment.createUser.bind(this.payment)} credential={env.get('credential')} changes={currentChangeSet} charmsGetById={db.charms.getById.bind(db.charms)} deploy={utils.deploy.bind(utils, this)} sendAnalytics={this.sendAnalytics} setModelName={env.set.bind(env, 'environmentName')} formatConstraints={utils.formatConstraints.bind(utils)} generateAllChangeDescriptions={ changesUtils.generateAllChangeDescriptions.bind( changesUtils, services, db.units)} generateCloudCredentialName={utils.generateCloudCredentialName} generateMachineDetails={ utils.generateMachineDetails.bind( utils, env.genericConstraints, db.units)} getAgreementsByTerms={ this.terms.getAgreementsByTerms.bind(this.terms)} isLoggedIn={isLoggedIn} getCloudCredentials={ controllerAPI.getCloudCredentials.bind(controllerAPI)} getCloudCredentialNames={ controllerAPI.getCloudCredentialNames.bind(controllerAPI)} getCloudProviderDetails={utils.getCloudProviderDetails.bind(utils)} getCurrentChangeSet={ecs.getCurrentChangeSet.bind(ecs)} getCountries={ this.payment && this.payment.getCountries.bind(this.payment) || null} getDiagramURL={charmstore.getDiagramURL.bind(charmstore)} getEntity={charmstore.getEntity.bind(charmstore)} getUser={this.payment && this.payment.getUser.bind(this.payment)} getUserName={getUserName} gisf={this.get('gisf')} groupedChanges={changesUtils.getGroupedChanges(currentChangeSet)} listBudgets={this.plans.listBudgets.bind(this.plans)} listClouds={controllerAPI.listClouds.bind(controllerAPI)} listPlansForCharm={this.plans.listPlansForCharm.bind(this.plans)} loginToController={loginToController} makeEntityModel={Y.juju.makeEntityModel} modelCommitted={connected} modelName={modelName} ddData={ddData} profileUsername={this._getUserInfo(state).profile} region={env.get('region')} renderMarkdown={marked} servicesGetById={services.getById.bind(services)} showPay={window.juju_config.payFlag || false} showTerms={this.terms.showTerms.bind(this.terms)} updateCloudCredential={ controllerAPI.updateCloudCredential.bind(controllerAPI)} validateForm={utils.validateForm.bind(utils)} withPlans={false} />, document.getElementById('deployment-container')); }, /** The cleanup dispatcher for the deployment flow state path. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _clearDeployment: function(state, next) { ReactDOM.unmountComponentAtNode( document.getElementById('deployment-container')); next(); }, /** Renders the Deployment component to the page in the designated element. @method _renderDeploymentBar */ _renderDeploymentBar: function() { var env = this.env; var ecs = env.get('ecs'); var db = this.db; var services = db.services; var servicesArray = services.toArray(); var machines = db.machines.toArray(); var units = db.units; var changesUtils = this.changesUtils; ReactDOM.render( <window.juju.components.DeploymentBar acl={this.acl} changeState={this.state.changeState.bind(this.state)} currentChangeSet={ecs.getCurrentChangeSet()} generateChangeDescription={ changesUtils.generateChangeDescription.bind( changesUtils, services, units)} hasEntities={servicesArray.length > 0 || machines.length > 0} modelCommitted={this.env.get('connected')} sendAnalytics={this.sendAnalytics} />, document.getElementById('deployment-bar-container')); }, /** Report whether the controller API connection is ready, connected and authenticated. @return {Boolean} Whether the controller is ready. */ _controllerIsReady: function() { return !!( this.controllerAPI && this.controllerAPI.get('connected') && this.controllerAPI.userIsAuthenticated ); }, /** Display or hide the sharing modal. @method _sharingVisibility @param {Boolean} visibility Controls whether to show (true) or hide (false); defaults to true. */ _sharingVisibility: function(visibility = true) { const sharing = document.getElementById('sharing-container'); if (!visibility) { ReactDOM.unmountComponentAtNode(sharing); return; } const db = this.db; const env = this.env; const grantRevoke = (action, username, access, callback) => { if (this.get('gisf') && username.indexOf('@') === -1) { username += '@external'; } action(env.get('modelUUID'), [username], access, callback); }; const controllerAPI = this.controllerAPI; const grantAccess = controllerAPI.grantModelAccess.bind(controllerAPI); const revokeAccess = controllerAPI.revokeModelAccess.bind(controllerAPI); ReactDOM.render( <window.juju.components.Sharing addNotification={db.notifications.add.bind(db.notifications)} canShareModel={this.acl.canShareModel()} closeHandler={this._sharingVisibility.bind(this, false)} getModelUserInfo={env.modelUserInfo.bind(env)} grantModelAccess={grantRevoke.bind(this, grantAccess)} humanizeTimestamp={views.utils.humanizeTimestamp} revokeModelAccess={grantRevoke.bind(this, revokeAccess)} />, sharing); }, /** Renders the model action components to the page in the designated element. @method _renderModelActions */ _renderModelActions: function() { const db = this.db; const utils = views.utils; const env = this.env; ReactDOM.render( <window.juju.components.ModelActions acl={this.acl} appState={this.state} changeState={this.state.changeState.bind(this.state)} exportEnvironmentFile={ utils.exportEnvironmentFile.bind(utils, db)} hideDragOverNotification={this._hideDragOverNotification.bind(this)} importBundleFile={this.bundleImporter.importBundleFile.bind( this.bundleImporter)} renderDragOverNotification={ this._renderDragOverNotification.bind(this)} sharingVisibility={this._sharingVisibility.bind(this)} loadingModel={env.loading} userIsAuthenticated={env.userIsAuthenticated} />, document.getElementById('model-actions-container')); }, /** Renders the logo for the current cloud provider. @method _renderProviderLogo */ _renderProviderLogo: function() { const container = document.getElementById('provider-logo-container'); const cloudProvider = this.env.get('providerType'); let providerDetails = views.utils.getCloudProviderDetails(cloudProvider); const currentState = this.state.current || {}; const isDisabled = ( // There is no provider. !cloudProvider || // It's not possible to get provider details. !providerDetails || // We are in the profile page. currentState.profile || // We are in the account page. currentState.root === 'account' ); const classes = classNames( 'provider-logo', { 'provider-logo--disabled': isDisabled, [`provider-logo--${cloudProvider}`]: cloudProvider } ); const scale = 0.65; if (!providerDetails) { // It's possible that the GUI is being run on a provider that we have // not yet setup in the cloud provider details. providerDetails = {}; } ReactDOM.render( <div className={classes}> <window.juju.components.SvgIcon height={providerDetails.svgHeight * scale} name={providerDetails.id || ''} width={providerDetails.svgWidth * scale} /> </div>, container); }, /** Renders the zoom component to the page in the designated element. @method _renderZoom */ _renderZoom: function() { ReactDOM.render( <window.juju.components.Zoom topo={this.views.environment.instance.topo} />, document.getElementById('zoom-container')); }, /** Renders the Added Services component to the page in the appropriate element. @method _renderAddedServices @param {String} hoveredId An id for a service. */ _renderAddedServices: function(hoveredId) { const instance = this.views.environment.instance; if (!instance) { // TODO frankban: investigate in what cases instance is undefined on // the environment object. Is this some kind of race? return; } const topo = instance.topo; const ServiceModule = topo.modules.ServiceModule; // Set up a handler for syncing the service token hover. This needs to be // attached only when the component is visible otherwise the added // services component will try to render if the user hovers a service // when they have the service details open. if (this.hoverService) { document.removeEventListener('topo.hoverService', this.hoverService); } this.hoverService = evt => { this._renderAddedServices(evt.detail.id); }; document.addEventListener('topo.hoverService', this.hoverService); // Deselect the active service token. This needs to happen so that when a // user closes the service details the service token deactivates. ServiceModule.deselectNodes(); const db = this.db; ReactDOM.render( <window.juju.components.Panel instanceName="inspector-panel" visible={db.services.size() > 0}> <window.juju.components.AddedServicesList services={db.services} hoveredId={hoveredId} updateUnitFlags={db.updateUnitFlags.bind(db)} findRelatedServices={db.findRelatedServices.bind(db)} findUnrelatedServices={db.findUnrelatedServices.bind(db)} getUnitStatusCounts={views.utils.getUnitStatusCounts} hoverService={ServiceModule.hoverService.bind(ServiceModule)} panToService={ServiceModule.panToService.bind(ServiceModule)} changeState={this.state.changeState.bind(this.state)} /> </window.juju.components.Panel>, document.getElementById('inspector-container')); }, /** The cleanup dispatcher for the inspector state path. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _clearInspector: function(state, next) { ReactDOM.unmountComponentAtNode( document.getElementById('inspector-container')); next(); }, /** Renders the Inspector component to the page. @param {Object} state - The app state. @param {Function} next - Call to continue dispatching. */ _renderInspector: function(state, next) { const relationUtils = this.relationUtils; const utils = views.utils; const instance = this.views.environment.instance; if (!instance) { return; } const topo = instance.topo; const charmstore = this.get('charmstore'); let inspector = {}; const inspectorState = state.gui.inspector; const service = this.db.services.getById(inspectorState.id); const localType = inspectorState.localType; // If there is a hoverService event listener then we need to detach it // when rendering the inspector. if (this.hoverService) { document.removeEventListener('topo.hoverService', this.hoverService); } const model = this.env; const db = this.db; // If the url was provided with a service id which isn't in the localType // db then change state back to the added services list. This usually // happens if the user tries to visit the inspector of a ghost service // id which no longer exists. if (service) { // Select the service token. topo.modules.ServiceModule.selectService(service.get('id')); const charm = db.charms.getById(service.get('charm')); const relatableApplications = relationUtils.getRelatableApplications( db, models.getEndpoints(service, this.endpointsController)); const ecs = model.get('ecs'); const addCharm = (url, callback, options) => { model.addCharm(url, charmstore, callback, options); }; inspector = ( <window.juju.components.Inspector acl={this.acl} addCharm={addCharm} addGhostAndEcsUnits={utils.addGhostAndEcsUnits.bind( this, db, model, service)} addNotification={db.notifications.add.bind(db.notifications)} appState={this.state} charm={charm} clearState={utils.clearState.bind(this, topo)} createMachinesPlaceUnits={utils.createMachinesPlaceUnits.bind( this, db, model, service)} createRelation={relationUtils.createRelation.bind(this, db, model)} destroyService={utils.destroyService.bind( this, db, model, service)} destroyRelations={this.relationUtils.destroyRelations.bind( this, db, model)} destroyUnits={utils.destroyUnits.bind(this, model)} displayPlans={utils.compareSemver( this.get('jujuCoreVersion'), '2') > -1} getCharm={model.get_charm.bind(model)} getUnitStatusCounts={utils.getUnitStatusCounts} getYAMLConfig={utils.getYAMLConfig.bind(this)} envResolved={model.resolved.bind(model)} exposeService={model.expose.bind(model)} getAvailableEndpoints={relationUtils.getAvailableEndpoints.bind( this, this.endpointsController, db, models.getEndpoints)} getAvailableVersions={charmstore.getAvailableVersions.bind( charmstore)} getServiceById={db.services.getById.bind(db.services)} getServiceByName={db.services.getServiceByName.bind(db.services)} linkify={utils.linkify} modelUUID={this.get('modelUUID') || ''} providerType={model.get('providerType') || ''} relatableApplications={relatableApplications} service={service} serviceRelations={ relationUtils.getRelationDataForService(db, service)} setCharm={model.setCharm.bind(model)} setConfig={model.set_config.bind(model)} showActivePlan={this.plans.showActivePlan.bind(this.plans)} showPlans={window.juju_config.plansFlag || false} unexposeService={model.unexpose.bind(model)} unplaceServiceUnits={ecs.unplaceServiceUnits.bind(ecs)} updateServiceUnitsDisplayname={ db.updateServiceUnitsDisplayname.bind(db)} /> ); } else if (localType && window.localCharmFile) { // When dragging a local charm zip over the canvas it animates the // drag over notification which needs to be closed when the inspector // is opened. this._hideDragOverNotification(); const localCharmHelpers = juju.localCharmHelpers; inspector = ( <window.juju.components.LocalInspector acl={this.acl} changeState={this.state.changeState.bind(this.state)} file={window.localCharmFile} localType={localType} services={db.services} series={utils.getSeriesList()} upgradeServiceUsingLocalCharm={ localCharmHelpers.upgradeServiceUsingLocalCharm.bind( this, model, db)} uploadLocalCharm={ localCharmHelpers.uploadLocalCharm.bind( this, model, db)} /> ); } else { this.state.changeState({gui: {inspector: null}}); return; } ReactDOM.render( <window.juju.components.Panel instanceName="inspector-panel" visible={true}> {inspector} </window.juju.components.Panel>, document.getElementById('inspector-container')); next(); }, /** Renders the Charmbrowser component to the page in the designated element. @param {Object} state - The app state. @param {Function} next - Call to continue dispatching. */ _renderCharmbrowser: function(state, next) { const utils = views.utils; const charmstore = this.get('charmstore'); // Configure syntax highlighting for the markdown renderer. marked.setOptions({ highlight: function(code, lang) { const language = Prism.languages[lang]; if (language) { return Prism.highlight(code, language); } } }); /* Retrieve from the charm store information on the charm or bundle with the given new style id. @returns {Object} The XHR reference for the getEntity call. */ const getEntity = (id, callback) => { let url; try { url = window.jujulib.URL.fromString(id); } catch(err) { callback(err, {}); return; } // Get the entity and return the XHR. return charmstore.getEntity(url.legacyPath(), callback); }; const getModelName = () => this.env.get('environmentName'); ReactDOM.render( <window.juju.components.Charmbrowser acl={this.acl} apiUrl={charmstore.url} charmstoreSearch={charmstore.search.bind(charmstore)} deployTarget={this.deployTarget.bind(this, charmstore)} series={utils.getSeriesList()} importBundleYAML={this.bundleImporter.importBundleYAML.bind( this.bundleImporter)} getBundleYAML={charmstore.getBundleYAML.bind(charmstore)} getEntity={getEntity} getFile={charmstore.getFile.bind(charmstore)} getDiagramURL={charmstore.getDiagramURL.bind(charmstore)} getModelName={getModelName} gisf={this.get('gisf')} listPlansForCharm={this.plans.listPlansForCharm.bind(this.plans)} renderMarkdown={marked} deployService={this.deployService.bind(this)} appState={this.state} utils={utils} staticURL={window.juju_config.staticURL} charmstoreURL={ utils.ensureTrailingSlash(window.juju_config.charmstoreURL)} apiVersion={window.jujulib.charmstoreAPIVersion} addNotification={ this.db.notifications.add.bind(this.db.notifications)} makeEntityModel={Y.juju.makeEntityModel} setPageTitle={this.setPageTitle.bind(this)} showTerms={this.terms.showTerms.bind(this.terms)} urllib={window.jujulib.URL} />, document.getElementById('charmbrowser-container')); next(); }, /** The cleanup dispatcher for the store state path. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _clearCharmbrowser: function(state, next) { if (state.search || state.store) { // State calls the cleanup methods on every dispatch even if the state // object exists between calls. Maybe this should be updated in state // but for now if we know that the new state still contains the // charmbrowser then just let the subsequent render method update // the rendered component. return; } ReactDOM.unmountComponentAtNode( document.getElementById('charmbrowser-container')); next(); }, /** The cleanup dispatcher for the root state path. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _clearLogin: function(state, next) { ReactDOM.unmountComponentAtNode( document.getElementById('login-container')); if (next) { next(); } }, _displayShortcutsModal: function() { ReactDOM.render( <window.juju.components.ModalShortcuts closeModal={this._clearShortcutsModal.bind(this)} guiVersion={window.GUI_VERSION.version} keybindings={this.keybindings} />, document.getElementById('modal-shortcuts')); }, _displaySettingsModal: function() { ReactDOM.render( <window.juju.components.ModalGUISettings closeModal={this._clearSettingsModal.bind(this)} localStorage={localStorage} />, document.getElementById('modal-gui-settings')); }, /** The cleanup dispatcher keyboard shortcuts modal. */ _clearShortcutsModal: function() { ReactDOM.unmountComponentAtNode( document.getElementById('modal-shortcuts')); }, /** The cleanup dispatcher global settings modal. */ _clearSettingsModal: function() { ReactDOM.unmountComponentAtNode( document.getElementById('modal-gui-settings')); }, /** Handles rendering and/or updating the machine UI component. @param {Object} state - The app state. @param {Function} next - Call to continue dispatching. */ _renderMachineView: function(state, next) { const db = this.db; const ecs = this.env.get('ecs'); const utils = views.utils; const genericConstraints = this.env.genericConstraints; ReactDOM.render( <window.juju.components.MachineView acl={this.acl} addGhostAndEcsUnits={utils.addGhostAndEcsUnits.bind( this, this.db, this.env)} autoPlaceUnits={this._autoPlaceUnits.bind(this)} changeState={this.state.changeState.bind(this.state)} createMachine={this._createMachine.bind(this)} destroyMachines={this.env.destroyMachines.bind(this.env)} environmentName={db.environment.get('name') || ''} generateMachineDetails={ utils.generateMachineDetails.bind( utils, genericConstraints, db.units)} machines={db.machines} parseConstraints={ utils.parseConstraints.bind(utils, genericConstraints)} placeUnit={this.env.placeUnit.bind(this.env)} providerType={this.env.get('providerType') || ''} removeUnits={this.env.remove_units.bind(this.env)} services={db.services} series={window.jujulib.CHARM_SERIES} units={db.units} updateMachineConstraints={ecs.updateMachineConstraints.bind(ecs)} updateMachineSeries={ecs.updateMachineSeries.bind(ecs)} />, document.getElementById('machine-view')); next(); }, /** The cleanup dispatcher for the machines state path. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _clearMachineView: function(state, next) { ReactDOM.unmountComponentAtNode( document.getElementById('machine-view')); next(); }, /** Renders the mask and animations for the drag over notification for when a user drags a yaml file or zip file over the canvas. @method _renderDragOverNotification @param {Boolean} showIndicator */ _renderDragOverNotification: function(showIndicator = true) { this.views.environment.instance.fadeHelpIndicator(showIndicator); ReactDOM.render( <window.juju.components.ExpandingProgress />, document.getElementById('drag-over-notification-container')); }, /** Handles the state changes for the model key. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _handleModelState: function(state, next) { const env = this.env; if (this.get('modelUUID') !== state.model.uuid || (!env.get('connected') && !env.get('connecting'))) { this._switchModelToUUID(state.model.uuid); } next(); }, /** Switches to the specified UUID, or if none is provided then switches to the unconnected mode. @param {String} uuid The uuid of the model to switch to, or none. */ _switchModelToUUID: function(uuid) { let socketURL = undefined; if (uuid) { console.log('switching to model: ', uuid); this.set('modelUUID', uuid); socketURL = this.createSocketURL(this.get('socketTemplate'), uuid); } else { console.log('switching to disconnected mode'); this.set('modelUUID', null); } this.switchEnv(socketURL); }, /** Determines if the user state is a store path or a model path. @param {String} userState The state value for the 'user' key. @return {Promise} A promise with the charmstore entity if one exists. */ _fetchEntityFromUserState: function(userState) { const userPaths = this.userPaths; const entityCache = userPaths.get(userState); if (entityCache && entityCache.promise) { return entityCache.promise; } const entityPromise = new Promise((resolve, reject) => { let legacyPath = undefined; try { legacyPath = window.jujulib.URL.fromString('u/' + userState).legacyPath(); } catch (e) { // If the state cannot be parsed into a url we can be sure it's // not an entity. reject(userState); return; } this.get('charmstore').getEntity( legacyPath, (err, entityData) => { if (err) { console.error(err); reject(userState); return; } resolve(userState); }); }); userPaths.set(userState, {promise:entityPromise}); return entityPromise; }, /** Calls the listModelsWithInfo method on the controller API and then switches to the provided model name or model uuid if available. If no matching model is found then state is changed to the users profile page. If both model name and model uuid are provided then the model name will win. @param {String} modelPath The model path to switch to in the format username/modelname. @param {String} modelUUID The model uuid to switch to. */ _listAndSwitchModel: function(modelPath, modelUUID) { this.controllerAPI.listModelsWithInfo((err, modelList) => { if (err) { console.error('unable to list models', err); this.db.notifications.add({ title: 'Unable to list models', message: 'Unable to list models: ' + err, level: 'error' }); return; } const noErrorModels = modelList.filter(model => !model.err); const generatePath = (owner, name) => `${owner.split('@')[0]}/${name}`; let model = undefined; if (modelPath) { model = noErrorModels.find(model => generatePath(model.owner, model.name) === modelPath); } else if (modelUUID) { model = noErrorModels.find(model => model.uuid === modelUUID); } this.maskVisibility(false); // If we're already connected to the model then don't do anything. if (model && this.env.get('modelUUID') === model.uuid) { return; } if (model) { this.state.changeState({ model: { path: generatePath(model.owner, model.name), uuid: model.uuid }, user: null, root: null }); } else { // If no model was found then navigate to the user profile. const msg = `no such charm, bundle or model: u/${modelPath}`; // TODO frankban: here we should put a notification, but we can't as // this seems to be dispatched twice. console.log(msg); // replace get auth with user.username this.state.changeState({ root: null, store: null, model: null, user: null, profile: this.user.displayName }); } }); }, /** Provided an entityPromise, attaches handlers for the resolve and reject cases. If resolved it changes state to the entity found, if rejected calls _listAndSwitchModel with the possible model name. @param {Promise} entityPromise A promise containing the result of a getEntity charmstore call. */ _disambiguateUserState: function(entityPromise) { entityPromise.then(userState => { console.log('entity found, showing store'); // The entity promise returned an entity so it is not a model and // we should navigate to the store. this.maskVisibility(false); this.state.changeState({ store: 'u/' + userState, user: null }); }).catch(userState => { // No entity was found so it's possible that this is a model. // We need to list the models that the user has access to and find // one which matches the name to extract the UUID. if (!this.controllerAPI.userIsAuthenticated) { console.log('not logged into controller'); return; } this._listAndSwitchModel(userState); }); }, /** Handle the request to display the user entity state. @method _handleUserEntity @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _handleUserEntity: function(state, next) { this._disambiguateUserState( this._fetchEntityFromUserState(state.user)); }, /** The cleanup dispatcher for the user entity state path. The store will be mounted if the path was for a bundle or charm. If the entity was a model we don't need to do anything. @method _clearUserEntity @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _clearUserEntity: function(state, next) { const container = document.getElementById('charmbrowser-container'); // The charmbrowser will only be mounted if the entity is a charm or // bundle. if (container.childNodes.length > 0) { ReactDOM.unmountComponentAtNode(container); } next(); }, /** Creates an instance of the State and registers the necessary dispatchers. @param {String} baseURL - The path the application is served from. @return {Object} The state instance. */ _setupState: function(baseURL) { const state = new window.jujugui.State({ baseURL: baseURL, seriesList: window.jujulib.SERIES, sendAnalytics: this.sendAnalytics }); state.register([ ['*', this.authorizeCookieUse.bind(this)], ['*', this.checkUserCredentials.bind(this)], ['*', this.show_environment.bind(this)], ['root', this._rootDispatcher.bind(this), this._clearRoot.bind(this)], ['profile', this._renderUserProfile.bind(this), this._clearUserProfile.bind(this)], ['user', this._handleUserEntity.bind(this), this._clearUserEntity.bind(this)], ['model', this._handleModelState.bind(this)], ['store', this._renderCharmbrowser.bind(this), this._clearCharmbrowser.bind(this)], ['search', this._renderCharmbrowser.bind(this), this._clearCharmbrowser.bind(this)], ['account', this._renderAccount.bind(this), this._clearAccount.bind(this)], ['special.deployTarget', this._deployTarget.bind(this)], ['gui', null, this._clearAllGUIComponents.bind(this)], ['gui.machines', this._renderMachineView.bind(this), this._clearMachineView.bind(this)], ['gui.inspector', this._renderInspector.bind(this) // the this._clearInspector method is not called here because the // added services component is also rendered into the inspector so // calling it here causes React to throw an error. ], ['gui.deploy', this._renderDeployment.bind(this), this._clearDeployment.bind(this)], // Nothing needs to be done at the top level when the hash changes. ['hash'] ]); return state; }, _clearAllGUIComponents: function(state, next) { const noop = () => {}; this._clearMachineView(state, noop); this._clearDeployment(state, noop); this._clearInspector(state, noop); }, /** The dispatcher for the root state path. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _rootDispatcher: function(state, next) { switch (state.root) { case 'login': // _renderLogin is called from various places with a different call // signature so we have to call next manually after. this._renderLogin(); next(); break; case 'store': this._renderCharmbrowser(state, next); break; case 'account': this._renderAccount(state, next); break; case 'new': // When going to disconnected mode we need to be disconnected from // models. if (this.env.get('connected')) { this._switchModelToUUID(); } // When dispatching, we only want to remove the mask if we're in // anonymousMode or the user is logged in; otherwise we need to // properly redirect to login. const userLoggedIn = this.controllerAPI.userIsAuthenticated; if (this.anonymousMode || userLoggedIn) { this.maskVisibility(false); } const specialState = state.special; if (specialState && specialState.dd) { this._directDeploy(specialState.dd); } break; default: next(); break; } }, /** The cleanup dispatcher for the root state path. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _clearRoot: function(state, next) { this._clearCharmbrowser(state, next); this._clearLogin(state, next); next(); }, /** State handler for he deploy target functionality. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _deployTarget: function(state, next) { // Remove the deployTarget from state so that we don't end up // dispatching it again by accident. this.state.changeState({ special: { deployTarget: null } }); this.deployTarget(this.get('charmstore'), state.special['deployTarget']); next(); }, /** Deploys the supplied entity Id from the supplied charmstore instance. @param {Object} charmstore The charmstore instance to fetch the entity. @param {String} entityId The entity id to deploy. */ deployTarget: function(charmstore, entityId) { /** Handles parsing and displaying the failure notification returned from the charmstore api. @param {Object} error The XHR request object from the charmstore req. */ const failureNotification = error => { let message = `Unable to deploy target: ${entityId}`; try { message = JSON.parse(error.currentTarget.responseText).Message; } catch (e) { console.error(e); } this.db.notifications.add({ title: 'Error deploying target.', message: message, level: 'error' }); }; // The charmstore apiv4 format can have the bundle keyword either at the // start, for charmers bundles, or after the username, for namespaced // bundles. ex) bundle/swift & ~jorge/bundle/swift if (entityId.indexOf('bundle/') > -1) { charmstore.getBundleYAML(entityId, (error, bundleYAML) => { if (error) { failureNotification(error); } else { this.bundleImporter.importBundleYAML(bundleYAML); } }); } else { // If it's not a bundle then it's a charm. charmstore.getEntity(entityId.replace('cs:', ''), (error, charm) => { if (error) { failureNotification(error); } else { charm = charm[0]; let config = {}, options = charm.get ? charm.get('options') : charm.options; Object.keys(options).forEach(function(key) { config[key] = options[key]['default']; }); // We call the env deploy method directly because we don't want // the ghost inspector to open. this.deployService(new Y.juju.models.Charm(charm)); } }); } }, /** Calls the necessary methods to setup the GUI and put the user in the Deployment Flow when they have used Direct Deploy. @param {Object} ddData - The Direct Deploy data from state. */ _directDeploy: function(ddData) { const current = this.state.current; if (current && current.gui && current.gui.deploy) { // If we're already in the deployment flow then return to stop // infinitely updating state. return; } this.deployTarget(this.get('charmstore'), ddData.id); this.state.changeState({ gui: { deploy: JSON.stringify(ddData) } }); }, /** Creates a new instance of the charm store API and assigns it to the "charmstore" attribute. This method is idempotent. @param {object} jujuConfig The app configuration. @param {Object} Charmstore The Charmstore class. */ _setupCharmstore: function(jujuConfig, Charmstore) { if (this.get('charmstore') === undefined) { this.set('charmstore', new Charmstore( jujuConfig.charmstoreURL, this.bakery)); // Store away the charmstore auth info. if (this.bakery.storage.get(jujuConfig.charmstoreURL)) { this.get('users')['charmstore'] = {loading: true}; this.storeUser('charmstore', false, true); } } }, /** Creates a new instance of the bundleservice API and stores it in the app in an idempotent fashion. @method _setupBundleservice @param {Object} Bundleservice The bundleservice API class to instantiate. */ _setupBundleservice: function(Bundleservice) { if (this.get('bundleService') === undefined) { const jujuConfig = window.juju_config; const bundleServiceURL = jujuConfig && jujuConfig.bundleServiceURL; if (!jujuConfig || !bundleServiceURL) { console.error('no juju config for bundleserviceURL availble'); return; } const bundleService = new Bundleservice( bundleServiceURL, new Y.juju.environments.web.WebHandler()); this.set('bundleService', bundleService); } }, /** Creates new API client instances for Romulus services. Assign them to the "plans" and "terms" app properties. @method _setupRomulusServices @param {Object} config The GUI application configuration. @param {Object} jujulib The Juju API client library. */ _setupRomulusServices: function(config, jujulib) { if (!config) { // We are probably running tests. return; } if (this.plans || this.terms) { console.error( 'romulus services are being redefined:', this.plans, this.terms); } this.plans = new window.jujulib.plans(config.plansURL, this.bakery); this.terms = new window.jujulib.terms(config.termsURL, this.bakery); if (config.payFlag) { this.payment = new window.jujulib.payment( config.paymentURL, this.bakery); this.stripe = new window.jujulib.stripe( 'https://js.stripe.com/', config.stripeKey); } }, /** Returns the current defaultSeries value from the environment. @method getEnvDefaultSeries @return {String} The default series. */ getEnvDefaultSeries: function() { return this.env.get('defaultSeries'); }, /** Hide the drag notifications. @method _hideDragOverNotification */ _hideDragOverNotification: function() { this.views.environment.instance.fadeHelpIndicator(false); ReactDOM.unmountComponentAtNode( document.getElementById('drag-over-notification-container')); }, /** Event handler for the dragenter, dragover, dragleave events on the document. It calls to determine the file type being dragged and manages the commands to the timerControl method. @method _appDragOverHandler @param {Object} e The event object from the various events. */ _appDragOverHandler: function(e) { e.preventDefault(); // required to allow items to be dropped // In this case, we want an empty string to be a truthy value. const fileType = this._determineFileType(e.dataTransfer); if (fileType === false) { return; // Ignore if it's not a supported type } if (e.type === 'dragenter') { this._renderDragOverNotification(); } // Possible values for type are 'dragover' and 'dragleave'. this._dragleaveTimerControl(e.type === 'dragover' ? 'stop' : 'start'); }, /** Handles the dragleave timer so that the periodic dragleave events which fire as the user is dragging the file around the browser do not stop the drag notification from showing. @method _dragleaveTimerControl @param {String} action The action that should be taken on the timer. */ _dragleaveTimerControl: function(action) { if (this._dragLeaveTimer) { window.clearTimeout(this._dragLeaveTimer); this._dragLeaveTimer = null; } if (action === 'start') { this._dragLeaveTimer = setTimeout(() => { this._hideDragOverNotification(); }, 100); } }, /** Takes the information from the dataTransfer object to determine what kind of file the user is dragging over the canvas. Unfortunately Safari and IE do not show mime types for files that they are not familiar with. This isn't an issue once the user has dropped the file because we can parse the file name but while it's still hovering the browser only tells us the mime type if it knows it, else it's an empty string. This means that we cannot determine between a yaml file or a folder during hover. Bug: https://code.google.com/p/chromium/issues/detail?id=342554 Real mime type for yaml files should be: application/x-yaml @method _determineFileType @param {Object} dataTransfer dataTransfer object from the dragover event. @return {String} The file type extension. */ _determineFileType: function(dataTransfer) { var types = dataTransfer.types; var fileFound = Object.keys(types).some(function(key) { // When dragging a single file in Firefox dataTransfer.types is an array // with two elements ["application/x-moz-file", "Files"] if (types[key] === 'Files') { return true; } }); if (!fileFound) { // If the dataTransfer type isn't `Files` then something is being // dragged from inside the browser. return false; } // IE10, 11 and Safari do not have this property during hover so we // cannot tell what type of file is being hovered over the canvas. if (dataTransfer.items) { // See method doc for bug information. var file = dataTransfer.items[0]; if (file.type === 'application/zip' || file.type === 'application/x-zip-compressed') { return 'zip'; } return 'yaml'; } return ''; }, /** Release resources and inform subcomponents to do the same. @method destructor */ destructor: function() { // Clear the database handler timer. Without this, the application could // dispatch after it is destroyed, resulting in a dirty state and bugs // difficult to debug, so please do not remove this code. if (this.dbChangedTimer) { clearTimeout(this.dbChangedTimer); } if (this._keybindings) { this._keybindings.detach(); } const toBeDestroyed = [ this.env, this.controllerAPI, this.db, this.endpointsController ]; toBeDestroyed.forEach(obj => { if (obj && obj.destroy) { obj.detachAll(); obj.destroy(); } }); ['dragenter', 'dragover', 'dragleave'].forEach((eventName) => { document.removeEventListener(eventName, this._boundAppDragOverHandler); }); document.removeEventListener('update', this.bound_on_database_changed); document.removeEventListener('initiateDeploy', this._onInitiateDeploy); document.removeEventListener( 'ecs.changeSetModified', this.renderDeploymentBarListener); document.removeEventListener( 'ecs.currentCommitFinished', this.renderDeploymentBarListener); document.removeEventListener('login', this.controllerLoginHandler); document.removeEventListener('delta', this.onDeltaBound); }, /** * On database changes update the view. * * @method on_database_changed */ on_database_changed: function(evt) { // This timeout helps to reduce the number of needless dispatches from // upwards of 8 to 2. At least until we can move to the model bound // views. if (this.dbChangedTimer) { clearTimeout(this.dbChangedTimer); } this.dbChangedTimer = setTimeout(this._dbChangedHandler.bind(this), 100); return; }, /** After the db has changed and the timer has timed out to reduce repeat calls then this is called to handle the db updates. @method _dbChangedHandler @private */ _dbChangedHandler: function() { // Regardless of which view we are rendering, // update the env view on db change. if (this.views.environment.instance) { this.views.environment.instance.topo.update(); } this.state.dispatch(); this._renderComponents(); }, /** Display the login page. @method _displayLogin */ _displayLogin: function() { this.set('loggedIn', false); const root = this.state.current.root; if (root !== 'login') { this.state.changeState({ root: 'login' }); } }, // Route handlers /** * Log the current user out and show the login screen again. * * @method logout * @param {Object} req The request. * @return {undefined} Nothing. */ logout: function(req) { // If the environment view is instantiated, clear out the topology local // database on log out, because we clear out the environment database as // well. The order of these is important because we need to tell // the env to log out after it has navigated to make sure that // it always shows the login screen. var environmentInstance = this.views.environment.instance; if (environmentInstance) { environmentInstance.topo.update(); } this.set('modelUUID', ''); this.set('loggedIn', false); const controllerAPI = this.controllerAPI; const closeController = controllerAPI.close.bind(controllerAPI); this.env.close(() => { closeController(() => { controllerAPI.connect(); this.maskVisibility(true); this.env.get('ecs').clear(); this.db.reset(); this.db.fireEvent('update'); this.state.changeState({ model: null, profile: null, root: null, store: null }); this._renderLogin(null); }); }); }, // Persistent Views /** Ensure that the current user has authenticated. @param {Object} state The application state. @param {Function} next The next route handler. */ checkUserCredentials: function(state, next) { // If we're in disconnected mode (either "/new" or "/store"), then allow // the canvas to be shown. if (state && (state.root === 'new' || state.root === 'store')) { next(); return; } const apis = [this.env, this.controllerAPI]; // Loop through each api connection and see if we are properly // authenticated. If we aren't then display the login screen. const shouldDisplayLogin = apis.some(api => { // Legacy Juju won't have a controller API. // If we do not have an api instance or if we are not connected with // it then we don't need to concern ourselves with being // authenticated to it. if (!api || !api.get('connected')) { return false; } // If the api is connecting then we can't know if they are properly // logged in yet. if (api.get('connecting')) { return false; } return !api.userIsAuthenticated && !this.get('gisf'); }); if (shouldDisplayLogin) { this._displayLogin(); return; } next(); }, /** Hide the login mask and redispatch the router. When the environment gets a response from a login attempt, it fires a login event, to which this responds. @method onLogin @param {Object} evt An event object that includes an "err" attribute with an error if the authentication failed. @private */ onLogin: function(evt) { if (evt.detail && evt.detail.err) { this._renderLogin(evt.detail.err); return; } // The login was a success. console.log('successfully logged into controller'); this.maskVisibility(false); this._clearLogin(); this.set('loggedIn', true); if (this.state.current.root === 'login') { this.state.changeState({root: null}); } }, /** Create the new socket URL based on the socket template and model details. @method createSocketURL @param {String} template The template to use to generate the url. @param {String} uuid The unique identifier for the model. @param {String} server The optional API server host address for the model. If not provided, defaults to the host name included in the provided apiAddress option. @param {String} port The optional API server port for the model. If not provided, defaults to the host name included in the provided apiAddress option. @return {String} The resulting fully qualified WebSocket URL. */ createSocketURL: function(template, uuid, server, port) { let baseUrl = ''; const apiAddress = this.get('apiAddress'); if (!apiAddress) { // It should not ever be possible to get here unless you're running the // gui in dev mode without pointing it to a proxy/server supplying // the necessary config values. alert( 'Unable to create socketURL, no apiAddress provided. The GUI must ' + 'be loaded with a valid configuration. Try GUIProxy if ' + 'running in development mode: https://github.com/frankban/guiproxy'); return; } if (template[0] === '/') { // The WebSocket path is passed so we need to calculate the base URL. const schema = this.get('socket_protocol') || 'wss'; baseUrl = schema + '://' + window.location.hostname; if (window.location.port !== '') { baseUrl += ':' + window.location.port; } } const defaults = apiAddress.replace('wss://', '').split(':'); template = template.replace('$uuid', uuid); template = template.replace('$server', server || defaults[0]); template = template.replace('$port', port || defaults[1]); return baseUrl + template; }, /** Switch the application to another environment. Disconnect the current WebSocket connection and establish a new one pointed to the environment referenced by the given URL. @method switchEnv @param {String} socketUrl The URL for the environment's websocket. @param {String} username The username for the new environment. @param {String} password The password for the new environment. @param {Function} callback A callback to be called after the env has been switched and logged into. @param {Boolean} reconnect Whether to reconnect to a new environment; by default, if the socketUrl is set, we assume we want to reconnect to the provided URL. @param {Boolean} clearDB Whether to clear the database and ecs. */ switchEnv: function( // TODO frankban: make the function defaults saner, for instance // clearDB=true should really be preserveDB=false by default. socketUrl, username, password, callback, reconnect=!!socketUrl, clearDB=true) { console.log('switching model connection'); this.env.loading = true; if (username && password) { // We don't always get a new username and password when switching // environments; only set new credentials if we've actually gotten them. // The GUI will automatically log in when we switch. this.user.model = { user: username, password: password }; }; const credentials = this.user.model; const onLogin = callback => { this.env.loading = false; if (callback) { callback(this.env); } }; // Delay the callback until after the env login as everything should be // set up by then. document.addEventListener( 'model.login', onLogin.bind(this, callback), {once: true}); if (clearDB) { // Clear uncommitted state. this.env.get('ecs').clear(); } const setUpModel = model => { // Tell the model to use the new socket URL when reconnecting. model.set('socket_url', socketUrl); // We need to reset the credentials each time we set up a model, // b/c we remove the credentials when we close down a model // connection in the `close()` method of base.js this.user.model = credentials; // Reconnect the model if required. if (reconnect) { model.connect(); } }; // Disconnect and reconnect the model. const onclose = function() { this.on_close(); setUpModel(this); }.bind(this.env); if (this.env.ws) { this.env.ws.onclose = onclose; this.env.close(); // If we are already disconnected then connect if we're supposed to. if (!this.env.get('connected')) { setUpModel(this.env); } } else { this.env.close(onclose); } if (clearDB) { this.db.reset(); this.db.fireEvent('update'); } // Reset canvas centering to new env will center on load. const instance = this.views.environment.instance; // TODO frankban: investigate in what cases instance is undefined on the // environment object. Is this some kind of race? if (instance) { instance.topo.modules.ServiceModule.centerOnLoad = true; } // If we're not reconnecting, then mark the switch as done. if (this.state.current.root === 'new') { this.env.loading = false; } }, /** If we are in a MAAS environment, react to the MAAS server address retrieval adding a link to the header pointing to the MAAS server. @method _onMaasServer @param {Object} evt An event object (with a "newVal" attribute). */ _onMaasServer: function(evt) { if (evt.newVal === evt.prevVal) { // This can happen if the attr is set blithely. Ignore if so. return; } this._displayMaasLink(evt.newVal); }, /** If the given maasServer is not null, create a link to the MAAS server in the GUI header. @method _displayMaasLink @param {String} maasServer The MAAS server URL (or null if not in MAAS). */ _displayMaasLink: function(maasServer) { if (maasServer === null) { // The current environment is not MAAS. return; } var maasContainer = document.querySelector('#maas-server'); maasContainer.querySelector('a').setAttribute('href', maasServer); maasContainer.classList.remove('hidden'); }, maskVisibility: function(visibility = true) { var mask = document.getElementById('full-screen-mask'); var display = visibility ? 'block' : 'none'; if (mask) { mask.style.display = display; } }, /** Sets the page title. @param {String} title The title to be appended with ' - Juju GUI' */ setPageTitle: function(title) { document.title = title ? `${title} - Juju GUI` : this.defaultPageTitle; }, /** * Record environment default series changes in our model. * * The provider type arrives asynchronously. Instead of updating the * display from the environment code (a separation of concerns violation), * we update it here. * * @method onDefaultSeriesChange */ onDefaultSeriesChange: function(evt) { this.db.environment.set('defaultSeries', evt.newVal); }, /** Display the Environment Name. The environment name can arrive asynchronously. Instead of updating the display from the environment view (a separtion of concerns violation), we update it here. @method onEnvironmentNameChange */ onEnvironmentNameChange: function(evt) { var environmentName = evt.newVal || 'untitled-model'; // Update the name on the current model. This is what the components use // to display the model name. this.db.environment.set('name', environmentName); // Update the breadcrumb with the new model name. this._renderBreadcrumb(); // Update the page title. this.defaultPageTitle = `${environmentName} - Juju GUI`; this.setPageTitle(); }, /** Render the react components. @method _renderComponents */ _renderComponents: function() { // Update the react views on database change this._renderEnvSizeDisplay( this.db.services.size(), this.db.machines.filterByParent().length ); this._renderDeploymentBar(); this._renderModelActions(); this._renderProviderLogo(); this._renderZoom(); this._renderBreadcrumb(); this._renderHeaderSearch(); this._renderHeaderHelp(); this._renderHeaderLogo(); const gui = this.state.current.gui; if (!gui || (gui && !gui.inspector)) { this._renderAddedServices(); } }, /** Show the environment view. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ show_environment: function(state, next) { if (!this.renderEnvironment) { next(); return; } var options = { endpointsController: this.endpointsController, db: this.db, env: this.env, ecs: this.env.ecs, charmstore: this.get('charmstore'), bundleImporter: this.bundleImporter, state: this.state, staticURL: window.juju_config.staticURL, sendAnalytics: this.sendAnalytics }; this.showView('environment', options, { /** * Let the component framework know that the view has been rendered. * * @method show_environment.callback */ callback: function() { var envView = this.views.environment.instance; envView.rendered(); }, render: true }); if (!this.env.get('environmentName')) { // If this is starting in an unconnected state there will not be a model // name so we set it so that onEnvironmentNameChange sets and updates // the name correctly. this.env.set('environmentName', null); } this._renderComponents(); this._renderNotifications(); this._renderUserMenu(); next(); }, /** Make sure the user agrees to cookie usage. @param {Object} state - The application state. @param {Function} next - The next route handler. */ authorizeCookieUse: function(state, next) { var GTM_enabled = this.get('GTM_enabled'); if (GTM_enabled) { this.cookieHandler = this.cookieHandler || new Y.juju.Cookies(); this.cookieHandler.check(); } next(); }, /** Get the user info for the supplied service. @method getUser @param {String} service The service the macaroon comes from. @return {Object} The user information. */ getUser: function(service) { return this.get('users')[service]; }, /** Clears the user info for the supplied service. @method clearUser @param {String} service The service the macaroon comes from. */ clearUser: function(service) { delete this.get('users')[service]; }, /** Takes a macaroon and stores the user info (if any) in the app. @method storeUser @param {String} service The service the macaroon comes from. @param {String} macaroon The base64 encoded macaroon. @param {Boolean} rerenderProfile Rerender the user profile. @param {Boolean} rerenderBreadcrumb Rerender the breadcrumb. */ storeUser: function(service, rerenderProfile, rerenderBreadcrumb) { var callback = function(error, auth) { if (error) { console.error('Unable to query user information', error); return; } if (auth) { this.get('users')[service] = auth; // If the profile is visible then we want to rerender it with the // updated username. if (rerenderProfile) { this._renderUserProfile(this.state.current, ()=>{}); } } if (rerenderBreadcrumb) { this._renderBreadcrumb(); } }; if (service === 'charmstore') { this.get('charmstore').whoami(callback.bind(this)); } else { console.error('Unrecognized service', service); } } }, { ATTRS: { html5: true, /** A flag to indicate if the user is actually logged into the environment. @attribute loggedIn @default false @type {Boolean} */ loggedIn: { value: false }, /** Store the instance of the charmstore api that we will be using throughout the application. @attribute charmstore @type {jujulib.charmstore} @default undefined */ charmstore: {}, /** Whether or not to use interactive login for the IdM/JEM connection. @attribute interactiveLogin @type {Boolean} @default false */ interactiveLogin: { value: true }, /** The address for the environment's state-server. Used for websocket creation. @attribute apiAddress @type {String} @default '' */ apiAddress: {value: ''}, /** The template to use to create websockets. It can include these vars: - $server: the WebSocket server, like "1.2.3.4"; - $port: the WebSocket port, like "17070"; - $uuid: the target model unique identifier. If the provided value starts with a "/" it is considered to be a path and not a full URL. In this case, the system assumes current host, current port and this.get('socket_protocol') (defaulting to 'wss'). @attribute socketTemplate @type {String} @default '/model/$uuid/api' */ socketTemplate: {value: '/model/$uuid/api'}, /** The authentication store for the user. This holds macaroons or other credential details for the user to connect to the controller. */ user: {value: null}, /** The users associated with various services that the GUI uses. The users are keyed by their service name. For example, this.get('users')['charmstore'] will return the user object for the charmstore service. @attribute users @type {Object} */ users: { value: {} } } }); Y.namespace('juju').App = JujuGUI; }, '0.5.3', { requires: [ 'acl', 'analytics', 'changes-utils', 'juju-charm-models', 'juju-bundle-models', 'juju-controller-api', 'juju-endpoints-controller', 'juju-env-base', 'juju-env-api', 'juju-env-web-handler', 'juju-models', 'jujulib-utils', 'bakery-utils', 'net-utils', // React components 'account', 'added-services-list', 'charmbrowser-component', 'deployment-bar', 'deployment-flow', 'deployment-signup', 'env-size-display', 'header-breadcrumb', 'model-actions', 'expanding-progress', 'header-help', 'header-logo', 'header-search', 'inspector-component', 'isv-profile', 'local-inspector', 'machine-view', 'login-component', 'logout-component', 'modal-gui-settings', 'modal-shortcuts', 'notification-list', 'panel-component', 'sharing', 'svg-icon', 'user-menu', 'user-profile', 'zoom', // juju-views group 'd3-components', 'juju-view-utils', 'juju-topology', 'juju-view-environment', 'juju-landscape', // end juju-views group 'autodeploy-extension', 'io', 'json-parse', 'app-base', 'app-transitions', 'base', 'bundle-importer', 'bundle-import-notifications', 'node', 'model', 'app-cookies-extension', 'app-renderer-extension', 'cookie', 'querystring', 'event-key', 'event-touch', 'model-controller', 'FileSaver', 'ghost-deployer-extension', 'local-charm-import-helpers', 'environment-change-set', 'relation-utils' ] });
jujugui/static/gui/src/app/app.js
/* This file is part of the Juju GUI, which lets users view and manage Juju environments within a graphical interface (https://launchpad.net/juju-gui). Copyright (C) 2012-2013 Canonical Ltd. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. */ 'use strict'; /** * Provide the main App class, based on the YUI App framework. Also provide * the routing definitions, which map the request paths to the top-level * views defined by the App class. * * @module app */ // Create a global for debug console access to YUI context. var yui; // eslint-disable-line no-unused-vars YUI.add('juju-gui', function(Y) { // Assign the global for console access. yui = Y; var juju = Y.namespace('juju'), models = Y.namespace('juju.models'), views = Y.namespace('juju.views'), widgets = Y.namespace('juju.widgets'), d3 = Y.namespace('d3'); /** * The main app class. * * @class App */ var extensions = [ widgets.AutodeployExtension, Y.juju.Cookies, Y.juju.AppRenderer, Y.juju.GhostDeployer ]; var JujuGUI = Y.Base.create('juju-gui', Y.App, extensions, { /** * Views * * The views encapsulate the functionality blocks that output * the GUI pages. The "parent" attribute defines the hierarchy. * * @attribute views */ views: { environment: { type: 'juju.views.environment', preserve: true } }, /* * Declarative keybindings on the window object. * * Prefix supported are: * C - Control * A - Alt * S - Shift * * Followed by a lowercase letter. For example * * A-s is the 'Alt + s' keybinding. * * This maps to an object which has the following behavior. * * target: {String} CSS selector of one element * focus: {Boolean} Focus the element. * toggle: {Boolean} Toggle element visibility. * fire: {String} Event to fire when triggered. (XXX: Target is topology) * condition: {Function} returns Boolean, should method be added to * keybindings. * callback: {Function} Taking (event, target). * help: {String} Help text to display in popup. * label: {String} The label to display in the help text. Defaults to the * specified keybinding. * * All are optional. */ keybindings: { 'A-s': { target: '#charm-search-field', focus: true, help: 'Select the charm Search', label: 'Alt + s' }, '/': { target: '.header-search__input', focus: true, help: 'Select the charm Search' }, 'S-1': { callback: function() { this._clearShortcutsModal(); if (document.getElementById('modal-gui-settings'). children.length > 0) { this._clearSettingsModal(); } else { this._displaySettingsModal(); } }, help: 'GUI Settings', label: 'Shift + !' }, 'S-/': { callback: function() { this._clearSettingsModal(); if (document.getElementById('modal-shortcuts'). children.length > 0) { this._clearShortcutsModal(); } else { this._displayShortcutsModal(); } }, help: 'Display this help', label: 'Shift + ?' }, 'S-+': { fire: 'topo.zoom_in', help: 'Zoom In', label: 'Shift + "+"' }, 'S--': { fire: 'topo.zoom_out', help: 'Zoom Out', label: 'Shift + -' }, 'S-0': { fire: 'topo.panToCenter', help: 'Center the model overview', label: 'Shift + 0' }, 'esc': { fire: 'topo.clearState', callback: function() { this._clearSettingsModal(); this._clearShortcutsModal(); }, help: 'Cancel current action', label: 'Esc' }, 'S-d': { callback: function(evt) { views.utils.exportEnvironmentFile(this.db); }, help: 'Export the model', label: 'Shift + d' } }, /** * Activate the keyboard listeners. Only called by the main index.html, * not by the tests' one. * * @method activateHotkeys */ activateHotkeys: function() { var key_map = { '1': 49, '/': 191, '?': 63, '+': 187, '-': 189, enter: 13, esc: 27, backspace: 8, tab: 9, pageup: 33, pagedown: 34}; var code_map = {}; Object.keys(key_map).forEach(k => { const v = key_map[k]; code_map[v] = k; }); this._keybindings = document.addEventListener('keydown', evt => { // Normalize key-code // This gets triggered by different types of elements some YUI some // React. So try and use the native tagName property first, if that // fails then fall back to ReactDOM.findDOMNode(). var tagName = evt.target.tagName; var contentEditable = evt.target.contentEditable; var currentKey; if (code_map[evt.keyCode]) { currentKey = code_map[evt.which]; } else { currentKey = String.fromCharCode(evt.which).toLowerCase(); } if (!tagName) { tagName = ReactDOM.findDOMNode(evt.target).tagName; } if (!contentEditable) { contentEditable = ReactDOM.findDOMNode(evt.target).contentEditable; } // Don't ignore esc in the search box. if (currentKey === 'esc' && evt.target.className === 'header-search__input') { // Remove the focus from the search box. evt.target.blur(); // Target filtering, we want to listen on window // but not honor hotkeys when focused on // text oriented input fields. } else if (['INPUT', 'TEXTAREA'].indexOf(tagName) !== -1 || contentEditable === 'true') { return; } var symbolic = []; if (evt.ctrlKey) { symbolic.push('C');} if (evt.altKey) { symbolic.push('A');} if (evt.shiftKey) { symbolic.push('S');} symbolic.push(currentKey); var trigger = symbolic.join('-'); var spec = this.keybindings[trigger]; if (spec) { if (spec.condition && !spec.condition.call(this)) { // Note that when a condition check fails, // the event still propagates. return; } var target = document.querySelector(spec.target); if (target) { if (spec.toggle) { if (target.classList.contains('hidden')) { target.classList.remove('hidden'); } else { target.classList.add('hidden'); } } if (spec.focus) { target.focus(); } } if (spec.callback) { spec.callback.call(this, evt, target); } // HACK w/o context/view restriction but right direction if (spec.fire) { document.dispatchEvent(new Event(spec.fire)); } // If we handled the event nothing else has to. evt.stopPropagation(); } }); }, /** Return the current model unique identifier. @method _getModelUUID @return {String} The model UUID. */ _getModelUUID: function() { return this.get('modelUUID') || (window.juju_config && window.juju_config.jujuEnvUUID); }, /** * @method initializer * @param {Object} cfg Application configuration data. */ initializer: function(cfg) { // If no cfg is passed in, use a default empty object so we don't blow up // getting at things. cfg = cfg || {}; // If this flag is true, start the application with the console activated. var consoleEnabled = this.get('consoleEnabled'); // Concession to testing, they need muck with console, we cannot as well. if (window.mochaPhantomJS === undefined) { if (consoleEnabled) { consoleManager.native(); } else { consoleManager.noop(); } } /** Reference to the juju.Cookies instance. @property cookieHandler @type {juju.Cookies} @default null */ this.cookieHandler = null; this.renderEnvironment = true; // When a user drags a file over the browser we show notifications which // are drop targets to illustrate what they can do with their selected // file. This array keeps track of those masks and their respective // handlers with a { mask: mask, handlers: handlers } format. this.dragNotifications = []; /** The object used for storing a mapping of previously visited user paths to the type of entity (model, store). e.g. /u/spinach/ghost would map to store. @property userPaths @type {Map} */ this.userPaths = new Map(); // Track anonymous mode. This value will be set to true when anonymous // navigation is allowed, in essence when a GISF anonymous user is being // modeling on a new canvas. this.anonymousMode = false; const config = window.juju_config || {}; config.interactiveLogin = this.get('interactiveLogin'); // Set up a client side database to store state. this.db = new models.Database(); // Create a user store to track authentication details. const userCfg = { externalAuth: this.get('auth'), expiration: window.sessionStorage.getItem('expirationDatetime') }; this.user = this.get('user') || new window.jujugui.User(userCfg); // Instantiate a macaroon bakery, which is used to handle the macaroon // acquisition over HTTP. const webHandler = new Y.juju.environments.web.WebHandler(); const stateGetter = () => { return this.state.current; }; const cookieSetter = (value, callback) => { this.get('charmstore').setAuthCookie(value, callback); }; this.bakery = Y.juju.bakeryutils.newBakery( config, this.user, stateGetter, cookieSetter, webHandler); // Create and set up a new instance of the charmstore. this._setupCharmstore(config, window.jujulib.charmstore); // Create and set up a new instance of the bundleservice. this._setupBundleservice(window.jujulib.bundleservice); // Set up a new modelController instance. this.modelController = new juju.ModelController({ db: this.db, charmstore: this.get('charmstore') }); let environments = juju.environments; // This is wrapped to be called twice. // The early return (at line 478) would state from being set (originally // at line 514). const setUpStateWrapper = function() { // If there is no protocol in the baseURL then prefix the origin when // creating state. let baseURL = cfg.baseUrl; if (baseURL.indexOf('://') < 0) { baseURL = `${window.location.origin}${baseURL}`; } this.state = this._setupState(baseURL); }.bind(this); // Create an environment facade to interact with. // Allow "env" as an attribute/option to ease testing. var env = this.get('env'); if (env) { setUpStateWrapper(); this._init(cfg, env, this.get('controllerAPI')); return; } var ecs = new juju.EnvironmentChangeSet({db: this.db}); this.renderDeploymentBarListener = this._renderDeploymentBar.bind(this); document.addEventListener( 'ecs.changeSetModified', this.renderDeploymentBarListener); document.addEventListener( 'ecs.currentCommitFinished', this.renderDeploymentBarListener); if (this.get('gisf')) { document.body.classList.add('u-is-beta'); } this.defaultPageTitle = 'Juju GUI'; let modelOptions = { user: this.user, ecs: ecs, conn: this.get('conn'), jujuCoreVersion: this.get('jujuCoreVersion'), bundleService: this.get('bundleService') }; let controllerOptions = Object.assign({}, modelOptions); modelOptions.webHandler = new environments.web.WebHandler(); const modelAPI = new environments.GoEnvironment(modelOptions); const controllerAPI = new Y.juju.ControllerAPI(controllerOptions); // For analytics to work we need to set it up before state is set up. // Relies on controllerAPI, is used by state this.sendAnalytics = juju.sendAnalyticsFactory( controllerAPI, window.dataLayer ); setUpStateWrapper(); this.defaultPageTitle = 'Juju GUI'; this._init(cfg, modelAPI, controllerAPI); }, /** Complete the application initialization. @method _init @param {Object} cfg Application configuration data. @param {Object} modelAPI The environment instance. @param {Object} controllerAPI The controller api instance. */ _init: function(cfg, modelAPI, controllerAPI) { // Store the initial model UUID. const modelUUID = this._getModelUUID(); this.set('modelUUID', modelUUID); const controllerCreds = this.user.controller; this.env = modelAPI; // Generate the application state then see if we have to disambiguate // the user portion of the state. const pathState = this.state.generateState(window.location.href, false); let entityPromise = null; if (!pathState.error && pathState.state.user) { // If we have a user component to the state then it is ambiguous. // disambiguate the user state by checking if the user fragment // represents a charm store entity. entityPromise = this._fetchEntityFromUserState(pathState.state.user); } this.controllerAPI = this.setUpControllerAPI( controllerAPI, controllerCreds.user, controllerCreds.password, controllerCreds.macaroons, entityPromise); const getBundleChanges = this.controllerAPI.getBundleChanges.bind( this.controllerAPI); // Create Romulus API client instances. this._setupRomulusServices(window.juju_config, window.jujulib); // Set the modelAPI in the model controller here so // that we know that it's been setup. this.modelController.set('env', this.env); // Create a Bundle Importer instance. this.bundleImporter = new Y.juju.BundleImporter({ db: this.db, modelAPI: this.env, getBundleChanges: getBundleChanges, makeEntityModel: Y.juju.makeEntityModel, charmstore: this.get('charmstore'), hideDragOverNotification: this._hideDragOverNotification.bind(this) }); // Create the ACL object. this.acl = new Y.juju.generateAcl(this.controllerAPI, this.env); this.changesUtils = window.juju.utils.ChangesUtils; this.relationUtils = window.juju.utils.RelationUtils; // Listen for window unloads and trigger the unloadWindow function. window.onbeforeunload = views.utils.unloadWindow.bind(this); // When the environment name becomes available, display it. this.env.after('environmentNameChange', this.onEnvironmentNameChange, this); this.env.after('defaultSeriesChange', this.onDefaultSeriesChange, this); // Once the user logs in, we need to redraw. this.onLoginHandler = this.onLogin.bind(this); document.addEventListener('login', this.onLoginHandler); // Once we know about MAAS server, update the header accordingly. let maasServer = this.env.get('maasServer'); if (!maasServer && this.controllerAPI) { maasServer = this.controllerAPI.get('maasServer'); } if (maasServer) { this._displayMaasLink(maasServer); } else { if (this.controllerAPI) { this.controllerAPI.once('maasServerChange', this._onMaasServer, this); } this.env.once('maasServerChange', this._onMaasServer, this); } // Feed environment changes directly into the database. this.onDeltaBound = this.db.onDelta.bind(this.db); document.addEventListener('delta', this.onDeltaBound); // Handlers for adding and removing services to the service list. this.endpointsController = new juju.EndpointsController({ db: this.db, modelController: this.modelController }); this.endpointsController.bind(); // Stash the location object so that tests can override it. this.location = window.location; // When the connection resets, reset the db, re-login (a delta will // arrive with successful authentication), and redispatch. this.env.after('connectedChange', evt => { this._renderProviderLogo(); if (!evt.newVal) { // The model is not connected, do nothing waiting for a reconnection. console.log('model disconnected'); return; } console.log('model connected'); this.env.userIsAuthenticated = false; // Attempt to log in if we already have credentials available. const credentials = this.user.model; if (credentials.areAvailable) { this.loginToAPIs(null, !!credentials.macaroons, [this.env]); return; } }); // If the database updates, redraw the view (distinct from model updates). // TODO: bound views will automatically update this on individual models. this.bound_on_database_changed = this.on_database_changed.bind(this); document.addEventListener('update', this.bound_on_database_changed); // Watch specific things, (add units), remove db.update above // Note: This hides under the flag as tests don't properly clean // up sometimes and this binding creates spooky interaction // at a distance and strange failures. this.db.machines.after( ['add', 'remove', '*:change'], this.on_database_changed, this); this.db.services.after( ['add', 'remove', '*:change'], this.on_database_changed, this); this.db.relations.after( ['add', 'remove', '*:change'], this.on_database_changed, this); this.db.environment.after( ['add', 'remove', '*:change'], this.on_database_changed, this); this.db.units.after( ['add', 'remove', '*:change'], this.on_database_changed, this); this.db.notifications.after('add', this._renderNotifications, this); // When someone wants a charm to be deployed they fire an event and we // show the charm panel to configure/deploy the service. this._onInitiateDeploy = evt => { this.deployService(evt.detail.charm, evt.detail.ghostAttributes); }; document.addEventListener('initiateDeploy', this._onInitiateDeploy); this._boundAppDragOverHandler = this._appDragOverHandler.bind(this); // These are manually detached in the destructor. ['dragenter', 'dragover', 'dragleave'].forEach((eventName) => { document.addEventListener( eventName, this._boundAppDragOverHandler); }); // In Juju >= 2 we connect to the controller and then to the model. this.controllerAPI.connect(); this.state.bootstrap(); }, /** Sends the discharge token via POST to the storefront. This is used when the GUI is operating in GISF mode, allowing a shared login between the GUI and the storefront. @method _sendGISFPostBack */ _sendGISFPostBack: function() { const dischargeToken = this.user.getMacaroon('identity'); if (!dischargeToken) { console.error('no discharge token in local storage after login'); return; } console.log('sending discharge token to storefront'); const content = 'discharge-token=' + dischargeToken; const webhandler = new Y.juju.environments.web.WebHandler(); webhandler.sendPostRequest( '/_login', {'Content-Type': 'application/x-www-form-urlencoded'}, content); }, /** Auto log the user into the charm store as part of the login process when the GUI operates in a GISF context. */ _ensureLoggedIntoCharmstore: function() { if (!this.user.getMacaroon('charmstore')) { this.get('charmstore').getMacaroon((err, macaroon) => { if (err) { console.error(err); return; } this.storeUser('charmstore', true); console.log('logged into charmstore'); }); } }, /** Creates the second instance of the WebSocket for communication with the Juju controller if it's necessary. A username and password must be supplied if you're connecting to a standalone Juju controller and not to one which requires macaroon authentication. @method setUpControllerAPI @param {Object} controllerAPI Instance of the GoEnvironment class. @param {String} user The username if not using macaroons. @param {String} password The password if not using macaroons. @param {Array} macaroons A list of macaroons that the user has saved. @param {Promise} entityPromise A promise with the entity if any. @return {environments.GoEnvironment} An instance of the environment class with the necessary events attached and values set. Or undefined if we're in a legacy juju model and no controllerAPI instance was supplied. */ setUpControllerAPI: function( controllerAPI, user, password, macaroons, entityPromise) { this.user.controller = { user, password, macaroons }; this.controllerLoginHandler = evt => { const state = this.state; const current = this.state.current; this.anonymousMode = false; if (evt.detail && evt.detail.err) { this._renderLogin(evt.detail.err); return; } this._renderUserMenu(); console.log('successfully logged into controller'); // If the GUI is embedded in storefront, we need to share login // data with the storefront backend and ensure we're already // logged into the charmstore. if (this.get('gisf')) { this._sendGISFPostBack(); this._ensureLoggedIntoCharmstore(); } // If state has a `next` property then that overrides all defaults. const specialState = current.special; const next = specialState && specialState.next; const dd = specialState && specialState.dd; if (state.current.root === 'login') { if (dd) { console.log('initiating direct deploy'); this.maskVisibility(false); this._directDeploy(dd); return; } else if (next) { // There should never be a `next` state if we aren't on login but // adding the state login check here just to be sure. console.log('redirecting to "next" state', next); const {error, state: newState} = state.generateState(next, false); if (error === null) { // The root at this point will be 'login' and because the `next` // url may not explicitly define a new root path we have to set it // to null to clear 'login' from the url. if (!newState.root) { newState.root = null; } newState.special = null; this.maskVisibility(false); state.changeState(newState); return; } console.error('error redirecting to previous state', error); return; } } // If the user is connected to a model then the modelList will be // fetched by the modelswitcher component. if (this.env.get('modelUUID')) { return; } const modelUUID = this._getModelUUID(); if (modelUUID && !current.profile && current.root !== 'store') { // A model uuid was defined in the config so attempt to connect to it. this._listAndSwitchModel(null, modelUUID); } else if (entityPromise !== null) { this._disambiguateUserState(entityPromise); } else { // Drop into disconnected mode and show the profile but only if there // is no state defined in root or store. If there is a state defined // either of those then we want to let that dispatcher handle the // routing. this.maskVisibility(false); const isLogin = current.root === 'login'; const previousState = state.previous; const previousRoot = previousState && previousState.root || null; // If there was a previous root before the login then redirect to that // otherwise go to the profile. let newState = { // We don't want to redirect to the previous root if it was the // login page. profile: previousRoot && previousRoot !== 'login' ? null : current.profile, root: isLogin ? previousRoot : current.root }; // If the current root is 'login' after logging into the controller, // and there is no root, no store and no profile defined then we // want to render the users profile. if ( !current.store && !newState.profile && newState.root !== 'account' && (isLogin || !current.root) && this.get('gisf') ) { newState.profile = this.user.displayName; } state.changeState(newState); } }; document.addEventListener('login', this.controllerLoginHandler); controllerAPI.after('connectedChange', evt => { if (!evt.newVal) { // The controller is not connected, do nothing waiting for a // reconnection. console.log('controller disconnected'); return; } console.log('controller connected'); const creds = this.user.controller; const gisf = this.get('gisf'); const currentState = this.state.current; const rootState = currentState ? currentState.root : null; // If an anonymous GISF user lands on the GUI at /new then don't // attempt to log into the controller. if (( !creds.areAvailable && gisf && rootState === 'new' ) || ( this.anonymousMode && rootState !== 'login' )) { this.anonymousMode = true; console.log('now in anonymous mode'); this.maskVisibility(false); return; } if (!creds.areAvailable || // When using direct deploy when a user is not logged in it will // navigate to show the login if we do not have this state check. (currentState.special && currentState.special.dd)) { this._displayLogin(); return; } // If macaroons are available or if we have an external token from // Keystone, then proceed with the macaroons based authentication. if (creds.macaroons || creds.areExternal) { this.loginToAPIs(null, true, [this.controllerAPI]); return; } // The traditional user/password authentication does not make sense if // the GUI is embedded in the storefront. if (!gisf) { this.loginToAPIs(null, false, [this.controllerAPI]); } }); controllerAPI.set('socket_url', this.createSocketURL(this.get('controllerSocketTemplate'))); return controllerAPI; }, /** Handles logging into both the env and controller api WebSockets. @method loginToAPIs @param {Object} credentials The credentials for the controller APIs. @param {Boolean} useMacaroons Whether to use macaroon based auth (macaraq) or simple username/password auth. @param {Array} apis The apis instances that we should be logging into. Defaults to [this.controllerAPI, this.env]. */ loginToAPIs: function( credentials, useMacaroons, apis=[this.controllerAPI, this.env]) { if (useMacaroons) { apis.forEach(api => { // The api may be unset if the current Juju does not support it. if (api && api.get('connected')) { console.log(`logging into ${api.name} with macaroons`); api.loginWithMacaroon( this.bakery, this._apiLoginHandler.bind(this, api)); } }); return; } apis.forEach(api => { // The api may be unset if the current Juju does not support it. if (!api) { return; } // Ensure the credentials are set, if available. if (credentials && api.name === 'model-api') { this.user.model = credentials; } else if (credentials) { this.user.controller = credentials; } if (api.get('connected')) { console.log(`logging into ${api.name} with user and password`); api.login(); } }); }, /** Callback handler for the API loginWithMacaroon method which handles the "redirection required" error message. @method _apiLoginHandler @param {Object} api The API that the user is attempting to log into. ex) this.env or this.controllerAPI @param {String} err The login error message, if any. */ _apiLoginHandler: function(api, err) { if (this.state.current.root === 'login') { this.state.changeState({root: null}); } if (!err) { return; } if (!views.utils.isRedirectError(err)) { // There is nothing to do in this case, and the user is already // prompted with the error in the login view. console.log(`cannot log into ${api.name}: ${err}`); return; } // If the error is that redirection is required then we have to // make a request to get the appropriate model connection information. console.log(`redirection required for loggin into ${api.name}`); api.redirectInfo((err, servers) => { if (err) { this.db.notifications.add({ title: 'Unable to log into Juju', message: err, level: 'error' }); return; } // Loop through the available servers and find the public IP. const hosts = servers[0]; const publicHosts = hosts.filter(host => host.scope === 'public'); if (!publicHosts.length) { this.db.notifications.add({ title: 'Model connection error', message: 'Cannot find a public host for connecting to the model', level: 'error' }); console.error('no public hosts found: ' + JSON.stringify(servers)); return; } const publicHost = publicHosts[0]; // Switch to the redirected model. // Make sure we keep the change set by not clearing the db when // creating a model with change set (last param false). this.switchEnv(this.createSocketURL( this.get('socketTemplate'), this.get('modelUUID'), publicHost.value, publicHost.port), null, null, null, true, false); }); }, /** Renders the login component. @method _renderLogin @param {String} err Possible authentication error, or null if no error message must be displayed. */ _renderLogin: function(err) { document.getElementById('loading-message').style.display = 'none'; // XXX j.c.sackett 2017-01-30 Right now USSO link is using // loginToController, while loginToAPIs is used by the login form. // We want to use loginToAPIs everywhere since it handles more. const loginToController = this.controllerAPI.loginWithMacaroon.bind( this.controllerAPI, this.bakery); const controllerIsConnected = () => { return this.controllerAPI && this.controllerAPI.get('connected'); }; ReactDOM.render( <window.juju.components.Login controllerIsConnected={controllerIsConnected} errorMessage={err} gisf={this.get('gisf')} loginToAPIs={this.loginToAPIs.bind(this)} loginToController={loginToController} />, document.getElementById('login-container')); }, /** Renders the Log out component or log in link depending on the environment the GUI is executing in. */ _renderUserMenu: function() { const controllerAPI = this.controllerAPI; const linkContainerId = 'profile-link-container'; const linkContainer = document.getElementById(linkContainerId); if (!linkContainer) { console.error(`no linkContainerId: ${linkContainerId}`); return; } const charmstore = this.get('charmstore'); const bakery = this.bakery; const USSOLoginLink = (<window.juju.components.USSOLoginLink displayType={'text'} loginToController={controllerAPI.loginWithMacaroon.bind( controllerAPI, bakery)} />); const LogoutLink = (<window.juju.components.Logout logout={this.logout.bind(this)} clearCookie={bakery.storage.clear.bind(bakery.storage)} gisfLogout={window.juju_config.gisfLogout || ''} gisf={window.juju_config.gisf || false} charmstoreLogoutUrl={charmstore.getLogoutUrl()} getUser={this.getUser.bind(this, 'charmstore')} clearUser={this.clearUser.bind(this, 'charmstore')} // If the charmbrowser is open then don't show the logout link. visible={!this.state.current.store} locationAssign={window.location.assign.bind(window.location)} />); const navigateUserProfile = () => { const username = this.user.displayName; if (!username) { return; } views.utils.showProfile( this.env && this.env.get('ecs'), this.state.changeState.bind(this.state), username); }; const navigateUserAccount = () => { const username = this.user.displayName; if (!username) { return; } views.utils.showAccount( this.env && this.env.get('ecs'), this.state.changeState.bind(this.state)); }; ReactDOM.render(<window.juju.components.UserMenu controllerAPI={controllerAPI} LogoutLink={LogoutLink} navigateUserAccount={navigateUserAccount} navigateUserProfile={navigateUserProfile} USSOLoginLink={USSOLoginLink} />, linkContainer); }, /** Renders the user profile component. @method _renderUserProfile @param {Object} state - The app state. @param {Function} next - Call to continue dispatching. */ _renderUserProfile: function(state, next) { // XXX Jeff - 1-2-2016 - Because of a bug in the state system the profile // view renders itself and then makes requests to identity before the // controller is setup and the user has successfully logged in. As a // temporary workaround we will just prevent rendering the profile until // the controller is connected. // XXX frankban: it seems that the profile is rendered even when the // profile is not included in the state. const guiState = state.gui || {}; if ( guiState.deploy !== undefined || !state.profile || !this.controllerAPI.get('connected') || !this.controllerAPI.userIsAuthenticated ) { return; } // XXX Jeff - 18-11-2016 - This profile gets rendered before the // controller has completed connecting and logging in when in gisf. The // proper fix is to queue up the RPC calls but due to time constraints // we're setting up this handler to simply re-render the profile when // the controller is properly connected. const facadesExist = !!this.controllerAPI.get('facades'); if (!facadesExist) { const handler = this.controllerAPI.after('facadesChange', e => { if (e.newVal) { this._renderUserProfile(state, next); handler.detach(); } }); } const charmstore = this.get('charmstore'); const utils = views.utils; const currentModel = this.get('modelUUID'); // When going to the profile view, we are theoretically no longer // connected to any model. Setting the current model identifier to null // also allows switching to the same model from the profile view. this.set('modelUUID', null); // NOTE: we need to clone this.get('users') below; passing in without // cloning breaks React's ability to distinguish between this.props and // nextProps on the lifecycle methods. ReactDOM.render( <window.juju.components.UserProfile acl={this.acl} addNotification= {this.db.notifications.add.bind(this.db.notifications)} charmstore={charmstore} currentModel={currentModel} d3={d3} facadesExist={facadesExist} listBudgets={this.plans.listBudgets.bind(this.plans)} listModelsWithInfo={ this.controllerAPI.listModelsWithInfo.bind(this.controllerAPI)} getKpiMetrics={this.plans.getKpiMetrics.bind(this.plans)} changeState={this.state.changeState.bind(this.state)} destroyModels={ this.controllerAPI.destroyModels.bind(this.controllerAPI)} getAgreements={this.terms.getAgreements.bind(this.terms)} getDiagramURL={charmstore.getDiagramURL.bind(charmstore)} interactiveLogin={this.get('interactiveLogin')} pluralize={utils.pluralize.bind(this)} setPageTitle={this.setPageTitle} staticURL={window.juju_config.staticURL} storeUser={this.storeUser.bind(this)} switchModel={utils.switchModel.bind(this, this.env)} userInfo={this._getUserInfo(state)} />, document.getElementById('top-page-container')); }, /** Generate a user info object. @param {Object} state - The application state. */ _getUserInfo: function(state) { const username = state.profile || this.user.displayName || ''; const userInfo = { external: username, isCurrent: false, profile: username }; if (userInfo.profile === this.user.displayName) { userInfo.isCurrent = true; // This is the current user, and might be a local one. Use the // authenticated charm store user as the external (USSO) name. const users = this.get('users') || {}; userInfo.external = users.charmstore ? users.charmstore.user : null; } return userInfo; }, /** The cleanup dispatcher for the user profile path. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _clearUserProfile: function(state, next) { ReactDOM.unmountComponentAtNode( document.getElementById('top-page-container')); next(); }, /** Renders the ISV profile component. @method _renderISVProfile */ _renderISVProfile: function() { ReactDOM.render( <window.juju.components.ISVProfile d3={d3} />, document.getElementById('top-page-container')); // The model name should not be visible when viewing the profile. this._renderBreadcrumb({ showEnvSwitcher: false }); }, /** Renders the account component. @method _renderAccount @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _renderAccount: function(state, next) { const controllerAPI = this.controllerAPI; if (!controllerAPI || !controllerAPI.userIsAuthenticated) { // If the controller isn't ready yet then don't render anything. return; } // When going to the account view, we are theoretically no longer // connected to any model. this.set('modelUUID', null); ReactDOM.render( <window.juju.components.Account acl={this.acl} addAddress={ this.payment && this.payment.addAddress.bind(this.payment)} addBillingAddress={ this.payment && this.payment.addBillingAddress.bind(this.payment)} addNotification={ this.db.notifications.add.bind(this.db.notifications)} controllerIsReady={this._controllerIsReady.bind(this)} createCardElement={ this.stripe && this.stripe.createCardElement.bind(this.stripe)} createPaymentMethod={ this.payment && this.payment.createPaymentMethod.bind(this.payment)} createToken={this.stripe && this.stripe.createToken.bind(this.stripe)} createUser={ this.payment && this.payment.createUser.bind(this.payment)} generateCloudCredentialName={views.utils.generateCloudCredentialName} getUser={this.payment && this.payment.getUser.bind(this.payment)} getCharges={ this.payment && this.payment.getCharges.bind(this.payment)} getCloudCredentialNames={ controllerAPI.getCloudCredentialNames.bind(controllerAPI)} getCloudProviderDetails={views.utils.getCloudProviderDetails.bind( views.utils)} getCountries={ this.payment && this.payment.getCountries.bind(this.payment)} getReceipt={ this.payment && this.payment.getReceipt.bind(this.payment)} listClouds={controllerAPI.listClouds.bind(controllerAPI)} removeAddress={ this.payment && this.payment.removeAddress.bind(this.payment)} removeBillingAddress={ this.payment && this.payment.removeBillingAddress.bind( this.payment)} removePaymentMethod={ this.payment && this.payment.removePaymentMethod.bind(this.payment)} revokeCloudCredential={ controllerAPI.revokeCloudCredential.bind(controllerAPI)} sendAnalytics={this.sendAnalytics} showPay={window.juju_config.payFlag || false} updateCloudCredential={ controllerAPI.updateCloudCredential.bind(controllerAPI)} updateAddress={ this.payment && this.payment.updateAddress.bind(this.payment)} updateBillingAddress={ this.payment && this.payment.updateBillingAddress.bind( this.payment)} updatePaymentMethod={ this.payment && this.payment.updatePaymentMethod.bind(this.payment)} user={this.user.controller.user} userInfo={this._getUserInfo(state)} validateForm={views.utils.validateForm.bind(views.utils)} />, document.getElementById('top-page-container')); next(); }, /** The cleanup dispatcher for the account path. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _clearAccount: function(state, next) { ReactDOM.unmountComponentAtNode( document.getElementById('top-page-container')); next(); }, /** Renders the Environment Size Display component to the page in the designated element. @method _renderEnvSizeDisplay @param {Integer} serviceCount The serviceCount to display. @param {Integer} machineCount The machineCount to display. */ _renderEnvSizeDisplay: function(serviceCount=0, machineCount=0) { ReactDOM.render( <window.juju.components.EnvSizeDisplay appState={this.state} machineCount={machineCount} pluralize={views.utils.pluralize.bind(this)} serviceCount={serviceCount} />, document.getElementById('env-size-display-container')); }, /** Renders the Header Search component to the page in the designated element. @method _renderHeaderSearch */ _renderHeaderSearch: function() { ReactDOM.render( <window.juju.components.HeaderSearch appState={this.state} />, document.getElementById('header-search-container')); }, _renderHeaderHelp: function() { ReactDOM.render( <window.juju.components.HeaderHelp appState={this.state} gisf={this.get('gisf')} displayShortcutsModal={this._displayShortcutsModal.bind(this)} user={this.user} />, document.getElementById('header-help')); }, _renderHeaderLogo: function() { const userName = this.user.displayName; const gisf = this.get('gisf'); const homePath = gisf ? '/' : this.state.generatePath({profile: userName}); const showProfile = () => this.state.changeState({ profile: userName, model: null, store: null, root: null, search: null, account: null, user: null }); ReactDOM.render( <window.juju.components.HeaderLogo gisf={gisf} homePath={homePath} showProfile={showProfile} />, document.getElementById('header-logo')); }, /** Renders the notification component to the page in the designated element. @method _renderNotifications */ _renderNotifications: function(e) { var notification = null; if (e && e.details) { notification = e.details[0].model.getAttrs(); } ReactDOM.render( <window.juju.components.NotificationList notification={notification}/>, document.getElementById('notifications-container')); }, /** Renders the Deployment component to the page in the designated element. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _renderDeployment: function(state, next) { const env = this.env; const db = this.db; const connected = this.env.get('connected'); const modelName = env.get('environmentName') || 'mymodel'; const utils = views.utils; const ecs = env.get('ecs'); const currentChangeSet = ecs.getCurrentChangeSet(); const deployState = state.gui.deploy; const ddData = deployState ? JSON.parse(deployState) : null; if (Object.keys(currentChangeSet).length === 0 && !ddData) { // If there are no changes then close the deployment flow. This is to // prevent showing the deployment flow if the user clicks back in the // browser or navigates directly to the url. This changeState needs to // happen in app.js, not the component otherwise it will have to try and // interrupt the mount to unmount the component. this.state.changeState({ gui: { deploy: null } }); return; } const changesUtils = this.changesUtils; const controllerAPI = this.controllerAPI; const services = db.services; // Auto place the units. This is probably not the best UX, but is required // to display the machines in the deployment flow. this._autoPlaceUnits(); let cloud = env.get('providerType'); if (cloud) { cloud = { cloudType: cloud, name: env.get('cloud') }; } const getUserName = () => { return this.user.username; }; const loginToController = controllerAPI.loginWithMacaroon.bind( controllerAPI, this.bakery); const charmstore = this.get('charmstore'); const isLoggedIn = () => this.controllerAPI.userIsAuthenticated; ReactDOM.render( <window.juju.components.DeploymentFlow acl={this.acl} addAgreement={this.terms.addAgreement.bind(this.terms)} addNotification={db.notifications.add.bind(db.notifications)} applications={services.toArray()} charmstore={charmstore} changesFilterByParent={ changesUtils.filterByParent.bind(changesUtils, currentChangeSet)} changeState={this.state.changeState.bind(this.state)} cloud={cloud} controllerIsReady={this._controllerIsReady.bind(this)} createToken={this.stripe && this.stripe.createToken.bind(this.stripe)} createCardElement={ this.stripe && this.stripe.createCardElement.bind(this.stripe)} createUser={ this.payment && this.payment.createUser.bind(this.payment)} credential={env.get('credential')} changes={currentChangeSet} charmsGetById={db.charms.getById.bind(db.charms)} deploy={utils.deploy.bind(utils, this)} sendAnalytics={this.sendAnalytics} setModelName={env.set.bind(env, 'environmentName')} formatConstraints={utils.formatConstraints.bind(utils)} generateAllChangeDescriptions={ changesUtils.generateAllChangeDescriptions.bind( changesUtils, services, db.units)} generateCloudCredentialName={utils.generateCloudCredentialName} generateMachineDetails={ utils.generateMachineDetails.bind( utils, env.genericConstraints, db.units)} getAgreementsByTerms={ this.terms.getAgreementsByTerms.bind(this.terms)} isLoggedIn={isLoggedIn} getCloudCredentials={ controllerAPI.getCloudCredentials.bind(controllerAPI)} getCloudCredentialNames={ controllerAPI.getCloudCredentialNames.bind(controllerAPI)} getCloudProviderDetails={utils.getCloudProviderDetails.bind(utils)} getCurrentChangeSet={ecs.getCurrentChangeSet.bind(ecs)} getCountries={ this.payment && this.payment.getCountries.bind(this.payment) || null} getDiagramURL={charmstore.getDiagramURL.bind(charmstore)} getEntity={charmstore.getEntity.bind(charmstore)} getUser={this.payment && this.payment.getUser.bind(this.payment)} getUserName={getUserName} gisf={this.get('gisf')} groupedChanges={changesUtils.getGroupedChanges(currentChangeSet)} listBudgets={this.plans.listBudgets.bind(this.plans)} listClouds={controllerAPI.listClouds.bind(controllerAPI)} listPlansForCharm={this.plans.listPlansForCharm.bind(this.plans)} loginToController={loginToController} makeEntityModel={Y.juju.makeEntityModel} modelCommitted={connected} modelName={modelName} ddData={ddData} profileUsername={this._getUserInfo(state).profile} region={env.get('region')} renderMarkdown={marked} servicesGetById={services.getById.bind(services)} showPay={window.juju_config.payFlag || false} showTerms={this.terms.showTerms.bind(this.terms)} updateCloudCredential={ controllerAPI.updateCloudCredential.bind(controllerAPI)} validateForm={utils.validateForm.bind(utils)} withPlans={false} />, document.getElementById('deployment-container')); }, /** The cleanup dispatcher for the deployment flow state path. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _clearDeployment: function(state, next) { ReactDOM.unmountComponentAtNode( document.getElementById('deployment-container')); next(); }, /** Renders the Deployment component to the page in the designated element. @method _renderDeploymentBar */ _renderDeploymentBar: function() { var env = this.env; var ecs = env.get('ecs'); var db = this.db; var services = db.services; var servicesArray = services.toArray(); var machines = db.machines.toArray(); var units = db.units; var changesUtils = this.changesUtils; ReactDOM.render( <window.juju.components.DeploymentBar acl={this.acl} changeState={this.state.changeState.bind(this.state)} currentChangeSet={ecs.getCurrentChangeSet()} generateChangeDescription={ changesUtils.generateChangeDescription.bind( changesUtils, services, units)} hasEntities={servicesArray.length > 0 || machines.length > 0} modelCommitted={this.env.get('connected')} sendAnalytics={this.sendAnalytics} />, document.getElementById('deployment-bar-container')); }, /** Report whether the controller API connection is ready, connected and authenticated. @return {Boolean} Whether the controller is ready. */ _controllerIsReady: function() { return !!( this.controllerAPI && this.controllerAPI.get('connected') && this.controllerAPI.userIsAuthenticated ); }, /** Display or hide the sharing modal. @method _sharingVisibility @param {Boolean} visibility Controls whether to show (true) or hide (false); defaults to true. */ _sharingVisibility: function(visibility = true) { const sharing = document.getElementById('sharing-container'); if (!visibility) { ReactDOM.unmountComponentAtNode(sharing); return; } const db = this.db; const env = this.env; const grantRevoke = (action, username, access, callback) => { if (this.get('gisf') && username.indexOf('@') === -1) { username += '@external'; } action(env.get('modelUUID'), [username], access, callback); }; const controllerAPI = this.controllerAPI; const grantAccess = controllerAPI.grantModelAccess.bind(controllerAPI); const revokeAccess = controllerAPI.revokeModelAccess.bind(controllerAPI); ReactDOM.render( <window.juju.components.Sharing addNotification={db.notifications.add.bind(db.notifications)} canShareModel={this.acl.canShareModel()} closeHandler={this._sharingVisibility.bind(this, false)} getModelUserInfo={env.modelUserInfo.bind(env)} grantModelAccess={grantRevoke.bind(this, grantAccess)} humanizeTimestamp={views.utils.humanizeTimestamp} revokeModelAccess={grantRevoke.bind(this, revokeAccess)} />, sharing); }, /** Renders the model action components to the page in the designated element. @method _renderModelActions */ _renderModelActions: function() { const db = this.db; const utils = views.utils; const env = this.env; ReactDOM.render( <window.juju.components.ModelActions acl={this.acl} appState={this.state} changeState={this.state.changeState.bind(this.state)} exportEnvironmentFile={ utils.exportEnvironmentFile.bind(utils, db)} hideDragOverNotification={this._hideDragOverNotification.bind(this)} importBundleFile={this.bundleImporter.importBundleFile.bind( this.bundleImporter)} renderDragOverNotification={ this._renderDragOverNotification.bind(this)} sharingVisibility={this._sharingVisibility.bind(this)} loadingModel={env.loading} userIsAuthenticated={env.userIsAuthenticated} />, document.getElementById('model-actions-container')); }, /** Renders the logo for the current cloud provider. @method _renderProviderLogo */ _renderProviderLogo: function() { const container = document.getElementById('provider-logo-container'); const cloudProvider = this.env.get('providerType'); let providerDetails = views.utils.getCloudProviderDetails(cloudProvider); const currentState = this.state.current || {}; const isDisabled = ( // There is no provider. !cloudProvider || // It's not possible to get provider details. !providerDetails || // We are in the profile page. currentState.profile || // We are in the account page. currentState.root === 'account' ); const classes = classNames( 'provider-logo', { 'provider-logo--disabled': isDisabled, [`provider-logo--${cloudProvider}`]: cloudProvider } ); const scale = 0.65; if (!providerDetails) { // It's possible that the GUI is being run on a provider that we have // not yet setup in the cloud provider details. providerDetails = {}; } ReactDOM.render( <div className={classes}> <window.juju.components.SvgIcon height={providerDetails.svgHeight * scale} name={providerDetails.id || ''} width={providerDetails.svgWidth * scale} /> </div>, container); }, /** Renders the zoom component to the page in the designated element. @method _renderZoom */ _renderZoom: function() { ReactDOM.render( <window.juju.components.Zoom topo={this.views.environment.instance.topo} />, document.getElementById('zoom-container')); }, /** Renders the Added Services component to the page in the appropriate element. @method _renderAddedServices @param {String} hoveredId An id for a service. */ _renderAddedServices: function(hoveredId) { const instance = this.views.environment.instance; if (!instance) { // TODO frankban: investigate in what cases instance is undefined on // the environment object. Is this some kind of race? return; } const topo = instance.topo; const ServiceModule = topo.modules.ServiceModule; // Set up a handler for syncing the service token hover. This needs to be // attached only when the component is visible otherwise the added // services component will try to render if the user hovers a service // when they have the service details open. if (this.hoverService) { document.removeEventListener('topo.hoverService', this.hoverService); } this.hoverService = evt => { this._renderAddedServices(evt.detail.id); }; document.addEventListener('topo.hoverService', this.hoverService); // Deselect the active service token. This needs to happen so that when a // user closes the service details the service token deactivates. ServiceModule.deselectNodes(); const db = this.db; ReactDOM.render( <window.juju.components.Panel instanceName="inspector-panel" visible={db.services.size() > 0}> <window.juju.components.AddedServicesList services={db.services} hoveredId={hoveredId} updateUnitFlags={db.updateUnitFlags.bind(db)} findRelatedServices={db.findRelatedServices.bind(db)} findUnrelatedServices={db.findUnrelatedServices.bind(db)} getUnitStatusCounts={views.utils.getUnitStatusCounts} hoverService={ServiceModule.hoverService.bind(ServiceModule)} panToService={ServiceModule.panToService.bind(ServiceModule)} changeState={this.state.changeState.bind(this.state)} /> </window.juju.components.Panel>, document.getElementById('inspector-container')); }, /** The cleanup dispatcher for the inspector state path. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _clearInspector: function(state, next) { ReactDOM.unmountComponentAtNode( document.getElementById('inspector-container')); next(); }, /** Renders the Inspector component to the page. @param {Object} state - The app state. @param {Function} next - Call to continue dispatching. */ _renderInspector: function(state, next) { const relationUtils = this.relationUtils; const utils = views.utils; const instance = this.views.environment.instance; if (!instance) { return; } const topo = instance.topo; const charmstore = this.get('charmstore'); let inspector = {}; const inspectorState = state.gui.inspector; const service = this.db.services.getById(inspectorState.id); const localType = inspectorState.localType; // If there is a hoverService event listener then we need to detach it // when rendering the inspector. if (this.hoverService) { document.removeEventListener('topo.hoverService', this.hoverService); } const model = this.env; const db = this.db; // If the url was provided with a service id which isn't in the localType // db then change state back to the added services list. This usually // happens if the user tries to visit the inspector of a ghost service // id which no longer exists. if (service) { // Select the service token. topo.modules.ServiceModule.selectService(service.get('id')); const charm = db.charms.getById(service.get('charm')); const relatableApplications = relationUtils.getRelatableApplications( db, models.getEndpoints(service, this.endpointsController)); const ecs = model.get('ecs'); const addCharm = (url, callback, options) => { model.addCharm(url, charmstore, callback, options); }; inspector = ( <window.juju.components.Inspector acl={this.acl} addCharm={addCharm} addGhostAndEcsUnits={utils.addGhostAndEcsUnits.bind( this, db, model, service)} addNotification={db.notifications.add.bind(db.notifications)} appState={this.state} charm={charm} clearState={utils.clearState.bind(this, topo)} createMachinesPlaceUnits={utils.createMachinesPlaceUnits.bind( this, db, model, service)} createRelation={relationUtils.createRelation.bind(this, db, model)} destroyService={utils.destroyService.bind( this, db, model, service)} destroyRelations={this.relationUtils.destroyRelations.bind( this, db, model)} destroyUnits={utils.destroyUnits.bind(this, model)} displayPlans={utils.compareSemver( this.get('jujuCoreVersion'), '2') > -1} getCharm={model.get_charm.bind(model)} getUnitStatusCounts={utils.getUnitStatusCounts} getYAMLConfig={utils.getYAMLConfig.bind(this)} envResolved={model.resolved.bind(model)} exposeService={model.expose.bind(model)} getAvailableEndpoints={relationUtils.getAvailableEndpoints.bind( this, this.endpointsController, db, models.getEndpoints)} getAvailableVersions={charmstore.getAvailableVersions.bind( charmstore)} getServiceById={db.services.getById.bind(db.services)} getServiceByName={db.services.getServiceByName.bind(db.services)} linkify={utils.linkify} modelUUID={this.get('modelUUID') || ''} providerType={model.get('providerType') || ''} relatableApplications={relatableApplications} service={service} serviceRelations={ relationUtils.getRelationDataForService(db, service)} setCharm={model.setCharm.bind(model)} setConfig={model.set_config.bind(model)} showActivePlan={this.plans.showActivePlan.bind(this.plans)} showPlans={window.juju_config.plansFlag || false} unexposeService={model.unexpose.bind(model)} unplaceServiceUnits={ecs.unplaceServiceUnits.bind(ecs)} updateServiceUnitsDisplayname={ db.updateServiceUnitsDisplayname.bind(db)} /> ); } else if (localType && window.localCharmFile) { // When dragging a local charm zip over the canvas it animates the // drag over notification which needs to be closed when the inspector // is opened. this._hideDragOverNotification(); const localCharmHelpers = juju.localCharmHelpers; inspector = ( <window.juju.components.LocalInspector acl={this.acl} changeState={this.state.changeState.bind(this.state)} file={window.localCharmFile} localType={localType} services={db.services} series={utils.getSeriesList()} upgradeServiceUsingLocalCharm={ localCharmHelpers.upgradeServiceUsingLocalCharm.bind( this, model, db)} uploadLocalCharm={ localCharmHelpers.uploadLocalCharm.bind( this, model, db)} /> ); } else { this.state.changeState({gui: {inspector: null}}); return; } ReactDOM.render( <window.juju.components.Panel instanceName="inspector-panel" visible={true}> {inspector} </window.juju.components.Panel>, document.getElementById('inspector-container')); next(); }, /** Renders the Charmbrowser component to the page in the designated element. @param {Object} state - The app state. @param {Function} next - Call to continue dispatching. */ _renderCharmbrowser: function(state, next) { const utils = views.utils; const charmstore = this.get('charmstore'); // Configure syntax highlighting for the markdown renderer. marked.setOptions({ highlight: function(code, lang) { const language = Prism.languages[lang]; if (language) { return Prism.highlight(code, language); } } }); /* Retrieve from the charm store information on the charm or bundle with the given new style id. @returns {Object} The XHR reference for the getEntity call. */ const getEntity = (id, callback) => { let url; try { url = window.jujulib.URL.fromString(id); } catch(err) { callback(err, {}); return; } // Get the entity and return the XHR. return charmstore.getEntity(url.legacyPath(), callback); }; const getModelName = () => this.env.get('environmentName'); ReactDOM.render( <window.juju.components.Charmbrowser acl={this.acl} apiUrl={charmstore.url} charmstoreSearch={charmstore.search.bind(charmstore)} deployTarget={this.deployTarget.bind(this, charmstore)} series={utils.getSeriesList()} importBundleYAML={this.bundleImporter.importBundleYAML.bind( this.bundleImporter)} getBundleYAML={charmstore.getBundleYAML.bind(charmstore)} getEntity={getEntity} getFile={charmstore.getFile.bind(charmstore)} getDiagramURL={charmstore.getDiagramURL.bind(charmstore)} getModelName={getModelName} gisf={this.get('gisf')} listPlansForCharm={this.plans.listPlansForCharm.bind(this.plans)} renderMarkdown={marked} deployService={this.deployService.bind(this)} appState={this.state} utils={utils} staticURL={window.juju_config.staticURL} charmstoreURL={ utils.ensureTrailingSlash(window.juju_config.charmstoreURL)} apiVersion={window.jujulib.charmstoreAPIVersion} addNotification={ this.db.notifications.add.bind(this.db.notifications)} makeEntityModel={Y.juju.makeEntityModel} setPageTitle={this.setPageTitle.bind(this)} showTerms={this.terms.showTerms.bind(this.terms)} urllib={window.jujulib.URL} />, document.getElementById('charmbrowser-container')); next(); }, /** The cleanup dispatcher for the store state path. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _clearCharmbrowser: function(state, next) { if (state.search || state.store) { // State calls the cleanup methods on every dispatch even if the state // object exists between calls. Maybe this should be updated in state // but for now if we know that the new state still contains the // charmbrowser then just let the subsequent render method update // the rendered component. return; } ReactDOM.unmountComponentAtNode( document.getElementById('charmbrowser-container')); next(); }, /** The cleanup dispatcher for the root state path. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _clearLogin: function(state, next) { ReactDOM.unmountComponentAtNode( document.getElementById('login-container')); if (next) { next(); } }, _displayShortcutsModal: function() { ReactDOM.render( <window.juju.components.ModalShortcuts closeModal={this._clearShortcutsModal.bind(this)} guiVersion={window.GUI_VERSION.version} keybindings={this.keybindings} />, document.getElementById('modal-shortcuts')); }, _displaySettingsModal: function() { ReactDOM.render( <window.juju.components.ModalGUISettings closeModal={this._clearSettingsModal.bind(this)} localStorage={localStorage} />, document.getElementById('modal-gui-settings')); }, /** The cleanup dispatcher keyboard shortcuts modal. */ _clearShortcutsModal: function() { ReactDOM.unmountComponentAtNode( document.getElementById('modal-shortcuts')); }, /** The cleanup dispatcher global settings modal. */ _clearSettingsModal: function() { ReactDOM.unmountComponentAtNode( document.getElementById('modal-gui-settings')); }, /** Handles rendering and/or updating the machine UI component. @param {Object} state - The app state. @param {Function} next - Call to continue dispatching. */ _renderMachineView: function(state, next) { const db = this.db; const ecs = this.env.get('ecs'); const utils = views.utils; const genericConstraints = this.env.genericConstraints; ReactDOM.render( <window.juju.components.MachineView acl={this.acl} addGhostAndEcsUnits={utils.addGhostAndEcsUnits.bind( this, this.db, this.env)} autoPlaceUnits={this._autoPlaceUnits.bind(this)} changeState={this.state.changeState.bind(this.state)} createMachine={this._createMachine.bind(this)} destroyMachines={this.env.destroyMachines.bind(this.env)} environmentName={db.environment.get('name') || ''} generateMachineDetails={ utils.generateMachineDetails.bind( utils, genericConstraints, db.units)} machines={db.machines} parseConstraints={ utils.parseConstraints.bind(utils, genericConstraints)} placeUnit={this.env.placeUnit.bind(this.env)} providerType={this.env.get('providerType') || ''} removeUnits={this.env.remove_units.bind(this.env)} services={db.services} series={window.jujulib.CHARM_SERIES} units={db.units} updateMachineConstraints={ecs.updateMachineConstraints.bind(ecs)} updateMachineSeries={ecs.updateMachineSeries.bind(ecs)} />, document.getElementById('machine-view')); next(); }, /** The cleanup dispatcher for the machines state path. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _clearMachineView: function(state, next) { ReactDOM.unmountComponentAtNode( document.getElementById('machine-view')); next(); }, /** Renders the mask and animations for the drag over notification for when a user drags a yaml file or zip file over the canvas. @method _renderDragOverNotification @param {Boolean} showIndicator */ _renderDragOverNotification: function(showIndicator = true) { this.views.environment.instance.fadeHelpIndicator(showIndicator); ReactDOM.render( <window.juju.components.ExpandingProgress />, document.getElementById('drag-over-notification-container')); }, /** Handles the state changes for the model key. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _handleModelState: function(state, next) { const env = this.env; if (this.get('modelUUID') !== state.model.uuid || (!env.get('connected') && !env.get('connecting'))) { this._switchModelToUUID(state.model.uuid); } next(); }, /** Switches to the specified UUID, or if none is provided then switches to the unconnected mode. @param {String} uuid The uuid of the model to switch to, or none. */ _switchModelToUUID: function(uuid) { let socketURL = undefined; if (uuid) { console.log('switching to model: ', uuid); this.set('modelUUID', uuid); socketURL = this.createSocketURL(this.get('socketTemplate'), uuid); } else { console.log('switching to disconnected mode'); this.set('modelUUID', null); } this.switchEnv(socketURL); }, /** Determines if the user state is a store path or a model path. @param {String} userState The state value for the 'user' key. @return {Promise} A promise with the charmstore entity if one exists. */ _fetchEntityFromUserState: function(userState) { const userPaths = this.userPaths; const entityCache = userPaths.get(userState); if (entityCache && entityCache.promise) { return entityCache.promise; } const entityPromise = new Promise((resolve, reject) => { let legacyPath = undefined; try { legacyPath = window.jujulib.URL.fromString('u/' + userState).legacyPath(); } catch (e) { // If the state cannot be parsed into a url we can be sure it's // not an entity. reject(userState); return; } this.get('charmstore').getEntity( legacyPath, (err, entityData) => { if (err) { console.error(err); reject(userState); return; } resolve(userState); }); }); userPaths.set(userState, {promise:entityPromise}); return entityPromise; }, /** Calls the listModelsWithInfo method on the controller API and then switches to the provided model name or model uuid if available. If no matching model is found then state is changed to the users profile page. If both model name and model uuid are provided then the model name will win. @param {String} modelPath The model path to switch to in the format username/modelname. @param {String} modelUUID The model uuid to switch to. */ _listAndSwitchModel: function(modelPath, modelUUID) { this.controllerAPI.listModelsWithInfo((err, modelList) => { if (err) { console.error('unable to list models', err); this.db.notifications.add({ title: 'Unable to list models', message: 'Unable to list models: ' + err, level: 'error' }); return; } const noErrorModels = modelList.filter(model => !model.err); const generatePath = (owner, name) => `${owner.split('@')[0]}/${name}`; let model = undefined; if (modelPath) { model = noErrorModels.find(model => generatePath(model.owner, model.name) === modelPath); } else if (modelUUID) { model = noErrorModels.find(model => model.uuid === modelUUID); } this.maskVisibility(false); // If we're already connected to the model then don't do anything. if (model && this.env.get('modelUUID') === model.uuid) { return; } if (model) { this.state.changeState({ model: { path: generatePath(model.owner, model.name), uuid: model.uuid }, user: null, root: null }); } else { // If no model was found then navigate to the user profile. const msg = `no such charm, bundle or model: u/${modelPath}`; // TODO frankban: here we should put a notification, but we can't as // this seems to be dispatched twice. console.log(msg); // replace get auth with user.username this.state.changeState({ root: null, store: null, model: null, user: null, profile: this.user.displayName }); } }); }, /** Provided an entityPromise, attaches handlers for the resolve and reject cases. If resolved it changes state to the entity found, if rejected calls _listAndSwitchModel with the possible model name. @param {Promise} entityPromise A promise containing the result of a getEntity charmstore call. */ _disambiguateUserState: function(entityPromise) { entityPromise.then(userState => { console.log('entity found, showing store'); // The entity promise returned an entity so it is not a model and // we should navigate to the store. this.maskVisibility(false); this.state.changeState({ store: 'u/' + userState, user: null }); }).catch(userState => { // No entity was found so it's possible that this is a model. // We need to list the models that the user has access to and find // one which matches the name to extract the UUID. if (!this.controllerAPI.userIsAuthenticated) { console.log('not logged into controller'); return; } this._listAndSwitchModel(userState); }); }, /** Handle the request to display the user entity state. @method _handleUserEntity @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _handleUserEntity: function(state, next) { this._disambiguateUserState( this._fetchEntityFromUserState(state.user)); }, /** The cleanup dispatcher for the user entity state path. The store will be mounted if the path was for a bundle or charm. If the entity was a model we don't need to do anything. @method _clearUserEntity @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _clearUserEntity: function(state, next) { const container = document.getElementById('charmbrowser-container'); // The charmbrowser will only be mounted if the entity is a charm or // bundle. if (container.childNodes.length > 0) { ReactDOM.unmountComponentAtNode(container); } next(); }, /** Creates an instance of the State and registers the necessary dispatchers. @param {String} baseURL - The path the application is served from. @return {Object} The state instance. */ _setupState: function(baseURL) { const state = new window.jujugui.State({ baseURL: baseURL, seriesList: window.jujulib.SERIES, sendAnalytics: this.sendAnalytics }); state.register([ ['*', this.authorizeCookieUse.bind(this)], ['*', this.checkUserCredentials.bind(this)], ['*', this.show_environment.bind(this)], ['root', this._rootDispatcher.bind(this), this._clearRoot.bind(this)], ['profile', this._renderUserProfile.bind(this), this._clearUserProfile.bind(this)], ['user', this._handleUserEntity.bind(this), this._clearUserEntity.bind(this)], ['model', this._handleModelState.bind(this)], ['store', this._renderCharmbrowser.bind(this), this._clearCharmbrowser.bind(this)], ['search', this._renderCharmbrowser.bind(this), this._clearCharmbrowser.bind(this)], ['account', this._renderAccount.bind(this), this._clearAccount.bind(this)], ['special.deployTarget', this._deployTarget.bind(this)], ['gui', null, this._clearAllGUIComponents.bind(this)], ['gui.machines', this._renderMachineView.bind(this), this._clearMachineView.bind(this)], ['gui.inspector', this._renderInspector.bind(this) // the this._clearInspector method is not called here because the // added services component is also rendered into the inspector so // calling it here causes React to throw an error. ], ['gui.deploy', this._renderDeployment.bind(this), this._clearDeployment.bind(this)], // Nothing needs to be done at the top level when the hash changes. ['hash'] ]); return state; }, _clearAllGUIComponents: function(state, next) { const noop = () => {}; this._clearMachineView(state, noop); this._clearDeployment(state, noop); this._clearInspector(state, noop); }, /** The dispatcher for the root state path. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _rootDispatcher: function(state, next) { switch (state.root) { case 'login': // _renderLogin is called from various places with a different call // signature so we have to call next manually after. this._renderLogin(); next(); break; case 'store': this._renderCharmbrowser(state, next); break; case 'account': this._renderAccount(state, next); break; case 'new': // When going to disconnected mode we need to be disconnected from // models. if (this.env.get('connected')) { this._switchModelToUUID(); } // When dispatching, we only want to remove the mask if we're in // anonymousMode or the user is logged in; otherwise we need to // properly redirect to login. const userLoggedIn = this.controllerAPI.userIsAuthenticated; if (this.anonymousMode || userLoggedIn) { this.maskVisibility(false); } const specialState = state.special; if (specialState && specialState.dd) { this._directDeploy(specialState.dd); } break; default: next(); break; } }, /** The cleanup dispatcher for the root state path. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _clearRoot: function(state, next) { this._clearCharmbrowser(state, next); this._clearLogin(state, next); next(); }, /** State handler for he deploy target functionality. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ _deployTarget: function(state, next) { // Remove the deployTarget from state so that we don't end up // dispatching it again by accident. this.state.changeState({ special: { deployTarget: null } }); this.deployTarget(this.get('charmstore'), state.special['deployTarget']); next(); }, /** Deploys the supplied entity Id from the supplied charmstore instance. @param {Object} charmstore The charmstore instance to fetch the entity. @param {String} entityId The entity id to deploy. */ deployTarget: function(charmstore, entityId) { /** Handles parsing and displaying the failure notification returned from the charmstore api. @param {Object} error The XHR request object from the charmstore req. */ const failureNotification = error => { let message = `Unable to deploy target: ${entityId}`; try { message = JSON.parse(error.currentTarget.responseText).Message; } catch (e) { console.error(e); } this.db.notifications.add({ title: 'Error deploying target.', message: message, level: 'error' }); }; // The charmstore apiv4 format can have the bundle keyword either at the // start, for charmers bundles, or after the username, for namespaced // bundles. ex) bundle/swift & ~jorge/bundle/swift if (entityId.indexOf('bundle/') > -1) { charmstore.getBundleYAML(entityId, (error, bundleYAML) => { if (error) { failureNotification(error); } else { this.bundleImporter.importBundleYAML(bundleYAML); } }); } else { // If it's not a bundle then it's a charm. charmstore.getEntity(entityId.replace('cs:', ''), (error, charm) => { if (error) { failureNotification(error); } else { charm = charm[0]; let config = {}, options = charm.get ? charm.get('options') : charm.options; Object.keys(options).forEach(function(key) { config[key] = options[key]['default']; }); // We call the env deploy method directly because we don't want // the ghost inspector to open. this.deployService(new Y.juju.models.Charm(charm)); } }); } }, /** Calls the necessary methods to setup the GUI and put the user in the Deployment Flow when they have used Direct Deploy. @param {Object} ddData - The Direct Deploy data from state. */ _directDeploy: function(ddData) { const current = this.state.current; if (current && current.gui && current.gui.deploy) { // If we're already in the deployment flow then return to stop // infinitely updating state. return; } this.deployTarget(this.get('charmstore'), ddData.id); this.state.changeState({ gui: { deploy: JSON.stringify(ddData) } }); }, /** Creates a new instance of the charm store API and assigns it to the "charmstore" attribute. This method is idempotent. @param {object} jujuConfig The app configuration. @param {Object} Charmstore The Charmstore class. */ _setupCharmstore: function(jujuConfig, Charmstore) { if (this.get('charmstore') === undefined) { this.set('charmstore', new Charmstore( jujuConfig.charmstoreURL, this.bakery)); // Store away the charmstore auth info. if (this.bakery.storage.get(jujuConfig.charmstoreURL)) { this.get('users')['charmstore'] = {loading: true}; this.storeUser('charmstore', false, true); } } }, /** Creates a new instance of the bundleservice API and stores it in the app in an idempotent fashion. @method _setupBundleservice @param {Object} Bundleservice The bundleservice API class to instantiate. */ _setupBundleservice: function(Bundleservice) { if (this.get('bundleService') === undefined) { const jujuConfig = window.juju_config; const bundleServiceURL = jujuConfig && jujuConfig.bundleServiceURL; if (!jujuConfig || !bundleServiceURL) { console.error('no juju config for bundleserviceURL availble'); return; } const bundleService = new Bundleservice( bundleServiceURL, new Y.juju.environments.web.WebHandler()); this.set('bundleService', bundleService); } }, /** Creates new API client instances for Romulus services. Assign them to the "plans" and "terms" app properties. @method _setupRomulusServices @param {Object} config The GUI application configuration. @param {Object} jujulib The Juju API client library. */ _setupRomulusServices: function(config, jujulib) { if (!config) { // We are probably running tests. return; } if (this.plans || this.terms) { console.error( 'romulus services are being redefined:', this.plans, this.terms); } this.plans = new window.jujulib.plans(config.plansURL, this.bakery); this.terms = new window.jujulib.terms(config.termsURL, this.bakery); if (config.payFlag) { this.payment = new window.jujulib.payment( config.paymentURL, this.bakery); this.stripe = new window.jujulib.stripe( 'https://js.stripe.com/', config.stripeKey); } }, /** Returns the current defaultSeries value from the environment. @method getEnvDefaultSeries @return {String} The default series. */ getEnvDefaultSeries: function() { return this.env.get('defaultSeries'); }, /** Hide the drag notifications. @method _hideDragOverNotification */ _hideDragOverNotification: function() { this.views.environment.instance.fadeHelpIndicator(false); ReactDOM.unmountComponentAtNode( document.getElementById('drag-over-notification-container')); }, /** Event handler for the dragenter, dragover, dragleave events on the document. It calls to determine the file type being dragged and manages the commands to the timerControl method. @method _appDragOverHandler @param {Object} e The event object from the various events. */ _appDragOverHandler: function(e) { e.preventDefault(); // required to allow items to be dropped // In this case, we want an empty string to be a truthy value. const fileType = this._determineFileType(e.dataTransfer); if (fileType === false) { return; // Ignore if it's not a supported type } if (e.type === 'dragenter') { this._renderDragOverNotification(); } // Possible values for type are 'dragover' and 'dragleave'. this._dragleaveTimerControl(e.type === 'dragover' ? 'stop' : 'start'); }, /** Handles the dragleave timer so that the periodic dragleave events which fire as the user is dragging the file around the browser do not stop the drag notification from showing. @method _dragleaveTimerControl @param {String} action The action that should be taken on the timer. */ _dragleaveTimerControl: function(action) { if (this._dragLeaveTimer) { window.clearTimeout(this._dragLeaveTimer); this._dragLeaveTimer = null; } if (action === 'start') { this._dragLeaveTimer = setTimeout(() => { this._hideDragOverNotification(); }, 100); } }, /** Takes the information from the dataTransfer object to determine what kind of file the user is dragging over the canvas. Unfortunately Safari and IE do not show mime types for files that they are not familiar with. This isn't an issue once the user has dropped the file because we can parse the file name but while it's still hovering the browser only tells us the mime type if it knows it, else it's an empty string. This means that we cannot determine between a yaml file or a folder during hover. Bug: https://code.google.com/p/chromium/issues/detail?id=342554 Real mime type for yaml files should be: application/x-yaml @method _determineFileType @param {Object} dataTransfer dataTransfer object from the dragover event. @return {String} The file type extension. */ _determineFileType: function(dataTransfer) { var types = dataTransfer.types; var fileFound = Object.keys(types).some(function(key) { // When dragging a single file in Firefox dataTransfer.types is an array // with two elements ["application/x-moz-file", "Files"] if (types[key] === 'Files') { return true; } }); if (!fileFound) { // If the dataTransfer type isn't `Files` then something is being // dragged from inside the browser. return false; } // IE10, 11 and Safari do not have this property during hover so we // cannot tell what type of file is being hovered over the canvas. if (dataTransfer.items) { // See method doc for bug information. var file = dataTransfer.items[0]; if (file.type === 'application/zip' || file.type === 'application/x-zip-compressed') { return 'zip'; } return 'yaml'; } return ''; }, /** Release resources and inform subcomponents to do the same. @method destructor */ destructor: function() { // Clear the database handler timer. Without this, the application could // dispatch after it is destroyed, resulting in a dirty state and bugs // difficult to debug, so please do not remove this code. if (this.dbChangedTimer) { clearTimeout(this.dbChangedTimer); } if (this._keybindings) { this._keybindings.detach(); } const toBeDestroyed = [ this.env, this.controllerAPI, this.db, this.endpointsController ]; toBeDestroyed.forEach(obj => { if (obj && obj.destroy) { obj.detachAll(); obj.destroy(); } }); ['dragenter', 'dragover', 'dragleave'].forEach((eventName) => { document.removeEventListener(eventName, this._boundAppDragOverHandler); }); document.removeEventListener('update', this.bound_on_database_changed); document.removeEventListener('initiateDeploy', this._onInitiateDeploy); document.removeEventListener( 'ecs.changeSetModified', this.renderDeploymentBarListener); document.removeEventListener( 'ecs.currentCommitFinished', this.renderDeploymentBarListener); document.removeEventListener('login', this.onLoginHandler); document.removeEventListener('login', this.controllerLoginHandler); document.removeEventListener('delta', this.onDeltaBound); }, /** * On database changes update the view. * * @method on_database_changed */ on_database_changed: function(evt) { // This timeout helps to reduce the number of needless dispatches from // upwards of 8 to 2. At least until we can move to the model bound // views. if (this.dbChangedTimer) { clearTimeout(this.dbChangedTimer); } this.dbChangedTimer = setTimeout(this._dbChangedHandler.bind(this), 100); return; }, /** After the db has changed and the timer has timed out to reduce repeat calls then this is called to handle the db updates. @method _dbChangedHandler @private */ _dbChangedHandler: function() { // Regardless of which view we are rendering, // update the env view on db change. if (this.views.environment.instance) { this.views.environment.instance.topo.update(); } this.state.dispatch(); this._renderComponents(); }, /** Display the login page. @method _displayLogin */ _displayLogin: function() { this.set('loggedIn', false); const root = this.state.current.root; if (root !== 'login') { this.state.changeState({ root: 'login' }); } }, // Route handlers /** * Log the current user out and show the login screen again. * * @method logout * @param {Object} req The request. * @return {undefined} Nothing. */ logout: function(req) { // If the environment view is instantiated, clear out the topology local // database on log out, because we clear out the environment database as // well. The order of these is important because we need to tell // the env to log out after it has navigated to make sure that // it always shows the login screen. var environmentInstance = this.views.environment.instance; if (environmentInstance) { environmentInstance.topo.update(); } this.set('modelUUID', ''); this.set('loggedIn', false); const controllerAPI = this.controllerAPI; const closeController = controllerAPI.close.bind(controllerAPI); this.env.close(() => { closeController(() => { controllerAPI.connect(); this.maskVisibility(true); this.env.get('ecs').clear(); this.db.reset(); this.db.fireEvent('update'); this.state.changeState({ model: null, profile: null, root: null, store: null }); this._renderLogin(null); }); }); }, // Persistent Views /** Ensure that the current user has authenticated. @param {Object} state The application state. @param {Function} next The next route handler. */ checkUserCredentials: function(state, next) { // If we're in disconnected mode (either "/new" or "/store"), then allow // the canvas to be shown. if (state && (state.root === 'new' || state.root === 'store')) { next(); return; } const apis = [this.env, this.controllerAPI]; // Loop through each api connection and see if we are properly // authenticated. If we aren't then display the login screen. const shouldDisplayLogin = apis.some(api => { // Legacy Juju won't have a controller API. if (!api) { return false; } // If the api is connecting then we can't know if they are properly // logged in yet. if (api.get('connecting')) { return true; } if (!api || !api.get('connected')) { // If we do not have an api instance or if we are not connected with // it then we don't need to concern ourselves with being // authenticated to it. return false; } return !api.userIsAuthenticated && !this.get('gisf'); }); if (shouldDisplayLogin) { this._displayLogin(); return; } next(); }, /** Hide the login mask and redispatch the router. When the environment gets a response from a login attempt, it fires a login event, to which this responds. @method onLogin @param {Object} evt An event object that includes an "err" attribute with an error if the authentication failed. @private */ onLogin: function(evt) { if (evt.detail && evt.detail.err) { this._renderLogin(evt.detail.err); return; } // The login was a success. console.log('successfully logged into model'); this.maskVisibility(false); this._clearLogin(); this.set('loggedIn', true); if (this.state.current.root === 'login') { this.state.changeState({root: null}); } }, /** Create the new socket URL based on the socket template and model details. @method createSocketURL @param {String} template The template to use to generate the url. @param {String} uuid The unique identifier for the model. @param {String} server The optional API server host address for the model. If not provided, defaults to the host name included in the provided apiAddress option. @param {String} port The optional API server port for the model. If not provided, defaults to the host name included in the provided apiAddress option. @return {String} The resulting fully qualified WebSocket URL. */ createSocketURL: function(template, uuid, server, port) { let baseUrl = ''; const apiAddress = this.get('apiAddress'); if (!apiAddress) { // It should not ever be possible to get here unless you're running the // gui in dev mode without pointing it to a proxy/server supplying // the necessary config values. alert( 'Unable to create socketURL, no apiAddress provided. The GUI must ' + 'be loaded with a valid configuration. Try GUIProxy if ' + 'running in development mode: https://github.com/frankban/guiproxy'); return; } if (template[0] === '/') { // The WebSocket path is passed so we need to calculate the base URL. const schema = this.get('socket_protocol') || 'wss'; baseUrl = schema + '://' + window.location.hostname; if (window.location.port !== '') { baseUrl += ':' + window.location.port; } } const defaults = apiAddress.replace('wss://', '').split(':'); template = template.replace('$uuid', uuid); template = template.replace('$server', server || defaults[0]); template = template.replace('$port', port || defaults[1]); return baseUrl + template; }, /** Switch the application to another environment. Disconnect the current WebSocket connection and establish a new one pointed to the environment referenced by the given URL. @method switchEnv @param {String} socketUrl The URL for the environment's websocket. @param {String} username The username for the new environment. @param {String} password The password for the new environment. @param {Function} callback A callback to be called after the env has been switched and logged into. @param {Boolean} reconnect Whether to reconnect to a new environment; by default, if the socketUrl is set, we assume we want to reconnect to the provided URL. @param {Boolean} clearDB Whether to clear the database and ecs. */ switchEnv: function( // TODO frankban: make the function defaults saner, for instance // clearDB=true should really be preserveDB=false by default. socketUrl, username, password, callback, reconnect=!!socketUrl, clearDB=true) { console.log('switching model connection'); this.env.loading = true; if (username && password) { // We don't always get a new username and password when switching // environments; only set new credentials if we've actually gotten them. // The GUI will automatically log in when we switch. this.user.model = { user: username, password: password }; }; const credentials = this.user.model; const onLogin = callback => { this.env.loading = false; if (callback) { callback(this.env); } }; // Delay the callback until after the env login as everything should be // set up by then. document.addEventListener( 'model.login', onLogin.bind(this, callback), {once: true}); if (clearDB) { // Clear uncommitted state. this.env.get('ecs').clear(); } const setUpModel = model => { // Tell the model to use the new socket URL when reconnecting. model.set('socket_url', socketUrl); // We need to reset the credentials each time we set up a model, // b/c we remove the credentials when we close down a model // connection in the `close()` method of base.js this.user.model = credentials; // Reconnect the model if required. if (reconnect) { model.connect(); } }; // Disconnect and reconnect the model. const onclose = function() { this.on_close(); setUpModel(this); }.bind(this.env); if (this.env.ws) { this.env.ws.onclose = onclose; this.env.close(); // If we are already disconnected then connect if we're supposed to. if (!this.env.get('connected')) { setUpModel(this.env); } } else { this.env.close(onclose); } if (clearDB) { this.db.reset(); this.db.fireEvent('update'); } // Reset canvas centering to new env will center on load. const instance = this.views.environment.instance; // TODO frankban: investigate in what cases instance is undefined on the // environment object. Is this some kind of race? if (instance) { instance.topo.modules.ServiceModule.centerOnLoad = true; } // If we're not reconnecting, then mark the switch as done. if (this.state.current.root === 'new') { this.env.loading = false; } }, /** If we are in a MAAS environment, react to the MAAS server address retrieval adding a link to the header pointing to the MAAS server. @method _onMaasServer @param {Object} evt An event object (with a "newVal" attribute). */ _onMaasServer: function(evt) { if (evt.newVal === evt.prevVal) { // This can happen if the attr is set blithely. Ignore if so. return; } this._displayMaasLink(evt.newVal); }, /** If the given maasServer is not null, create a link to the MAAS server in the GUI header. @method _displayMaasLink @param {String} maasServer The MAAS server URL (or null if not in MAAS). */ _displayMaasLink: function(maasServer) { if (maasServer === null) { // The current environment is not MAAS. return; } var maasContainer = document.querySelector('#maas-server'); maasContainer.querySelector('a').setAttribute('href', maasServer); maasContainer.classList.remove('hidden'); }, maskVisibility: function(visibility = true) { var mask = document.getElementById('full-screen-mask'); var display = visibility ? 'block' : 'none'; if (mask) { mask.style.display = display; } }, /** Sets the page title. @param {String} title The title to be appended with ' - Juju GUI' */ setPageTitle: function(title) { document.title = title ? `${title} - Juju GUI` : this.defaultPageTitle; }, /** * Record environment default series changes in our model. * * The provider type arrives asynchronously. Instead of updating the * display from the environment code (a separation of concerns violation), * we update it here. * * @method onDefaultSeriesChange */ onDefaultSeriesChange: function(evt) { this.db.environment.set('defaultSeries', evt.newVal); }, /** Display the Environment Name. The environment name can arrive asynchronously. Instead of updating the display from the environment view (a separtion of concerns violation), we update it here. @method onEnvironmentNameChange */ onEnvironmentNameChange: function(evt) { var environmentName = evt.newVal || 'untitled-model'; // Update the name on the current model. This is what the components use // to display the model name. this.db.environment.set('name', environmentName); // Update the breadcrumb with the new model name. this._renderBreadcrumb(); // Update the page title. this.defaultPageTitle = `${environmentName} - Juju GUI`; this.setPageTitle(); }, /** Render the react components. @method _renderComponents */ _renderComponents: function() { // Update the react views on database change this._renderEnvSizeDisplay( this.db.services.size(), this.db.machines.filterByParent().length ); this._renderDeploymentBar(); this._renderModelActions(); this._renderProviderLogo(); this._renderZoom(); this._renderBreadcrumb(); this._renderHeaderSearch(); this._renderHeaderHelp(); this._renderHeaderLogo(); const gui = this.state.current.gui; if (!gui || (gui && !gui.inspector)) { this._renderAddedServices(); } }, /** Show the environment view. @param {Object} state - The application state. @param {Function} next - Run the next route handler, if any. */ show_environment: function(state, next) { if (!this.renderEnvironment) { next(); return; } var options = { endpointsController: this.endpointsController, db: this.db, env: this.env, ecs: this.env.ecs, charmstore: this.get('charmstore'), bundleImporter: this.bundleImporter, state: this.state, staticURL: window.juju_config.staticURL, sendAnalytics: this.sendAnalytics }; this.showView('environment', options, { /** * Let the component framework know that the view has been rendered. * * @method show_environment.callback */ callback: function() { var envView = this.views.environment.instance; envView.rendered(); }, render: true }); if (!this.env.get('environmentName')) { // If this is starting in an unconnected state there will not be a model // name so we set it so that onEnvironmentNameChange sets and updates // the name correctly. this.env.set('environmentName', null); } this._renderComponents(); this._renderNotifications(); this._renderUserMenu(); next(); }, /** Make sure the user agrees to cookie usage. @param {Object} state - The application state. @param {Function} next - The next route handler. */ authorizeCookieUse: function(state, next) { var GTM_enabled = this.get('GTM_enabled'); if (GTM_enabled) { this.cookieHandler = this.cookieHandler || new Y.juju.Cookies(); this.cookieHandler.check(); } next(); }, /** Get the user info for the supplied service. @method getUser @param {String} service The service the macaroon comes from. @return {Object} The user information. */ getUser: function(service) { return this.get('users')[service]; }, /** Clears the user info for the supplied service. @method clearUser @param {String} service The service the macaroon comes from. */ clearUser: function(service) { delete this.get('users')[service]; }, /** Takes a macaroon and stores the user info (if any) in the app. @method storeUser @param {String} service The service the macaroon comes from. @param {String} macaroon The base64 encoded macaroon. @param {Boolean} rerenderProfile Rerender the user profile. @param {Boolean} rerenderBreadcrumb Rerender the breadcrumb. */ storeUser: function(service, rerenderProfile, rerenderBreadcrumb) { var callback = function(error, auth) { if (error) { console.error('Unable to query user information', error); return; } if (auth) { this.get('users')[service] = auth; // If the profile is visible then we want to rerender it with the // updated username. if (rerenderProfile) { this._renderUserProfile(this.state.current, ()=>{}); } } if (rerenderBreadcrumb) { this._renderBreadcrumb(); } }; if (service === 'charmstore') { this.get('charmstore').whoami(callback.bind(this)); } else { console.error('Unrecognized service', service); } } }, { ATTRS: { html5: true, /** A flag to indicate if the user is actually logged into the environment. @attribute loggedIn @default false @type {Boolean} */ loggedIn: { value: false }, /** Store the instance of the charmstore api that we will be using throughout the application. @attribute charmstore @type {jujulib.charmstore} @default undefined */ charmstore: {}, /** Whether or not to use interactive login for the IdM/JEM connection. @attribute interactiveLogin @type {Boolean} @default false */ interactiveLogin: { value: true }, /** The address for the environment's state-server. Used for websocket creation. @attribute apiAddress @type {String} @default '' */ apiAddress: {value: ''}, /** The template to use to create websockets. It can include these vars: - $server: the WebSocket server, like "1.2.3.4"; - $port: the WebSocket port, like "17070"; - $uuid: the target model unique identifier. If the provided value starts with a "/" it is considered to be a path and not a full URL. In this case, the system assumes current host, current port and this.get('socket_protocol') (defaulting to 'wss'). @attribute socketTemplate @type {String} @default '/model/$uuid/api' */ socketTemplate: {value: '/model/$uuid/api'}, /** The authentication store for the user. This holds macaroons or other credential details for the user to connect to the controller. */ user: {value: null}, /** The users associated with various services that the GUI uses. The users are keyed by their service name. For example, this.get('users')['charmstore'] will return the user object for the charmstore service. @attribute users @type {Object} */ users: { value: {} } } }); Y.namespace('juju').App = JujuGUI; }, '0.5.3', { requires: [ 'acl', 'analytics', 'changes-utils', 'juju-charm-models', 'juju-bundle-models', 'juju-controller-api', 'juju-endpoints-controller', 'juju-env-base', 'juju-env-api', 'juju-env-web-handler', 'juju-models', 'jujulib-utils', 'bakery-utils', 'net-utils', // React components 'account', 'added-services-list', 'charmbrowser-component', 'deployment-bar', 'deployment-flow', 'deployment-signup', 'env-size-display', 'header-breadcrumb', 'model-actions', 'expanding-progress', 'header-help', 'header-logo', 'header-search', 'inspector-component', 'isv-profile', 'local-inspector', 'machine-view', 'login-component', 'logout-component', 'modal-gui-settings', 'modal-shortcuts', 'notification-list', 'panel-component', 'sharing', 'svg-icon', 'user-menu', 'user-profile', 'zoom', // juju-views group 'd3-components', 'juju-view-utils', 'juju-topology', 'juju-view-environment', 'juju-landscape', // end juju-views group 'autodeploy-extension', 'io', 'json-parse', 'app-base', 'app-transitions', 'base', 'bundle-importer', 'bundle-import-notifications', 'node', 'model', 'app-cookies-extension', 'app-renderer-extension', 'cookie', 'querystring', 'event-key', 'event-touch', 'model-controller', 'FileSaver', 'ghost-deployer-extension', 'local-charm-import-helpers', 'environment-change-set', 'relation-utils' ] });
Update login handling code to no longer listen for removed events and fix the credential check on dispatch to work cross platform.
jujugui/static/gui/src/app/app.js
Update login handling code to no longer listen for removed events and fix the credential check on dispatch to work cross platform.
<ide><path>ujugui/static/gui/src/app/app.js <ide> this.onEnvironmentNameChange, this); <ide> this.env.after('defaultSeriesChange', this.onDefaultSeriesChange, this); <ide> <del> // Once the user logs in, we need to redraw. <del> this.onLoginHandler = this.onLogin.bind(this); <del> document.addEventListener('login', this.onLoginHandler); <del> <ide> // Once we know about MAAS server, update the header accordingly. <ide> let maasServer = this.env.get('maasServer'); <ide> if (!maasServer && this.controllerAPI) { <ide> 'ecs.changeSetModified', this.renderDeploymentBarListener); <ide> document.removeEventListener( <ide> 'ecs.currentCommitFinished', this.renderDeploymentBarListener); <del> document.removeEventListener('login', this.onLoginHandler); <ide> document.removeEventListener('login', this.controllerLoginHandler); <ide> document.removeEventListener('delta', this.onDeltaBound); <ide> }, <ide> // authenticated. If we aren't then display the login screen. <ide> const shouldDisplayLogin = apis.some(api => { <ide> // Legacy Juju won't have a controller API. <del> if (!api) { <add> // If we do not have an api instance or if we are not connected with <add> // it then we don't need to concern ourselves with being <add> // authenticated to it. <add> if (!api || !api.get('connected')) { <ide> return false; <ide> } <ide> // If the api is connecting then we can't know if they are properly <ide> // logged in yet. <ide> if (api.get('connecting')) { <del> return true; <del> } <del> if (!api || !api.get('connected')) { <del> // If we do not have an api instance or if we are not connected with <del> // it then we don't need to concern ourselves with being <del> // authenticated to it. <ide> return false; <ide> } <ide> return !api.userIsAuthenticated && !this.get('gisf'); <ide> return; <ide> } <ide> // The login was a success. <del> console.log('successfully logged into model'); <add> console.log('successfully logged into controller'); <ide> this.maskVisibility(false); <ide> this._clearLogin(); <ide> this.set('loggedIn', true);
Java
bsd-3-clause
b23517a11b4c6af7825b1abdaa8d6c0c68e13928
0
morfologik/morfologik-stemming
package morfologik.speller; import static morfologik.fsa.MatchResult.EXACT_MATCH; import static morfologik.fsa.MatchResult.SEQUENCE_IS_A_PREFIX; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import java.text.Normalizer; import java.text.Normalizer.Form; import java.util.*; import morfologik.fsa.FSA; import morfologik.fsa.ByteSequenceIterator; import morfologik.fsa.FSATraversal; import morfologik.fsa.MatchResult; import morfologik.stemming.BufferUtils; import morfologik.stemming.Dictionary; import morfologik.stemming.DictionaryLookup; import morfologik.stemming.DictionaryMetadata; import morfologik.stemming.UnmappableInputException; /** * Finds spelling suggestions. Implements K. Oflazer's algorithm as described * in: Oflazer, Kemal. 1996. * "Error-Tolerant Finite-State Recognition with Applications to Morphological Analysis and Spelling Correction." * <i>Computational Linguistics</i> 22 (1): 73–89. * * <p> * See Jan Daciuk's <code>s_fsa</code> package. */ public class Speller { /** * Maximum length of the word to be checked. */ public static final int MAX_WORD_LENGTH = 120; static final int FREQ_RANGES = 'Z' - 'A' + 1; static final int FIRST_RANGE_CODE = 'A'; // less frequent words //FIXME: this is an upper limit for replacement searches, we need //proper tree traversal instead of generation of all possible candidates static final int UPPER_SEARCH_LIMIT = 15; private static final int MIN_WORD_LENGTH = 4; private static final int MAX_RECURSION_LEVEL = 6; private final int editDistance; private int effectEditDistance; // effective edit distance private final HMatrix hMatrix; private char[] candidate; /* current replacement */ private int candLen; private int wordLen; /* length of word being processed */ private char[] wordProcessed; /* word being processed */ private Map<Character, List<char[]>> replacementsAnyToOne = new HashMap<Character, List<char[]>>(); private Map<String, List<char[]>> replacementsAnyToTwo = new HashMap<String, List<char[]>>(); private Map<String, List<String>> replacementsTheRest = new HashMap<String, List<String>>(); /** * List of candidate strings, including same additional data such as edit * distance from the original word. */ private final List<CandidateData> candidates = new ArrayList<CandidateData>(); private boolean containsSeparators = true; /** * Internal reusable buffer for encoding words into byte arrays using * {@link #encoder}. */ private ByteBuffer byteBuffer = ByteBuffer.allocate(MAX_WORD_LENGTH); /** * Internal reusable buffer for encoding words into byte arrays using * {@link #encoder}. */ private CharBuffer charBuffer = CharBuffer.allocate(MAX_WORD_LENGTH); /** * Reusable match result. */ private final MatchResult matchResult = new MatchResult(); /** * Features of the compiled dictionary. * * @see DictionaryMetadata */ private final DictionaryMetadata dictionaryMetadata; /** * Charset encoder for the FSA. */ private final CharsetEncoder encoder; /** * Charset decoder for the FSA. */ private final CharsetDecoder decoder; /** An FSA used for lookups. */ private final FSATraversal matcher; /** FSA's root node. */ private final int rootNode; /** * The FSA we are using. */ private final FSA fsa; /** An iterator for walking along the final states of {@link #fsa}. */ private final ByteSequenceIterator finalStatesIterator; public Speller(final Dictionary dictionary) { this(dictionary, 1); } public Speller(final Dictionary dictionary, final int editDistance) { this.editDistance = editDistance; this.hMatrix = new HMatrix(editDistance, MAX_WORD_LENGTH); this.dictionaryMetadata = dictionary.metadata; this.rootNode = dictionary.fsa.getRootNode(); this.fsa = dictionary.fsa; this.matcher = new FSATraversal(fsa); this.finalStatesIterator = new ByteSequenceIterator(fsa, rootNode); if (rootNode == 0) { throw new IllegalArgumentException("Dictionary must have at least the root node."); } if (dictionaryMetadata == null) { throw new IllegalArgumentException("Dictionary metadata must not be null."); } encoder = dictionaryMetadata.getEncoder(); decoder = dictionaryMetadata.getDecoder(); // Multibyte separator will result in an exception here. dictionaryMetadata.getSeparatorAsChar(); this.createReplacementsMaps(); } private void createReplacementsMaps() { for (Map.Entry<String, List<String>> entry : dictionaryMetadata.getReplacementPairs().entrySet()) { for (String s : entry.getValue()) { // replacements any to one // the new key is the target of the replacement pair if (s.length() == 1) { if (!replacementsAnyToOne.containsKey(s.charAt(0))) { List<char[]> charList = new ArrayList<char[]>(); charList.add(entry.getKey().toCharArray()); replacementsAnyToOne.put(s.charAt(0), charList); } else { replacementsAnyToOne.get(s.charAt(0)).add(entry.getKey().toCharArray()); } } // replacements any to two // the new key is the target of the replacement pair else if (s.length() == 2) { if (!replacementsAnyToTwo.containsKey(s)) { List<char[]> charList = new ArrayList<char[]>(); charList.add(entry.getKey().toCharArray()); replacementsAnyToTwo.put(s, charList); } else { replacementsAnyToTwo.get(s).add(entry.getKey().toCharArray()); } } else { if (!replacementsTheRest.containsKey(entry.getKey())) { List<String> charList = new ArrayList<String>(); charList.add(s); replacementsTheRest.put(entry.getKey(), charList); } else { replacementsTheRest.get(entry.getKey()).add(s); } } } } } private ByteBuffer charSequenceToBytes(final CharSequence word) throws UnmappableInputException { // Encode word characters into bytes in the same encoding as the FSA's. charBuffer = BufferUtils.clearAndEnsureCapacity(charBuffer, word.length()); for (int i = 0; i < word.length(); i++) { final char chr = word.charAt(i); charBuffer.put(chr); } charBuffer.flip(); return BufferUtils.charsToBytes(encoder, charBuffer, byteBuffer); } /** * Checks whether the word is misspelled, by performing a series of checks * according to properties of the dictionary. * * If the flag <code>fsa.dict.speller.ignore-punctuation</code> is set, then * all non-alphabetic characters are considered to be correctly spelled. * * If the flag <code>fsa.dict.speller.ignore-numbers</code> is set, then all * words containing decimal digits are considered to be correctly spelled. * * If the flag <code>fsa.dict.speller.ignore-camel-case</code> is set, then * all CamelCase words are considered to be correctly spelled. * * If the flag <code>fsa.dict.speller.ignore-all-uppercase</code> is set, then * all alphabetic words composed of only uppercase characters are considered * to be correctly spelled. * * Otherwise, the word is checked in the dictionary. If the test fails, and * the dictionary does not perform any case conversions (as set by * <code>fsa.dict.speller.convert-case</code> flag), then the method returns * false. In case of case conversions, it is checked whether a non-mixed case * word is found in its lowercase version in the dictionary, and for * all-uppercase words, whether the word is found in the dictionary with the * initial uppercase letter. * * @param word * - the word to be checked * @return true if the word is misspelled **/ public boolean isMisspelled(final String word) { // dictionaries usually do not contain punctuation String wordToCheck = word; if (!dictionaryMetadata.getInputConversionPairs().isEmpty()) { wordToCheck = DictionaryLookup.applyReplacements(word, dictionaryMetadata.getInputConversionPairs()); } boolean isAlphabetic = wordToCheck.length() != 1 || isAlphabetic(wordToCheck.charAt(0)); return wordToCheck.length() > 0 && (!dictionaryMetadata.isIgnoringPunctuation() || isAlphabetic) && (!dictionaryMetadata.isIgnoringNumbers() || containsNoDigit(wordToCheck)) && !(dictionaryMetadata.isIgnoringCamelCase() && isCamelCase(wordToCheck)) && !(dictionaryMetadata.isIgnoringAllUppercase() && isAlphabetic && isAllUppercase(wordToCheck)) && !isInDictionary(wordToCheck) && (!dictionaryMetadata.isConvertingCase() || !(!isMixedCase(wordToCheck) && (isInDictionary(wordToCheck.toLowerCase(dictionaryMetadata.getLocale())) || isAllUppercase(wordToCheck) && isInDictionary(initialUppercase(wordToCheck))))); } private CharSequence initialUppercase(final String wordToCheck) { return wordToCheck.substring(0, 1) + wordToCheck.substring(1).toLowerCase(dictionaryMetadata.getLocale()); } /** * Test whether the word is found in the dictionary. * * @param word * the word to be tested * @return True if it is found. */ public boolean isInDictionary(final CharSequence word) { try { byteBuffer = charSequenceToBytes(word); } catch (UnmappableInputException e) { return false; } // Try to find a partial match in the dictionary. final MatchResult match = matcher.match(matchResult, byteBuffer.array(), 0, byteBuffer.remaining(), rootNode); // Make sure the word doesn't contain a separator if there is an exact match if (containsSeparators && match.kind == EXACT_MATCH) { containsSeparators = false; for (int i=0; i<word.length(); i++) { if (word.charAt(i) == dictionaryMetadata.getSeparator()) { containsSeparators = true; break; } } } if (match.kind == EXACT_MATCH && !containsSeparators) { return true; } return containsSeparators && match.kind == SEQUENCE_IS_A_PREFIX && byteBuffer.remaining() > 0 && fsa.getArc(match.node, dictionaryMetadata.getSeparator()) != 0; } /** * Get the frequency value for a word form. It is taken from the first entry * with this word form. * * @param word * the word to be tested * @return frequency value in range: 0..FREQ_RANGE-1 (0: less frequent). */ public int getFrequency(final CharSequence word) { if (!dictionaryMetadata.isFrequencyIncluded()) { return 0; } final byte separator = dictionaryMetadata.getSeparator(); try { byteBuffer = charSequenceToBytes(word); } catch (UnmappableInputException e) { return 0; } final MatchResult match = matcher.match(matchResult, byteBuffer.array(), 0, byteBuffer.remaining(), rootNode); if (match.kind == SEQUENCE_IS_A_PREFIX) { final int arc = fsa.getArc(match.node, separator); if (arc != 0 && !fsa.isArcFinal(arc)) { finalStatesIterator.restartFrom(fsa.getEndNode(arc)); if (finalStatesIterator.hasNext()) { final ByteBuffer bb = finalStatesIterator.next(); final byte[] ba = bb.array(); final int bbSize = bb.remaining(); //the last byte contains the frequency after a separator return ba[bbSize - 1] - FIRST_RANGE_CODE; } } } return 0; } /** * Propose suggestions for misspelled run-on words. This algorithm is inspired * by spell.cc in s_fsa package by Jan Daciuk. * * @param original * The original misspelled word. * @return The list of suggested pairs, as space-concatenated strings. */ public List<String> replaceRunOnWords(final String original) { final List<String> candidates = new ArrayList<String>(); String wordToCheck = original; if (!dictionaryMetadata.getInputConversionPairs().isEmpty()) { wordToCheck = DictionaryLookup.applyReplacements(original, dictionaryMetadata.getInputConversionPairs()); } if (!isInDictionary(wordToCheck) && dictionaryMetadata.isSupportingRunOnWords()) { for (int i = 1; i < wordToCheck.length(); i++) { // chop from left to right final CharSequence firstCh = wordToCheck.subSequence(0, i); if (isInDictionary(firstCh) && isInDictionary(wordToCheck.subSequence(i, wordToCheck.length()))) { if (dictionaryMetadata.getOutputConversionPairs().isEmpty()) { candidates.add(firstCh + " " + wordToCheck.subSequence(i, wordToCheck.length())); } else { candidates.add(DictionaryLookup.applyReplacements(firstCh + " " + wordToCheck.subSequence(i, wordToCheck.length()), dictionaryMetadata.getOutputConversionPairs()).toString()); } } } } return candidates; } /** * Find suggestions by using K. Oflazer's algorithm. See Jan Daciuk's s_fsa * package, spell.cc for further explanation. * * @param w The original misspelled word. * @return A list of suggested replacements. */ public List<String> findReplacements(final String w) { String word = w; if (!dictionaryMetadata.getInputConversionPairs().isEmpty()) { word = DictionaryLookup.applyReplacements(w, dictionaryMetadata.getInputConversionPairs()); } candidates.clear(); if (word.length() > 0 && word.length() < MAX_WORD_LENGTH && !isInDictionary(word)) { List<String> wordsToCheck = new ArrayList<String>(); if (replacementsTheRest != null && word.length() > 1) { for (final String wordChecked : getAllReplacements(word, 0, 0)) { boolean found = false; if (isInDictionary(wordChecked)) { candidates.add(new CandidateData(wordChecked, 0)); found = true; } else { String lowerWord = wordChecked.toLowerCase(dictionaryMetadata.getLocale()); String upperWord = wordChecked.toUpperCase(dictionaryMetadata.getLocale()); if (isInDictionary(lowerWord)) { //add the word as it is in the dictionary, not mixed-case versions of it candidates.add(new CandidateData(lowerWord, 0)); found = true; } if (isInDictionary(upperWord)) { candidates.add(new CandidateData(upperWord, 0)); found = true; } if (lowerWord.length() > 1) { String firstupperWord = Character.toUpperCase(lowerWord.charAt(0)) + lowerWord.substring(1); if (isInDictionary(firstupperWord)) { candidates.add(new CandidateData(firstupperWord, 0)); found = true; } } } if (!found) { wordsToCheck.add(wordChecked); } } } else { wordsToCheck.add(word); } //If at least one candidate was found with the replacement pairs (which are usual errors), //probably there is no need for more candidates if (candidates.isEmpty()) { int i = 1; for (final String wordChecked : wordsToCheck) { i++; if (i > UPPER_SEARCH_LIMIT) { // for performance reasons, do not search too deeply break; } wordProcessed = wordChecked.toCharArray(); wordLen = wordProcessed.length; if (wordLen < MIN_WORD_LENGTH && i > 2) { // three-letter replacements make little sense anyway break; } candidate = new char[MAX_WORD_LENGTH]; candLen = candidate.length; effectEditDistance = wordLen <= editDistance ? wordLen - 1 : editDistance; charBuffer = BufferUtils.clearAndEnsureCapacity(charBuffer, MAX_WORD_LENGTH); byteBuffer = BufferUtils.clearAndEnsureCapacity(byteBuffer, MAX_WORD_LENGTH); final byte[] prevBytes = new byte[0]; findRepl(0, fsa.getRootNode(), prevBytes, 0, 0); } } } Collections.sort(candidates); // Use a linked set to avoid duplicates and preserve the ordering of candidates. final Set<String> candStringSet = new LinkedHashSet<String>(); for (final CandidateData cd : candidates) { candStringSet.add(DictionaryLookup.applyReplacements(cd.getWord(), dictionaryMetadata.getOutputConversionPairs()).toString()); } final List<String> candStringList = new ArrayList<String>(candStringSet.size()); candStringList.addAll(candStringSet); return candStringList; } private void findRepl(final int depth, final int node, final byte[] prevBytes, final int wordIndex, final int candIndex) { int dist = 0; for (int arc = fsa.getFirstArc(node); arc != 0; arc = fsa.getNextArc(arc)) { byteBuffer = BufferUtils.clearAndEnsureCapacity(byteBuffer, prevBytes.length + 1); byteBuffer.put(prevBytes); byteBuffer.put(fsa.getArcLabel(arc)); final int bufPos = byteBuffer.position(); byteBuffer.flip(); decoder.reset(); // FIXME: this isn't correct -- no checks for overflows, no decoder flush. I don't think this should be in here // too, the decoder should run once on accumulated temporary byte buffer (current path) only when there's // a potential that this buffer can become a replacement candidate (isEndOfCandidate). Because we assume candidates // are valid input strings (this is verified when building the dictionary), it's save a lot of conversions. final CoderResult c = decoder.decode(byteBuffer, charBuffer, true); if (c.isMalformed()) { // assume that only valid // encodings are there final byte[] prev = new byte[bufPos]; byteBuffer.position(0); byteBuffer.get(prev); if (!fsa.isArcTerminal(arc)) { findRepl(depth, fsa.getEndNode(arc), prev, wordIndex, candIndex); // note: depth is not incremented } byteBuffer.clear(); } else if (!c.isError()) { // unmappable characters are silently discarded charBuffer.flip(); candidate[candIndex] = charBuffer.get(); charBuffer.clear(); byteBuffer.clear(); int lengthReplacement; // replacement "any to two" if ((lengthReplacement = matchAnyToTwo(wordIndex, candIndex)) > 0) { // the replacement takes place at the end of the candidate if (isEndOfCandidate(arc, wordIndex) && (dist = hMatrix.get(depth - 1, depth - 1)) <= effectEditDistance) { if (Math.abs(wordLen - 1 - (wordIndex + lengthReplacement - 2)) > 0) { // there are extra letters in the word after the replacement dist = dist + Math.abs(wordLen - 1 - (wordIndex + lengthReplacement - 2)); } if (dist <= effectEditDistance) { addCandidate(candIndex, dist); } } if (isArcNotTerminal(arc, candIndex)) { int x = hMatrix.get(depth, depth); hMatrix.set(depth, depth, hMatrix.get(depth - 1, depth - 1)); findRepl(Math.max(0, depth), fsa.getEndNode(arc), new byte[0], wordIndex + lengthReplacement - 1, candIndex + 1); hMatrix.set(depth, depth, x); } } //replacement "any to one" if ((lengthReplacement = matchAnyToOne(wordIndex, candIndex)) > 0) { // the replacement takes place at the end of the candidate if (isEndOfCandidate(arc, wordIndex) && (dist = hMatrix.get(depth, depth)) <= effectEditDistance) { if (Math.abs(wordLen - 1 - (wordIndex + lengthReplacement - 1)) > 0) { // there are extra letters in the word after the replacement dist = dist + Math.abs(wordLen - 1 - (wordIndex + lengthReplacement - 1)); } if (dist <= effectEditDistance) { addCandidate(candIndex, dist); } } if (isArcNotTerminal(arc, candIndex)) { findRepl(depth, fsa.getEndNode(arc), new byte[0], wordIndex + lengthReplacement, candIndex + 1); } } //general if (cuted(depth, wordIndex, candIndex) <= effectEditDistance) { if ((isEndOfCandidate(arc, wordIndex)) && (dist = ed(wordLen - 1 - (wordIndex - depth), depth, wordLen - 1, candIndex)) <= effectEditDistance) { addCandidate(candIndex, dist); } if (isArcNotTerminal(arc, candIndex)) { findRepl(depth + 1, fsa.getEndNode(arc), new byte[0], wordIndex + 1, candIndex + 1); } } } } } private boolean isArcNotTerminal(final int arc, final int candIndex) { return !fsa.isArcTerminal(arc) && !(containsSeparators && candidate[candIndex] == dictionaryMetadata.getSeparatorAsChar()); } private boolean isEndOfCandidate(final int arc, final int wordIndex) { return (fsa.isArcFinal(arc) || isBeforeSeparator(arc)) //candidate has proper length && (Math.abs(wordLen - 1 - (wordIndex)) <= effectEditDistance); } private boolean isBeforeSeparator(final int arc) { if (containsSeparators) { final int arc1 = fsa.getArc(fsa.getEndNode(arc), dictionaryMetadata.getSeparator()); return arc1 != 0 && !fsa.isArcTerminal(arc1); } return false; } private void addCandidate(final int depth, final int dist) { candidates.add(new CandidateData(String.valueOf(candidate, 0, depth + 1), dist)); } /** * Calculates edit distance. * * @param i length of first word (here: misspelled) - 1; * @param j length of second word (here: candidate) - 1. * @param wordIndex (TODO: javadoc?) * @param candIndex (TODO: javadoc?) * @return Edit distance between the two words. Remarks: See Oflazer. */ public int ed(final int i, final int j, final int wordIndex, final int candIndex) { int result; int a, b, c; if (areEqual(wordProcessed[wordIndex], candidate[candIndex])) { // last characters are the same result = hMatrix.get(i, j); } else if (wordIndex > 0 && candIndex > 0 && wordProcessed[wordIndex] == candidate[candIndex - 1] && wordProcessed[wordIndex - 1] == candidate[candIndex]) { // last two characters are transposed a = hMatrix.get(i - 1, j - 1); // transposition, e.g. ababab, ababba b = hMatrix.get(i + 1, j); // deletion, e.g. abab, aba c = hMatrix.get(i, j + 1); // insertion e.g. aba, abab result = 1 + min(a, b, c); } else { // otherwise a = hMatrix.get(i, j); // replacement, e.g. ababa, ababb b = hMatrix.get(i + 1, j); // deletion, e.g. ab, a c = hMatrix.get(i, j + 1); // insertion e.g. a, ab result = 1 + min(a, b, c); } hMatrix.set(i + 1, j + 1, result); return result; } // by Jaume Ortola private boolean areEqual(final char x, final char y) { if (x == y) { return true; } if (dictionaryMetadata.getEquivalentChars() != null && dictionaryMetadata.getEquivalentChars().containsKey(x) && dictionaryMetadata.getEquivalentChars().get(x).contains(y)) { return true; } if (dictionaryMetadata.isIgnoringDiacritics()) { String xn = Normalizer.normalize(Character.toString(x), Form.NFD); String yn = Normalizer.normalize(Character.toString(y), Form.NFD); if (xn.charAt(0) == yn.charAt(0)) { // avoid case conversion, if possible return true; } if (dictionaryMetadata.isConvertingCase()) { //again case conversion only when needed -- we // do not need String.lowercase because we only check // single characters, so a cheaper method is enough if (Character.isLetter(xn.charAt(0))) { boolean testNeeded = Character.isLowerCase(xn.charAt(0)) != Character.isLowerCase(yn.charAt(0)); if (testNeeded) { return Character.toLowerCase(xn.charAt(0)) == Character.toLowerCase(yn.charAt(0)); } } } return xn.charAt(0) == yn.charAt(0); } return false; } /** * Calculates cut-off edit distance. * * @param depth current length of candidates. * @param wordIndex (TODO: javadoc?) * @param candIndex (TODO: javadoc?) * @return Cut-off edit distance. Remarks: See Oflazer. */ public int cuted(final int depth, final int wordIndex, final int candIndex) { final int l = Math.max(0, depth - effectEditDistance); // min chars from word to consider - 1 final int u = Math.min(wordLen - 1 - (wordIndex - depth), depth + effectEditDistance); // max chars from word to // consider - 1 int minEd = effectEditDistance + 1; // what is to be computed int wi = wordIndex + l - depth; int d; for (int i = l; i <= u; i++, wi++) { if ((d = ed(i, depth, wi, candIndex)) < minEd) { minEd = d; } } return minEd; } // Match the last letter of the candidate against two or more letters of the word. private int matchAnyToOne(final int wordIndex, final int candIndex) { if (replacementsAnyToOne.containsKey(candidate[candIndex])) { for (final char[] rep : replacementsAnyToOne.get(candidate[candIndex])) { int i = 0; while (i < rep.length && (wordIndex + i) < wordLen && rep[i] == wordProcessed[wordIndex + i]) { i++; } if (i == rep.length) { return i; } } } return 0; } private int matchAnyToTwo(final int wordIndex, final int candIndex) { if (candIndex > 0 && candIndex < candidate.length && wordIndex > 0) { char[] twoChar = { candidate[candIndex - 1], candidate[candIndex] }; String sTwoChar = new String(twoChar); if (replacementsAnyToTwo.containsKey(sTwoChar)) { for (final char[] rep : replacementsAnyToTwo.get(sTwoChar)) { if (rep.length == 2 && wordIndex < wordLen && candidate[candIndex - 1] == wordProcessed[wordIndex - 1] && candidate[candIndex] == wordProcessed[wordIndex]) { return 0; //unnecessary replacements } int i = 0; while (i < rep.length && (wordIndex - 1 + i) < wordLen && rep[i] == wordProcessed[wordIndex - 1 + i]) { i++; } if (i == rep.length) { return i; } } } } return 0; } private static int min(final int a, final int b, final int c) { return Math.min(a, Math.min(b, c)); } /** * Copy-paste of Character.isAlphabetic() (needed as we require only 1.6) * * @param codePoint * The input character. * @return True if the character is a Unicode alphabetic character. */ static boolean isAlphabetic(final int codePoint) { return ((1 << Character.UPPERCASE_LETTER | 1 << Character.LOWERCASE_LETTER | 1 << Character.TITLECASE_LETTER | 1 << Character.MODIFIER_LETTER | 1 << Character.OTHER_LETTER | 1 << Character.LETTER_NUMBER) >> Character .getType(codePoint) & 1) != 0; } /** * Checks whether a string contains a digit. Used for ignoring words with * numbers * * @param s * Word to be checked. * @return True if there is a digit inside the word. */ static boolean containsNoDigit(final String s) { for (int k = 0; k < s.length(); k++) { if (Character.isDigit(s.charAt(k))) { return false; } } return true; } /** * Returns true if <code>str</code> is made up of all-uppercase characters * (ignoring characters for which no upper-/lowercase distinction exists). */ boolean isAllUppercase(final String str) { for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (Character.isLetter(c) && Character.isLowerCase(c)) { return false; } } return true; } /** * Returns true if <code>str</code> is made up of all-lowercase characters * (ignoring characters for which no upper-/lowercase distinction exists). */ boolean isNotAllLowercase(final String str) { for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (Character.isLetter(c) && !Character.isLowerCase(c)) { return true; } } return false; } /** * @param str * input string */ boolean isNotCapitalizedWord(final String str) { if (isNotEmpty(str) && Character.isUpperCase(str.charAt(0))) { for (int i = 1; i < str.length(); i++) { char c = str.charAt(i); if (Character.isLetter(c) && !Character.isLowerCase(c)) { return true; } } return false; } return true; } /** * Helper method to replace calls to "".equals(). * * @param str * String to check * @return true if string is empty OR null */ static boolean isNotEmpty(final String str) { return str != null && str.length() != 0; } /** * @param str * input str * @return Returns true if str is MixedCase. */ boolean isMixedCase(final String str) { return !isAllUppercase(str) && isNotCapitalizedWord(str) && isNotAllLowercase(str); } /** * @param str The string to check. * @return Returns true if str is CamelCase. Note that German compounds with a dash * (like "Waschmaschinen-Test") are also considered camel case by this method. */ public boolean isCamelCase(final String str) { return isNotEmpty(str) && !isAllUppercase(str) && isNotCapitalizedWord(str) && Character.isUpperCase(str.charAt(0)) && (!(str.length() > 1) || Character.isLowerCase(str.charAt(1))) && isNotAllLowercase(str); } /** * Used to determine whether the dictionary supports case conversions. * * @return boolean value that answers this question in a deep and meaningful * way. * * @since 1.9 * */ public boolean convertsCase() { return dictionaryMetadata.isConvertingCase(); } /** * @param str * The string to find the replacements for. * @param fromIndex * The index from which replacements are found. * @param level * The recursion level. The search stops if level is &gt; MAX_RECURSION_LEVEL. * @return A list of all possible replacements of a {#link str} given string */ public List<String> getAllReplacements(final String str, final int fromIndex, final int level) { List<String> replaced = new ArrayList<>(); if (level > MAX_RECURSION_LEVEL) { // Stop searching at some point replaced.add(str); return replaced; } StringBuilder sb = new StringBuilder(); sb.append(str); int index = MAX_WORD_LENGTH; String key = ""; int keyLength = 0; boolean found = false; // find first possible replacement after fromIndex position for (final String auxKey : replacementsTheRest.keySet()) { int auxIndex = sb.indexOf(auxKey, fromIndex); if (auxIndex > -1 && (auxIndex < index || (auxIndex == index && !(auxKey.length() < keyLength)))) { //select the longest possible key index = auxIndex; key = auxKey; keyLength = auxKey.length(); } } if (index < MAX_WORD_LENGTH) { for (final String rep : replacementsTheRest.get(key)) { // start a branch without replacement (only once per key) if (!found) { replaced.addAll(getAllReplacements(str, index + key.length(), level + 1)); found = true; } // avoid unnecessary replacements (ex. don't replace L by L·L when L·L already present) int ind = sb.indexOf(rep, fromIndex - rep.length() + 1); if (rep.length() > key.length() && ind > -1 && (ind == index || ind == index - rep.length() + 1)) { continue; } // start a branch with replacement sb.replace(index, index + key.length(), rep); replaced.addAll(getAllReplacements(sb.toString(), index + rep.length(), level + 1)); sb.setLength(0); sb.append(str); } } if (!found) { replaced.add(sb.toString()); } return replaced; } /** * Sets up the word and candidate. Used only to test the edit distance in * JUnit tests. * * @param word * the first word * @param candidate * the second word used for edit distance calculation */ void setWordAndCandidate(final String word, final String candidate) { wordProcessed = word.toCharArray(); wordLen = wordProcessed.length; this.candidate = candidate.toCharArray(); candLen = this.candidate.length; effectEditDistance = wordLen <= editDistance ? wordLen - 1 : editDistance; } public final int getWordLen() { return wordLen; } public final int getCandLen() { return candLen; } public final int getEffectiveED() { return effectEditDistance; } /** * Used to sort candidates according to edit distance, and possibly according * to their frequency in the future. * */ private class CandidateData implements Comparable<CandidateData> { private final String word; private final int distance; CandidateData(final String word, final int distance) { this.word = word; this.distance = distance * FREQ_RANGES + FREQ_RANGES - getFrequency(word) - 1; } final String getWord() { return word; } final int getDistance() { return distance; } @Override public int compareTo(final CandidateData cd) { // Assume no overflow. return cd.getDistance() > this.distance ? -1 : cd.getDistance() == this.distance ? 0 : 1; } } }
morfologik-speller/src/main/java/morfologik/speller/Speller.java
package morfologik.speller; import static morfologik.fsa.MatchResult.EXACT_MATCH; import static morfologik.fsa.MatchResult.SEQUENCE_IS_A_PREFIX; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import java.text.Normalizer; import java.text.Normalizer.Form; import java.util.*; import morfologik.fsa.FSA; import morfologik.fsa.ByteSequenceIterator; import morfologik.fsa.FSATraversal; import morfologik.fsa.MatchResult; import morfologik.stemming.BufferUtils; import morfologik.stemming.Dictionary; import morfologik.stemming.DictionaryLookup; import morfologik.stemming.DictionaryMetadata; import morfologik.stemming.UnmappableInputException; /** * Finds spelling suggestions. Implements K. Oflazer's algorithm as described * in: Oflazer, Kemal. 1996. * "Error-Tolerant Finite-State Recognition with Applications to Morphological Analysis and Spelling Correction." * <i>Computational Linguistics</i> 22 (1): 73–89. * * <p> * See Jan Daciuk's <code>s_fsa</code> package. */ public class Speller { /** * Maximum length of the word to be checked. */ public static final int MAX_WORD_LENGTH = 120; static final int FREQ_RANGES = 'Z' - 'A' + 1; static final int FIRST_RANGE_CODE = 'A'; // less frequent words //FIXME: this is an upper limit for replacement searches, we need //proper tree traversal instead of generation of all possible candidates static final int UPPER_SEARCH_LIMIT = 15; private static final int MIN_WORD_LENGTH = 4; private static final int MAX_RECURSION_LEVEL = 6; private final int editDistance; private int effectEditDistance; // effective edit distance private final HMatrix hMatrix; private char[] candidate; /* current replacement */ private int candLen; private int wordLen; /* length of word being processed */ private char[] wordProcessed; /* word being processed */ private Map<Character, List<char[]>> replacementsAnyToOne = new HashMap<Character, List<char[]>>(); private Map<String, List<char[]>> replacementsAnyToTwo = new HashMap<String, List<char[]>>(); private Map<String, List<String>> replacementsTheRest = new HashMap<String, List<String>>(); /** * List of candidate strings, including same additional data such as edit * distance from the original word. */ private final List<CandidateData> candidates = new ArrayList<CandidateData>(); private boolean containsSeparators = true; /** * Internal reusable buffer for encoding words into byte arrays using * {@link #encoder}. */ private ByteBuffer byteBuffer = ByteBuffer.allocate(MAX_WORD_LENGTH); /** * Internal reusable buffer for encoding words into byte arrays using * {@link #encoder}. */ private CharBuffer charBuffer = CharBuffer.allocate(MAX_WORD_LENGTH); /** * Reusable match result. */ private final MatchResult matchResult = new MatchResult(); /** * Features of the compiled dictionary. * * @see DictionaryMetadata */ private final DictionaryMetadata dictionaryMetadata; /** * Charset encoder for the FSA. */ private final CharsetEncoder encoder; /** * Charset decoder for the FSA. */ private final CharsetDecoder decoder; /** An FSA used for lookups. */ private final FSATraversal matcher; /** FSA's root node. */ private final int rootNode; /** * The FSA we are using. */ private final FSA fsa; /** An iterator for walking along the final states of {@link #fsa}. */ private final ByteSequenceIterator finalStatesIterator; public Speller(final Dictionary dictionary) { this(dictionary, 1); } public Speller(final Dictionary dictionary, final int editDistance) { this.editDistance = editDistance; this.hMatrix = new HMatrix(editDistance, MAX_WORD_LENGTH); this.dictionaryMetadata = dictionary.metadata; this.rootNode = dictionary.fsa.getRootNode(); this.fsa = dictionary.fsa; this.matcher = new FSATraversal(fsa); this.finalStatesIterator = new ByteSequenceIterator(fsa, rootNode); if (rootNode == 0) { throw new IllegalArgumentException("Dictionary must have at least the root node."); } if (dictionaryMetadata == null) { throw new IllegalArgumentException("Dictionary metadata must not be null."); } encoder = dictionaryMetadata.getEncoder(); decoder = dictionaryMetadata.getDecoder(); // Multibyte separator will result in an exception here. dictionaryMetadata.getSeparatorAsChar(); this.createReplacementsMaps(); } private void createReplacementsMaps() { for (Map.Entry<String, List<String>> entry : dictionaryMetadata.getReplacementPairs().entrySet()) { for (String s : entry.getValue()) { // replacements any to one // the new key is the target of the replacement pair if (s.length() == 1) { if (!replacementsAnyToOne.containsKey(s.charAt(0))) { List<char[]> charList = new ArrayList<char[]>(); charList.add(entry.getKey().toCharArray()); replacementsAnyToOne.put(s.charAt(0), charList); } else { replacementsAnyToOne.get(s.charAt(0)).add(entry.getKey().toCharArray()); } } // replacements any to two // the new key is the target of the replacement pair else if (s.length() == 2) { if (!replacementsAnyToTwo.containsKey(s)) { List<char[]> charList = new ArrayList<char[]>(); charList.add(entry.getKey().toCharArray()); replacementsAnyToTwo.put(s, charList); } else { replacementsAnyToTwo.get(s).add(entry.getKey().toCharArray()); } } else { if (!replacementsTheRest.containsKey(entry.getKey())) { List<String> charList = new ArrayList<String>(); charList.add(s); replacementsTheRest.put(entry.getKey(), charList); } else { replacementsTheRest.get(entry.getKey()).add(s); } } } } } private ByteBuffer charSequenceToBytes(final CharSequence word) throws UnmappableInputException { // Encode word characters into bytes in the same encoding as the FSA's. charBuffer = BufferUtils.clearAndEnsureCapacity(charBuffer, word.length()); for (int i = 0; i < word.length(); i++) { final char chr = word.charAt(i); charBuffer.put(chr); } charBuffer.flip(); return BufferUtils.charsToBytes(encoder, charBuffer, byteBuffer); } /** * Checks whether the word is misspelled, by performing a series of checks * according to properties of the dictionary. * * If the flag <code>fsa.dict.speller.ignore-punctuation</code> is set, then * all non-alphabetic characters are considered to be correctly spelled. * * If the flag <code>fsa.dict.speller.ignore-numbers</code> is set, then all * words containing decimal digits are considered to be correctly spelled. * * If the flag <code>fsa.dict.speller.ignore-camel-case</code> is set, then * all CamelCase words are considered to be correctly spelled. * * If the flag <code>fsa.dict.speller.ignore-all-uppercase</code> is set, then * all alphabetic words composed of only uppercase characters are considered * to be correctly spelled. * * Otherwise, the word is checked in the dictionary. If the test fails, and * the dictionary does not perform any case conversions (as set by * <code>fsa.dict.speller.convert-case</code> flag), then the method returns * false. In case of case conversions, it is checked whether a non-mixed case * word is found in its lowercase version in the dictionary, and for * all-uppercase words, whether the word is found in the dictionary with the * initial uppercase letter. * * @param word * - the word to be checked * @return true if the word is misspelled **/ public boolean isMisspelled(final String word) { // dictionaries usually do not contain punctuation String wordToCheck = word; if (!dictionaryMetadata.getInputConversionPairs().isEmpty()) { wordToCheck = DictionaryLookup.applyReplacements(word, dictionaryMetadata.getInputConversionPairs()); } boolean isAlphabetic = wordToCheck.length() != 1 || isAlphabetic(wordToCheck.charAt(0)); return wordToCheck.length() > 0 && (!dictionaryMetadata.isIgnoringPunctuation() || isAlphabetic) && (!dictionaryMetadata.isIgnoringNumbers() || containsNoDigit(wordToCheck)) && !(dictionaryMetadata.isIgnoringCamelCase() && isCamelCase(wordToCheck)) && !(dictionaryMetadata.isIgnoringAllUppercase() && isAlphabetic && isAllUppercase(wordToCheck)) && !isInDictionary(wordToCheck) && (!dictionaryMetadata.isConvertingCase() || !(!isMixedCase(wordToCheck) && (isInDictionary(wordToCheck.toLowerCase(dictionaryMetadata.getLocale())) || isAllUppercase(wordToCheck) && isInDictionary(initialUppercase(wordToCheck))))); } private CharSequence initialUppercase(final String wordToCheck) { return wordToCheck.substring(0, 1) + wordToCheck.substring(1).toLowerCase(dictionaryMetadata.getLocale()); } /** * Test whether the word is found in the dictionary. * * @param word * the word to be tested * @return True if it is found. */ public boolean isInDictionary(final CharSequence word) { try { byteBuffer = charSequenceToBytes(word); } catch (UnmappableInputException e) { return false; } // Try to find a partial match in the dictionary. final MatchResult match = matcher.match(matchResult, byteBuffer.array(), 0, byteBuffer.remaining(), rootNode); // Make sure the word doesn't contain a separator if there is an exact match if (containsSeparators && match.kind == EXACT_MATCH) { containsSeparators = false; for (int i=0; i<word.length(); i++) { if (word.charAt(i) == dictionaryMetadata.getSeparator()) { containsSeparators = true; break; } } } if (match.kind == EXACT_MATCH && !containsSeparators) { return true; } return containsSeparators && match.kind == SEQUENCE_IS_A_PREFIX && byteBuffer.remaining() > 0 && fsa.getArc(match.node, dictionaryMetadata.getSeparator()) != 0; } /** * Get the frequency value for a word form. It is taken from the first entry * with this word form. * * @param word * the word to be tested * @return frequency value in range: 0..FREQ_RANGE-1 (0: less frequent). */ public int getFrequency(final CharSequence word) { if (!dictionaryMetadata.isFrequencyIncluded()) { return 0; } final byte separator = dictionaryMetadata.getSeparator(); try { byteBuffer = charSequenceToBytes(word); } catch (UnmappableInputException e) { return 0; } final MatchResult match = matcher.match(matchResult, byteBuffer.array(), 0, byteBuffer.remaining(), rootNode); if (match.kind == SEQUENCE_IS_A_PREFIX) { final int arc = fsa.getArc(match.node, separator); if (arc != 0 && !fsa.isArcFinal(arc)) { finalStatesIterator.restartFrom(fsa.getEndNode(arc)); if (finalStatesIterator.hasNext()) { final ByteBuffer bb = finalStatesIterator.next(); final byte[] ba = bb.array(); final int bbSize = bb.remaining(); //the last byte contains the frequency after a separator return ba[bbSize - 1] - FIRST_RANGE_CODE; } } } return 0; } /** * Propose suggestions for misspelled run-on words. This algorithm is inspired * by spell.cc in s_fsa package by Jan Daciuk. * * @param original * The original misspelled word. * @return The list of suggested pairs, as space-concatenated strings. */ public List<String> replaceRunOnWords(final String original) { final List<String> candidates = new ArrayList<String>(); String wordToCheck = original; if (!dictionaryMetadata.getInputConversionPairs().isEmpty()) { wordToCheck = DictionaryLookup.applyReplacements(original, dictionaryMetadata.getInputConversionPairs()); } if (!isInDictionary(wordToCheck) && dictionaryMetadata.isSupportingRunOnWords()) { for (int i = 1; i < original.length(); i++) { // chop from left to right final CharSequence firstCh = original.subSequence(0, i); if (isInDictionary(firstCh) && isInDictionary(original.subSequence(i, original.length()))) { if (dictionaryMetadata.getOutputConversionPairs().isEmpty()) { candidates.add(firstCh + " " + original.subSequence(i, original.length())); } else { candidates.add(DictionaryLookup.applyReplacements(firstCh + " " + original.subSequence(i, original.length()), dictionaryMetadata.getOutputConversionPairs()).toString()); } } } } return candidates; } /** * Find suggestions by using K. Oflazer's algorithm. See Jan Daciuk's s_fsa * package, spell.cc for further explanation. * * @param w The original misspelled word. * @return A list of suggested replacements. */ public List<String> findReplacements(final String w) { String word = w; if (!dictionaryMetadata.getInputConversionPairs().isEmpty()) { word = DictionaryLookup.applyReplacements(w, dictionaryMetadata.getInputConversionPairs()); } candidates.clear(); if (word.length() > 0 && word.length() < MAX_WORD_LENGTH && !isInDictionary(word)) { List<String> wordsToCheck = new ArrayList<String>(); if (replacementsTheRest != null && word.length() > 1) { for (final String wordChecked : getAllReplacements(word, 0, 0)) { boolean found = false; if (isInDictionary(wordChecked)) { candidates.add(new CandidateData(wordChecked, 0)); found = true; } else { String lowerWord = wordChecked.toLowerCase(dictionaryMetadata.getLocale()); String upperWord = wordChecked.toUpperCase(dictionaryMetadata.getLocale()); if (isInDictionary(lowerWord)) { //add the word as it is in the dictionary, not mixed-case versions of it candidates.add(new CandidateData(lowerWord, 0)); found = true; } if (isInDictionary(upperWord)) { candidates.add(new CandidateData(upperWord, 0)); found = true; } if (lowerWord.length() > 1) { String firstupperWord = Character.toUpperCase(lowerWord.charAt(0)) + lowerWord.substring(1); if (isInDictionary(firstupperWord)) { candidates.add(new CandidateData(firstupperWord, 0)); found = true; } } } if (!found) { wordsToCheck.add(wordChecked); } } } else { wordsToCheck.add(word); } //If at least one candidate was found with the replacement pairs (which are usual errors), //probably there is no need for more candidates if (candidates.isEmpty()) { int i = 1; for (final String wordChecked : wordsToCheck) { i++; if (i > UPPER_SEARCH_LIMIT) { // for performance reasons, do not search too deeply break; } wordProcessed = wordChecked.toCharArray(); wordLen = wordProcessed.length; if (wordLen < MIN_WORD_LENGTH && i > 2) { // three-letter replacements make little sense anyway break; } candidate = new char[MAX_WORD_LENGTH]; candLen = candidate.length; effectEditDistance = wordLen <= editDistance ? wordLen - 1 : editDistance; charBuffer = BufferUtils.clearAndEnsureCapacity(charBuffer, MAX_WORD_LENGTH); byteBuffer = BufferUtils.clearAndEnsureCapacity(byteBuffer, MAX_WORD_LENGTH); final byte[] prevBytes = new byte[0]; findRepl(0, fsa.getRootNode(), prevBytes, 0, 0); } } } Collections.sort(candidates); // Use a linked set to avoid duplicates and preserve the ordering of candidates. final Set<String> candStringSet = new LinkedHashSet<String>(); for (final CandidateData cd : candidates) { candStringSet.add(DictionaryLookup.applyReplacements(cd.getWord(), dictionaryMetadata.getOutputConversionPairs()).toString()); } final List<String> candStringList = new ArrayList<String>(candStringSet.size()); candStringList.addAll(candStringSet); return candStringList; } private void findRepl(final int depth, final int node, final byte[] prevBytes, final int wordIndex, final int candIndex) { int dist = 0; for (int arc = fsa.getFirstArc(node); arc != 0; arc = fsa.getNextArc(arc)) { byteBuffer = BufferUtils.clearAndEnsureCapacity(byteBuffer, prevBytes.length + 1); byteBuffer.put(prevBytes); byteBuffer.put(fsa.getArcLabel(arc)); final int bufPos = byteBuffer.position(); byteBuffer.flip(); decoder.reset(); // FIXME: this isn't correct -- no checks for overflows, no decoder flush. I don't think this should be in here // too, the decoder should run once on accumulated temporary byte buffer (current path) only when there's // a potential that this buffer can become a replacement candidate (isEndOfCandidate). Because we assume candidates // are valid input strings (this is verified when building the dictionary), it's save a lot of conversions. final CoderResult c = decoder.decode(byteBuffer, charBuffer, true); if (c.isMalformed()) { // assume that only valid // encodings are there final byte[] prev = new byte[bufPos]; byteBuffer.position(0); byteBuffer.get(prev); if (!fsa.isArcTerminal(arc)) { findRepl(depth, fsa.getEndNode(arc), prev, wordIndex, candIndex); // note: depth is not incremented } byteBuffer.clear(); } else if (!c.isError()) { // unmappable characters are silently discarded charBuffer.flip(); candidate[candIndex] = charBuffer.get(); charBuffer.clear(); byteBuffer.clear(); int lengthReplacement; // replacement "any to two" if ((lengthReplacement = matchAnyToTwo(wordIndex, candIndex)) > 0) { // the replacement takes place at the end of the candidate if (isEndOfCandidate(arc, wordIndex) && (dist = hMatrix.get(depth - 1, depth - 1)) <= effectEditDistance) { if (Math.abs(wordLen - 1 - (wordIndex + lengthReplacement - 2)) > 0) { // there are extra letters in the word after the replacement dist = dist + Math.abs(wordLen - 1 - (wordIndex + lengthReplacement - 2)); } if (dist <= effectEditDistance) { addCandidate(candIndex, dist); } } if (isArcNotTerminal(arc, candIndex)) { int x = hMatrix.get(depth, depth); hMatrix.set(depth, depth, hMatrix.get(depth - 1, depth - 1)); findRepl(Math.max(0, depth), fsa.getEndNode(arc), new byte[0], wordIndex + lengthReplacement - 1, candIndex + 1); hMatrix.set(depth, depth, x); } } //replacement "any to one" if ((lengthReplacement = matchAnyToOne(wordIndex, candIndex)) > 0) { // the replacement takes place at the end of the candidate if (isEndOfCandidate(arc, wordIndex) && (dist = hMatrix.get(depth, depth)) <= effectEditDistance) { if (Math.abs(wordLen - 1 - (wordIndex + lengthReplacement - 1)) > 0) { // there are extra letters in the word after the replacement dist = dist + Math.abs(wordLen - 1 - (wordIndex + lengthReplacement - 1)); } if (dist <= effectEditDistance) { addCandidate(candIndex, dist); } } if (isArcNotTerminal(arc, candIndex)) { findRepl(depth, fsa.getEndNode(arc), new byte[0], wordIndex + lengthReplacement, candIndex + 1); } } //general if (cuted(depth, wordIndex, candIndex) <= effectEditDistance) { if ((isEndOfCandidate(arc, wordIndex)) && (dist = ed(wordLen - 1 - (wordIndex - depth), depth, wordLen - 1, candIndex)) <= effectEditDistance) { addCandidate(candIndex, dist); } if (isArcNotTerminal(arc, candIndex)) { findRepl(depth + 1, fsa.getEndNode(arc), new byte[0], wordIndex + 1, candIndex + 1); } } } } } private boolean isArcNotTerminal(final int arc, final int candIndex) { return !fsa.isArcTerminal(arc) && !(containsSeparators && candidate[candIndex] == dictionaryMetadata.getSeparatorAsChar()); } private boolean isEndOfCandidate(final int arc, final int wordIndex) { return (fsa.isArcFinal(arc) || isBeforeSeparator(arc)) //candidate has proper length && (Math.abs(wordLen - 1 - (wordIndex)) <= effectEditDistance); } private boolean isBeforeSeparator(final int arc) { if (containsSeparators) { final int arc1 = fsa.getArc(fsa.getEndNode(arc), dictionaryMetadata.getSeparator()); return arc1 != 0 && !fsa.isArcTerminal(arc1); } return false; } private void addCandidate(final int depth, final int dist) { candidates.add(new CandidateData(String.valueOf(candidate, 0, depth + 1), dist)); } /** * Calculates edit distance. * * @param i length of first word (here: misspelled) - 1; * @param j length of second word (here: candidate) - 1. * @param wordIndex (TODO: javadoc?) * @param candIndex (TODO: javadoc?) * @return Edit distance between the two words. Remarks: See Oflazer. */ public int ed(final int i, final int j, final int wordIndex, final int candIndex) { int result; int a, b, c; if (areEqual(wordProcessed[wordIndex], candidate[candIndex])) { // last characters are the same result = hMatrix.get(i, j); } else if (wordIndex > 0 && candIndex > 0 && wordProcessed[wordIndex] == candidate[candIndex - 1] && wordProcessed[wordIndex - 1] == candidate[candIndex]) { // last two characters are transposed a = hMatrix.get(i - 1, j - 1); // transposition, e.g. ababab, ababba b = hMatrix.get(i + 1, j); // deletion, e.g. abab, aba c = hMatrix.get(i, j + 1); // insertion e.g. aba, abab result = 1 + min(a, b, c); } else { // otherwise a = hMatrix.get(i, j); // replacement, e.g. ababa, ababb b = hMatrix.get(i + 1, j); // deletion, e.g. ab, a c = hMatrix.get(i, j + 1); // insertion e.g. a, ab result = 1 + min(a, b, c); } hMatrix.set(i + 1, j + 1, result); return result; } // by Jaume Ortola private boolean areEqual(final char x, final char y) { if (x == y) { return true; } if (dictionaryMetadata.getEquivalentChars() != null && dictionaryMetadata.getEquivalentChars().containsKey(x) && dictionaryMetadata.getEquivalentChars().get(x).contains(y)) { return true; } if (dictionaryMetadata.isIgnoringDiacritics()) { String xn = Normalizer.normalize(Character.toString(x), Form.NFD); String yn = Normalizer.normalize(Character.toString(y), Form.NFD); if (xn.charAt(0) == yn.charAt(0)) { // avoid case conversion, if possible return true; } if (dictionaryMetadata.isConvertingCase()) { //again case conversion only when needed -- we // do not need String.lowercase because we only check // single characters, so a cheaper method is enough if (Character.isLetter(xn.charAt(0))) { boolean testNeeded = Character.isLowerCase(xn.charAt(0)) != Character.isLowerCase(yn.charAt(0)); if (testNeeded) { return Character.toLowerCase(xn.charAt(0)) == Character.toLowerCase(yn.charAt(0)); } } } return xn.charAt(0) == yn.charAt(0); } return false; } /** * Calculates cut-off edit distance. * * @param depth current length of candidates. * @param wordIndex (TODO: javadoc?) * @param candIndex (TODO: javadoc?) * @return Cut-off edit distance. Remarks: See Oflazer. */ public int cuted(final int depth, final int wordIndex, final int candIndex) { final int l = Math.max(0, depth - effectEditDistance); // min chars from word to consider - 1 final int u = Math.min(wordLen - 1 - (wordIndex - depth), depth + effectEditDistance); // max chars from word to // consider - 1 int minEd = effectEditDistance + 1; // what is to be computed int wi = wordIndex + l - depth; int d; for (int i = l; i <= u; i++, wi++) { if ((d = ed(i, depth, wi, candIndex)) < minEd) { minEd = d; } } return minEd; } // Match the last letter of the candidate against two or more letters of the word. private int matchAnyToOne(final int wordIndex, final int candIndex) { if (replacementsAnyToOne.containsKey(candidate[candIndex])) { for (final char[] rep : replacementsAnyToOne.get(candidate[candIndex])) { int i = 0; while (i < rep.length && (wordIndex + i) < wordLen && rep[i] == wordProcessed[wordIndex + i]) { i++; } if (i == rep.length) { return i; } } } return 0; } private int matchAnyToTwo(final int wordIndex, final int candIndex) { if (candIndex > 0 && candIndex < candidate.length && wordIndex > 0) { char[] twoChar = { candidate[candIndex - 1], candidate[candIndex] }; String sTwoChar = new String(twoChar); if (replacementsAnyToTwo.containsKey(sTwoChar)) { for (final char[] rep : replacementsAnyToTwo.get(sTwoChar)) { if (rep.length == 2 && wordIndex < wordLen && candidate[candIndex - 1] == wordProcessed[wordIndex - 1] && candidate[candIndex] == wordProcessed[wordIndex]) { return 0; //unnecessary replacements } int i = 0; while (i < rep.length && (wordIndex - 1 + i) < wordLen && rep[i] == wordProcessed[wordIndex - 1 + i]) { i++; } if (i == rep.length) { return i; } } } } return 0; } private static int min(final int a, final int b, final int c) { return Math.min(a, Math.min(b, c)); } /** * Copy-paste of Character.isAlphabetic() (needed as we require only 1.6) * * @param codePoint * The input character. * @return True if the character is a Unicode alphabetic character. */ static boolean isAlphabetic(final int codePoint) { return ((1 << Character.UPPERCASE_LETTER | 1 << Character.LOWERCASE_LETTER | 1 << Character.TITLECASE_LETTER | 1 << Character.MODIFIER_LETTER | 1 << Character.OTHER_LETTER | 1 << Character.LETTER_NUMBER) >> Character .getType(codePoint) & 1) != 0; } /** * Checks whether a string contains a digit. Used for ignoring words with * numbers * * @param s * Word to be checked. * @return True if there is a digit inside the word. */ static boolean containsNoDigit(final String s) { for (int k = 0; k < s.length(); k++) { if (Character.isDigit(s.charAt(k))) { return false; } } return true; } /** * Returns true if <code>str</code> is made up of all-uppercase characters * (ignoring characters for which no upper-/lowercase distinction exists). */ boolean isAllUppercase(final String str) { for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (Character.isLetter(c) && Character.isLowerCase(c)) { return false; } } return true; } /** * Returns true if <code>str</code> is made up of all-lowercase characters * (ignoring characters for which no upper-/lowercase distinction exists). */ boolean isNotAllLowercase(final String str) { for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (Character.isLetter(c) && !Character.isLowerCase(c)) { return true; } } return false; } /** * @param str * input string */ boolean isNotCapitalizedWord(final String str) { if (isNotEmpty(str) && Character.isUpperCase(str.charAt(0))) { for (int i = 1; i < str.length(); i++) { char c = str.charAt(i); if (Character.isLetter(c) && !Character.isLowerCase(c)) { return true; } } return false; } return true; } /** * Helper method to replace calls to "".equals(). * * @param str * String to check * @return true if string is empty OR null */ static boolean isNotEmpty(final String str) { return str != null && str.length() != 0; } /** * @param str * input str * @return Returns true if str is MixedCase. */ boolean isMixedCase(final String str) { return !isAllUppercase(str) && isNotCapitalizedWord(str) && isNotAllLowercase(str); } /** * @param str The string to check. * @return Returns true if str is CamelCase. Note that German compounds with a dash * (like "Waschmaschinen-Test") are also considered camel case by this method. */ public boolean isCamelCase(final String str) { return isNotEmpty(str) && !isAllUppercase(str) && isNotCapitalizedWord(str) && Character.isUpperCase(str.charAt(0)) && (!(str.length() > 1) || Character.isLowerCase(str.charAt(1))) && isNotAllLowercase(str); } /** * Used to determine whether the dictionary supports case conversions. * * @return boolean value that answers this question in a deep and meaningful * way. * * @since 1.9 * */ public boolean convertsCase() { return dictionaryMetadata.isConvertingCase(); } /** * @param str * The string to find the replacements for. * @param fromIndex * The index from which replacements are found. * @param level * The recursion level. The search stops if level is &gt; MAX_RECURSION_LEVEL. * @return A list of all possible replacements of a {#link str} given string */ public List<String> getAllReplacements(final String str, final int fromIndex, final int level) { List<String> replaced = new ArrayList<>(); if (level > MAX_RECURSION_LEVEL) { // Stop searching at some point replaced.add(str); return replaced; } StringBuilder sb = new StringBuilder(); sb.append(str); int index = MAX_WORD_LENGTH; String key = ""; int keyLength = 0; boolean found = false; // find first possible replacement after fromIndex position for (final String auxKey : replacementsTheRest.keySet()) { int auxIndex = sb.indexOf(auxKey, fromIndex); if (auxIndex > -1 && (auxIndex < index || (auxIndex == index && !(auxKey.length() < keyLength)))) { //select the longest possible key index = auxIndex; key = auxKey; keyLength = auxKey.length(); } } if (index < MAX_WORD_LENGTH) { for (final String rep : replacementsTheRest.get(key)) { // start a branch without replacement (only once per key) if (!found) { replaced.addAll(getAllReplacements(str, index + key.length(), level + 1)); found = true; } // avoid unnecessary replacements (ex. don't replace L by L·L when L·L already present) int ind = sb.indexOf(rep, fromIndex - rep.length() + 1); if (rep.length() > key.length() && ind > -1 && (ind == index || ind == index - rep.length() + 1)) { continue; } // start a branch with replacement sb.replace(index, index + key.length(), rep); replaced.addAll(getAllReplacements(sb.toString(), index + rep.length(), level + 1)); sb.setLength(0); sb.append(str); } } if (!found) { replaced.add(sb.toString()); } return replaced; } /** * Sets up the word and candidate. Used only to test the edit distance in * JUnit tests. * * @param word * the first word * @param candidate * the second word used for edit distance calculation */ void setWordAndCandidate(final String word, final String candidate) { wordProcessed = word.toCharArray(); wordLen = wordProcessed.length; this.candidate = candidate.toCharArray(); candLen = this.candidate.length; effectEditDistance = wordLen <= editDistance ? wordLen - 1 : editDistance; } public final int getWordLen() { return wordLen; } public final int getCandLen() { return candLen; } public final int getEffectiveED() { return effectEditDistance; } /** * Used to sort candidates according to edit distance, and possibly according * to their frequency in the future. * */ private class CandidateData implements Comparable<CandidateData> { private final String word; private final int distance; CandidateData(final String word, final int distance) { this.word = word; this.distance = distance * FREQ_RANGES + FREQ_RANGES - getFrequency(word) - 1; } final String getWord() { return word; } final int getDistance() { return distance; } @Override public int compareTo(final CandidateData cd) { // Assume no overflow. return cd.getDistance() > this.distance ? -1 : cd.getDistance() == this.distance ? 0 : 1; } } }
use converted word
morfologik-speller/src/main/java/morfologik/speller/Speller.java
use converted word
<ide><path>orfologik-speller/src/main/java/morfologik/speller/Speller.java <ide> wordToCheck = DictionaryLookup.applyReplacements(original, dictionaryMetadata.getInputConversionPairs()); <ide> } <ide> if (!isInDictionary(wordToCheck) && dictionaryMetadata.isSupportingRunOnWords()) { <del> for (int i = 1; i < original.length(); i++) { <add> for (int i = 1; i < wordToCheck.length(); i++) { <ide> // chop from left to right <del> final CharSequence firstCh = original.subSequence(0, i); <del> if (isInDictionary(firstCh) && isInDictionary(original.subSequence(i, original.length()))) { <add> final CharSequence firstCh = wordToCheck.subSequence(0, i); <add> if (isInDictionary(firstCh) && isInDictionary(wordToCheck.subSequence(i, wordToCheck.length()))) { <ide> if (dictionaryMetadata.getOutputConversionPairs().isEmpty()) { <del> candidates.add(firstCh + " " + original.subSequence(i, original.length())); <add> candidates.add(firstCh + " " + wordToCheck.subSequence(i, wordToCheck.length())); <ide> } else { <del> candidates.add(DictionaryLookup.applyReplacements(firstCh + " " + original.subSequence(i, original.length()), <add> candidates.add(DictionaryLookup.applyReplacements(firstCh + " " + wordToCheck.subSequence(i, wordToCheck.length()), <ide> dictionaryMetadata.getOutputConversionPairs()).toString()); <ide> } <ide> }
Java
apache-2.0
3b869b6eda5562d11cfa0eafd6f0aaaee491e366
0
universal-development/zulu-storage
package com.unidev.zerostorage.index; import com.unidev.zerostorage.Metadata; import com.unidev.zerostorage.Storage; import java.io.File; import java.util.List; import java.util.Optional; import static com.unidev.zerostorage.StorageMapper.storageMapper; /** * Index storage for metadata files <br/> * Index manage index.json file which have links to rest of the storages * */ public class IndexStorage { public static final String INDEX_FILE = "index.json"; public static final String FILE_EXT = ".json"; public static final Integer META_PER_STORAGE = 50; public static final String STORAGE_RECORDS_KEY = "storage_records_"; public static final String META_PER_STORAGE_KEY = "meta_per_storage"; private File storageRoot; private File indexFile; private Storage index; public IndexStorage() { index = new Storage(); } /** * Load from index from root file */ public IndexStorage load() { if (indexFile.exists()) { index = storageMapper().loadSource(indexFile).load(); } else { index = new Storage(); } return this; } /** * Save index state */ public void save() { storageMapper().saveSource(indexFile).save(index); } /** * Change index root */ public IndexStorage storageRoot(File file) { this.storageRoot = file; this.indexFile = new File(storageRoot, INDEX_FILE); return this; } /** * Fetch metadata list * @return */ public List<Metadata> storageFiles() { return index.metadata(); } /** * Add metadata to storage - metadata will be stored in appropriate storage and logged in storage index * @param metadata Metadata to add * @return */ public IndexStorage addMetadata(Metadata metadata) { if (index.metadata().isEmpty()) { addNextStorageFile(); } Integer recordsPerStorage = index.details().opt(META_PER_STORAGE_KEY, META_PER_STORAGE); String storageFileName = index.metadata().get(0).getLink(); int recordCount = index.details().opt(STORAGE_RECORDS_KEY + storageFileName, 0); if (recordCount >= recordsPerStorage) { addNextStorageFile(); storageFileName = index.metadata().get(0).getLink(); } File storageFile = new File(storageRoot, storageFileName); Storage storage = storageMapper().loadSource(storageFile).load(); storage.addMetadataFirst(metadata); storageMapper().saveSource(storageFile).save(storage); index.details().put(STORAGE_RECORDS_KEY + storageFileName, storage.metadata().size()); save(); return this; } /** * Fetch storage by metadata id * @return storage object or null empty optional */ public Optional<Storage> storage(String metaId) { Optional<Metadata> metadata = index.fetchMetaById(metaId); if (!metadata.isPresent()) { return Optional.empty(); } File storageFile = new File(storageRoot, metadata.get()._id()); return Optional.of(storageMapper().loadSource(storageFile).load()); } private IndexStorage addNextStorageFile() { int fileCount = index.metadata().size(); File metadataFile = new File(storageRoot, (fileCount + 1) + FILE_EXT); Storage storage = new Storage(); storageMapper().saveSource(metadataFile).save(storage); Metadata indexMetadata = new Metadata(); indexMetadata.setLink(metadataFile.getName()); indexMetadata.set_id(metadataFile.getName()); index.addMetadataFirst(indexMetadata); save(); return this; } public IndexStorage index(Storage index) { this.index = index; return this; } public Storage index() { return index; } public Storage getIndex() { return this.index; } public void setIndex(Storage index) { this.index = index; } }
zero-storage-core/src/main/java/com/unidev/zerostorage/index/IndexStorage.java
package com.unidev.zerostorage.index; import com.unidev.zerostorage.Metadata; import com.unidev.zerostorage.Storage; import java.io.File; import java.util.List; import static com.unidev.zerostorage.StorageMapper.storageMapper; /** * Index storage for metadata files <br/> * Index manage index.json file which have links to rest of the storages * */ public class IndexStorage { public static final String INDEX_FILE = "index.json"; public static final String FILE_EXT = ".json"; public static final Integer META_PER_STORAGE = 50; public static final String STORAGE_RECORDS_KEY = "storage_records_"; public static final String META_PER_STORAGE_KEY = "meta_per_storage"; private File storageRoot; private File indexFile; private Storage index; public IndexStorage() { index = new Storage(); } public IndexStorage load() { if (indexFile.exists()) { index = storageMapper().loadSource(indexFile).load(); } else { index = new Storage(); } return this; } public void save() { storageMapper().saveSource(indexFile).save(index); } public IndexStorage storageRoot(File file) { this.storageRoot = file; this.indexFile = new File(storageRoot, INDEX_FILE); return this; } public List<Metadata> sorageFiles() { return index.metadata(); } public IndexStorage addMetadata(Metadata metadata) { if (index.metadata().isEmpty()) { addNextStorageFile(); } Integer recordsPerStorage = index.details().opt(META_PER_STORAGE_KEY, META_PER_STORAGE); String storageFileName = index.metadata().get(0).getLink(); int recordCount = index.details().opt(STORAGE_RECORDS_KEY + storageFileName, 0); if (recordCount >= recordsPerStorage) { addNextStorageFile(); storageFileName = index.metadata().get(0).getLink(); } File storageFile = new File(storageRoot, storageFileName); Storage storage = storageMapper().loadSource(storageFile).load(); storage.addMetadateFirst(metadata); storageMapper().saveSource(storageFile).save(storage); index.details().put(STORAGE_RECORDS_KEY + storageFileName, storage.metadata().size()); save(); return this; } private IndexStorage addNextStorageFile() { int fileCount = index.metadata().size(); File metadataFile = new File(storageRoot, (fileCount + 1) + FILE_EXT); Storage storage = new Storage(); storageMapper().saveSource(metadataFile).save(storage); Metadata indexMetadata = new Metadata(); indexMetadata.setLink(metadataFile.getName()); indexMetadata.set_id(metadataFile.getName()); index.addMetadateFirst(indexMetadata); save(); return this; } public IndexStorage index(Storage index) { this.index = index; return this; } public Storage index() { return index; } public Storage getIndex() { return this.index; } public void setIndex(Storage index) { this.index = index; } }
Added method for fetching storage by metadata id(file name)
zero-storage-core/src/main/java/com/unidev/zerostorage/index/IndexStorage.java
Added method for fetching storage by metadata id(file name)
<ide><path>ero-storage-core/src/main/java/com/unidev/zerostorage/index/IndexStorage.java <ide> <ide> import java.io.File; <ide> import java.util.List; <add>import java.util.Optional; <ide> <ide> import static com.unidev.zerostorage.StorageMapper.storageMapper; <ide> <ide> index = new Storage(); <ide> } <ide> <add> /** <add> * Load from index from root file <add> */ <ide> public IndexStorage load() { <ide> if (indexFile.exists()) { <ide> index = storageMapper().loadSource(indexFile).load(); <ide> return this; <ide> } <ide> <add> /** <add> * Save index state <add> */ <ide> public void save() { <ide> storageMapper().saveSource(indexFile).save(index); <ide> } <ide> <add> /** <add> * Change index root <add> */ <ide> public IndexStorage storageRoot(File file) { <ide> this.storageRoot = file; <ide> this.indexFile = new File(storageRoot, INDEX_FILE); <ide> return this; <ide> } <ide> <del> public List<Metadata> sorageFiles() { <add> /** <add> * Fetch metadata list <add> * @return <add> */ <add> public List<Metadata> storageFiles() { <ide> return index.metadata(); <ide> } <ide> <add> /** <add> * Add metadata to storage - metadata will be stored in appropriate storage and logged in storage index <add> * @param metadata Metadata to add <add> * @return <add> */ <ide> public IndexStorage addMetadata(Metadata metadata) { <ide> if (index.metadata().isEmpty()) { <ide> addNextStorageFile(); <ide> <ide> File storageFile = new File(storageRoot, storageFileName); <ide> Storage storage = storageMapper().loadSource(storageFile).load(); <del> storage.addMetadateFirst(metadata); <add> storage.addMetadataFirst(metadata); <ide> storageMapper().saveSource(storageFile).save(storage); <ide> <ide> index.details().put(STORAGE_RECORDS_KEY + storageFileName, storage.metadata().size()); <ide> <ide> return this; <ide> } <add> <add> /** <add> * Fetch storage by metadata id <add> * @return storage object or null empty optional <add> */ <add> public Optional<Storage> storage(String metaId) { <add> Optional<Metadata> metadata = index.fetchMetaById(metaId); <add> if (!metadata.isPresent()) { <add> return Optional.empty(); <add> } <add> File storageFile = new File(storageRoot, metadata.get()._id()); <add> return Optional.of(storageMapper().loadSource(storageFile).load()); <add> } <add> <ide> <ide> private IndexStorage addNextStorageFile() { <ide> int fileCount = index.metadata().size(); <ide> Metadata indexMetadata = new Metadata(); <ide> indexMetadata.setLink(metadataFile.getName()); <ide> indexMetadata.set_id(metadataFile.getName()); <del> index.addMetadateFirst(indexMetadata); <add> index.addMetadataFirst(indexMetadata); <ide> save(); <ide> <ide> return this;
Java
apache-2.0
6fa8f7abe41e90119f926d80f5696fc11dbe3035
0
TangHao1987/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,signed/intellij-community,fnouama/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,adedayo/intellij-community,amith01994/intellij-community,allotria/intellij-community,caot/intellij-community,apixandru/intellij-community,izonder/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,allotria/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,ol-loginov/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,supersven/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,supersven/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,caot/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,fitermay/intellij-community,signed/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,ibinti/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,signed/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,vladmm/intellij-community,FHannes/intellij-community,consulo/consulo,jagguli/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,da1z/intellij-community,izonder/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,signed/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,slisson/intellij-community,hurricup/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,petteyg/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,caot/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,jexp/idea2,vladmm/intellij-community,vladmm/intellij-community,fitermay/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,hurricup/intellij-community,semonte/intellij-community,nicolargo/intellij-community,caot/intellij-community,blademainer/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,jexp/idea2,orekyuu/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,asedunov/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,jexp/idea2,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,joewalnes/idea-community,signed/intellij-community,kool79/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,ryano144/intellij-community,fnouama/intellij-community,kdwink/intellij-community,holmes/intellij-community,vladmm/intellij-community,samthor/intellij-community,fnouama/intellij-community,vladmm/intellij-community,fnouama/intellij-community,retomerz/intellij-community,samthor/intellij-community,allotria/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,hurricup/intellij-community,joewalnes/idea-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,jexp/idea2,kool79/intellij-community,kool79/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,samthor/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,izonder/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,holmes/intellij-community,joewalnes/idea-community,vvv1559/intellij-community,xfournet/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,semonte/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,jexp/idea2,pwoodworth/intellij-community,ryano144/intellij-community,retomerz/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,caot/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,semonte/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,FHannes/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,allotria/intellij-community,retomerz/intellij-community,slisson/intellij-community,kool79/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,vladmm/intellij-community,robovm/robovm-studio,FHannes/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,caot/intellij-community,pwoodworth/intellij-community,consulo/consulo,retomerz/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,izonder/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,consulo/consulo,robovm/robovm-studio,SerCeMan/intellij-community,petteyg/intellij-community,ibinti/intellij-community,xfournet/intellij-community,da1z/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,signed/intellij-community,slisson/intellij-community,xfournet/intellij-community,da1z/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,kool79/intellij-community,Distrotech/intellij-community,da1z/intellij-community,semonte/intellij-community,ahb0327/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,signed/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,samthor/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,semonte/intellij-community,ryano144/intellij-community,vladmm/intellij-community,ernestp/consulo,kdwink/intellij-community,slisson/intellij-community,retomerz/intellij-community,dslomov/intellij-community,adedayo/intellij-community,blademainer/intellij-community,signed/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,jexp/idea2,hurricup/intellij-community,supersven/intellij-community,akosyakov/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,semonte/intellij-community,joewalnes/idea-community,supersven/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,consulo/consulo,signed/intellij-community,ibinti/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,xfournet/intellij-community,supersven/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,supersven/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,ernestp/consulo,petteyg/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,signed/intellij-community,suncycheng/intellij-community,consulo/consulo,fengbaicanhe/intellij-community,Lekanich/intellij-community,slisson/intellij-community,ernestp/consulo,FHannes/intellij-community,vvv1559/intellij-community,izonder/intellij-community,retomerz/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,diorcety/intellij-community,caot/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,holmes/intellij-community,clumsy/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,ahb0327/intellij-community,Distrotech/intellij-community,signed/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,caot/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,jagguli/intellij-community,orekyuu/intellij-community,ernestp/consulo,nicolargo/intellij-community,clumsy/intellij-community,ryano144/intellij-community,hurricup/intellij-community,petteyg/intellij-community,fitermay/intellij-community,fitermay/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,joewalnes/idea-community,ivan-fedorov/intellij-community,dslomov/intellij-community,jexp/idea2,alphafoobar/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,kool79/intellij-community,asedunov/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,amith01994/intellij-community,adedayo/intellij-community,robovm/robovm-studio,FHannes/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,caot/intellij-community,xfournet/intellij-community,petteyg/intellij-community,kdwink/intellij-community,ryano144/intellij-community,samthor/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,signed/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,apixandru/intellij-community,slisson/intellij-community,slisson/intellij-community,samthor/intellij-community,petteyg/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,asedunov/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,joewalnes/idea-community,izonder/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,samthor/intellij-community,fitermay/intellij-community,retomerz/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,semonte/intellij-community,clumsy/intellij-community,kdwink/intellij-community,robovm/robovm-studio,ibinti/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,izonder/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,semonte/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,asedunov/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,joewalnes/idea-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,clumsy/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,clumsy/intellij-community,da1z/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,jexp/idea2,lucafavatella/intellij-community,consulo/consulo,supersven/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,jagguli/intellij-community,apixandru/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,ernestp/consulo,nicolargo/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,semonte/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd
/* * Copyright 2000-2007 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.ui; import com.intellij.openapi.Disposable; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.SystemInfo; import com.intellij.util.ReflectionUtil; import com.intellij.util.ui.treetable.TreeTableCellRenderer; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import javax.swing.border.Border; import javax.swing.plaf.ProgressBarUI; import java.awt.*; import java.awt.event.*; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.regex.Pattern; /** * @author max */ public class UIUtil { private static final Logger LOG = Logger.getInstance("#com.intellij.util.ui.UIUtil"); public static final @NonNls String HTML_MIME = "text/html"; public static final char MNEMONIC = 0x1B; @NonNls public static final String JSLIDER_ISFILLED = "JSlider.isFilled"; @NonNls public static final String ARIAL_FONT_NAME = "Arial"; @NonNls public static final String TABLE_FOCUS_CELL_BACKGROUND_PROPERTY = "Table.focusCellBackground"; private static Color ACTIVE_COLOR = new Color(160, 186, 213); private static Color INACTIVE_COLOR = new Color(128, 128, 128); private static Color SEPARATOR_COLOR = INACTIVE_COLOR.brighter(); public static final Pattern CLOSE_TAG_PATTERN = Pattern.compile("<\\s*([^<>/ ]+)([^<>]*)/\\s*>", Pattern.CASE_INSENSITIVE); private UIUtil() { } public static boolean isReallyTypedEvent(KeyEvent e) { char c = e.getKeyChar(); if (!(c >= 0x20 && c != 0x7F)) return false; int modifiers = e.getModifiers(); if (SystemInfo.isMac) { return !e.isMetaDown() && !e.isControlDown(); } return (modifiers & ActionEvent.ALT_MASK) == (modifiers & ActionEvent.CTRL_MASK); } public static void setEnabled(Component component, boolean enabled, boolean recursively) { component.setEnabled(enabled); if (recursively) { if (component instanceof Container) { final Container container = ((Container)component); final int subComponentCount = container.getComponentCount(); for (int i = 0; i < subComponentCount; i++) { setEnabled(container.getComponent(i), enabled, recursively); } } } } public static void drawLine(Graphics g, int x1, int y1, int x2, int y2) { g.drawLine(x1, y1, x2, y2); } public static void setActionNameAndMnemonic(String text, Action action) { int mnemoPos = text.indexOf("&"); if (mnemoPos >= 0 && mnemoPos < text.length() - 2) { String mnemoChar = text.substring(mnemoPos + 1, mnemoPos + 2).trim(); if (mnemoChar.length() == 1) { action.putValue(Action.MNEMONIC_KEY, Integer.valueOf((int)mnemoChar.charAt(0))); } } text = text.replaceAll("&", ""); action.putValue(Action.NAME, text); } public static Font getLabelFont() { return UIManager.getFont("Label.font"); } public static Color getLabelBackground() { return UIManager.getColor("Label.background"); } public static Color getLabelForeground() { return UIManager.getColor("Label.foreground"); } public static Icon getOptionPanelWarningIcon() { return UIManager.getIcon("OptionPane.warningIcon"); } public static Icon getOptionPanelQuestionIcon() { return UIManager.getIcon("OptionPane.questionIcon"); } public static String replaceMnemonicAmpersand(final String value) { if (value.indexOf('&') >= 0) { boolean useMacMnemonic = value.indexOf("&&") >= 0; StringBuffer realValue = new StringBuffer(); int i = 0; while (i < value.length()) { char c = value.charAt(i); if (c == '\\') { if (i < value.length() - 1 && value.charAt(i + 1) == '&') { realValue.append('&'); i++; } else { realValue.append(c); } } else if (c == '&') { if (i < value.length() - 1 && value.charAt(i + 1) == '&') { if (SystemInfo.isMac) { realValue.append(MNEMONIC); } i++; } else { if (!SystemInfo.isMac || !useMacMnemonic) { realValue.append(MNEMONIC); } } } else { realValue.append(c); } i++; } return realValue.toString(); } return value; } public static Color getTableHeaderBackground() { return UIManager.getColor("TableHeader.background"); } public static Color getTreeTextForeground() { return UIManager.getColor("Tree.textForeground"); } public static Color getTreeSelectonForeground() { return UIManager.getColor("Tree.selectionForeground"); } public static Color getTreeSelectionBackground() { return UIManager.getColor("Tree.selectionBackground"); } public static Color getTreeTextBackground() { return UIManager.getColor("Tree.textBackground"); } public static Color getListSelectionForeground() { final Color color = UIManager.getColor("List.selectionForeground"); if (color == null) { return UIManager.getColor("List[Selected].textForeground"); // Nimbus } return color; } public static Color getFieldForegroundColor() { return UIManager.getColor("field.foreground"); } public static Color getTableSelectionBackground() { return UIManager.getColor("Table.selectionBackground"); } public static Color getActiveTextColor() { return UIManager.getColor("textActiveText"); } public static Color getInactiveTextColor() { return UIManager.getColor("textInactiveText"); } public static Font getTreeFont() { return UIManager.getFont("Tree.font"); } public static Font getListFont() { return UIManager.getFont("List.font"); } public static Color getTreeSelectionForeground() { return UIManager.getColor("Tree.selectionForeground"); } public static Color getTextInactiveTextColor() { return UIManager.getColor("textInactiveText"); } public static void installPopupMenuColorAndFonts(final JComponent contentPane) { LookAndFeel.installColorsAndFont(contentPane, "PopupMenu.background", "PopupMenu.foreground", "PopupMenu.font"); } public static void installPopupMenuBorder(final JComponent contentPane) { LookAndFeel.installBorder(contentPane, "PopupMenu.border"); } public static boolean isMotifLookAndFeel() { return "Motif".equals(UIManager.getLookAndFeel().getID()); } public static Color getTreeSelectionBorderColor() { return UIManager.getColor("Tree.selectionBorderColor"); } public static Object getTreeRightChildIndent() { return UIManager.get("Tree.rightChildIndent"); } public static Object getTreeLeftChildIndent() { return UIManager.get("Tree.leftChildIndent"); } static public Color getToolTipBackground() { return UIManager.getColor("ToolTip.background"); } static public Color getToolTipForeground() { return UIManager.getColor("ToolTip.foreground"); } public static Color getComboBoxDisabledForeground() { return UIManager.getColor("ComboBox.disabledForeground"); } public static Color getComboBoxDisabledBackground() { return UIManager.getColor("ComboBox.disabledBackground"); } public static Color getButtonSelectColor() { return UIManager.getColor("Button.select"); } public static Integer getPropertyMaxGutterIconWidth(final String propertyPrefix) { return (Integer)UIManager.get(propertyPrefix + ".maxGutterIconWidth"); } public static Color getMenuItemDisabledForeground() { return UIManager.getColor("MenuItem.disabledForeground"); } public static Object getMenuItemDisabledForegroundObject() { return UIManager.get("MenuItem.disabledForeground"); } public static Object getTabbedPanePaintContentBorder(final JComponent c) { return c.getClientProperty("TabbedPane.paintContentBorder"); } public static boolean isMenuCrossMenuMnemonics() { return UIManager.getBoolean("Menu.crossMenuMnemonic"); } public static Color getTableBackground() { return UIManager.getColor("Table.background"); } public static Color getTableSelectionForeground() { return UIManager.getColor("Table.selectionForeground"); } public static Color getTableForeground() { return UIManager.getColor("Table.foreground"); } public static Color getListBackground() { return UIManager.getColor("List.background"); } public static Color getListForeground() { return UIManager.getColor("List.foreground"); } public static Color getPanelBackground() { return UIManager.getColor("Panel.background"); } public static Color getTreeForeground() { return UIManager.getColor("Tree.foreground"); } public static Color getTableFocusCellBackground() { return UIManager.getColor("Table.focusCellBackground"); } public static Color getListSelectionBackground() { final Color color = UIManager.getColor("List.selectionBackground"); if (color == null) { return UIManager.getColor("List[Selected].textBackground"); // Nimbus } return color; } public static Color getTextFieldForeground() { return UIManager.getColor("TextField.foreground"); } public static Color getTextFieldBackground() { return UIManager.getColor("TextField.background"); } public static Font getButtonFont() { return UIManager.getFont("Button.font"); } public static Font getToolTipFont() { return UIManager.getFont("ToolTip.font"); } public static Color getTabbedPaneBackground() { return UIManager.getColor("TabbedPane.background"); } public static void setSliderIsFilled(final JSlider slider, final boolean value) { slider.putClientProperty("JSlider.isFilled", Boolean.valueOf(value)); } public static Color getLabelTextForeground() { return UIManager.getColor("Label.textForeground"); } public static Color getControlColor() { return UIManager.getColor("control"); } public static Font getOptionPaneMessageFont() { return UIManager.getFont("OptionPane.messageFont"); } public static Color getSeparatorShadow() { return UIManager.getColor("Separator.shadow"); } public static Font getMenuFont() { return UIManager.getFont("Menu.font"); } public static Color getSeparatorHighlight() { return UIManager.getColor("Separator.highlight"); } public static Border getTableFocusCellHighlightBorder() { return UIManager.getBorder("Table.focusCellHighlightBorder"); } public static void setLineStyleAngled(final TreeTableCellRenderer component) { component.putClientProperty("JTree.lineStyle", "Angled"); } public static void setLineStyleAngled(final JTree component) { component.putClientProperty("JTree.lineStyle", "Angled"); } public static Color getTableFocusCellForeground() { return UIManager.getColor("Table.focusCellForeground"); } public static Color getPanelBackgound() { return UIManager.getColor("Panel.background"); } public static Border getTextFieldBorder() { return UIManager.getBorder("TextField.border"); } public static Border getButtonBorder() { return UIManager.getBorder("Button.border"); } public static Icon getErrorIcon() { return UIManager.getIcon("OptionPane.errorIcon"); } public static Icon getInformationIcon() { return UIManager.getIcon("OptionPane.informationIcon"); } public static Icon getQuestionIcon() { return UIManager.getIcon("OptionPane.questionIcon"); } public static Icon getWarningIcon() { return UIManager.getIcon("OptionPane.warningIcon"); } public static Icon getRadioButtonIcon() { return UIManager.getIcon("RadioButton.icon"); } public static Icon getTreeCollapsedIcon() { return UIManager.getIcon("Tree.collapsedIcon"); } public static Icon getTreeExpandedIcon() { return UIManager.getIcon("Tree.expandedIcon"); } public static Border getTableHeaderCellBorder() { return UIManager.getBorder("TableHeader.cellBorder"); } public static Color getWindowColor() { return UIManager.getColor("window"); } public static Color getTextAreaForeground() { return UIManager.getColor("TextArea.foreground"); } public static Color getOptionPaneBackground() { return UIManager.getColor("OptionPane.background"); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderQuaquaLookAndFeel() { return UIManager.getLookAndFeel().getName().indexOf("Quaqua") >= 0; } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderNimbusLookAndFeel() { return UIManager.getLookAndFeel().getName().indexOf("Nimbus") >= 0; } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderAquaLookAndFeel() { return UIManager.getLookAndFeel().getName().indexOf("Mac OS X") >= 0; } public static boolean isFullRowSelectionLAF() { return isUnderNimbusLookAndFeel() || isUnderQuaquaLookAndFeel(); } public static boolean isUnderNativeMacLookAndFeel() { return isUnderAquaLookAndFeel() || isUnderQuaquaLookAndFeel(); } @SuppressWarnings({"HardCodedStringLiteral"}) public static void removeQuaquaVisualMarginsIn(Component component) { if (component instanceof JComponent) { final JComponent jComponent = (JComponent)component; final Component[] children = jComponent.getComponents(); for (Component child : children) { removeQuaquaVisualMarginsIn(child); } jComponent.putClientProperty("Quaqua.Component.visualMargin", new Insets(0, 0, 0, 0)); } } public static boolean isControlKeyDown(MouseEvent mouseEvent) { return SystemInfo.isMac ? mouseEvent.isMetaDown() : mouseEvent.isControlDown(); } public static String[] getValidFontNames(final boolean familyName) { Set<String> result = new TreeSet<String>(); Font[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); for (Font font : fonts) { // Adds fonts that can display symbols at [A, Z] + [a, z] + [0, 9] try { if (font.canDisplay('a') && font.canDisplay('z') && font.canDisplay('A') && font.canDisplay('Z') && font.canDisplay('0') && font.canDisplay('1')) { result.add(familyName ? font.getFamily() : font.getName()); } } catch (Exception e) { // JRE has problems working with the font. Just skip. } } return result.toArray(new String[result.size()]); } public static String[] getStandardFontSizes() { return new String[]{"8", "9", "10", "11", "12", "14", "16", "18", "20", "22", "24", "26", "28", "36", "48", "72"}; } public static void setupEnclosingDialogBounds(final JComponent component) { component.revalidate(); component.repaint(); final Window window = SwingUtilities.windowForComponent(component); if (window != null && (window.getSize().height < window.getMinimumSize().height || window.getSize().width < window.getMinimumSize().width)) { window.pack(); } } public static String displayPropertiesToCSS(Font font, Color fg) { @NonNls StringBuffer rule = new StringBuffer("body {"); if (font != null) { rule.append(" font-family: "); rule.append(font.getFamily()); rule.append(" ; "); rule.append(" font-size: "); rule.append(font.getSize()); rule.append("pt ;"); if (font.isBold()) { rule.append(" font-weight: 700 ; "); } if (font.isItalic()) { rule.append(" font-style: italic ; "); } } if (fg != null) { rule.append(" color: #"); if (fg.getRed() < 16) { rule.append('0'); } rule.append(Integer.toHexString(fg.getRed())); if (fg.getGreen() < 16) { rule.append('0'); } rule.append(Integer.toHexString(fg.getGreen())); if (fg.getBlue() < 16) { rule.append('0'); } rule.append(Integer.toHexString(fg.getBlue())); rule.append(" ; "); } rule.append(" }"); return rule.toString(); } /** * @param g * @param x top left X coordinate. * @param y top left Y coordinate. * @param x1 right bottom X coordinate. * @param y1 right bottom Y coordinate. */ public static void drawDottedRectangle(Graphics g, int x, int y, int x1, int y1) { int i1; for (i1 = x; i1 <= x1; i1 += 2) { drawLine(g, i1, y, i1, y); } for (i1 = i1 != x1 + 1 ? y + 2 : y + 1; i1 <= y1; i1 += 2) { drawLine(g, x1, i1, x1, i1); } for (i1 = i1 != y1 + 1 ? x1 - 2 : x1 - 1; i1 >= x; i1 -= 2) { drawLine(g, i1, y1, i1, y1); } for (i1 = i1 != x - 1 ? y1 - 2 : y1 - 1; i1 >= y; i1 -= 2) { drawLine(g, x, i1, x, i1); } } public static void applyRenderingHints(final Graphics g) { Toolkit tk = Toolkit.getDefaultToolkit(); //noinspection HardCodedStringLiteral Map map = (Map)(tk.getDesktopProperty("awt.font.desktophints")); if (map != null) { ((Graphics2D)g).addRenderingHints(map); } } @TestOnly public static void dispatchAllInvocationEvents() { assert SwingUtilities.isEventDispatchThread(); final EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue(); while (true) { AWTEvent event = eventQueue.peekEvent(); if (event == null) break; try { AWTEvent event1 = eventQueue.getNextEvent(); if (event1 instanceof InvocationEvent) { ((InvocationEvent)event1).dispatch(); } } catch (Exception e) { LOG.error(e); //? } } } public static void pump() { assert !SwingUtilities.isEventDispatchThread(); final BlockingQueue queue = new LinkedBlockingQueue(); SwingUtilities.invokeLater(new Runnable() { public void run() { queue.offer(queue); } }); try { queue.take(); } catch (InterruptedException e) { LOG.error(e); } } public static void addAwtListener(final AWTEventListener listener, long mask, Disposable parent) { Toolkit.getDefaultToolkit().addAWTEventListener(listener, mask); Disposer.register(parent, new Disposable() { public void dispose() { Toolkit.getDefaultToolkit().removeAWTEventListener(listener); } }); } public static void drawVDottedLine(Graphics2D g, int lineX, int startY, int endY, final Color bgColor, final Color fgColor) { g.setColor(bgColor); drawLine(g, lineX, startY, lineX, endY); g.setColor(fgColor); for (int i = (startY / 2) * 2; i < endY; i += 2) { g.drawRect(lineX, i, 0, 0); } } public static void drawHDottedLine(Graphics2D g, int startX, int endX, int lineY, final Color bgColor, final Color fgColor) { g.setColor(bgColor); drawLine(g, startX, lineY, endX, lineY); g.setColor(fgColor); for (int i = (startX / 2) * 2; i < endX; i += 2) { g.drawRect(i, lineY, 0, 0); } } public static void drawDottedLine(Graphics2D g, int x1, int y1, int x2, int y2, final Color bgColor, final Color fgColor) { if (x1 == x2) { drawVDottedLine(g, x1, y1, y2, bgColor, fgColor); } else if (y1 == y2) { drawHDottedLine(g, x1, x2, y1, bgColor, fgColor); } else { throw new IllegalArgumentException("Only vertical or horizontal lines are supported"); } } public static boolean isFocusAncestor(@NotNull final JComponent component) { final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (owner == null) return false; if (owner == component) return true; return SwingUtilities.isDescendingFrom(owner, component); } public static boolean isCloseClick(MouseEvent e) { if (e.isPopupTrigger() || e.getID() != MouseEvent.MOUSE_PRESSED) return false; return e.getButton() == MouseEvent.BUTTON2 || (e.getButton() == MouseEvent.BUTTON1 && e.isShiftDown()); } public static boolean isActionClick(MouseEvent e) { if (isCloseClick(e)) return false; return e.getButton() == MouseEvent.BUTTON1; } public static @NotNull Color getBgFillColor(@NotNull JComponent c) { final Component parent = findNearestOpaque(c); return parent == null ? c.getBackground() : parent.getBackground(); } public static @Nullable Component findNearestOpaque(JComponent c) { Component eachParent = c; while (eachParent != null) { if (eachParent.isOpaque()) return eachParent; eachParent = eachParent.getParent(); } return eachParent; } @NonNls public static String getCssFontDeclaration(final Font font) { return "<style> body, div, td { font-family: " + font.getFamily() + "; font-size: " + font.getSize() + "; } </style>"; } public static boolean isWinLafOnVista() { return SystemInfo.isWindowsVista && "Windows".equals(UIManager.getLookAndFeel().getName()); } public static boolean isStandardMenuLAF() { return isWinLafOnVista() || "Nimbus".equals(UIManager.getLookAndFeel().getName()); } public static Color getFocusedFillColor() { return toAlpha(UIUtil.getListSelectionBackground(), 100); } public static Color getFocusedBoundsColor() { return getBoundsColor(); } public static Color getBoundsColor() { return new Color(128, 128, 128); } public static Color getBoundsColor(boolean focused) { return focused ? getFocusedBoundsColor() : getBoundsColor(); } public static Color toAlpha(final Color color, final int alpha) { Color actual = color != null ? color : Color.black; return new Color(actual.getRed(), actual.getGreen(), actual.getBlue(), alpha); } public static void requestFocus(@NotNull final JComponent c) { if (c.isShowing()) { c.requestFocus(); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { c.requestFocus(); } }); } } //todo maybe should do for all kind of listeners via the AWTEventMulticaster class public static void dispose(final Component c) { if (c == null) return; final MouseListener[] mouseListeners = c.getMouseListeners(); for (MouseListener each : mouseListeners) { c.removeMouseListener(each); } final MouseMotionListener[] motionListeners = c.getMouseMotionListeners(); for (MouseMotionListener each : motionListeners) { c.removeMouseMotionListener(each); } final MouseWheelListener[] mouseWheelListeners = c.getMouseWheelListeners(); for (MouseWheelListener each : mouseWheelListeners) { c.removeMouseWheelListener(each); } } public static void disposeProgress(final JProgressBar progress) { if (!isUnderNativeMacLookAndFeel()) return; SwingUtilities.invokeLater(new Runnable() { public void run() { if (isToDispose(progress)) { progress.getUI().uninstallUI(progress); progress.putClientProperty("isDisposed", Boolean.TRUE); } } }); } private static boolean isToDispose(final JProgressBar progress) { final ProgressBarUI ui = progress.getUI(); if (ui == null) return false; if (Boolean.TYPE.equals(progress.getClientProperty("isDisposed"))) return false; try { final Field progressBarField = ReflectionUtil.findField(ui.getClass(), JProgressBar.class, "progressBar"); progressBarField.setAccessible(true); return progressBarField.get(ui) != null; } catch (NoSuchFieldException e) { return true; } catch (IllegalAccessException e) { return true; } } public static @Nullable Component findUltimateParent(Component c) { if (c == null) return null; Component eachParent = c; while (true) { if (eachParent.getParent() == null) return eachParent; eachParent = eachParent.getParent(); } } public static void setToolkitModal(final JDialog dialog) { try { final Class<?> modalityType = dialog.getClass().getClassLoader().loadClass("java.awt.Dialog$ModalityType"); final Field field = modalityType.getField("TOOLKIT_MODAL"); final Object value = field.get(null); final Method method = dialog.getClass().getMethod("setModalityType", modalityType); method.invoke(dialog, value); } catch (Exception e) { // ignore - no JDK 6 } } public static void updateDialogIcon(final JDialog dialog, final List<Image> images) { try { final Method method = dialog.getClass().getMethod("setIconImages", List.class); method.invoke(dialog, images); } catch (Exception e) { // ignore - no JDK 6 } } public static boolean hasJdk6Dialogs() { try { UIUtil.class.getClassLoader().loadClass("java.awt.Dialog$ModalityType"); } catch (Throwable e) { return false; } return true; } public static Color getBorderActiveColor() { return ACTIVE_COLOR; } public static Color getBorderInactiveColor() { return INACTIVE_COLOR; } public static Color getBorderSeparatorColor() { return SEPARATOR_COLOR; } public static void removeScrollBorder(final Component c) { new AwtVisitor(c) { public boolean visit(final Component component) { if (component instanceof JScrollPane) { if (!hasNonPrimitiveParents(c, component)) { ((JScrollPane)component).setBorder(null); } } return false; } }; } public static boolean hasNonPrimitiveParents(Component stopParent, Component c) { Component eachParent = c.getParent(); while (true) { if (eachParent == null || eachParent == stopParent) return false; if (!isPrimitive(eachParent)) return true; eachParent = eachParent.getParent(); } } public static boolean isPrimitive(Component c) { return c instanceof JPanel || c instanceof JLayeredPane; } public static Point getCenterPoint(Dimension container, Dimension child) { return getCenterPoint(new Rectangle(new Point(), container), child); } public static Point getCenterPoint(Rectangle container, Dimension child) { Point result = new Point(); Point containerLocation = container.getLocation(); Dimension containerSize = container.getSize(); result.x = containerLocation.x + (containerSize.width / 2 - child.width / 2); result.y = containerLocation.y + (containerSize.height / 2 - child.height / 2); return result; } public static String toHtml(String html) { return toHtml(html, 0); } public static String toHtml(String html, final int hPadding) { html = CLOSE_TAG_PATTERN.matcher(html).replaceAll("<$1$2></$1>"); Font font = UIManager.getFont("Label.font"); String family = font != null ? font.getFamily() : "Tahoma"; int size = font != null ? font.getSize() : 11; return "<html><style>body { font-family: " + family + "; font-size: " + size + ";} ul li {list-style-type:circle;}</style>" + addPadding(html, hPadding) + "</html>"; } public static String addPadding(final String html, int hPadding) { return "<table border=0 hspace=" + hPadding + "><tr><td>" + html + "</td></tr></table>"; } public static void invokeLaterIfNeeded(@NotNull Runnable runnable) { if (SwingUtilities.isEventDispatchThread()) { runnable.run(); } else { SwingUtilities.invokeLater(runnable); } } }
util/src/com/intellij/util/ui/UIUtil.java
/* * Copyright 2000-2007 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.ui; import com.intellij.openapi.Disposable; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.SystemInfo; import com.intellij.util.ReflectionUtil; import com.intellij.util.ui.treetable.TreeTableCellRenderer; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import javax.swing.border.Border; import javax.swing.plaf.ProgressBarUI; import java.awt.*; import java.awt.event.*; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.regex.Pattern; /** * @author max */ public class UIUtil { private static final Logger LOG = Logger.getInstance("#com.intellij.util.ui.UIUtil"); public static final @NonNls String HTML_MIME = "text/html"; public static final char MNEMONIC = 0x1B; @NonNls public static final String JSLIDER_ISFILLED = "JSlider.isFilled"; @NonNls public static final String ARIAL_FONT_NAME = "Arial"; @NonNls public static final String TABLE_FOCUS_CELL_BACKGROUND_PROPERTY = "Table.focusCellBackground"; private static Color ACTIVE_COLOR = new Color(160, 186, 213); private static Color INACTIVE_COLOR = new Color(128, 128, 128); private static Color SEPARATOR_COLOR = INACTIVE_COLOR.brighter(); public static final Pattern CLOSE_TAG_PATTERN = Pattern.compile("<\\s*([^<>/ ]+)([^<>]*)/\\s*>", Pattern.CASE_INSENSITIVE); private UIUtil() { } public static boolean isReallyTypedEvent(KeyEvent e) { char c = e.getKeyChar(); if (!(c >= 0x20 && c != 0x7F)) return false; int modifiers = e.getModifiers(); if (SystemInfo.isMac) { return !e.isMetaDown() && !e.isControlDown(); } return (modifiers & ActionEvent.ALT_MASK) == (modifiers & ActionEvent.CTRL_MASK); } public static void setEnabled(Component component, boolean enabled, boolean recursively) { component.setEnabled(enabled); if (recursively) { if (component instanceof Container) { final Container container = ((Container)component); final int subComponentCount = container.getComponentCount(); for (int i = 0; i < subComponentCount; i++) { setEnabled(container.getComponent(i), enabled, recursively); } } } } public static void drawLine(Graphics g, int x1, int y1, int x2, int y2) { g.drawLine(x1, y1, x2, y2); } public static void setActionNameAndMnemonic(String text, Action action) { int mnemoPos = text.indexOf("&"); if (mnemoPos >= 0 && mnemoPos < text.length() - 2) { String mnemoChar = text.substring(mnemoPos + 1, mnemoPos + 2).trim(); if (mnemoChar.length() == 1) { action.putValue(Action.MNEMONIC_KEY, Integer.valueOf((int)mnemoChar.charAt(0))); } } text = text.replaceAll("&", ""); action.putValue(Action.NAME, text); } public static Font getLabelFont() { return UIManager.getFont("Label.font"); } public static Color getLabelBackground() { return UIManager.getColor("Label.background"); } public static Color getLabelForeground() { return UIManager.getColor("Label.foreground"); } public static Icon getOptionPanelWarningIcon() { return UIManager.getIcon("OptionPane.warningIcon"); } public static Icon getOptionPanelQuestionIcon() { return UIManager.getIcon("OptionPane.questionIcon"); } public static String replaceMnemonicAmpersand(final String value) { if (value.indexOf('&') >= 0) { boolean useMacMnemonic = value.indexOf("&&") >= 0; StringBuffer realValue = new StringBuffer(); int i = 0; while (i < value.length()) { char c = value.charAt(i); if (c == '\\') { if (i < value.length() - 1 && value.charAt(i + 1) == '&') { realValue.append('&'); i++; } else { realValue.append(c); } } else if (c == '&') { if (i < value.length() - 1 && value.charAt(i + 1) == '&') { if (SystemInfo.isMac) { realValue.append(MNEMONIC); } i++; } else { if (!SystemInfo.isMac || !useMacMnemonic) { realValue.append(MNEMONIC); } } } else { realValue.append(c); } i++; } return realValue.toString(); } return value; } public static Color getTableHeaderBackground() { return UIManager.getColor("TableHeader.background"); } public static Color getTreeTextForeground() { return UIManager.getColor("Tree.textForeground"); } public static Color getTreeSelectonForeground() { return UIManager.getColor("Tree.selectionForeground"); } public static Color getTreeSelectionBackground() { return UIManager.getColor("Tree.selectionBackground"); } public static Color getTreeTextBackground() { return UIManager.getColor("Tree.textBackground"); } public static Color getListSelectionForeground() { final Color color = UIManager.getColor("List.selectionForeground"); if (color == null) { return UIManager.getColor("List[Selected].textForeground"); // Nimbus } return color; } public static Color getFieldForegroundColor() { return UIManager.getColor("field.foreground"); } public static Color getTableSelectionBackground() { return UIManager.getColor("Table.selectionBackground"); } public static Color getActiveTextColor() { return UIManager.getColor("textActiveText"); } public static Color getInactiveTextColor() { return UIManager.getColor("textInactiveText"); } public static Font getTreeFont() { return UIManager.getFont("Tree.font"); } public static Font getListFont() { return UIManager.getFont("List.font"); } public static Color getTreeSelectionForeground() { return UIManager.getColor("Tree.selectionForeground"); } public static Color getTextInactiveTextColor() { return UIManager.getColor("textInactiveText"); } public static void installPopupMenuColorAndFonts(final JComponent contentPane) { LookAndFeel.installColorsAndFont(contentPane, "PopupMenu.background", "PopupMenu.foreground", "PopupMenu.font"); } public static void installPopupMenuBorder(final JComponent contentPane) { LookAndFeel.installBorder(contentPane, "PopupMenu.border"); } public static boolean isMotifLookAndFeel() { return "Motif".equals(UIManager.getLookAndFeel().getID()); } public static Color getTreeSelectionBorderColor() { return UIManager.getColor("Tree.selectionBorderColor"); } public static Object getTreeRightChildIndent() { return UIManager.get("Tree.rightChildIndent"); } public static Object getTreeLeftChildIndent() { return UIManager.get("Tree.leftChildIndent"); } static public Color getToolTipBackground() { return UIManager.getColor("ToolTip.background"); } static public Color getToolTipForeground() { return UIManager.getColor("ToolTip.foreground"); } public static Color getComboBoxDisabledForeground() { return UIManager.getColor("ComboBox.disabledForeground"); } public static Color getComboBoxDisabledBackground() { return UIManager.getColor("ComboBox.disabledBackground"); } public static Color getButtonSelectColor() { return UIManager.getColor("Button.select"); } public static Integer getPropertyMaxGutterIconWidth(final String propertyPrefix) { return (Integer)UIManager.get(propertyPrefix + ".maxGutterIconWidth"); } public static Color getMenuItemDisabledForeground() { return UIManager.getColor("MenuItem.disabledForeground"); } public static Object getMenuItemDisabledForegroundObject() { return UIManager.get("MenuItem.disabledForeground"); } public static Object getTabbedPanePaintContentBorder(final JComponent c) { return c.getClientProperty("TabbedPane.paintContentBorder"); } public static boolean isMenuCrossMenuMnemonics() { return UIManager.getBoolean("Menu.crossMenuMnemonic"); } public static Color getTableBackground() { return UIManager.getColor("Table.background"); } public static Color getTableSelectionForeground() { return UIManager.getColor("Table.selectionForeground"); } public static Color getTableForeground() { return UIManager.getColor("Table.foreground"); } public static Color getListBackground() { return UIManager.getColor("List.background"); } public static Color getListForeground() { return UIManager.getColor("List.foreground"); } public static Color getPanelBackground() { return UIManager.getColor("Panel.background"); } public static Color getTreeForeground() { return UIManager.getColor("Tree.foreground"); } public static Color getTableFocusCellBackground() { return UIManager.getColor("Table.focusCellBackground"); } public static Color getListSelectionBackground() { final Color color = UIManager.getColor("List.selectionBackground"); if (color == null) { return UIManager.getColor("List[Selected].textBackground"); // Nimbus } return color; } public static Color getTextFieldForeground() { return UIManager.getColor("TextField.foreground"); } public static Color getTextFieldBackground() { return UIManager.getColor("TextField.background"); } public static Font getButtonFont() { return UIManager.getFont("Button.font"); } public static Font getToolTipFont() { return UIManager.getFont("ToolTip.font"); } public static Color getTabbedPaneBackground() { return UIManager.getColor("TabbedPane.background"); } public static void setSliderIsFilled(final JSlider slider, final boolean value) { slider.putClientProperty("JSlider.isFilled", Boolean.valueOf(value)); } public static Color getLabelTextForeground() { return UIManager.getColor("Label.textForeground"); } public static Color getControlColor() { return UIManager.getColor("control"); } public static Font getOptionPaneMessageFont() { return UIManager.getFont("OptionPane.messageFont"); } public static Color getSeparatorShadow() { return UIManager.getColor("Separator.shadow"); } public static Font getMenuFont() { return UIManager.getFont("Menu.font"); } public static Color getSeparatorHighlight() { return UIManager.getColor("Separator.highlight"); } public static Border getTableFocusCellHighlightBorder() { return UIManager.getBorder("Table.focusCellHighlightBorder"); } public static void setLineStyleAngled(final TreeTableCellRenderer component) { component.putClientProperty("JTree.lineStyle", "Angled"); } public static void setLineStyleAngled(final JTree component) { component.putClientProperty("JTree.lineStyle", "Angled"); } public static Color getTableFocusCellForeground() { return UIManager.getColor("Table.focusCellForeground"); } public static Color getPanelBackgound() { return UIManager.getColor("Panel.background"); } public static Border getTextFieldBorder() { return UIManager.getBorder("TextField.border"); } public static Border getButtonBorder() { return UIManager.getBorder("Button.border"); } public static Icon getErrorIcon() { return UIManager.getIcon("OptionPane.errorIcon"); } public static Icon getInformationIcon() { return UIManager.getIcon("OptionPane.informationIcon"); } public static Icon getQuestionIcon() { return UIManager.getIcon("OptionPane.questionIcon"); } public static Icon getWarningIcon() { return UIManager.getIcon("OptionPane.warningIcon"); } public static Icon getRadioButtonIcon() { return UIManager.getIcon("RadioButton.icon"); } public static Icon getTreeCollapsedIcon() { return UIManager.getIcon("Tree.collapsedIcon"); } public static Icon getTreeExpandedIcon() { return UIManager.getIcon("Tree.expandedIcon"); } public static Border getTableHeaderCellBorder() { return UIManager.getBorder("TableHeader.cellBorder"); } public static Color getWindowColor() { return UIManager.getColor("window"); } public static Color getTextAreaForeground() { return UIManager.getColor("TextArea.foreground"); } public static Color getOptionPaneBackground() { return UIManager.getColor("OptionPane.background"); } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderQuaquaLookAndFeel() { return UIManager.getLookAndFeel().getName().indexOf("Quaqua") >= 0; } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderNimbusLookAndFeel() { return UIManager.getLookAndFeel().getName().indexOf("Nimbus") >= 0; } @SuppressWarnings({"HardCodedStringLiteral"}) public static boolean isUnderAquaLookAndFeel() { return UIManager.getLookAndFeel().getName().indexOf("Mac OS X") >= 0; } public static boolean isFullRowSelectionLAF() { return isUnderNimbusLookAndFeel() || isUnderQuaquaLookAndFeel(); } public static boolean isUnderNativeMacLookAndFeel() { return isUnderAquaLookAndFeel() || isUnderQuaquaLookAndFeel(); } @SuppressWarnings({"HardCodedStringLiteral"}) public static void removeQuaquaVisualMarginsIn(Component component) { if (component instanceof JComponent) { final JComponent jComponent = (JComponent)component; final Component[] children = jComponent.getComponents(); for (Component child : children) { removeQuaquaVisualMarginsIn(child); } jComponent.putClientProperty("Quaqua.Component.visualMargin", new Insets(0, 0, 0, 0)); } } public static boolean isControlKeyDown(MouseEvent mouseEvent) { return SystemInfo.isMac ? mouseEvent.isMetaDown() : mouseEvent.isControlDown(); } public static String[] getValidFontNames(final boolean familyName) { Set<String> result = new TreeSet<String>(); Font[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); for (Font font : fonts) { // Adds fonts that can display symbols at [A, Z] + [a, z] + [0, 9] try { if (font.canDisplay('a') && font.canDisplay('z') && font.canDisplay('A') && font.canDisplay('Z') && font.canDisplay('0') && font.canDisplay('1')) { result.add(familyName ? font.getFamily() : font.getName()); } } catch (Exception e) { // JRE has problems working with the font. Just skip. } } return result.toArray(new String[result.size()]); } public static String[] getStandardFontSizes() { return new String[]{"8", "9", "10", "11", "12", "14", "16", "18", "20", "22", "24", "26", "28", "36", "48", "72"}; } public static void setupEnclosingDialogBounds(final JComponent component) { component.revalidate(); component.repaint(); final Window window = SwingUtilities.windowForComponent(component); if (window != null && (window.getSize().height < window.getMinimumSize().height || window.getSize().width < window.getMinimumSize().width)) { window.pack(); } } public static String displayPropertiesToCSS(Font font, Color fg) { @NonNls StringBuffer rule = new StringBuffer("body {"); if (font != null) { rule.append(" font-family: "); rule.append(font.getFamily()); rule.append(" ; "); rule.append(" font-size: "); rule.append(font.getSize()); rule.append("pt ;"); if (font.isBold()) { rule.append(" font-weight: 700 ; "); } if (font.isItalic()) { rule.append(" font-style: italic ; "); } } if (fg != null) { rule.append(" color: #"); if (fg.getRed() < 16) { rule.append('0'); } rule.append(Integer.toHexString(fg.getRed())); if (fg.getGreen() < 16) { rule.append('0'); } rule.append(Integer.toHexString(fg.getGreen())); if (fg.getBlue() < 16) { rule.append('0'); } rule.append(Integer.toHexString(fg.getBlue())); rule.append(" ; "); } rule.append(" }"); return rule.toString(); } /** * @param g * @param x top left X coordinate. * @param y top left Y coordinate. * @param x1 right bottom X coordinate. * @param y1 right bottom Y coordinate. */ public static void drawDottedRectangle(Graphics g, int x, int y, int x1, int y1) { int i1; for (i1 = x; i1 <= x1; i1 += 2) { drawLine(g, i1, y, i1, y); } for (i1 = i1 != x1 + 1 ? y + 2 : y + 1; i1 <= y1; i1 += 2) { drawLine(g, x1, i1, x1, i1); } for (i1 = i1 != y1 + 1 ? x1 - 2 : x1 - 1; i1 >= x; i1 -= 2) { drawLine(g, i1, y1, i1, y1); } for (i1 = i1 != x - 1 ? y1 - 2 : y1 - 1; i1 >= y; i1 -= 2) { drawLine(g, x, i1, x, i1); } } public static void applyRenderingHints(final Graphics g) { Toolkit tk = Toolkit.getDefaultToolkit(); //noinspection HardCodedStringLiteral Map map = (Map)(tk.getDesktopProperty("awt.font.desktophints")); if (map != null) { ((Graphics2D)g).addRenderingHints(map); } } @TestOnly public static void dispatchAllInvocationEvents() { assert SwingUtilities.isEventDispatchThread(); final EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue(); while (true) { AWTEvent event = eventQueue.peekEvent(); if (event == null) break; try { AWTEvent event1 = eventQueue.getNextEvent(); if (event1 instanceof InvocationEvent) { ((InvocationEvent)event1).dispatch(); } } catch (Exception e) { LOG.error(e); //? } } } public static void pump() { assert !SwingUtilities.isEventDispatchThread(); final BlockingQueue queue = new LinkedBlockingQueue(); SwingUtilities.invokeLater(new Runnable() { public void run() { queue.offer(queue); } }); try { queue.take(); } catch (InterruptedException e) { LOG.error(e); } } public static void addAwtListener(final AWTEventListener listener, long mask, Disposable parent) { Toolkit.getDefaultToolkit().addAWTEventListener(listener, mask); Disposer.register(parent, new Disposable() { public void dispose() { Toolkit.getDefaultToolkit().removeAWTEventListener(listener); } }); } public static void drawVDottedLine(Graphics2D g, int lineX, int startY, int endY, final Color bgColor, final Color fgColor) { g.setColor(bgColor); drawLine(g, lineX, startY, lineX, endY); g.setColor(fgColor); for (int i = (startY / 2) * 2; i < endY; i += 2) { g.drawRect(lineX, i, 0, 0); } } public static void drawHDottedLine(Graphics2D g, int startX, int endX, int lineY, final Color bgColor, final Color fgColor) { g.setColor(bgColor); drawLine(g, startX, lineY, endX, lineY); g.setColor(fgColor); for (int i = (startX / 2) * 2; i < endX; i += 2) { g.drawRect(i, lineY, 0, 0); } } public static void drawDottedLine(Graphics2D g, int x1, int y1, int x2, int y2, final Color bgColor, final Color fgColor) { if (x1 == x2) { drawVDottedLine(g, x1, y1, y2, bgColor, fgColor); } else if (y1 == y2) { drawHDottedLine(g, x1, x2, y1, bgColor, fgColor); } else { throw new IllegalArgumentException("Only vertical or horizontal lines are supported"); } } public static boolean isFocusAncestor(@NotNull final JComponent component) { final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (owner == null) return false; if (owner == component) return true; return SwingUtilities.isDescendingFrom(owner, component); } public static boolean isCloseClick(MouseEvent e) { if (e.isPopupTrigger() || e.getID() != MouseEvent.MOUSE_PRESSED) return false; return e.getButton() == MouseEvent.BUTTON2 || (e.getButton() == MouseEvent.BUTTON1 && e.isShiftDown()); } public static boolean isActionClick(MouseEvent e) { if (isCloseClick(e)) return false; return e.getButton() == MouseEvent.BUTTON1; } public static @NotNull Color getBgFillColor(@NotNull JComponent c) { final Component parent = findNearestOpaque(c); return parent == null ? c.getBackground() : parent.getBackground(); } public static @Nullable Component findNearestOpaque(JComponent c) { Component eachParent = c; while (eachParent != null) { if (eachParent.isOpaque()) return eachParent; eachParent = eachParent.getParent(); } return eachParent; } @NonNls public static String getCssFontDeclaration(final Font font) { return "<style> body, div, td { font-family: " + font.getFamily() + "; font-size: " + font.getSize() + "; } </style>"; } public static boolean isWinLafOnVista() { return SystemInfo.isWindowsVista && "Windows".equals(UIManager.getLookAndFeel().getName()); } public static boolean isStandardMenuLAF() { return isWinLafOnVista() || "Nimbus".equals(UIManager.getLookAndFeel().getName()); } public static Color getFocusedFillColor() { return toAlpha(UIUtil.getListSelectionBackground(), 100); } public static Color getFocusedBoundsColor() { return getBoundsColor(); } public static Color getBoundsColor() { return new Color(128, 128, 128); } public static Color getBoundsColor(boolean focused) { return focused ? getFocusedBoundsColor() : getBoundsColor(); } public static Color toAlpha(final Color color, final int alpha) { Color actual = color != null ? color : Color.black; return new Color(actual.getRed(), actual.getGreen(), actual.getBlue(), alpha); } public static void requestFocus(@NotNull final JComponent c) { if (c.isShowing()) { c.requestFocus(); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { c.requestFocus(); } }); } } //todo maybe should do for all kind of listeners via the AWTEventMulticaster class public static void dispose(final Component c) { if (c == null) return; final MouseListener[] mouseListeners = c.getMouseListeners(); for (MouseListener each : mouseListeners) { c.removeMouseListener(each); } final MouseMotionListener[] motionListeners = c.getMouseMotionListeners(); for (MouseMotionListener each : motionListeners) { c.removeMouseMotionListener(each); } final MouseWheelListener[] mouseWheelListeners = c.getMouseWheelListeners(); for (MouseWheelListener each : mouseWheelListeners) { c.removeMouseWheelListener(each); } } public static void disposeProgress(final JProgressBar progress) { if (!isUnderNativeMacLookAndFeel()) return; SwingUtilities.invokeLater(new Runnable() { public void run() { if (isToDispose(progress)) { progress.getUI().uninstallUI(progress); progress.putClientProperty("isDisposed", Boolean.TRUE); } } }); } private static boolean isToDispose(final JProgressBar progress) { final ProgressBarUI ui = progress.getUI(); if (ui == null) return false; if (Boolean.TYPE.equals(progress.getClientProperty("isDisposed"))) return false; try { final Field progressBarField = ReflectionUtil.findField(ui.getClass(), JProgressBar.class, "progressBar"); progressBarField.setAccessible(true); return progressBarField.get(ui) != null; } catch (NoSuchFieldException e) { return true; } catch (IllegalAccessException e) { return true; } } public static @Nullable Component findUltimateParent(Component c) { if (c == null) return null; Component eachParent = c; while (true) { if (eachParent.getParent() == null) return eachParent; eachParent = eachParent.getParent(); } } public static void setToolkitModal(final JDialog dialog) { try { final Class<?> modalityType = dialog.getClass().getClassLoader().loadClass("java.awt.Dialog$ModalityType"); final Field field = modalityType.getField("TOOLKIT_MODAL"); final Object value = field.get(null); final Method method = dialog.getClass().getMethod("setModalityType", modalityType); method.invoke(dialog, value); } catch (Exception e) { e.printStackTrace(); } } public static void updateDialogIcon(final JDialog dialog, final List<Image> images) { try { final Method method = dialog.getClass().getMethod("setIconImages", List.class); method.invoke(dialog, images); } catch (Exception e) { // ignore - no JDK 6 } } public static boolean hasJdk6Dialogs() { try { UIUtil.class.getClassLoader().loadClass("java.awt.Dialog$ModalityType"); } catch (Throwable e) { return false; } return true; } public static Color getBorderActiveColor() { return ACTIVE_COLOR; } public static Color getBorderInactiveColor() { return INACTIVE_COLOR; } public static Color getBorderSeparatorColor() { return SEPARATOR_COLOR; } public static void removeScrollBorder(final Component c) { new AwtVisitor(c) { public boolean visit(final Component component) { if (component instanceof JScrollPane) { if (!hasNonPrimitiveParents(c, component)) { ((JScrollPane)component).setBorder(null); } } return false; } }; } public static boolean hasNonPrimitiveParents(Component stopParent, Component c) { Component eachParent = c.getParent(); while (true) { if (eachParent == null || eachParent == stopParent) return false; if (!isPrimitive(eachParent)) return true; eachParent = eachParent.getParent(); } } public static boolean isPrimitive(Component c) { return c instanceof JPanel || c instanceof JLayeredPane; } public static Point getCenterPoint(Dimension container, Dimension child) { return getCenterPoint(new Rectangle(new Point(), container), child); } public static Point getCenterPoint(Rectangle container, Dimension child) { Point result = new Point(); Point containerLocation = container.getLocation(); Dimension containerSize = container.getSize(); result.x = containerLocation.x + (containerSize.width / 2 - child.width / 2); result.y = containerLocation.y + (containerSize.height / 2 - child.height / 2); return result; } public static String toHtml(String html) { return toHtml(html, 0); } public static String toHtml(String html, final int hPadding) { html = CLOSE_TAG_PATTERN.matcher(html).replaceAll("<$1$2></$1>"); Font font = UIManager.getFont("Label.font"); String family = font != null ? font.getFamily() : "Tahoma"; int size = font != null ? font.getSize() : 11; return "<html><style>body { font-family: " + family + "; font-size: " + size + ";} ul li {list-style-type:circle;}</style>" + addPadding(html, hPadding) + "</html>"; } public static String addPadding(final String html, int hPadding) { return "<table border=0 hspace=" + hPadding + "><tr><td>" + html + "</td></tr></table>"; } public static void invokeLaterIfNeeded(@NotNull Runnable runnable) { if (SwingUtilities.isEventDispatchThread()) { runnable.run(); } else { SwingUtilities.invokeLater(runnable); } } }
Don't print exception stacktraces to console
util/src/com/intellij/util/ui/UIUtil.java
Don't print exception stacktraces to console
<ide><path>til/src/com/intellij/util/ui/UIUtil.java <ide> import java.awt.event.*; <ide> import java.lang.reflect.Field; <ide> import java.lang.reflect.Method; <add>import java.util.List; <ide> import java.util.Map; <ide> import java.util.Set; <ide> import java.util.TreeSet; <del>import java.util.List; <ide> import java.util.concurrent.BlockingQueue; <ide> import java.util.concurrent.LinkedBlockingQueue; <ide> import java.util.regex.Pattern; <ide> method.invoke(dialog, value); <ide> } <ide> catch (Exception e) { <del> e.printStackTrace(); <add> // ignore - no JDK 6 <ide> } <ide> } <ide>
Java
apache-2.0
9fff3857c4940e5cb945f9b031f3aa7609533e6a
0
orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb
/* * * * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.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 more information: http://www.orientechnologies.com * */ package com.orientechnologies.orient.graph.handler; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.orient.core.Orient; import com.orientechnologies.orient.core.command.script.OScriptInjection; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.graph.gremlin.OGremlinHelper; import com.orientechnologies.orient.graph.script.OScriptGraphOrientWrapper; import com.orientechnologies.orient.server.OClientConnection; import com.orientechnologies.orient.server.OServer; import com.orientechnologies.orient.server.config.OServerParameterConfiguration; import com.orientechnologies.orient.server.plugin.OServerPluginAbstract; import com.tinkerpop.blueprints.impls.orient.OrientBaseGraph; import javax.script.Bindings; public class OGraphServerHandler extends OServerPluginAbstract implements OScriptInjection { private boolean enabled = true; private int graphPoolMax = OGlobalConfiguration.DB_POOL_MAX.getValueAsInteger(); @Override public void config(OServer oServer, OServerParameterConfiguration[] iParams) { for (OServerParameterConfiguration param : iParams) { if (param.name.equalsIgnoreCase("enabled")) { if (!Boolean.parseBoolean(param.value)) // DISABLE IT return; } else if (param.name.equalsIgnoreCase("graph.pool.max")) graphPoolMax = Integer.parseInt(param.value); } if (OGremlinHelper.isGremlinAvailable()) { enabled = true; OLogManager.instance().info(this, "Installed GREMLIN language v.%s - graph.pool.max=%d", OGremlinHelper.getEngineVersion(), graphPoolMax); Orient.instance().getScriptManager().registerInjection(this); } else enabled = false; } @Override public String getName() { return "graph"; } @Override public void startup() { if (!enabled) return; OGremlinHelper.global().setMaxGraphPool(graphPoolMax).create(); } @Override public void shutdown() { if (!enabled) return; OGremlinHelper.global().destroy(); } @Override public void bind(Bindings binding) { Object scriptGraph = binding.get("orient"); if (scriptGraph == null || !(scriptGraph instanceof OScriptGraphOrientWrapper)) binding.put("orient", new OScriptGraphOrientWrapper()); } @Override public void unbind(Bindings binding) { binding.put("orient", null); } @Override public void onAfterClientRequest(OClientConnection connection, byte requestType) { super.onAfterClientRequest(connection, requestType); OrientBaseGraph.clearInitStack(); } }
graphdb/src/main/java/com/orientechnologies/orient/graph/handler/OGraphServerHandler.java
/* * * * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.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 more information: http://www.orientechnologies.com * */ package com.orientechnologies.orient.graph.handler; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.orient.core.Orient; import com.orientechnologies.orient.core.command.script.OScriptInjection; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.graph.gremlin.OGremlinHelper; import com.orientechnologies.orient.graph.script.OScriptGraphOrientWrapper; import com.orientechnologies.orient.server.OClientConnection; import com.orientechnologies.orient.server.OServer; import com.orientechnologies.orient.server.config.OServerParameterConfiguration; import com.orientechnologies.orient.server.plugin.OServerPluginAbstract; import com.tinkerpop.blueprints.impls.orient.OrientBaseGraph; import javax.script.Bindings; public class OGraphServerHandler extends OServerPluginAbstract implements OScriptInjection { private boolean enabled = true; private int graphPoolMax = OGlobalConfiguration.DB_POOL_MAX.getValueAsInteger(); @Override public void config(OServer oServer, OServerParameterConfiguration[] iParams) { for (OServerParameterConfiguration param : iParams) { if (param.name.equalsIgnoreCase("enabled")) { if (!Boolean.parseBoolean(param.value)) // DISABLE IT return; } else if (param.name.equalsIgnoreCase("graph.pool.max")) graphPoolMax = Integer.parseInt(param.value); } if (OGremlinHelper.isGremlinAvailable()) { enabled = true; OLogManager.instance().info(this, "Installing GREMLIN language v.%s - graph.pool.max=%d", OGremlinHelper.getEngineVersion(), graphPoolMax); Orient.instance().getScriptManager().registerInjection(this); } else enabled = false; } @Override public String getName() { return "graph"; } @Override public void startup() { if (!enabled) return; OGremlinHelper.global().setMaxGraphPool(graphPoolMax).create(); } @Override public void shutdown() { if (!enabled) return; OGremlinHelper.global().destroy(); } @Override public void bind(Bindings binding) { Object scriptGraph = binding.get("orient"); if (scriptGraph == null || !(scriptGraph instanceof OScriptGraphOrientWrapper)) binding.put("orient", new OScriptGraphOrientWrapper()); } @Override public void unbind(Bindings binding) { binding.put("orient", null); } @Override public void onAfterClientRequest(OClientConnection connection, byte requestType) { super.onAfterClientRequest(connection, requestType); OrientBaseGraph.clearInitStack(); } }
Minor: changed log message
graphdb/src/main/java/com/orientechnologies/orient/graph/handler/OGraphServerHandler.java
Minor: changed log message
<ide><path>raphdb/src/main/java/com/orientechnologies/orient/graph/handler/OGraphServerHandler.java <ide> <ide> if (OGremlinHelper.isGremlinAvailable()) { <ide> enabled = true; <del> OLogManager.instance().info(this, "Installing GREMLIN language v.%s - graph.pool.max=%d", OGremlinHelper.getEngineVersion(), <add> OLogManager.instance().info(this, "Installed GREMLIN language v.%s - graph.pool.max=%d", OGremlinHelper.getEngineVersion(), <ide> graphPoolMax); <ide> <ide> Orient.instance().getScriptManager().registerInjection(this);
Java
mit
6c3c97574fda3f6874aff5f227942a18f8848283
0
elixir-no-nels/trackfind,elixir-no-nels/trackfind,elixir-no-nels/trackfind
package no.uio.ifi.trackfind.backend.data.providers.trackhub; import com.google.common.collect.HashMultimap; import lombok.extern.slf4j.Slf4j; import no.uio.ifi.trackfind.backend.data.providers.AbstractDataProvider; import no.uio.ifi.trackfind.backend.pojo.TfHub; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.*; import java.util.stream.Collectors; /** * Draft of Data Provider for TrackHubRegistry. * * @author Dmytro Titov */ @Slf4j @Component @Transactional public class TrackHubRegistryDataProvider extends AbstractDataProvider { private static final String HUBS_URL = "https://www.trackhubregistry.org/api/info/trackhubs"; @Cacheable(value = "thr-hubs", key = "#root.method.name", sync = true) @SuppressWarnings("unchecked") @Override public Collection<TfHub> getAllTrackHubs() { try (InputStream inputStream = new URL(HUBS_URL).openStream(); InputStreamReader reader = new InputStreamReader(inputStream)) { Collection<Map> hubs = gson.fromJson(reader, Collection.class); return hubs.stream().map(h -> new TfHub(getName(), String.valueOf(h.get("name")))) .filter(h -> h.getName().contains("Blueprint")) .collect(Collectors.toSet()); } catch (Exception e) { log.error(e.getMessage(), e); return Collections.emptyList(); } } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override protected void fetchData(String hubName) { Collection<String> fetchURLs = getFetchURLs(hubName); HashMultimap<String, String> mapToSave = HashMultimap.create(); for (String fetchURL : fetchURLs) { try (InputStream inputStream = new URL(fetchURL).openStream(); InputStreamReader reader = new InputStreamReader(inputStream)) { Map<String, Object> hub = (Map<String, Object>) gson.fromJson(reader, Map.class); Map<String, Object> source = (Map<String, Object>) hub.get("_source"); Collection<Map<String, Object>> data = (Collection<Map<String, Object>>) source.get("data"); for (Map<String, Object> entry : data) { mapToSave.put("data", gson.toJson(entry)); } } catch (Exception e) { log.error(e.getMessage(), e); } } save(hubName, mapToSave.asMap()); } @SuppressWarnings("unchecked") private Collection<String> getFetchURLs(String hubName) { Collection<String> fetchURLs = new HashSet<>(); try (InputStream inputStream = new URL(HUBS_URL).openStream(); InputStreamReader reader = new InputStreamReader(inputStream)) { Collection<Map> hubs = gson.fromJson(reader, Collection.class); Optional<Map> hubOptional = hubs.stream().filter(h -> String.valueOf(h.get("name")).equalsIgnoreCase(hubName)).findAny(); if (!hubOptional.isPresent()) { log.warn("No hubs found!"); return Collections.emptyList(); } Map hub = hubOptional.get(); Collection<Map> trackDBs = (Collection<Map>) hub.get("trackdbs"); for (Map trackDB : trackDBs) { fetchURLs.add(String.valueOf(trackDB.get("uri"))); } } catch (Exception e) { log.error(e.getMessage(), e); return Collections.emptyList(); } return fetchURLs; } }
src/main/java/no/uio/ifi/trackfind/backend/data/providers/trackhub/TrackHubRegistryDataProvider.java
package no.uio.ifi.trackfind.backend.data.providers.trackhub; import com.google.common.collect.HashMultimap; import lombok.extern.slf4j.Slf4j; import no.uio.ifi.trackfind.backend.data.providers.AbstractDataProvider; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.Collection; import java.util.Map; /** * Draft of Data Provider for TrackHubRegistry. * * @author Dmytro Titov */ @Slf4j @Component @Transactional public class TrackHubRegistryDataProvider extends AbstractDataProvider { // private static final String HUBS_URL = "https://www.trackhubregistry.org/api/info/trackhubs"; // private static final String FETCH_URL = "https://hyperbrowser.uio.no/hb/static/hyperbrowser/files/trackfind/blueprint_hub.json"; private static final String FETCH_URL = "http://www-test.trackhubregistry.org/api/search/all"; // @SuppressWarnings("unchecked") // @Override // public Collection<TfHub> getAllTrackHubs() { // try (InputStream inputStream = new URL(HUBS_URL).openStream(); // InputStreamReader reader = new InputStreamReader(inputStream)) { // Collection<Map> hubs = gson.fromJson(reader, Collection.class); // return hubs.stream().map(h -> new TfHub(getName(), String.valueOf(h.get("name")))).collect(Collectors.toSet()); // } catch (Exception e) { // log.error(e.getMessage(), e); // return Collections.emptyList(); // } // } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override protected void fetchData(String hubName) { HashMultimap<String, String> mapToSave = HashMultimap.create(); try (InputStream inputStream = new URL(FETCH_URL).openStream(); InputStreamReader reader = new InputStreamReader(inputStream)) { Collection entries = gson.fromJson(reader, Collection.class); for (Object entry : entries) { Map<String, Object> map = (Map<String, Object>) entry; mapToSave.put("TrackHubRegistry_entry", gson.toJson(map.get("_source"))); } } catch (Exception e) { log.error(e.getMessage(), e); } save(hubName, mapToSave.asMap()); } }
Draft implementation of TrackHubRegistryDataProvider
src/main/java/no/uio/ifi/trackfind/backend/data/providers/trackhub/TrackHubRegistryDataProvider.java
Draft implementation of TrackHubRegistryDataProvider
<ide><path>rc/main/java/no/uio/ifi/trackfind/backend/data/providers/trackhub/TrackHubRegistryDataProvider.java <ide> import com.google.common.collect.HashMultimap; <ide> import lombok.extern.slf4j.Slf4j; <ide> import no.uio.ifi.trackfind.backend.data.providers.AbstractDataProvider; <add>import no.uio.ifi.trackfind.backend.pojo.TfHub; <add>import org.springframework.cache.annotation.Cacheable; <ide> import org.springframework.stereotype.Component; <ide> import org.springframework.transaction.annotation.Transactional; <ide> <ide> import java.io.InputStream; <ide> import java.io.InputStreamReader; <ide> import java.net.URL; <del>import java.util.Collection; <del>import java.util.Map; <add>import java.util.*; <add>import java.util.stream.Collectors; <ide> <ide> /** <ide> * Draft of Data Provider for TrackHubRegistry. <ide> @Transactional <ide> public class TrackHubRegistryDataProvider extends AbstractDataProvider { <ide> <del> // private static final String HUBS_URL = "https://www.trackhubregistry.org/api/info/trackhubs"; <del>// private static final String FETCH_URL = "https://hyperbrowser.uio.no/hb/static/hyperbrowser/files/trackfind/blueprint_hub.json"; <del> private static final String FETCH_URL = "http://www-test.trackhubregistry.org/api/search/all"; <add> private static final String HUBS_URL = "https://www.trackhubregistry.org/api/info/trackhubs"; <ide> <del>// @SuppressWarnings("unchecked") <del>// @Override <del>// public Collection<TfHub> getAllTrackHubs() { <del>// try (InputStream inputStream = new URL(HUBS_URL).openStream(); <del>// InputStreamReader reader = new InputStreamReader(inputStream)) { <del>// Collection<Map> hubs = gson.fromJson(reader, Collection.class); <del>// return hubs.stream().map(h -> new TfHub(getName(), String.valueOf(h.get("name")))).collect(Collectors.toSet()); <del>// } catch (Exception e) { <del>// log.error(e.getMessage(), e); <del>// return Collections.emptyList(); <del>// } <del>// } <add> @Cacheable(value = "thr-hubs", key = "#root.method.name", sync = true) <add> @SuppressWarnings("unchecked") <add> @Override <add> public Collection<TfHub> getAllTrackHubs() { <add> try (InputStream inputStream = new URL(HUBS_URL).openStream(); <add> InputStreamReader reader = new InputStreamReader(inputStream)) { <add> Collection<Map> hubs = gson.fromJson(reader, Collection.class); <add> return hubs.stream().map(h -> new TfHub(getName(), String.valueOf(h.get("name")))) <add> .filter(h -> h.getName().contains("Blueprint")) <add> .collect(Collectors.toSet()); <add> } catch (Exception e) { <add> log.error(e.getMessage(), e); <add> return Collections.emptyList(); <add> } <add> } <ide> <ide> /** <ide> * {@inheritDoc} <ide> @SuppressWarnings("unchecked") <ide> @Override <ide> protected void fetchData(String hubName) { <add> Collection<String> fetchURLs = getFetchURLs(hubName); <ide> HashMultimap<String, String> mapToSave = HashMultimap.create(); <del> try (InputStream inputStream = new URL(FETCH_URL).openStream(); <del> InputStreamReader reader = new InputStreamReader(inputStream)) { <del> Collection entries = gson.fromJson(reader, Collection.class); <del> for (Object entry : entries) { <del> Map<String, Object> map = (Map<String, Object>) entry; <del> mapToSave.put("TrackHubRegistry_entry", gson.toJson(map.get("_source"))); <add> for (String fetchURL : fetchURLs) { <add> try (InputStream inputStream = new URL(fetchURL).openStream(); <add> InputStreamReader reader = new InputStreamReader(inputStream)) { <add> Map<String, Object> hub = (Map<String, Object>) gson.fromJson(reader, Map.class); <add> Map<String, Object> source = (Map<String, Object>) hub.get("_source"); <add> Collection<Map<String, Object>> data = (Collection<Map<String, Object>>) source.get("data"); <add> for (Map<String, Object> entry : data) { <add> mapToSave.put("data", gson.toJson(entry)); <add> } <add> } catch (Exception e) { <add> log.error(e.getMessage(), e); <ide> } <del> } catch (Exception e) { <del> log.error(e.getMessage(), e); <ide> } <ide> save(hubName, mapToSave.asMap()); <ide> } <ide> <add> @SuppressWarnings("unchecked") <add> private Collection<String> getFetchURLs(String hubName) { <add> Collection<String> fetchURLs = new HashSet<>(); <add> try (InputStream inputStream = new URL(HUBS_URL).openStream(); <add> InputStreamReader reader = new InputStreamReader(inputStream)) { <add> Collection<Map> hubs = gson.fromJson(reader, Collection.class); <add> Optional<Map> hubOptional = hubs.stream().filter(h -> String.valueOf(h.get("name")).equalsIgnoreCase(hubName)).findAny(); <add> if (!hubOptional.isPresent()) { <add> log.warn("No hubs found!"); <add> return Collections.emptyList(); <add> } <add> Map hub = hubOptional.get(); <add> Collection<Map> trackDBs = (Collection<Map>) hub.get("trackdbs"); <add> for (Map trackDB : trackDBs) { <add> fetchURLs.add(String.valueOf(trackDB.get("uri"))); <add> } <add> } catch (Exception e) { <add> log.error(e.getMessage(), e); <add> return Collections.emptyList(); <add> } <add> return fetchURLs; <add> } <add> <ide> }
Java
apache-2.0
4285730b861866b6b498acc7849b587adb0b8674
0
osglworks/java-tool,greenlaw110/java-tool
package org.osgl.util; import org.osgl.$; import org.osgl.exception.NotAppliedException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; /** * A String value resolver resolves a {@link String string value} into * a certain type of object instance. */ public abstract class StringValueResolver<T> extends $.F1<String, T> { public abstract T resolve(String value); @Override public final T apply(String s) throws NotAppliedException, $.Break { return resolve(s); } public static <T> StringValueResolver<T> wrap(final $.Function<String, T> func) { if (func instanceof StringValueResolver) { return (StringValueResolver) func; } else { return new StringValueResolver<T>() { @Override public T resolve(String value) { return func.apply(value); } }; } } // For primary types private static final StringValueResolver<Boolean> _boolean = new StringValueResolver<Boolean>() { @Override public Boolean resolve(String value) { if (S.empty(value)) { return Boolean.FALSE; } return Boolean.parseBoolean(value); } }; private static final StringValueResolver<Boolean> _Boolean = new StringValueResolver<Boolean>() { @Override public Boolean resolve(String value) { if (S.empty(value)) { return null; } return Boolean.parseBoolean(value); } }; private static final Map<String, Character> PREDEFINED_CHARS = new HashMap<String, Character>(); static { PREDEFINED_CHARS.put("\\b", '\b'); PREDEFINED_CHARS.put("\\f", '\f'); PREDEFINED_CHARS.put("\\n", '\n'); PREDEFINED_CHARS.put("\\r", '\r'); PREDEFINED_CHARS.put("\\t", '\t'); PREDEFINED_CHARS.put("\\", '\"'); PREDEFINED_CHARS.put("\\'", '\''); PREDEFINED_CHARS.put("\\\\", '\\'); } /** * Parsing String into char. The rules are: * * 1. if there value is null or empty length String then return `defval` specified * 2. if the length of the String is `1`, then return that one char in the string * 3. if the value not starts with '\', then throw `IllegalArgumentException` * 4. if the value starts with `\\u` then parse the integer using `16` radix. The check * the range, if it fall into Character range, then return that number, otherwise raise * `IllegalArgumentException` * 5. if the value length is 2 then check if it one of {@link #PREDEFINED_CHARS}, if found * then return * 6. check if it valid OctalEscape defined in the <a href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.6">spec</a> * if pass the check then return that char * 7. all other cases throw `IllegalArgumentException` * * @param value * @param defVal * @return */ private static Character resolveChar(String value, Character defVal) { if (null == value) { return defVal; } switch (value.length()) { case 0: return defVal; case 1: return value.charAt(0); default: if (value.startsWith("\\")) { if (value.length() == 2) { Character c = PREDEFINED_CHARS.get(value); if (null != c) { return c; } } try { String s = value.substring(1); if (s.startsWith("u")) { int i = Integer.parseInt(s.substring(1), 16); if (i > Character.MAX_VALUE || i < Character.MIN_VALUE) { throw new IllegalArgumentException("Invalid character: " + value); } return (char) i; } else if (s.length() > 3) { throw new IllegalArgumentException("Invalid character: " + value); } else { if (s.length() == 3) { int i = Integer.parseInt(s.substring(0, 1)); if (i > 3) { throw new IllegalArgumentException("Invalid character: " + value); } } int i = Integer.parseInt(s, 8); return (char) i; } } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid character: " + value); } } else { throw new IllegalArgumentException("Invalid character: " + value); } } } /** * Returns the char resolver based on {@link #resolveChar(String, Character)} with `\0` as * default value */ private static final StringValueResolver<Character> _char = new StringValueResolver<Character>() { @Override public Character resolve(String value) { return resolveChar(value, '\0'); } }; /** * Returns the char resolver based on {@link #resolveChar(String, Character)} with `null` as * default value */ private static final StringValueResolver<Character> _Char = new StringValueResolver<Character>() { @Override public Character resolve(String value) { return resolveChar(value, null); } }; private static final StringValueResolver<Byte> _byte = new StringValueResolver<Byte>() { @Override public Byte resolve(String value) { if (S.blank(value)) { return (byte) 0; } return Byte.parseByte(value); } }; private static final StringValueResolver<Byte> _Byte = new StringValueResolver<Byte>() { @Override public Byte resolve(String value) { if (S.blank(value)) { return null; } return Byte.parseByte(value); } }; private static final StringValueResolver<Short> _short = new StringValueResolver<Short>() { @Override public Short resolve(String value) { if (S.blank(value)) { return (short) 0; } return Short.valueOf(value); } }; private static final StringValueResolver<Short> _Short = new StringValueResolver<Short>() { @Override public Short resolve(String value) { if (S.blank(value)) { return null; } return Short.valueOf(value); } }; private static int _int(String s) { if (s.contains(".")) { float f = Float.valueOf(s); return Math.round(f); } else { return Integer.valueOf(s); } } private static final StringValueResolver<Integer> _int = new StringValueResolver<Integer>() { @Override public Integer resolve(String value) { if (S.blank(value)) { return 0; } return _int(value); } }; private static final StringValueResolver<Integer> _Integer = new StringValueResolver<Integer>() { @Override public Integer resolve(String value) { if (S.blank(value)) { return null; } return _int(value); } }; private static final StringValueResolver<Long> _long = new StringValueResolver<Long>() { @Override public Long resolve(String value) { if (S.blank(value)) { return 0l; } return Long.valueOf(value); } }; private static final StringValueResolver<Long> _Long = new StringValueResolver<Long>() { @Override public Long resolve(String value) { if (S.blank(value)) { return null; } return Long.valueOf(value); } }; private static final StringValueResolver<Float> _float = new StringValueResolver<Float>() { @Override public Float resolve(String value) { if (S.blank(value)) { return 0f; } return Float.valueOf(value); } }; private static final StringValueResolver<Float> _Float = new StringValueResolver<Float>() { @Override public Float resolve(String value) { if (S.blank(value)) { return null; } return Float.valueOf(value); } }; private static final StringValueResolver<Double> _double = new StringValueResolver<Double>() { @Override public Double resolve(String value) { if (S.blank(value)) { return 0d; } return Double.valueOf(value); } }; private static final StringValueResolver<Double> _Double = new StringValueResolver<Double>() { @Override public Double resolve(String value) { if (S.blank(value)) { return null; } return Double.valueOf(value); } }; private static final StringValueResolver<String> _String = wrap($.F.<String>identity()); private static final StringValueResolver<Str> _Str = new StringValueResolver<Str>() { @Override public Str resolve(String value) { if (null == value) { return null; } return S.str(value); } }; private static final StringValueResolver<FastStr> _FastStr = new StringValueResolver<FastStr>() { @Override public FastStr resolve(String value) { if (null == value) { return null; } return FastStr.of(value); } }; private static Map<Class, StringValueResolver> predefined = C.newMap( boolean.class, _boolean, Boolean.class, _Boolean, char.class, _char, Character.class, _Char, byte.class, _byte, Byte.class, _Byte, short.class, _short, Short.class, _Short, int.class, _int, Integer.class, _Integer, long.class, _long, Long.class, _Long, float.class, _float, Float.class, _Float, double.class, _double, Double.class, _Double, String.class, _String, Str.class, _Str, FastStr.class, _FastStr, BigInteger.class, new BigIntegerValueObjectCodec(), BigDecimal.class, new BigDecimalValueObjectCodec(), Keyword.class, new KeywordValueObjectCodec() ); public static <T> void addPredefinedResolver(Class<T> type, StringValueResolver<T> resolver) { predefined.put(type, resolver); } public static Map<Class, StringValueResolver> predefined() { return C.map(predefined); } @SuppressWarnings("unchecked") public static <T> StringValueResolver<T> predefined(Class<T> type) { return predefined.get(type); } }
src/main/java/org/osgl/util/StringValueResolver.java
package org.osgl.util; import org.osgl.$; import org.osgl.exception.NotAppliedException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; /** * A String value resolver resolves a {@link String string value} into * a certain type of object instance. */ public abstract class StringValueResolver<T> extends $.F1<String, T> { public abstract T resolve(String value); @Override public final T apply(String s) throws NotAppliedException, $.Break { return resolve(s); } public static <T> StringValueResolver<T> wrap(final $.Function<String, T> func) { if (func instanceof StringValueResolver) { return (StringValueResolver) func; } else { return new StringValueResolver<T>() { @Override public T resolve(String value) { return func.apply(value); } }; } } // For primary types private static final StringValueResolver<Boolean> _boolean = new StringValueResolver<Boolean>() { @Override public Boolean resolve(String value) { if (S.empty(value)) { return Boolean.FALSE; } return Boolean.parseBoolean(value); } }; private static final StringValueResolver<Boolean> _Boolean = new StringValueResolver<Boolean>() { @Override public Boolean resolve(String value) { if (S.empty(value)) { return null; } return Boolean.parseBoolean(value); } }; private static final Map<String, Character> PREDEFINED_CHARS = new HashMap<String, Character>(); static { PREDEFINED_CHARS.put("\\b", '\b'); PREDEFINED_CHARS.put("\\f", '\f'); PREDEFINED_CHARS.put("\\n", '\n'); PREDEFINED_CHARS.put("\\r", '\r'); PREDEFINED_CHARS.put("\\t", '\t'); PREDEFINED_CHARS.put("\\", '\"'); PREDEFINED_CHARS.put("\\'", '\''); PREDEFINED_CHARS.put("\\\\", '\\'); } /** * Parsing String into char. The rules are: * * 1. if there value is null or empty length String then return `defval` specified * 2. if the length of the String is `1`, then return that one char in the string * 3. if the value not starts with '\', then throw `IllegalArgumentException` * 4. if the value starts with `\u` then parse the integer using `16` radix. The check * the range, if it fall into Character range, then return that number, otherwise raise * `IllegalArgumentException` * 5. if the value length is 2 then check if it one of {@link #PREDEFINED_CHARS}, if found * then return * 6. check if it valid OctalEscape defined in the <a href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.6">spec</a> * if pass the check then return that char * 7. all other cases throw `IllegalArgumentException` * * @param value * @param defVal * @return */ private static Character resolveChar(String value, Character defVal) { if (null == value) { return defVal; } switch (value.length()) { case 0: return defVal; case 1: return value.charAt(0); default: if (value.startsWith("\\")) { if (value.length() == 2) { Character c = PREDEFINED_CHARS.get(value); if (null != c) { return c; } } try { String s = value.substring(1); if (s.startsWith("u")) { int i = Integer.parseInt(s.substring(1), 16); if (i > Character.MAX_VALUE || i < Character.MIN_VALUE) { throw new IllegalArgumentException("Invalid character: " + value); } return (char) i; } else if (s.length() > 3) { throw new IllegalArgumentException("Invalid character: " + value); } else { if (s.length() == 3) { int i = Integer.parseInt(s.substring(0, 1)); if (i > 3) { throw new IllegalArgumentException("Invalid character: " + value); } } int i = Integer.parseInt(s, 8); return (char) i; } } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid character: " + value); } } else { throw new IllegalArgumentException("Invalid character: " + value); } } } /** * Returns the char resolver based on {@link #resolveChar(String, Character)} with `\0` as * default value */ private static final StringValueResolver<Character> _char = new StringValueResolver<Character>() { @Override public Character resolve(String value) { return resolveChar(value, '\0'); } }; /** * Returns the char resolver based on {@link #resolveChar(String, Character)} with `null` as * default value */ private static final StringValueResolver<Character> _Char = new StringValueResolver<Character>() { @Override public Character resolve(String value) { return resolveChar(value, null); } }; private static final StringValueResolver<Byte> _byte = new StringValueResolver<Byte>() { @Override public Byte resolve(String value) { if (S.blank(value)) { return (byte) 0; } return Byte.parseByte(value); } }; private static final StringValueResolver<Byte> _Byte = new StringValueResolver<Byte>() { @Override public Byte resolve(String value) { if (S.blank(value)) { return null; } return Byte.parseByte(value); } }; private static final StringValueResolver<Short> _short = new StringValueResolver<Short>() { @Override public Short resolve(String value) { if (S.blank(value)) { return (short) 0; } return Short.valueOf(value); } }; private static final StringValueResolver<Short> _Short = new StringValueResolver<Short>() { @Override public Short resolve(String value) { if (S.blank(value)) { return null; } return Short.valueOf(value); } }; private static int _int(String s) { if (s.contains(".")) { float f = Float.valueOf(s); return Math.round(f); } else { return Integer.valueOf(s); } } private static final StringValueResolver<Integer> _int = new StringValueResolver<Integer>() { @Override public Integer resolve(String value) { if (S.blank(value)) { return 0; } return _int(value); } }; private static final StringValueResolver<Integer> _Integer = new StringValueResolver<Integer>() { @Override public Integer resolve(String value) { if (S.blank(value)) { return null; } return _int(value); } }; private static final StringValueResolver<Long> _long = new StringValueResolver<Long>() { @Override public Long resolve(String value) { if (S.blank(value)) { return 0l; } return Long.valueOf(value); } }; private static final StringValueResolver<Long> _Long = new StringValueResolver<Long>() { @Override public Long resolve(String value) { if (S.blank(value)) { return null; } return Long.valueOf(value); } }; private static final StringValueResolver<Float> _float = new StringValueResolver<Float>() { @Override public Float resolve(String value) { if (S.blank(value)) { return 0f; } return Float.valueOf(value); } }; private static final StringValueResolver<Float> _Float = new StringValueResolver<Float>() { @Override public Float resolve(String value) { if (S.blank(value)) { return null; } return Float.valueOf(value); } }; private static final StringValueResolver<Double> _double = new StringValueResolver<Double>() { @Override public Double resolve(String value) { if (S.blank(value)) { return 0d; } return Double.valueOf(value); } }; private static final StringValueResolver<Double> _Double = new StringValueResolver<Double>() { @Override public Double resolve(String value) { if (S.blank(value)) { return null; } return Double.valueOf(value); } }; private static final StringValueResolver<String> _String = wrap($.F.<String>identity()); private static final StringValueResolver<Str> _Str = new StringValueResolver<Str>() { @Override public Str resolve(String value) { if (null == value) { return null; } return S.str(value); } }; private static final StringValueResolver<FastStr> _FastStr = new StringValueResolver<FastStr>() { @Override public FastStr resolve(String value) { if (null == value) { return null; } return FastStr.of(value); } }; private static Map<Class, StringValueResolver> predefined = C.newMap( boolean.class, _boolean, Boolean.class, _Boolean, char.class, _char, Character.class, _Char, byte.class, _byte, Byte.class, _Byte, short.class, _short, Short.class, _Short, int.class, _int, Integer.class, _Integer, long.class, _long, Long.class, _Long, float.class, _float, Float.class, _Float, double.class, _double, Double.class, _Double, String.class, _String, Str.class, _Str, FastStr.class, _FastStr, BigInteger.class, new BigIntegerValueObjectCodec(), BigDecimal.class, new BigDecimalValueObjectCodec(), Keyword.class, new KeywordValueObjectCodec() ); public static <T> void addPredefinedResolver(Class<T> type, StringValueResolver<T> resolver) { predefined.put(type, resolver); } public static Map<Class, StringValueResolver> predefined() { return C.map(predefined); } @SuppressWarnings("unchecked") public static <T> StringValueResolver<T> predefined(Class<T> type) { return predefined.get(type); } }
fix javadoc issue
src/main/java/org/osgl/util/StringValueResolver.java
fix javadoc issue
<ide><path>rc/main/java/org/osgl/util/StringValueResolver.java <ide> * 1. if there value is null or empty length String then return `defval` specified <ide> * 2. if the length of the String is `1`, then return that one char in the string <ide> * 3. if the value not starts with '\', then throw `IllegalArgumentException` <del> * 4. if the value starts with `\u` then parse the integer using `16` radix. The check <add> * 4. if the value starts with `\\u` then parse the integer using `16` radix. The check <ide> * the range, if it fall into Character range, then return that number, otherwise raise <ide> * `IllegalArgumentException` <ide> * 5. if the value length is 2 then check if it one of {@link #PREDEFINED_CHARS}, if found
Java
mit
67a77aa6e91fd7936a0db07709ed047b03c39ddd
0
PLOS/wombat,PLOS/wombat,PLOS/wombat,PLOS/wombat
package org.ambraproject.wombat.controller; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import org.ambraproject.wombat.config.site.RequestMappingContextDictionary; import org.ambraproject.wombat.config.site.Site; import org.ambraproject.wombat.config.site.SiteParam; import org.ambraproject.wombat.config.site.url.Link; import org.ambraproject.wombat.identity.RequestedDoiVersion; import org.ambraproject.wombat.service.ApiAddress; import org.ambraproject.wombat.service.remote.ArticleApi; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.Comparator; import java.util.EnumSet; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @Controller public class FigureImageController extends WombatController { private static final Logger log = LoggerFactory.getLogger(FigureImageController.class); @Autowired private RequestMappingContextDictionary requestMappingContextDictionary; @Autowired private GeneralDoiController generalDoiController; @Autowired private ArticleApi articleApi; private static enum LegacyFileExtensionRedirectStrategy { ARTICLE("article") { private final ImmutableSortedMap<String, String> extensions = ImmutableSortedMap .<String, String>orderedBy(String.CASE_INSENSITIVE_ORDER) .put("XML", "manuscript") .put("PDF", "printable") .build(); @Override protected String resolveToFileType(String fileExtension) { return resolveFromMap(extensions, fileExtension); } }, FIGURE("figure", "table", "standaloneStrikingImage") { private final ImmutableSortedMap<String, String> extensions = ImmutableSortedMap .<String, String>orderedBy(String.CASE_INSENSITIVE_ORDER) .put("TIF", "original").put("TIFF", "original").put("GIF", "original") .put("PNG_S", "small") .put("PNG_I", "inline") .put("PNG_M", "medium") .put("PNG_L", "large") .build(); @Override protected String resolveToFileType(String fileExtension) { return resolveFromMap(extensions, fileExtension); } }, GRAPHIC("graphic") { private final ImmutableSortedMap<String, String> extensions = ImmutableSortedMap .<String, String>orderedBy(String.CASE_INSENSITIVE_ORDER) .put("TIF", "original").put("TIFF", "original").put("GIF", "original") .put("PNG", "thumbnail") .build(); @Override protected String resolveToFileType(String fileExtension) { return resolveFromMap(extensions, fileExtension); } }, SUPPLEMENTARY_MATERIAL("supplementaryMaterial") { @Override protected String resolveToFileType(String fileExtension) { return "supplementary"; } }; private static String resolveFromMap(Map<String, String> map, String fileExtension) { String fileType = map.get(fileExtension); if (fileType == null) throw new NotFoundException("Unrecognized file extension: " + fileExtension); return fileType; } private final ImmutableSet<String> associatedTypes; private LegacyFileExtensionRedirectStrategy(String... associatedTypes) { this.associatedTypes = ImmutableSet.copyOf(associatedTypes); } /** * @param fileExtension a legacy file extension * @return the equivalent file type */ protected abstract String resolveToFileType(String fileExtension); private static final ImmutableMap<String, LegacyFileExtensionRedirectStrategy> STRATEGIES = ImmutableMap.copyOf( // Map each LegacyFileExtensionRedirectStrategy by its associated types. // A strategy with more than one type goes under more than one map key. EnumSet.allOf(LegacyFileExtensionRedirectStrategy.class).stream() .flatMap((LegacyFileExtensionRedirectStrategy strategy) -> strategy.associatedTypes.stream() .map((String associatedType) -> Maps.immutableEntry(associatedType, strategy))) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); public static String resolveToFileType(String itemType, String fileExtension) { LegacyFileExtensionRedirectStrategy strategy = STRATEGIES.get(Objects.requireNonNull(itemType)); if (strategy == null) { // Not NotFoundException; we expect to recognize any work type that the service returns. throw new RuntimeException("Unrecognized item type: " + itemType); } return strategy.resolveToFileType(Objects.requireNonNull(fileExtension)); } } /** * Serve the identified asset file. * * @param rawId an ID for an asset (if {@code unique} is present) or an asset file (if {@code unique} is absent) * @param unique if present, assume the asset has a single file and serve that file; else, serve an identified file * @param download forward Content-Disposition headers with "attachment" value only if {@code true} */ @RequestMapping(name = "asset", value = "/article/asset") public String serveAsset(HttpServletRequest request, @SiteParam Site site, @RequestParam(value = "id", required = true) String rawId, @RequestParam(value = "unique", required = false) String unique, @RequestParam(value = "download", required = false) String download) throws IOException { requireNonemptyParameter(rawId); final String assetDoi; final Optional<String> fileExtension; if (booleanParameter(unique)) { assetDoi = rawId; fileExtension = Optional.empty(); } else { int extensionIndex = rawId.lastIndexOf("."); fileExtension = (extensionIndex < 0) ? Optional.empty() : Optional.of(rawId.substring(extensionIndex + 1)); assetDoi = (extensionIndex < 0) ? rawId : rawId.substring(0, extensionIndex); } Map<String, Object> workMetadata = generalDoiController.getWorkMetadata(RequestedDoiVersion.of(assetDoi)); Map<String, ?> itemMetadata = getItemMetadata(workMetadata); final String fileType; if (fileExtension.isPresent()) { String itemType = (String) itemMetadata.get("itemType"); fileType = LegacyFileExtensionRedirectStrategy.resolveToFileType(itemType, fileExtension.get()); } else { Map<String, ?> itemFiles = (Map<String, ?>) itemMetadata.get("files"); Set<String> fileTypes = itemFiles.keySet(); if (fileTypes.size() == 1) { fileType = Iterables.getOnlyElement(fileTypes); } else { /* * The user queried for the unique file of a non-unique asset. Because they might have manually punched in an * invalid URL, show a 404 page. Also log a warning in case it was caused by a buggy link. */ log.warn("Received request for unique asset file with ID=\"{}\". More than one associated file type: {}", assetDoi, fileTypes); throw new NotFoundException(); } } return redirectToAssetFile(request, site, assetDoi, fileType, booleanParameter(download)); } private Map<String, ?> getItemMetadata(Map<String, Object> assetMetadata) throws IOException { Map<String, ?> article = (Map<String, ?>) assetMetadata.get("article"); String articleDoi = (String) article.get("doi"); Map<String, ?> revisions = (Map<String, ?>) article.get("revisions"); Map.Entry<String, ?> latestRevisionEntry = revisions.entrySet().stream() .max(Comparator.comparing(entry -> Integer.valueOf(entry.getKey()))) .orElseThrow(() -> new NotFoundException("Article is not published: " + articleDoi)); int ingestionNumber = ((Number) latestRevisionEntry.getValue()).intValue(); Map<String, ?> itemResponse = articleApi.requestObject( ApiAddress.builder("articles").embedDoi(articleDoi) .addToken("ingestions").addToken(Integer.toString(ingestionNumber)) .addToken("items").build(), Map.class); Map<String, ?> itemTable = (Map<String, ?>) itemResponse.get("items"); String assetDoi = (String) assetMetadata.get("doi"); return (Map<String, ?>) Objects.requireNonNull(itemTable.get(assetDoi)); } /** * Serve the asset file for an identified figure thumbnail. */ @RequestMapping(name = "figureImage", value = "/article/figure/image") public String serveFigureImage(HttpServletRequest request, @SiteParam Site site, @RequestParam("id") String figureId, @RequestParam("size") String figureSize, @RequestParam(value = "download", required = false) String download) throws IOException { requireNonemptyParameter(figureId); Map<String, Object> workMetadata = generalDoiController.getWorkMetadata(RequestedDoiVersion.of(figureId)); Set<String> fileTypes = ((Map<String, ?>) workMetadata.get("files")).keySet(); if (fileTypes.contains(figureSize)) { return redirectToAssetFile(request, site, figureId, figureSize, booleanParameter(download)); } else { throw new NotFoundException("Not a valid size: " + figureSize); } } private String redirectToAssetFile(HttpServletRequest request, Site site, String id, String fileType, boolean isDownload) { Link.Factory.PatternBuilder link = Link.toLocalSite(site) .toPattern(requestMappingContextDictionary, "assetFile") .addQueryParameter("id", id) .addQueryParameter("type", fileType); if (isDownload) { link = link.addQueryParameter("download", ""); } return link.build().getRedirect(request); } }
src/main/java/org/ambraproject/wombat/controller/FigureImageController.java
package org.ambraproject.wombat.controller; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import org.ambraproject.wombat.config.site.RequestMappingContextDictionary; import org.ambraproject.wombat.config.site.Site; import org.ambraproject.wombat.config.site.SiteParam; import org.ambraproject.wombat.config.site.url.Link; import org.ambraproject.wombat.identity.RequestedDoiVersion; import org.ambraproject.wombat.service.ApiAddress; import org.ambraproject.wombat.service.remote.ArticleApi; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.Comparator; import java.util.EnumSet; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @Controller public class FigureImageController extends WombatController { private static final Logger log = LoggerFactory.getLogger(FigureImageController.class); @Autowired private RequestMappingContextDictionary requestMappingContextDictionary; @Autowired private GeneralDoiController generalDoiController; @Autowired private ArticleApi articleApi; private static enum LegacyFileExtensionRedirectStrategy { ARTICLE("article") { private final ImmutableSortedMap<String, String> extensions = ImmutableSortedMap .<String, String>orderedBy(String.CASE_INSENSITIVE_ORDER) .put("XML", "manuscript") .put("PDF", "printable") .build(); @Override protected String resolveToFileType(String fileExtension) { return resolveFromMap(extensions, fileExtension); } }, FIGURE("figure", "table") { private final ImmutableSortedMap<String, String> extensions = ImmutableSortedMap .<String, String>orderedBy(String.CASE_INSENSITIVE_ORDER) .put("TIF", "original").put("TIFF", "original").put("GIF", "original") .put("PNG_S", "small") .put("PNG_I", "inline") .put("PNG_M", "medium") .put("PNG_L", "large") .build(); @Override protected String resolveToFileType(String fileExtension) { return resolveFromMap(extensions, fileExtension); } }, GRAPHIC("graphic") { private final ImmutableSortedMap<String, String> extensions = ImmutableSortedMap .<String, String>orderedBy(String.CASE_INSENSITIVE_ORDER) .put("TIF", "original").put("TIFF", "original").put("GIF", "original") .put("PNG", "thumbnail") .build(); @Override protected String resolveToFileType(String fileExtension) { return resolveFromMap(extensions, fileExtension); } }, SUPPLEMENTARY_MATERIAL("supplementaryMaterial") { @Override protected String resolveToFileType(String fileExtension) { return "supplementary"; } }, STANDALONE_STRIKING_IMAGE("standaloneStrikingImage") { @Override protected String resolveToFileType(String fileExtension) { return "strikingImage"; } }; private static String resolveFromMap(Map<String, String> map, String fileExtension) { String fileType = map.get(fileExtension); if (fileType == null) throw new NotFoundException("Unrecognized file extension: " + fileExtension); return fileType; } private final ImmutableSet<String> associatedTypes; private LegacyFileExtensionRedirectStrategy(String... associatedTypes) { this.associatedTypes = ImmutableSet.copyOf(associatedTypes); } /** * @param fileExtension a legacy file extension * @return the equivalent file type */ protected abstract String resolveToFileType(String fileExtension); private static final ImmutableMap<String, LegacyFileExtensionRedirectStrategy> STRATEGIES = ImmutableMap.copyOf( // Map each LegacyFileExtensionRedirectStrategy by its associated types. // A strategy with more than one type goes under more than one map key. EnumSet.allOf(LegacyFileExtensionRedirectStrategy.class).stream() .flatMap((LegacyFileExtensionRedirectStrategy strategy) -> strategy.associatedTypes.stream() .map((String associatedType) -> Maps.immutableEntry(associatedType, strategy))) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); public static String resolveToFileType(String itemType, String fileExtension) { LegacyFileExtensionRedirectStrategy strategy = STRATEGIES.get(Objects.requireNonNull(itemType)); if (strategy == null) { // Not NotFoundException; we expect to recognize any work type that the service returns. throw new RuntimeException("Unrecognized item type: " + itemType); } return strategy.resolveToFileType(Objects.requireNonNull(fileExtension)); } } /** * Serve the identified asset file. * * @param rawId an ID for an asset (if {@code unique} is present) or an asset file (if {@code unique} is absent) * @param unique if present, assume the asset has a single file and serve that file; else, serve an identified file * @param download forward Content-Disposition headers with "attachment" value only if {@code true} */ @RequestMapping(name = "asset", value = "/article/asset") public String serveAsset(HttpServletRequest request, @SiteParam Site site, @RequestParam(value = "id", required = true) String rawId, @RequestParam(value = "unique", required = false) String unique, @RequestParam(value = "download", required = false) String download) throws IOException { requireNonemptyParameter(rawId); final String assetDoi; final Optional<String> fileExtension; if (booleanParameter(unique)) { assetDoi = rawId; fileExtension = Optional.empty(); } else { int extensionIndex = rawId.lastIndexOf("."); fileExtension = (extensionIndex < 0) ? Optional.empty() : Optional.of(rawId.substring(extensionIndex + 1)); assetDoi = (extensionIndex < 0) ? rawId : rawId.substring(0, extensionIndex); } Map<String, Object> workMetadata = generalDoiController.getWorkMetadata(RequestedDoiVersion.of(assetDoi)); Map<String, ?> itemMetadata = getItemMetadata(workMetadata); final String fileType; if (fileExtension.isPresent()) { String itemType = (String) itemMetadata.get("itemType"); fileType = LegacyFileExtensionRedirectStrategy.resolveToFileType(itemType, fileExtension.get()); } else { Map<String, ?> itemFiles = (Map<String, ?>) itemMetadata.get("files"); Set<String> fileTypes = itemFiles.keySet(); if (fileTypes.size() == 1) { fileType = Iterables.getOnlyElement(fileTypes); } else { /* * The user queried for the unique file of a non-unique asset. Because they might have manually punched in an * invalid URL, show a 404 page. Also log a warning in case it was caused by a buggy link. */ log.warn("Received request for unique asset file with ID=\"{}\". More than one associated file type: {}", assetDoi, fileTypes); throw new NotFoundException(); } } return redirectToAssetFile(request, site, assetDoi, fileType, booleanParameter(download)); } private Map<String, ?> getItemMetadata(Map<String, Object> assetMetadata) throws IOException { Map<String, ?> article = (Map<String, ?>) assetMetadata.get("article"); String articleDoi = (String) article.get("doi"); Map<String, ?> revisions = (Map<String, ?>) article.get("revisions"); Map.Entry<String, ?> latestRevisionEntry = revisions.entrySet().stream() .max(Comparator.comparing(entry -> Integer.valueOf(entry.getKey()))) .orElseThrow(() -> new NotFoundException("Article is not published: " + articleDoi)); int ingestionNumber = ((Number) latestRevisionEntry.getValue()).intValue(); Map<String, ?> itemResponse = articleApi.requestObject( ApiAddress.builder("articles").embedDoi(articleDoi) .addToken("ingestions").addToken(Integer.toString(ingestionNumber)) .addToken("items").build(), Map.class); Map<String, ?> itemTable = (Map<String, ?>) itemResponse.get("items"); String assetDoi = (String) assetMetadata.get("doi"); return (Map<String, ?>) Objects.requireNonNull(itemTable.get(assetDoi)); } /** * Serve the asset file for an identified figure thumbnail. */ @RequestMapping(name = "figureImage", value = "/article/figure/image") public String serveFigureImage(HttpServletRequest request, @SiteParam Site site, @RequestParam("id") String figureId, @RequestParam("size") String figureSize, @RequestParam(value = "download", required = false) String download) throws IOException { requireNonemptyParameter(figureId); Map<String, Object> workMetadata = generalDoiController.getWorkMetadata(RequestedDoiVersion.of(figureId)); Set<String> fileTypes = ((Map<String, ?>) workMetadata.get("files")).keySet(); if (fileTypes.contains(figureSize)) { return redirectToAssetFile(request, site, figureId, figureSize, booleanParameter(download)); } else { throw new NotFoundException("Not a valid size: " + figureSize); } } private String redirectToAssetFile(HttpServletRequest request, Site site, String id, String fileType, boolean isDownload) { Link.Factory.PatternBuilder link = Link.toLocalSite(site) .toPattern(requestMappingContextDictionary, "assetFile") .addQueryParameter("id", id) .addQueryParameter("type", fileType); if (isDownload) { link = link.addQueryParameter("download", ""); } return link.build().getRedirect(request); } }
DPRO-2952: Make standaloneStrikingImage redirect strategy like figures The system should have been using the same set of thumbnail extensions for stand-alone striking images all along.
src/main/java/org/ambraproject/wombat/controller/FigureImageController.java
DPRO-2952: Make standaloneStrikingImage redirect strategy like figures
<ide><path>rc/main/java/org/ambraproject/wombat/controller/FigureImageController.java <ide> } <ide> }, <ide> <del> FIGURE("figure", "table") { <add> FIGURE("figure", "table", "standaloneStrikingImage") { <ide> private final ImmutableSortedMap<String, String> extensions = ImmutableSortedMap <ide> .<String, String>orderedBy(String.CASE_INSENSITIVE_ORDER) <ide> .put("TIF", "original").put("TIFF", "original").put("GIF", "original") <ide> @Override <ide> protected String resolveToFileType(String fileExtension) { <ide> return "supplementary"; <del> } <del> }, <del> <del> STANDALONE_STRIKING_IMAGE("standaloneStrikingImage") { <del> @Override <del> protected String resolveToFileType(String fileExtension) { <del> return "strikingImage"; <ide> } <ide> }; <ide>
Java
mit
584050a64578c3b15323bcc38b887c79acf811d0
0
matthieu-vergne/jMetal
// R2.java // // Author: // Juan J. Durillo <[email protected]> // // Copyright (c) 2013 Juan J. Durillo // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // 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 Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.uma.jmetal.qualityindicator.impl; import org.uma.jmetal.qualityindicator.QualityIndicator; import org.uma.jmetal.solution.Solution; import org.uma.jmetal.util.front.Front; import org.uma.jmetal.util.front.imp.ArrayFront; import org.uma.jmetal.util.front.util.FrontNormalizer; import org.uma.jmetal.util.front.util.FrontUtils; import org.uma.jmetal.util.naming.impl.SimpleDescribedEntity; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * TODO: Add comments here */ @SuppressWarnings("serial") public class R2<Evaluate extends List<? extends Solution<?>>> extends SimpleDescribedEntity implements QualityIndicator<Evaluate,Double> { private final double[][] lambda; private final Front referenceParetoFront; /** * Creates a new instance of the R2 indicator for a problem with * two objectives and 100 lambda vectors */ public R2(Front referenceParetoFront) { // by default it creates an R2 indicator for a two dimensions problem and // uses only 100 weight vectors for the R2 computation this(100, referenceParetoFront); } /** * Creates a new instance of the R2 indicator for a problem with * two objectives and 100 lambda vectors */ public R2() { // by default it creates an R2 indicator for a two dimensions problem and // uses only 100 weight vectors for the R2 computation this(100); } /** * Creates a new instance of the R2 indicator for a problem with * two objectives and N lambda vectors */ public R2(int nVectors, Front referenceParetoFront) { // by default it creates an R2 indicator for a two dimensions problem and // uses only <code>nVectors</code> weight vectors for the R2 computation super("R2", "R2 quality indicator") ; this.lambda = generateWeights(nVectors); this.referenceParetoFront = referenceParetoFront; } private static double[][] generateWeights(int nVectors) { double[][] lambda = new double[nVectors][2]; for (int n = 0; n < nVectors; n++) { double a = 1.0 * n / (nVectors - 1); lambda[n][0] = a; lambda[n][1] = 1 - a; } return lambda; } /** * Creates a new instance of the R2 indicator for a problem with * two objectives and N lambda vectors */ public R2(int nVectors) { this(nVectors, null); } /** * Constructor * Creates a new instance of the R2 indicator for nDimensiosn * It loads the weight vectors from the file fileName */ public R2(String file, Front referenceParetoFront) throws java.io.IOException { this.lambda = readWeightsFrom(file); this.referenceParetoFront = referenceParetoFront; } private static double[][] readWeightsFrom(String file) throws java.io.IOException { FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); String line = br.readLine(); double[][] lambda; if (line==null) { lambda = null; } else { int numberOfObjectives = (new StringTokenizer(line)).countTokens(); int numberOfVectors = (int) br.lines().count(); lambda = new double[numberOfVectors][numberOfObjectives]; int index = 0; while (line!=null) { StringTokenizer st = new StringTokenizer(line); for (int i = 0; i < numberOfObjectives; i++) lambda[index][i] = new Double(st.nextToken()); index++; line = br.readLine(); } br.close(); } return lambda; } /** * Constructor * Creates a new instance of the R2 indicator for nDimensiosn * It loads the weight vectors from the file fileName */ public R2(String file) throws java.io.IOException { this(file, null); } // R2 @Override public Double evaluate(Evaluate solutionList) { return r2(new ArrayFront(solutionList)); } @Override public String getName() { return super.getName(); } public double r2(Front front) { if (this.referenceParetoFront != null) { // STEP 1. Obtain the maximum and minimum values of the Pareto front double[] maximumValues = FrontUtils.getMaximumValues(this.referenceParetoFront); double[] minimumValues = FrontUtils.getMinimumValues(this.referenceParetoFront); // STEP 2. Get the normalized front FrontNormalizer frontNormalizer = new FrontNormalizer(minimumValues, maximumValues); front = frontNormalizer.normalize(front); } int numberOfObjectives = front.getPoint(0).getNumberOfDimensions(); // STEP 3. compute all the matrix of Tschebyscheff values if it is null double[][] matrix = new double[front.getNumberOfPoints()][lambda.length]; for (int i = 0; i < front.getNumberOfPoints(); i++) { for (int j = 0; j < lambda.length; j++) { matrix[i][j] = lambda[j][0] * Math.abs(front.getPoint(i).getDimensionValue(0)); for (int n = 1; n < numberOfObjectives; n++) { matrix[i][j] = Math.max(matrix[i][j], lambda[j][n] * Math.abs(front.getPoint(i).getDimensionValue(n))); } } } double sum = 0.0; for (int i = 0; i < lambda.length; i++) { double tmp = matrix[0][i]; for (int j = 1; j < front.getNumberOfPoints(); j++) { tmp = Math.min(tmp, matrix[j][i]); } sum += tmp; } return sum / (double) lambda.length; } }
jmetal-core/src/main/java/org/uma/jmetal/qualityindicator/impl/R2.java
// R2.java // // Author: // Juan J. Durillo <[email protected]> // // Copyright (c) 2013 Juan J. Durillo // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // 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 Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.uma.jmetal.qualityindicator.impl; import org.uma.jmetal.qualityindicator.QualityIndicator; import org.uma.jmetal.solution.Solution; import org.uma.jmetal.util.front.Front; import org.uma.jmetal.util.front.imp.ArrayFront; import org.uma.jmetal.util.front.util.FrontNormalizer; import org.uma.jmetal.util.front.util.FrontUtils; import org.uma.jmetal.util.naming.impl.SimpleDescribedEntity; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * TODO: Add comments here */ @SuppressWarnings("serial") public class R2<Evaluate extends List<? extends Solution<?>>> extends SimpleDescribedEntity implements QualityIndicator<Evaluate,Double> { private final double[][] lambda; private final Front referenceParetoFront; /** * Creates a new instance of the R2 indicator for a problem with * two objectives and 100 lambda vectors */ public R2(Front referenceParetoFront) { // by default it creates an R2 indicator for a two dimensions problem and // uses only 100 weight vectors for the R2 computation this(100, referenceParetoFront); } /** * Creates a new instance of the R2 indicator for a problem with * two objectives and 100 lambda vectors */ public R2() { // by default it creates an R2 indicator for a two dimensions problem and // uses only 100 weight vectors for the R2 computation this(100); } /** * Creates a new instance of the R2 indicator for a problem with * two objectives and N lambda vectors */ public R2(int nVectors, Front referenceParetoFront) { // by default it creates an R2 indicator for a two dimensions problem and // uses only <code>nVectors</code> weight vectors for the R2 computation super("R2", "R2 quality indicator") ; // generating the weights lambda = new double[nVectors][2]; for (int n = 0; n < nVectors; n++) { double a = 1.0 * n / (nVectors - 1); lambda[n][0] = a; lambda[n][1] = 1 - a; } this.referenceParetoFront = referenceParetoFront; } /** * Creates a new instance of the R2 indicator for a problem with * two objectives and N lambda vectors */ public R2(int nVectors) { this(nVectors, null); } /** * Constructor * Creates a new instance of the R2 indicator for nDimensiosn * It loads the weight vectors from the file fileName */ public R2(String file, Front referenceParetoFront) throws java.io.IOException { this.lambda = readWeightsFrom(file); this.referenceParetoFront = referenceParetoFront; } private static double[][] readWeightsFrom(String file) throws java.io.IOException { FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); String line = br.readLine(); double[][] lambda; if (line==null) { lambda = null; } else { int numberOfObjectives = (new StringTokenizer(line)).countTokens(); int numberOfVectors = (int) br.lines().count(); lambda = new double[numberOfVectors][numberOfObjectives]; int index = 0; while (line!=null) { StringTokenizer st = new StringTokenizer(line); for (int i = 0; i < numberOfObjectives; i++) lambda[index][i] = new Double(st.nextToken()); index++; line = br.readLine(); } br.close(); } return lambda; } /** * Constructor * Creates a new instance of the R2 indicator for nDimensiosn * It loads the weight vectors from the file fileName */ public R2(String file) throws java.io.IOException { this(file, null); } // R2 @Override public Double evaluate(Evaluate solutionList) { return r2(new ArrayFront(solutionList)); } @Override public String getName() { return super.getName(); } public double r2(Front front) { if (this.referenceParetoFront != null) { // STEP 1. Obtain the maximum and minimum values of the Pareto front double[] maximumValues = FrontUtils.getMaximumValues(this.referenceParetoFront); double[] minimumValues = FrontUtils.getMinimumValues(this.referenceParetoFront); // STEP 2. Get the normalized front FrontNormalizer frontNormalizer = new FrontNormalizer(minimumValues, maximumValues); front = frontNormalizer.normalize(front); } int numberOfObjectives = front.getPoint(0).getNumberOfDimensions(); // STEP 3. compute all the matrix of Tschebyscheff values if it is null double[][] matrix = new double[front.getNumberOfPoints()][lambda.length]; for (int i = 0; i < front.getNumberOfPoints(); i++) { for (int j = 0; j < lambda.length; j++) { matrix[i][j] = lambda[j][0] * Math.abs(front.getPoint(i).getDimensionValue(0)); for (int n = 1; n < numberOfObjectives; n++) { matrix[i][j] = Math.max(matrix[i][j], lambda[j][n] * Math.abs(front.getPoint(i).getDimensionValue(n))); } } } double sum = 0.0; for (int i = 0; i < lambda.length; i++) { double tmp = matrix[0][i]; for (int j = 1; j < front.getNumberOfPoints(); j++) { tmp = Math.min(tmp, matrix[j][i]); } sum += tmp; } return sum / (double) lambda.length; } }
Extract lambda generation into dedicated method for readability.
jmetal-core/src/main/java/org/uma/jmetal/qualityindicator/impl/R2.java
Extract lambda generation into dedicated method for readability.
<ide><path>metal-core/src/main/java/org/uma/jmetal/qualityindicator/impl/R2.java <ide> // by default it creates an R2 indicator for a two dimensions problem and <ide> // uses only <code>nVectors</code> weight vectors for the R2 computation <ide> super("R2", "R2 quality indicator") ; <del> // generating the weights <del> lambda = new double[nVectors][2]; <add> this.lambda = generateWeights(nVectors); <add> this.referenceParetoFront = referenceParetoFront; <add> } <add> <add> private static double[][] generateWeights(int nVectors) { <add> double[][] lambda = new double[nVectors][2]; <ide> for (int n = 0; n < nVectors; n++) { <ide> double a = 1.0 * n / (nVectors - 1); <ide> lambda[n][0] = a; <ide> lambda[n][1] = 1 - a; <ide> } <del> <del> this.referenceParetoFront = referenceParetoFront; <add> return lambda; <ide> } <ide> <ide> /**
JavaScript
mit
5cd10b7d3f5e1f9c55a83d86f6221fea4da83e84
0
dongliu/runcheck,dongliu/runcheck
var express = require('express'); var slots = express.Router(); var auth = require('../lib/auth'); var Slot = require('../models/slot').Slot; var SlotGroup = require('../models/slot-group').SlotGroup; var log = require('../lib/log'); slots.get('/', auth.ensureAuthenticated, function (req, res) { res.render('slots'); }); slots.get('/json', auth.ensureAuthenticated, function (req, res) { Slot.find(function (err, docs) { if (err) { log.error(err); return res.status(500).send(err.message); } // data just for test. var slotDocs = docs.map(function (s) { return { _id: s._id, name: s.name, owner: 'wen', area: 'unknow in xlsx', level: s.level, deviceType: s.deviceType, location: [s.coordinateX, s.coordinateY, s.coordinateZ], device: s.deviceNaming, approvalStatus: 'unknow in xlsx', machineMode: 'unknow in xlsx', ReadinessCheckedValue: 10, ReadinessTotalValue: 10, DRRCheckedValue: 4, DRRTotalValue: 10, ARRCheckedValue: 0, ARRTotalValue: 10 } }); res.status(200).json(slotDocs); }); }); slots.get('/:id', auth.ensureAuthenticated, function (req, res) { Slot.findOne({ _id: req.params.id }, function (err, slot) { if (err) { log.error(err); return res.status(500).send(err.message); } SlotGroup.findOne({ _id: slot.inGroup }, function (err, slotGroup) { if (err) { log.error(err); return res.status(500).send(err.message); } res.render('slot', { slot: slot, slotGroup: slotGroup }); }); }); }); slots.get('/:id/json', auth.ensureAuthenticated, function (req, res) { Slot.findOne({ _id: req.params.id }, function (err, doc) { if (err) { log.error(err); return res.status(500).send(err.message); } res.status(200).send(doc); }); }); module.exports = slots;
routes/slots.js
var express = require('express'); var slots = express.Router(); var auth = require('../lib/auth'); var Slot = require('../models/slot').Slot; var SlotGroup = require('../models/slot-group').SlotGroup; var log = require('../lib/log'); slots.get('/', auth.ensureAuthenticated, function (req, res) { res.render('slots'); }); slots.get('/json', auth.ensureAuthenticated, function (req, res) { var slotDocs = []; Slot.find(function (err, docs) { if (err) { log.error(err); return res.status(500).send(err.message); } var count = 0; // data just for test. docs.forEach(function(d) { var slotDoc = { _id: d._id, name: d.name, owner: 'wen', area: 'unknow in xlsx', level: d.level, deviceType: d.deviceType, location: [d.coordinateX, d.coordinateY, d.coordinateZ], device: d.deviceNaming, approvalStatus: 'unknow in xlsx', machineMode: 'unknow in xlsx', ReadinessCheckedValue: 10, ReadinessTotalValue: 10, DRRCheckedValue: 4, DRRTotalValue: 10, ARRCheckedValue: 0, ARRTotalValue:10 }; slotDocs.push(slotDoc); count = count + 1; if(count === docs.length) { res.status(200).json(slotDocs); } }); }); }); slots.get('/:id', auth.ensureAuthenticated, function (req, res) { Slot.findOne({_id: req.params.id },function(err, slot) { if (err) { log.error(err); return res.status(500).send(err.message); } SlotGroup.findOne({_id: slot.inGroup },function(err, slotGroup) { if (err) { log.error(err); return res.status(500).send(err.message); } res.render('slot',{ slot: slot, slotGroup: slotGroup }); }); }); }); slots.get('/:id/json', auth.ensureAuthenticated, function (req, res) { Slot.findOne({_id: req.params.id },function(err, doc) { if (err) { log.error(err); return res.status(500).send(err.message); } res.status(200).send(doc); }); }); module.exports = slots;
fix slots/json, eslint
routes/slots.js
fix slots/json, eslint
<ide><path>outes/slots.js <ide> }); <ide> <ide> slots.get('/json', auth.ensureAuthenticated, function (req, res) { <del> var slotDocs = []; <ide> Slot.find(function (err, docs) { <ide> if (err) { <ide> log.error(err); <ide> return res.status(500).send(err.message); <ide> } <del> var count = 0; <ide> // data just for test. <del> docs.forEach(function(d) { <del> var slotDoc = { <del> _id: d._id, <del> name: d.name, <add> var slotDocs = docs.map(function (s) { <add> return { <add> _id: s._id, <add> name: s.name, <ide> owner: 'wen', <ide> area: 'unknow in xlsx', <del> level: d.level, <del> deviceType: d.deviceType, <del> location: [d.coordinateX, d.coordinateY, d.coordinateZ], <del> device: d.deviceNaming, <add> level: s.level, <add> deviceType: s.deviceType, <add> location: [s.coordinateX, s.coordinateY, s.coordinateZ], <add> device: s.deviceNaming, <ide> approvalStatus: 'unknow in xlsx', <ide> machineMode: 'unknow in xlsx', <ide> ReadinessCheckedValue: 10, <ide> DRRCheckedValue: 4, <ide> DRRTotalValue: 10, <ide> ARRCheckedValue: 0, <del> ARRTotalValue:10 <del> }; <del> slotDocs.push(slotDoc); <del> count = count + 1; <del> if(count === docs.length) { <del> res.status(200).json(slotDocs); <add> ARRTotalValue: 10 <ide> } <ide> }); <add> res.status(200).json(slotDocs); <ide> }); <ide> }); <ide> <ide> <ide> slots.get('/:id', auth.ensureAuthenticated, function (req, res) { <del> Slot.findOne({_id: req.params.id },function(err, slot) { <add> Slot.findOne({ <add> _id: req.params.id <add> }, function (err, slot) { <ide> if (err) { <ide> log.error(err); <ide> return res.status(500).send(err.message); <ide> } <del> SlotGroup.findOne({_id: slot.inGroup },function(err, slotGroup) { <add> SlotGroup.findOne({ <add> _id: slot.inGroup <add> }, function (err, slotGroup) { <ide> if (err) { <ide> log.error(err); <ide> return res.status(500).send(err.message); <ide> } <del> res.render('slot',{ <add> res.render('slot', { <ide> slot: slot, <ide> slotGroup: slotGroup <ide> }); <ide> <ide> <ide> slots.get('/:id/json', auth.ensureAuthenticated, function (req, res) { <del> Slot.findOne({_id: req.params.id },function(err, doc) { <add> Slot.findOne({ <add> _id: req.params.id <add> }, function (err, doc) { <ide> if (err) { <ide> log.error(err); <ide> return res.status(500).send(err.message);
JavaScript
mit
ed1f01d346eebd70e40653034b51e696dd444432
0
Zozman/hatinLolServer
var express = require('express'); var router = express.Router(); var request = require('request'); var fs = require('fs'); var NodeCache = require( "node-cache" ); var myCache = new NodeCache( { stdTTL: 3600, checkperiod: 120 } ); /* GET Insult API call */ router.get('/', function(req, res) { // Get region and character name var region = req.query.region; var charName = req.query.charName; // Get key for cache var cacheKey = charName.toLowerCase()+"|"+region; // Attempt to find a cached version of the data var cacheData = myCache.get(cacheKey); // If there is no cached data, get fresh data if (isEmptyObject(cacheData)) { // Make request to turn charName into charID request(makeIDURL(charName, region), function (error, response, body) { // If a good response was returned if (!error && response.statusCode == 200) { // Parse the returned JSON var jsonObj = JSON.parse(body); var searchNameForArray = charName.replaceAll(" ","").toLowerCase(); var charID = String(jsonObj[searchNameForArray].id); // Make request to get summoner's public game stats request(makeSummaryURL(charID, region), function (error2, response2, body2) { // If good value was returned if (!error2 && response2.statusCode == 200) { // Create array to hold AggregatedStats objects var aggArray = []; // Parse the returned JSON and for each playerStatSummary // Initialize wins and losses var wins = 0; var losses = 0; try { JSON.parse(body2).playerStatSummaries.forEach(function(item, index) { // Get wins if any are returned if (item.hasOwnProperty('wins')) { wins = item.wins; } // Get losses if any are returned if (item.hasOwnProperty('losses')) { losses = item.losses; } // Take JSON and wins and losses and create new AggregatedStats object // Then add it to the array aggArray.push(new AggregatedStats().fromJson(item.aggregatedStats, wins, losses)); }); } catch (Exception) { aggArray.push(new AggregatedStats()); } // Make a request for all ranked games stats request(makeRankedURL(charID, region), function (error3, response3, body3) { // If a good result was returned if (!error3 && response3.statusCode == 200) { // Parse all the champions data JSON.parse(body3).champions.forEach(function(item, index) { // If item 0 is found (item 0 is data for all Champions) if (item.id === 0) { // Add it to the array aggArray.push(new AggregatedStats().fromJson(item.stats, 0, 0)); } }); // Generate the insult var combinedData = combineStatsArray(aggArray); var finalResult = findInsult(combinedData, charName); // Cache data for an hour myCache.set(cacheKey, combinedData); // Return insult res.json({ result: finalResult, summoner:charName}); // Else if no ranked data is returned } else { // Generate the insult var combinedData2 = combineStatsArray(aggArray); var finalResult2 = findInsult(combinedData2, charName); // Cache data for an hour myCache.set(cacheKey, combinedData2); // Return the insult res.json({ result: finalResult2, summoner:charName}); } }) // Else if a 503 is returned for the player game stats } else if (response.statusCode == 503) { // Return 503 error res.json({ result: Error503() }); // Else any other error return generic error code }else { res.json({ result: makeGenericError() }); } }) // Else if a 503 is returned for the player id lookup } else if (response.statusCode == 503) { // Return 503 error res.json({ result: Error503() }); } else { // Else any other error return generic error code res.json({ result: makeGenericError() }); } }) // Else return an insult using cached data } else { res.json({ result: findInsult(cacheData[cacheKey], charName), summoner:charName}); } }); // Function compiles and returns the url to make a call to the Riot API to get the summoner's id function makeIDURL(charName, region) { return "https://" + region + ".api.pvp.net/api/lol/" + region + "/v1.4/summoner/by-name/" + charName + "?api_key=" + apiKey; } // Function that compiles and returns the url to make a call to the Riot API to get a summoner's player game stats function makeSummaryURL(charID, region) { return "https://" + region + ".api.pvp.net/api/lol/" + region + "/v1.3/stats/by-summoner/" + charID + "/summary?api_key=" + apiKey; } // Function that compiles and returns the url to make a call to the Riot API to get a summoner's ranked game stats function makeRankedURL(charID, region) { return "https://" + region + ".api.pvp.net/api/lol/" + region + "/v1.3/stats/by-summoner/" + charID + "/ranked?api_key=" + apiKey; } // Function to return a generic error function makeGenericError() { return "ERROR: Summoner not found. Hopefully it was deleted to make room for someone who can play."; } // Object to hold a player's stats function AggregatedStats() { this.botGamesPlayed = 0; this.killingSpree = 0; this.maxAssists = 0; this.maxChampionsKilled = 0; this.maxCombatPlayerScore = 0; this.maxLargestCriticalStrike = 0; this.maxLargestKillingSpree = 0; this.maxNodeCapture = 0; this.maxNodeCaptureAssist = 0; this.maxNodeNeutralize = 0; this.maxNodeNeutralizeAssist = 0; this.maxNumDeaths = 0; this.maxObjectivePlayerScore = 0; this.maxTeamObjective = 0; this.maxTimePlayed = 0; this.maxTimeSpentLiving = 0; this.maxTotalPlayerScore = 0; this.mostChampionKillsPerSession = 0; this.mostSpellsCast = 0; this.normalGamesPlayed = 0; this.rankedPremadeGamesPlayed = 0; this.rankedSoloGamesPlayed = 0; this.totalAssists = 0; this.totalChampionKills = 0; this.totalDamageDealt = 0; this.totalDamageTaken = 0; this.totalDeathsPerSession = 0; this.totalDoubleKills = 0; this.totalFirstBlood = 0; this.totalGoldEarned = 0; this.totalHeal = 0; this.totalMagicDamageDealt = 0; this.totalMinionKills = 0; this.totalNeutralMinionsKilled = 0; this.totalNodeCapture = 0; this.totalNodeNeutralize = 0; this.totalPentaKills = 0; this.totalPhysicalDamageDealt = 0; this.totalQuadraKills = 0; this.totalSessionsLost = 0; this.totalSessionsPlayed = 0; this.totalSessionsWon = 0; this.totalTripleKills = 0; this.totalTurretsKilled = 0; this.totalUnrealKills = 0; this.wins = 0; this.losses = 0; } // Function to convert a JSON AggregatedStats object to a JavaScript AggregatedStats object AggregatedStats.prototype.fromJson = function(input, winInput, lossInput) { // For each member in AggregatedStats for (var name in this) { // If the JSON has a key with the same name if (input.hasOwnProperty(name)) { // Set that key in the object to the input's value this[name] = input[name]; } } // If there are wins, get the wins if (winInput !== null) { this.wins = winInput; } // If there are losses, get the losses if (lossInput !== null) { this.losses = lossInput; } // Return the converted object return this; } // Function to combine an array of AggregatedStats objects into one AggregatedStats object function combineStatsArray(input) { // Get the first item var first = input[0]; // For every other item in the array for (var x = 1; x < input.length; x++) { // For each member in AggregatedStats for (var name in input[x]) { // If it is a 'max' object if (name.indexOf('max') === 0) { // Set the master item to the larger of the two first[name] = Math.max(first[name], input[x][name]); // Else if it is a total item } else { // Add the new item to the original first[name] = first[name] + input[x][name]; } } } // Return the combined AggregatedStats return first; } // Function to return a random integer based on a min and max value function randomIntFromInterval(min,max) { return Math.floor(Math.random()*(max-min+1)+min); } // Function to take AggregatedStats data and a charName and make an insult using them function findInsult(input, charName) { // Make array to hold insults var insultArray = []; // Read the insult file var jsonReturned = JSON.parse(fs.readFileSync('./insults.json', 'utf8')); // For each insult returned, save it to the array jsonReturned.insults.forEach(function(item, index) { insultArray.push(String(item)); }); // Randomly choose 1 insult from the array var chosenInsult = insultArray[randomIntFromInterval(0,insultArray.length)]; // If the insult did not get returned correctly, use the backup insult if ((chosenInsult === null) || (chosenInsult === undefined)) { chosenInsult = "_name, I got nothing."; } // Replace all instances of _name in the insult with the charName chosenInsult = chosenInsult.replaceAll('_name',charName); // For each member in the AggregatedStats object for (var name in input) { // Replace the _nameOfTheCharacteristic with the stored value chosenInsult = chosenInsult.replaceAll("_" + String(name),input[name]); } // Return the completed insult return chosenInsult; } // Helper function to handle Regular Expressions escape RegExp.escape = function(text) { return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); } // Helper function to handle a replace all for a string String.prototype.replaceAll = function(search, replace) { return this.replace(new RegExp(RegExp.escape(search),'g'), replace); }; // Function to tell if we have an empty object (used with cache) // From http://stackoverflow.com/questions/11480769/how-can-i-check-if-a-json-is-empty-in-nodejs function isEmptyObject(obj) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { return false; } } return true; } // Function to return a basic 503 error message function Error503() { return "ERROR: The Riot API is TOTALLY DOWN (503 Error). I would complain to everyone on the Internet. Because that makes it get fixed faster."; } // Function to generate an insult function generateInsult(input, charName) { // Combine all character data into one AggregatedStats var combined = combineStatsArray(input); // Build and find the insult return findInsult(combined, charName); } module.exports = router;
routes/insult.js
var express = require('express'); var router = express.Router(); var request = require('request'); var fs = require('fs'); var NodeCache = require( "node-cache" ); var myCache = new NodeCache( { stdTTL: 3600, checkperiod: 120 } ); /* GET Insult API call */ router.get('/', function(req, res) { // Get region and character name var region = req.query.region; var charName = req.query.charName; // Get key for cache var cacheKey = charName.toLowerCase()+"|"+region; // Attempt to find a cached version of the data var cacheData = myCache.get(cacheKey); // If there is no cached data, get fresh data if (isEmptyObject(cacheData)) { // Make request to turn charName into charID request(makeIDURL(charName, region), function (error, response, body) { // If a good response was returned if (!error && response.statusCode == 200) { // Parse the returned JSON var jsonObj = JSON.parse(body); var searchNameForArray = charName.replaceAll(" ","").toLowerCase(); var charID = String(jsonObj[searchNameForArray].id); // Make request to get summoner's public game stats request(makeSummaryURL(charID, region), function (error2, response2, body2) { // If good value was returned if (!error2 && response2.statusCode == 200) { // Create array to hold AggregatedStats objects var aggArray = []; // Parse the returned JSON and for each playerStatSummary // Initialize wins and losses var wins = 0; var losses = 0; try { JSON.parse(body2).playerStatSummaries.forEach(function(item, index) { // Get wins if any are returned if (item.hasOwnProperty('wins')) { wins = item.wins; } // Get losses if any are returned if (item.hasOwnProperty('losses')) { losses = item.losses; } // Take JSON and wins and losses and create new AggregatedStats object // Then add it to the array aggArray.push(new AggregatedStats().fromJson(item.aggregatedStats, wins, losses)); }); } catch (Exception) { } // Make a request for all ranked games stats request(makeRankedURL(charID, region), function (error3, response3, body3) { // If a good result was returned if (!error3 && response3.statusCode == 200) { // Parse all the champions data JSON.parse(body3).champions.forEach(function(item, index) { // If item 0 is found (item 0 is data for all Champions) if (item.id === 0) { // Add it to the array aggArray.push(new AggregatedStats().fromJson(item.stats, 0, 0)); } }); // Generate the insult var combinedData = combineStatsArray(aggArray); var finalResult = findInsult(combinedData, charName); // Cache data for an hour myCache.set(cacheKey, combinedData); // Return insult res.json({ result: finalResult, summoner:charName}); // Else if no ranked data is returned } else { // Generate the insult var combinedData2 = combineStatsArray(aggArray); var finalResult2 = findInsult(combinedData2, charName); // Cache data for an hour myCache.set(cacheKey, combinedData2); // Return the insult res.json({ result: finalResult2, summoner:charName}); } }) // Else if a 503 is returned for the player game stats } else if (response.statusCode == 503) { // Return 503 error res.json({ result: Error503() }); // Else any other error return generic error code }else { res.json({ result: makeGenericError() }); } }) // Else if a 503 is returned for the player id lookup } else if (response.statusCode == 503) { // Return 503 error res.json({ result: Error503() }); } else { // Else any other error return generic error code res.json({ result: makeGenericError() }); } }) // Else return an insult using cached data } else { res.json({ result: findInsult(cacheData[cacheKey], charName), summoner:charName}); } }); // Function compiles and returns the url to make a call to the Riot API to get the summoner's id function makeIDURL(charName, region) { return "https://" + region + ".api.pvp.net/api/lol/" + region + "/v1.4/summoner/by-name/" + charName + "?api_key=" + apiKey; } // Function that compiles and returns the url to make a call to the Riot API to get a summoner's player game stats function makeSummaryURL(charID, region) { return "https://" + region + ".api.pvp.net/api/lol/" + region + "/v1.3/stats/by-summoner/" + charID + "/summary?api_key=" + apiKey; } // Function that compiles and returns the url to make a call to the Riot API to get a summoner's ranked game stats function makeRankedURL(charID, region) { return "https://" + region + ".api.pvp.net/api/lol/" + region + "/v1.3/stats/by-summoner/" + charID + "/ranked?api_key=" + apiKey; } // Function to return a generic error function makeGenericError() { return "ERROR: Summoner not found. Hopefully it was deleted to make room for someone who can play."; } // Object to hold a player's stats function AggregatedStats() { this.botGamesPlayed = 0; this.killingSpree = 0; this.maxAssists = 0; this.maxChampionsKilled = 0; this.maxCombatPlayerScore = 0; this.maxLargestCriticalStrike = 0; this.maxLargestKillingSpree = 0; this.maxNodeCapture = 0; this.maxNodeCaptureAssist = 0; this.maxNodeNeutralize = 0; this.maxNodeNeutralizeAssist = 0; this.maxNumDeaths = 0; this.maxObjectivePlayerScore = 0; this.maxTeamObjective = 0; this.maxTimePlayed = 0; this.maxTimeSpentLiving = 0; this.maxTotalPlayerScore = 0; this.mostChampionKillsPerSession = 0; this.mostSpellsCast = 0; this.normalGamesPlayed = 0; this.rankedPremadeGamesPlayed = 0; this.rankedSoloGamesPlayed = 0; this.totalAssists = 0; this.totalChampionKills = 0; this.totalDamageDealt = 0; this.totalDamageTaken = 0; this.totalDeathsPerSession = 0; this.totalDoubleKills = 0; this.totalFirstBlood = 0; this.totalGoldEarned = 0; this.totalHeal = 0; this.totalMagicDamageDealt = 0; this.totalMinionKills = 0; this.totalNeutralMinionsKilled = 0; this.totalNodeCapture = 0; this.totalNodeNeutralize = 0; this.totalPentaKills = 0; this.totalPhysicalDamageDealt = 0; this.totalQuadraKills = 0; this.totalSessionsLost = 0; this.totalSessionsPlayed = 0; this.totalSessionsWon = 0; this.totalTripleKills = 0; this.totalTurretsKilled = 0; this.totalUnrealKills = 0; this.wins = 0; this.losses = 0; } // Function to convert a JSON AggregatedStats object to a JavaScript AggregatedStats object AggregatedStats.prototype.fromJson = function(input, winInput, lossInput) { // For each member in AggregatedStats for (var name in this) { // If the JSON has a key with the same name if (input.hasOwnProperty(name)) { // Set that key in the object to the input's value this[name] = input[name]; } } // If there are wins, get the wins if (winInput !== null) { this.wins = winInput; } // If there are losses, get the losses if (lossInput !== null) { this.losses = lossInput; } // Return the converted object return this; } // Function to combine an array of AggregatedStats objects into one AggregatedStats object function combineStatsArray(input) { // Get the first item var first = input[0]; // For every other item in the array for (var x = 1; x < input.length; x++) { // For each member in AggregatedStats for (var name in input[x]) { // If it is a 'max' object if (name.indexOf('max') === 0) { // Set the master item to the larger of the two first[name] = Math.max(first[name], input[x][name]); // Else if it is a total item } else { // Add the new item to the original first[name] = first[name] + input[x][name]; } } } // Return the combined AggregatedStats return first; } // Function to return a random integer based on a min and max value function randomIntFromInterval(min,max) { return Math.floor(Math.random()*(max-min+1)+min); } // Function to take AggregatedStats data and a charName and make an insult using them function findInsult(input, charName) { // Make array to hold insults var insultArray = []; // Read the insult file var jsonReturned = JSON.parse(fs.readFileSync('./insults.json', 'utf8')); // For each insult returned, save it to the array jsonReturned.insults.forEach(function(item, index) { insultArray.push(String(item)); }); // Randomly choose 1 insult from the array var chosenInsult = insultArray[randomIntFromInterval(0,insultArray.length)]; // If the insult did not get returned correctly, use the backup insult if ((chosenInsult === null) || (chosenInsult === undefined)) { chosenInsult = "_name, I got nothing."; } // Replace all instances of _name in the insult with the charName chosenInsult = chosenInsult.replaceAll('_name',charName); // For each member in the AggregatedStats object for (var name in input) { // Replace the _nameOfTheCharacteristic with the stored value chosenInsult = chosenInsult.replaceAll("_" + String(name),input[name]); } // Return the completed insult return chosenInsult; } // Helper function to handle Regular Expressions escape RegExp.escape = function(text) { return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); } // Helper function to handle a replace all for a string String.prototype.replaceAll = function(search, replace) { return this.replace(new RegExp(RegExp.escape(search),'g'), replace); }; // Function to tell if we have an empty object (used with cache) // From http://stackoverflow.com/questions/11480769/how-can-i-check-if-a-json-is-empty-in-nodejs function isEmptyObject(obj) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { return false; } } return true; } // Function to return a basic 503 error message function Error503() { return "ERROR: The Riot API is TOTALLY DOWN (503 Error). I would complain to everyone on the Internet. Because that makes it get fixed faster."; } // Function to generate an insult function generateInsult(input, charName) { // Combine all character data into one AggregatedStats var combined = combineStatsArray(input); // Build and find the insult return findInsult(combined, charName); } module.exports = router;
Season bug
routes/insult.js
Season bug
<ide><path>outes/insult.js <ide> aggArray.push(new AggregatedStats().fromJson(item.aggregatedStats, wins, losses)); <ide> }); <ide> } catch (Exception) { <del> <add> aggArray.push(new AggregatedStats()); <ide> } <ide> // Make a request for all ranked games stats <ide> request(makeRankedURL(charID, region), function (error3, response3, body3) {
Java
mit
e9e55a0841ba09aa89e46439d09f6cccf2b8e29f
0
NestedWorld/NestedWorld-Android
package com.nestedworld.nestedworld.models; import android.support.annotation.Nullable; import com.google.gson.annotations.Expose; import com.nestedworld.nestedworld.R; import com.orm.SugarRecord; import com.orm.query.Condition; import com.orm.query.Select; /** * Simple model for : * - mapping a json response with Gson anotation * - mapping a sql table with SugarORM * /!\ Keep the default constructor empty (see sugarOrm doc) */ public class UserMonster extends SugarRecord { @Expose public Monster infos; @Expose public Long level; @Expose public String surname; @Expose public String experience; //Empty constructor for SugarRecord public UserMonster() { //Keep empty } public Long fkmonster;//key for Monster<->UserMonster relationship @Nullable public Monster info() { if (infos == null) { infos = Select.from(Monster.class).where(Condition.prop("monsterid").eq(fkmonster)).first(); } return infos; } //Generated @Override public String toString() { return "UserMonster{" + "infos=" + infos + ", level='" + level + '\'' + ", surname='" + surname + '\'' + ", experience='" + experience + '\'' + ", fkMonster=" + fkmonster + '}'; } //Utils public int getColorResource() { Monster info = info(); if (info == null) { return R.color.black; } return info.getColorResource(); } }
app/src/main/java/com/nestedworld/nestedworld/models/UserMonster.java
package com.nestedworld.nestedworld.models; import android.support.annotation.Nullable; import com.google.gson.annotations.Expose; import com.orm.SugarRecord; import com.orm.query.Condition; import com.orm.query.Select; /** * Simple model for : * - mapping a json response with Gson anotation * - mapping a sql table with SugarORM * /!\ Keep the default constructor empty (see sugarOrm doc) */ public class UserMonster extends SugarRecord { @Expose public Monster infos; @Expose public String level; @Expose public String surname; @Expose public String experience; //Empty constructor for SugarRecord public UserMonster() { //Keep empty } public Long fkmonster;//key for Monster<->UserMonster relationship @Nullable public Monster info() { return Select.from(Monster.class).where(Condition.prop("monsterid").eq(fkmonster)).first(); } //Generated @Override public String toString() { return "UserMonster{" + "infos=" + infos + ", level='" + level + '\'' + ", surname='" + surname + '\'' + ", experience='" + experience + '\'' + ", fkMonster=" + fkmonster + '}'; } }
update model / add getColorResource()
app/src/main/java/com/nestedworld/nestedworld/models/UserMonster.java
update model / add getColorResource()
<ide><path>pp/src/main/java/com/nestedworld/nestedworld/models/UserMonster.java <ide> import android.support.annotation.Nullable; <ide> <ide> import com.google.gson.annotations.Expose; <add>import com.nestedworld.nestedworld.R; <ide> import com.orm.SugarRecord; <ide> import com.orm.query.Condition; <ide> import com.orm.query.Select; <ide> public Monster infos; <ide> <ide> @Expose <del> public String level; <add> public Long level; <ide> <ide> @Expose <ide> public String surname; <ide> <ide> @Nullable <ide> public Monster info() { <del> return Select.from(Monster.class).where(Condition.prop("monsterid").eq(fkmonster)).first(); <add> if (infos == null) { <add> infos = Select.from(Monster.class).where(Condition.prop("monsterid").eq(fkmonster)).first(); <add> } <add> return infos; <ide> } <ide> <ide> //Generated <ide> ", fkMonster=" + fkmonster + <ide> '}'; <ide> } <add> <add> //Utils <add> public int getColorResource() { <add> Monster info = info(); <add> if (info == null) { <add> return R.color.black; <add> } <add> return info.getColorResource(); <add> } <ide> }
Java
apache-2.0
e100619f12a35fbf2437d4f7c714b6800e116167
0
olehmberg/winter
/* * Copyright (c) 2017 Data and Web Science Group, University of Mannheim, Germany (http://dws.informatik.uni-mannheim.de/) * * 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 de.uni_mannheim.informatik.dws.winter.processing; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import de.uni_mannheim.informatik.dws.winter.model.Pair; import de.uni_mannheim.informatik.dws.winter.utils.ProgressReporter; /** * * Single-Threaded implementation of {@link Processable} * * @author Oliver Lehmberg ([email protected]) * */ public class ProcessableCollection<RecordType> implements Processable<RecordType> { private static final long serialVersionUID = 1L; protected Collection<RecordType> elements; public ProcessableCollection() { elements = new LinkedList<>(); } public ProcessableCollection(Collection<RecordType> elements) { if(elements!=null) { this.elements = elements; } else { elements = new LinkedList<>(); } } public ProcessableCollection(Processable<RecordType> elements) { if(elements!=null) { this.elements = elements.get(); } else { this.elements = new LinkedList<>(); } } public void add(RecordType element) { elements.add(element); } public Collection<RecordType> get() { return elements; } public int size() { return elements.size(); } public void merge(Processable<RecordType> other) { if(other!=null) { for(RecordType elem : other.get()) { add(elem); } } } public void remove(RecordType element) { elements.remove(element); } public void remove(Collection<RecordType> element) { elements.removeAll(element); } @Override public Processable<RecordType> copy() { return createProcessableFromCollection(get()); } public RecordType firstOrNull() { Collection<RecordType> data = get(); if(data==null || data.size()==0) { return null; } else { return data.iterator().next(); } } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#createProcessable(java.lang.Object) */ @Override public <OutputRecordType> Processable<OutputRecordType> createProcessable( OutputRecordType dummyForTypeInference) { return new ProcessableCollection<>(); } /* (non-Javadoc) * @see de.uni_mannheim.informatik.wdi.processing.Processable#createProcessableFromCollection(java.util.Collection) */ @Override public <OutputRecordType> Processable<OutputRecordType> createProcessableFromCollection( Collection<OutputRecordType> data) { return new ProcessableCollection<>(data); } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#assignUniqueRecordIds(de.uni_mannheim.informatik.dws.winter.processing.Function) */ @Override public Processable<RecordType> assignUniqueRecordIds( Function<RecordType, Pair<Long,RecordType>> assignUniqueId) { long id = 0; Processable<RecordType> result = createProcessable((RecordType)null); for(RecordType record : get()) { RecordType r = assignUniqueId.execute(new Pair<Long, RecordType>(id++, record)); result.add(r); } return result; } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#iterateDataset(de.uni_mannheim.informatik.dws.winter.processing.DatasetIterator) */ @Override public void foreach( DataIterator<RecordType> iterator) { iterator.initialise(); for(RecordType r : get()) { iterator.next(r); } iterator.finalise(); } @Override public void foreach(Action<RecordType> action) { for(RecordType r : get()) { action.execute(r); } } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#transform(de.uni_mannheim.informatik.dws.winter.processing.RecordMapper) */ @Override public <OutputRecordType> Processable<OutputRecordType> map( RecordMapper<RecordType, OutputRecordType> transformation) { ProgressReporter progress = new ProgressReporter(size(),""); ProcessableCollector<OutputRecordType> resultCollector = new ProcessableCollector<>(); resultCollector.setResult(createProcessable((OutputRecordType)null)); resultCollector.initialise(); for(RecordType record : get()) { transformation.mapRecord(record, resultCollector); progress.incrementProgress(); progress.report(); } resultCollector.finalise(); return resultCollector.getResult(); } /** * Applies the hash function to all records * @param dataset * @param hash * @return A map from the hash value to the respective records */ protected <KeyType, ElementType> Map<KeyType, List<ElementType>> hashRecords( Processable<ElementType> dataset, Function<KeyType, ElementType> hash) { HashMap<KeyType, List<ElementType>> hashMap = new HashMap<>(); for(ElementType record : dataset.get()) { KeyType key = hash.execute(record); if(key!=null) { List<ElementType> records = hashMap.get(key); if(records==null) { records = new ArrayList<>(); hashMap.put(key, records); } records.add(record); } } return hashMap; } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#symmetricJoin(de.uni_mannheim.informatik.dws.winter.processing.Function) */ @Override public <KeyType> Processable<Pair<RecordType,RecordType>> symmetricJoin( Function<KeyType, RecordType> joinKeyGenerator) { return symmetricJoin(joinKeyGenerator, new ProcessableCollector<Pair<RecordType, RecordType>>()); } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#symmetricJoin(de.uni_mannheim.informatik.dws.winter.processing.Function, de.uni_mannheim.informatik.dws.winter.processing.ProcessableCollector) */ @Override public <KeyType> Processable<Pair<RecordType,RecordType>> symmetricJoin( Function<KeyType, RecordType> joinKeyGenerator, final ProcessableCollector<Pair<RecordType, RecordType>> collector) { Map<KeyType, List<RecordType>> joinKeys = hashRecords(this, joinKeyGenerator); collector.setResult(createProcessable((Pair<RecordType,RecordType>)null)); collector.initialise(); for(List<RecordType> block : joinKeys.values()) { for(int i = 0; i < block.size(); i++) { for(int j = i+1; j<block.size(); j++) { if(i!=j) { collector.next(new Pair<>(block.get(i), block.get(j))); } } } } collector.finalise(); return collector.getResult(); } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#join(de.uni_mannheim.informatik.dws.winter.processing.Processable, de.uni_mannheim.informatik.dws.winter.processing.Function) */ @Override public <KeyType> Processable<Pair<RecordType,RecordType>> join( Processable<RecordType> dataset2, Function<KeyType, RecordType> joinKeyGenerator) { return join(dataset2, joinKeyGenerator, joinKeyGenerator); } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#join(de.uni_mannheim.informatik.dws.winter.processing.Processable, de.uni_mannheim.informatik.dws.winter.processing.Function, de.uni_mannheim.informatik.dws.winter.processing.Function) */ @Override public <KeyType, RecordType2> Processable<Pair<RecordType,RecordType2>> join( Processable<RecordType2> dataset2, Function<KeyType, RecordType> joinKeyGenerator1, Function<KeyType, RecordType2> joinKeyGenerator2) { final Map<KeyType, List<RecordType>> joinKeys1 = hashRecords(this, joinKeyGenerator1); final Map<KeyType, List<RecordType2>> joinKeys2 = hashRecords(dataset2, joinKeyGenerator2); Processable<Pair<RecordType, RecordType2>> result = createProcessableFromCollection(joinKeys1.keySet()).map(new RecordMapper<KeyType, Pair<RecordType, RecordType2>>() { private static final long serialVersionUID = 1L; @Override public void mapRecord(KeyType key1, DataIterator<Pair<RecordType, RecordType2>> resultCollector) { List<RecordType> block = joinKeys1.get(key1); List<RecordType2> block2 = joinKeys2.get(key1); if(block2!=null) { for(RecordType r1 : block) { for(RecordType2 r2 : block2) { resultCollector.next(new Pair<>(r1, r2)); } } } } }); return result; } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#leftJoin(de.uni_mannheim.informatik.dws.winter.processing.Processable, de.uni_mannheim.informatik.dws.winter.processing.Function) */ @Override public <KeyType> Processable<Pair<RecordType,RecordType>> leftJoin( Processable<RecordType> dataset2, Function<KeyType, RecordType> joinKeyGenerator) { return leftJoin(dataset2, joinKeyGenerator, joinKeyGenerator); } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#leftJoin(de.uni_mannheim.informatik.dws.winter.processing.Processable, de.uni_mannheim.informatik.dws.winter.processing.Function, de.uni_mannheim.informatik.dws.winter.processing.Function) */ @Override public <KeyType, RecordType2> Processable<Pair<RecordType,RecordType2>> leftJoin( Processable<RecordType2> dataset2, Function<KeyType, RecordType> joinKeyGenerator1, Function<KeyType, RecordType2> joinKeyGenerator2) { Processable<Pair<RecordType, RecordType2>> result = createProcessable((Pair<RecordType, RecordType2>)null); Map<KeyType, List<RecordType>> joinKeys1 = hashRecords(this, joinKeyGenerator1); Map<KeyType, List<RecordType2>> joinKeys2 = hashRecords(dataset2, joinKeyGenerator2); for(KeyType key1 : joinKeys1.keySet()) { List<RecordType> block = joinKeys1.get(key1); List<RecordType2> block2 = joinKeys2.get(key1); for(RecordType r1 : block) { if(block2!=null) { for(RecordType2 r2 : block2) { result.add(new Pair<>(r1, r2)); } } else { result.add(new Pair<>(r1, (RecordType2)null)); } } } return result; } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#groupRecords(de.uni_mannheim.informatik.dws.winter.processing.RecordKeyValueMapper) */ @Override public <KeyType, OutputRecordType> Processable<Group<KeyType, OutputRecordType>> group( RecordKeyValueMapper<KeyType, RecordType, OutputRecordType> groupBy) { GroupCollector<KeyType, OutputRecordType> groupCollector = new GroupCollector<>(); groupCollector.initialise(); for(RecordType r : get()) { groupBy.mapRecordToKey(r, groupCollector); } groupCollector.finalise(); return groupCollector.getResult(); } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#aggregateRecords(de.uni_mannheim.informatik.dws.winter.processing.RecordKeyValueMapper, de.uni_mannheim.informatik.dws.winter.processing.DataAggregator) */ @Override public <KeyType, OutputRecordType, ResultType> Processable<Pair<KeyType, ResultType>> aggregate( RecordKeyValueMapper<KeyType, RecordType, OutputRecordType> groupBy, DataAggregator<KeyType, OutputRecordType, ResultType> aggregator) { AggregateCollector<KeyType, OutputRecordType, ResultType> aggregateCollector = new AggregateCollector<>(); aggregateCollector.setAggregator(aggregator); aggregateCollector.initialise(); for(RecordType r : get()) { groupBy.mapRecordToKey(r, aggregateCollector); } aggregateCollector.finalise(); return aggregateCollector.getAggregationResult(); } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#sort(de.uni_mannheim.informatik.dws.winter.processing.Function) */ @Override public <KeyType extends Comparable<KeyType>> Processable<RecordType> sort(Function<KeyType, RecordType> sortingKey) { return sort(sortingKey, true); } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#sort(de.uni_mannheim.informatik.dws.winter.processing.Function, boolean) */ @Override public <KeyType extends Comparable<KeyType>> Processable<RecordType> sort( final Function<KeyType, RecordType> sortingKey, final boolean ascending) { ArrayList<RecordType> list = new ArrayList<>(get()); Collections.sort(list, new Comparator<RecordType>() { @Override public int compare(RecordType o1, RecordType o2) { return (ascending ? 1 : -1) * sortingKey.execute(o1).compareTo(sortingKey.execute(o2)); } }); Processable<RecordType> result = createProcessable((RecordType)null); for(RecordType elem : list) { result.add(elem); } return result; } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#filter(de.uni_mannheim.informatik.dws.winter.processing.Function) */ @Override public Processable<RecordType> where(Function<Boolean, RecordType> criteria) { Processable<RecordType> result = createProcessable((RecordType)null); for(RecordType element : get()) { if(criteria.execute(element)) { result.add(element); } } return result; } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#coGroup(de.uni_mannheim.informatik.dws.winter.processing.Processable, de.uni_mannheim.informatik.dws.winter.processing.Function, de.uni_mannheim.informatik.dws.winter.processing.Function, de.uni_mannheim.informatik.dws.winter.processing.RecordMapper) */ @Override public <KeyType, RecordType2, OutputRecordType> Processable<OutputRecordType> coGroup( Processable<RecordType2> data2, final Function<KeyType, RecordType> groupingKeyGenerator1, final Function<KeyType, RecordType2> groupingKeyGenerator2, final RecordMapper<Pair<Iterable<RecordType>, Iterable<RecordType2>>, OutputRecordType> resultMapper) { Processable<Group<KeyType, RecordType>> group1 = group(new RecordKeyValueMapper<KeyType, RecordType, RecordType>() { private static final long serialVersionUID = 1L; @Override public void mapRecordToKey(RecordType record, DataIterator<Pair<KeyType, RecordType>> resultCollector) { resultCollector.next(new Pair<KeyType, RecordType>(groupingKeyGenerator1.execute(record), record)); } }); Processable<Group<KeyType, RecordType2>> group2 = data2.group(new RecordKeyValueMapper<KeyType, RecordType2, RecordType2>() { private static final long serialVersionUID = 1L; @Override public void mapRecordToKey(RecordType2 record, DataIterator<Pair<KeyType, RecordType2>> resultCollector) { resultCollector.next(new Pair<KeyType, RecordType2>(groupingKeyGenerator2.execute(record), record)); } }); Processable<Pair<Group<KeyType, RecordType>, Group<KeyType, RecordType2>>> joined = group1.join(group2, new Function<KeyType, Group<KeyType, RecordType>>() { /** * */ private static final long serialVersionUID = 1L; @Override public KeyType execute(Group<KeyType, RecordType> input) { return input.getKey(); } },new Function<KeyType, Group<KeyType, RecordType2>>() { /** * */ private static final long serialVersionUID = 1L; @Override public KeyType execute(Group<KeyType, RecordType2> input) { return (KeyType)input.getKey(); } }); return joined.map(new RecordMapper<Pair<Group<KeyType, RecordType>, Group<KeyType, RecordType2>>, OutputRecordType>() { /** * */ private static final long serialVersionUID = 1L; @Override public void mapRecord(Pair<Group<KeyType, RecordType>, Group<KeyType, RecordType2>> record, DataIterator<OutputRecordType> resultCollector) { resultMapper.mapRecord(new Pair<Iterable<RecordType>, Iterable<RecordType2>>(record.getFirst().getRecords().get(), record.getSecond().getRecords().get()), resultCollector); } }); } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#append(de.uni_mannheim.informatik.dws.winter.processing.Processable) */ @Override public Processable<RecordType> append(Processable<RecordType> data2) { Processable<RecordType> result = createProcessable((RecordType)null); for(RecordType r : get()) { result.add(r); } if(data2!=null) { for(RecordType r : data2.get()) { result.add(r); } } return result; } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#distinct() */ @Override public Processable<RecordType> distinct() { return createProcessableFromCollection(new ArrayList<>(new HashSet<>(get()))); } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#take(int) */ @Override public Processable<RecordType> take(int numberOfRecords) { Processable<RecordType> result = createProcessable((RecordType)null); Iterator<RecordType> it = get().iterator(); while(it.hasNext() && result.size() < numberOfRecords) { result.add(it.next()); } return result; } }
src/main/java/de/uni_mannheim/informatik/dws/winter/processing/ProcessableCollection.java
/* * Copyright (c) 2017 Data and Web Science Group, University of Mannheim, Germany (http://dws.informatik.uni-mannheim.de/) * * 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 de.uni_mannheim.informatik.dws.winter.processing; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import de.uni_mannheim.informatik.dws.winter.model.Pair; import de.uni_mannheim.informatik.dws.winter.utils.ProgressReporter; /** * * Single-Threaded implementation of {@link Processable} * * @author Oliver Lehmberg ([email protected]) * */ public class ProcessableCollection<RecordType> implements Processable<RecordType> { private static final long serialVersionUID = 1L; protected Collection<RecordType> elements; public ProcessableCollection() { elements = new LinkedList<>(); } public ProcessableCollection(Collection<RecordType> elements) { if(elements!=null) { this.elements = elements; } else { elements = new LinkedList<>(); } } public ProcessableCollection(Processable<RecordType> elements) { if(elements!=null) { this.elements = elements.get(); } else { this.elements = new LinkedList<>(); } } public void add(RecordType element) { elements.add(element); } public Collection<RecordType> get() { return elements; } public int size() { return elements.size(); } public void merge(Processable<RecordType> other) { if(other!=null) { for(RecordType elem : other.get()) { add(elem); } } } public void remove(RecordType element) { elements.remove(element); } public void remove(Collection<RecordType> element) { elements.removeAll(element); } @Override public Processable<RecordType> copy() { return createProcessableFromCollection(get()); } public RecordType firstOrNull() { Collection<RecordType> data = get(); if(data==null || data.size()==0) { return null; } else { return data.iterator().next(); } } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#createProcessable(java.lang.Object) */ @Override public <OutputRecordType> Processable<OutputRecordType> createProcessable( OutputRecordType dummyForTypeInference) { return new ProcessableCollection<>(); } /* (non-Javadoc) * @see de.uni_mannheim.informatik.wdi.processing.Processable#createProcessableFromCollection(java.util.Collection) */ @Override public <OutputRecordType> Processable<OutputRecordType> createProcessableFromCollection( Collection<OutputRecordType> data) { return new ProcessableCollection<>(data); } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#assignUniqueRecordIds(de.uni_mannheim.informatik.dws.winter.processing.Function) */ @Override public Processable<RecordType> assignUniqueRecordIds( Function<RecordType, Pair<Long,RecordType>> assignUniqueId) { long id = 0; Processable<RecordType> result = createProcessable((RecordType)null); for(RecordType record : get()) { RecordType r = assignUniqueId.execute(new Pair<Long, RecordType>(id++, record)); result.add(r); } return result; } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#iterateDataset(de.uni_mannheim.informatik.dws.winter.processing.DatasetIterator) */ @Override public void foreach( DataIterator<RecordType> iterator) { iterator.initialise(); for(RecordType r : get()) { iterator.next(r); } iterator.finalise(); } @Override public void foreach(Action<RecordType> action) { for(RecordType r : get()) { action.execute(r); } } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#transform(de.uni_mannheim.informatik.dws.winter.processing.RecordMapper) */ @Override public <OutputRecordType> Processable<OutputRecordType> map( RecordMapper<RecordType, OutputRecordType> transformation) { ProgressReporter progress = new ProgressReporter(size(),""); ProcessableCollector<OutputRecordType> resultCollector = new ProcessableCollector<>(); resultCollector.setResult(createProcessable((OutputRecordType)null)); resultCollector.initialise(); for(RecordType record : get()) { transformation.mapRecord(record, resultCollector); progress.incrementProgress(); progress.report(); } resultCollector.finalise(); return resultCollector.getResult(); } /** * Applies the hash function to all records * @param dataset * @param hash * @return A map from the hash value to the respective records */ protected <KeyType, ElementType> Map<KeyType, List<ElementType>> hashRecords( Processable<ElementType> dataset, Function<KeyType, ElementType> hash) { HashMap<KeyType, List<ElementType>> hashMap = new HashMap<>(); for(ElementType record : dataset.get()) { KeyType key = hash.execute(record); if(key!=null) { List<ElementType> records = hashMap.get(key); if(records==null) { records = new ArrayList<>(); hashMap.put(key, records); } records.add(record); } } return hashMap; } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#symmetricJoin(de.uni_mannheim.informatik.dws.winter.processing.Function) */ @Override public <KeyType> Processable<Pair<RecordType,RecordType>> symmetricJoin( Function<KeyType, RecordType> joinKeyGenerator) { return symmetricJoin(joinKeyGenerator, new ProcessableCollector<Pair<RecordType, RecordType>>()); } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#symmetricJoin(de.uni_mannheim.informatik.dws.winter.processing.Function, de.uni_mannheim.informatik.dws.winter.processing.ProcessableCollector) */ @Override public <KeyType> Processable<Pair<RecordType,RecordType>> symmetricJoin( Function<KeyType, RecordType> joinKeyGenerator, final ProcessableCollector<Pair<RecordType, RecordType>> collector) { Map<KeyType, List<RecordType>> joinKeys = hashRecords(this, joinKeyGenerator); collector.setResult(createProcessable((Pair<RecordType,RecordType>)null)); collector.initialise(); for(List<RecordType> block : joinKeys.values()) { for(int i = 0; i < block.size(); i++) { for(int j = i+1; j<block.size(); j++) { if(i!=j) { collector.next(new Pair<>(block.get(i), block.get(j))); } } } } collector.finalise(); return collector.getResult(); } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#join(de.uni_mannheim.informatik.dws.winter.processing.Processable, de.uni_mannheim.informatik.dws.winter.processing.Function) */ @Override public <KeyType> Processable<Pair<RecordType,RecordType>> join( Processable<RecordType> dataset2, Function<KeyType, RecordType> joinKeyGenerator) { return join(dataset2, joinKeyGenerator, joinKeyGenerator); } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#join(de.uni_mannheim.informatik.dws.winter.processing.Processable, de.uni_mannheim.informatik.dws.winter.processing.Function, de.uni_mannheim.informatik.dws.winter.processing.Function) */ @Override public <KeyType, RecordType2> Processable<Pair<RecordType,RecordType2>> join( Processable<RecordType2> dataset2, Function<KeyType, RecordType> joinKeyGenerator1, Function<KeyType, RecordType2> joinKeyGenerator2) { final Map<KeyType, List<RecordType>> joinKeys1 = hashRecords(this, joinKeyGenerator1); final Map<KeyType, List<RecordType2>> joinKeys2 = hashRecords(dataset2, joinKeyGenerator2); Processable<Pair<RecordType, RecordType2>> result = createProcessableFromCollection(joinKeys1.keySet()).map(new RecordMapper<KeyType, Pair<RecordType, RecordType2>>() { private static final long serialVersionUID = 1L; @Override public void mapRecord(KeyType key1, DataIterator<Pair<RecordType, RecordType2>> resultCollector) { List<RecordType> block = joinKeys1.get(key1); List<RecordType2> block2 = joinKeys2.get(key1); if(block2!=null) { for(RecordType r1 : block) { for(RecordType2 r2 : block2) { resultCollector.next(new Pair<>(r1, r2)); } } } } }); return result; } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#leftJoin(de.uni_mannheim.informatik.dws.winter.processing.Processable, de.uni_mannheim.informatik.dws.winter.processing.Function) */ @Override public <KeyType> Processable<Pair<RecordType,RecordType>> leftJoin( Processable<RecordType> dataset2, Function<KeyType, RecordType> joinKeyGenerator) { return leftJoin(dataset2, joinKeyGenerator, joinKeyGenerator); } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#leftJoin(de.uni_mannheim.informatik.dws.winter.processing.Processable, de.uni_mannheim.informatik.dws.winter.processing.Function, de.uni_mannheim.informatik.dws.winter.processing.Function) */ @Override public <KeyType, RecordType2> Processable<Pair<RecordType,RecordType2>> leftJoin( Processable<RecordType2> dataset2, Function<KeyType, RecordType> joinKeyGenerator1, Function<KeyType, RecordType2> joinKeyGenerator2) { Processable<Pair<RecordType, RecordType2>> result = createProcessable((Pair<RecordType, RecordType2>)null); Map<KeyType, List<RecordType>> joinKeys1 = hashRecords(this, joinKeyGenerator1); Map<KeyType, List<RecordType2>> joinKeys2 = hashRecords(dataset2, joinKeyGenerator2); for(KeyType key1 : joinKeys1.keySet()) { List<RecordType> block = joinKeys1.get(key1); List<RecordType2> block2 = joinKeys2.get(key1); for(RecordType r1 : block) { if(block2!=null) { for(RecordType2 r2 : block2) { result.add(new Pair<>(r1, r2)); } } else { result.add(new Pair<>(r1, (RecordType2)null)); } } } return result; } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#groupRecords(de.uni_mannheim.informatik.dws.winter.processing.RecordKeyValueMapper) */ @Override public <KeyType, OutputRecordType> Processable<Group<KeyType, OutputRecordType>> group( RecordKeyValueMapper<KeyType, RecordType, OutputRecordType> groupBy) { GroupCollector<KeyType, OutputRecordType> groupCollector = new GroupCollector<>(); groupCollector.initialise(); for(RecordType r : get()) { groupBy.mapRecordToKey(r, groupCollector); } groupCollector.finalise(); return groupCollector.getResult(); } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#aggregateRecords(de.uni_mannheim.informatik.dws.winter.processing.RecordKeyValueMapper, de.uni_mannheim.informatik.dws.winter.processing.DataAggregator) */ @Override public <KeyType, OutputRecordType, ResultType> Processable<Pair<KeyType, ResultType>> aggregate( RecordKeyValueMapper<KeyType, RecordType, OutputRecordType> groupBy, DataAggregator<KeyType, OutputRecordType, ResultType> aggregator) { AggregateCollector<KeyType, OutputRecordType, ResultType> aggregateCollector = new AggregateCollector<>(); aggregateCollector.setAggregator(aggregator); aggregateCollector.initialise(); for(RecordType r : get()) { groupBy.mapRecordToKey(r, aggregateCollector); } aggregateCollector.finalise(); return aggregateCollector.getAggregationResult(); } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#sort(de.uni_mannheim.informatik.dws.winter.processing.Function) */ @Override public <KeyType extends Comparable<KeyType>> Processable<RecordType> sort(Function<KeyType, RecordType> sortingKey) { return sort(sortingKey, true); } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#sort(de.uni_mannheim.informatik.dws.winter.processing.Function, boolean) */ @Override public <KeyType extends Comparable<KeyType>> Processable<RecordType> sort( final Function<KeyType, RecordType> sortingKey, final boolean ascending) { ArrayList<RecordType> list = new ArrayList<>(get()); Collections.sort(list, new Comparator<RecordType>() { @Override public int compare(RecordType o1, RecordType o2) { return (ascending ? 1 : -1) * sortingKey.execute(o1).compareTo(sortingKey.execute(o2)); } }); Processable<RecordType> result = new ProcessableCollection<>(); for(RecordType elem : list) { result.add(elem); } return result; } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#filter(de.uni_mannheim.informatik.dws.winter.processing.Function) */ @Override public Processable<RecordType> where(Function<Boolean, RecordType> criteria) { Processable<RecordType> result = createProcessable((RecordType)null); for(RecordType element : get()) { if(criteria.execute(element)) { result.add(element); } } return result; } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#coGroup(de.uni_mannheim.informatik.dws.winter.processing.Processable, de.uni_mannheim.informatik.dws.winter.processing.Function, de.uni_mannheim.informatik.dws.winter.processing.Function, de.uni_mannheim.informatik.dws.winter.processing.RecordMapper) */ @Override public <KeyType, RecordType2, OutputRecordType> Processable<OutputRecordType> coGroup( Processable<RecordType2> data2, final Function<KeyType, RecordType> groupingKeyGenerator1, final Function<KeyType, RecordType2> groupingKeyGenerator2, final RecordMapper<Pair<Iterable<RecordType>, Iterable<RecordType2>>, OutputRecordType> resultMapper) { Processable<Group<KeyType, RecordType>> group1 = group(new RecordKeyValueMapper<KeyType, RecordType, RecordType>() { private static final long serialVersionUID = 1L; @Override public void mapRecordToKey(RecordType record, DataIterator<Pair<KeyType, RecordType>> resultCollector) { resultCollector.next(new Pair<KeyType, RecordType>(groupingKeyGenerator1.execute(record), record)); } }); Processable<Group<KeyType, RecordType2>> group2 = data2.group(new RecordKeyValueMapper<KeyType, RecordType2, RecordType2>() { private static final long serialVersionUID = 1L; @Override public void mapRecordToKey(RecordType2 record, DataIterator<Pair<KeyType, RecordType2>> resultCollector) { resultCollector.next(new Pair<KeyType, RecordType2>(groupingKeyGenerator2.execute(record), record)); } }); Processable<Pair<Group<KeyType, RecordType>, Group<KeyType, RecordType2>>> joined = group1.join(group2, new Function<KeyType, Group<KeyType, RecordType>>() { /** * */ private static final long serialVersionUID = 1L; @Override public KeyType execute(Group<KeyType, RecordType> input) { return input.getKey(); } },new Function<KeyType, Group<KeyType, RecordType2>>() { /** * */ private static final long serialVersionUID = 1L; @Override public KeyType execute(Group<KeyType, RecordType2> input) { return (KeyType)input.getKey(); } }); return joined.map(new RecordMapper<Pair<Group<KeyType, RecordType>, Group<KeyType, RecordType2>>, OutputRecordType>() { /** * */ private static final long serialVersionUID = 1L; @Override public void mapRecord(Pair<Group<KeyType, RecordType>, Group<KeyType, RecordType2>> record, DataIterator<OutputRecordType> resultCollector) { resultMapper.mapRecord(new Pair<Iterable<RecordType>, Iterable<RecordType2>>(record.getFirst().getRecords().get(), record.getSecond().getRecords().get()), resultCollector); } }); } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#append(de.uni_mannheim.informatik.dws.winter.processing.Processable) */ @Override public Processable<RecordType> append(Processable<RecordType> data2) { Processable<RecordType> result = createProcessable((RecordType)null); for(RecordType r : get()) { result.add(r); } if(data2!=null) { for(RecordType r : data2.get()) { result.add(r); } } return result; } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#distinct() */ @Override public Processable<RecordType> distinct() { return createProcessableFromCollection(new ArrayList<>(new HashSet<>(get()))); } /* * (non-Javadoc) * @see de.uni_mannheim.informatik.dws.winter.processing.Processable#take(int) */ @Override public Processable<RecordType> take(int numberOfRecords) { Processable<RecordType> result = createProcessable((RecordType)null); Iterator<RecordType> it = get().iterator(); while(it.hasNext() && result.size() < numberOfRecords) { result.add(it.next()); } return result; } }
ProcessableCollection.sort no longer changes the type of processable the type was always changed to ProcessableCollection, even if called from a sub class, such as ParallelProcessableCollection
src/main/java/de/uni_mannheim/informatik/dws/winter/processing/ProcessableCollection.java
ProcessableCollection.sort no longer changes the type of processable
<ide><path>rc/main/java/de/uni_mannheim/informatik/dws/winter/processing/ProcessableCollection.java <ide> } <ide> }); <ide> <del> Processable<RecordType> result = new ProcessableCollection<>(); <add> Processable<RecordType> result = createProcessable((RecordType)null); <ide> for(RecordType elem : list) { <ide> result.add(elem); <ide> }
Java
apache-2.0
47550e6b0d300279a732de629d7d074b39cf6877
0
ceylon/ceylon-js,ceylon/ceylon-js,ceylon/ceylon-js
package com.redhat.ceylon.compiler.js; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import com.redhat.ceylon.compiler.js.GenerateJsVisitor.PrototypeInitCallback; import com.redhat.ceylon.compiler.js.GenerateJsVisitor.SuperVisitor; import com.redhat.ceylon.compiler.js.util.TypeUtils; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Tree.StaticType; import com.redhat.ceylon.model.typechecker.model.Class; import com.redhat.ceylon.model.typechecker.model.ClassOrInterface; import com.redhat.ceylon.model.typechecker.model.Constructor; import com.redhat.ceylon.model.typechecker.model.Declaration; import com.redhat.ceylon.model.typechecker.model.Interface; import com.redhat.ceylon.model.typechecker.model.Method; import com.redhat.ceylon.model.typechecker.model.ParameterList; import com.redhat.ceylon.model.typechecker.model.ProducedType; import com.redhat.ceylon.model.typechecker.model.Scope; import com.redhat.ceylon.model.typechecker.model.TypeDeclaration; import com.redhat.ceylon.model.typechecker.model.TypeParameter; import com.redhat.ceylon.model.typechecker.model.TypedDeclaration; import com.redhat.ceylon.model.typechecker.model.Util; import com.redhat.ceylon.model.typechecker.model.Value; public class TypeGenerator { private static final ErrorVisitor errVisitor = new ErrorVisitor(); /** Generates a function to initialize the specified type. */ static void initializeType(final Node type, final GenerateJsVisitor gen) { Tree.ExtendedType extendedType = null; Tree.SatisfiedTypes satisfiedTypes = null; final ClassOrInterface decl; final List<Tree.Statement> stmts; if (type instanceof Tree.ClassDefinition) { Tree.ClassDefinition classDef = (Tree.ClassDefinition) type; extendedType = classDef.getExtendedType(); satisfiedTypes = classDef.getSatisfiedTypes(); decl = classDef.getDeclarationModel(); stmts = classDef.getClassBody().getStatements(); } else if (type instanceof Tree.InterfaceDefinition) { satisfiedTypes = ((Tree.InterfaceDefinition) type).getSatisfiedTypes(); decl = ((Tree.InterfaceDefinition) type).getDeclarationModel(); stmts = ((Tree.InterfaceDefinition) type).getInterfaceBody().getStatements(); } else if (type instanceof Tree.ObjectDefinition) { Tree.ObjectDefinition objectDef = (Tree.ObjectDefinition) type; extendedType = objectDef.getExtendedType(); satisfiedTypes = objectDef.getSatisfiedTypes(); decl = (ClassOrInterface)objectDef.getDeclarationModel().getTypeDeclaration(); stmts = objectDef.getClassBody().getStatements(); } else if (type instanceof Tree.ObjectExpression) { Tree.ObjectExpression objectDef = (Tree.ObjectExpression) type; extendedType = objectDef.getExtendedType(); satisfiedTypes = objectDef.getSatisfiedTypes(); decl = (ClassOrInterface)objectDef.getAnonymousClass(); stmts = objectDef.getClassBody().getStatements(); } else { stmts = null; decl = null; } final PrototypeInitCallback callback = new PrototypeInitCallback() { @Override public void addToPrototypeCallback() { if (decl != null) { gen.addToPrototype(type, decl, stmts); } } }; typeInitialization(extendedType, satisfiedTypes, decl, callback, gen); } /** This is now the main method to generate the type initialization code. * @param extendedType The type that is being extended. * @param satisfiedTypes The types satisfied by the type being initialized. * @param d The declaration for the type being initialized * @param callback A callback to add something more to the type initializer in prototype style. */ static void typeInitialization(final Tree.ExtendedType extendedType, final Tree.SatisfiedTypes satisfiedTypes, final ClassOrInterface d, PrototypeInitCallback callback, final GenerateJsVisitor gen) { final boolean isInterface = d instanceof com.redhat.ceylon.model.typechecker.model.Interface; String initFuncName = isInterface ? "initTypeProtoI" : "initTypeProto"; final String typename = gen.getNames().name(d); final String initname; if (d.isAnonymous()) { final String _initname = gen.getNames().objectName(d); if (d.isToplevel()) { initname = "$init$" + _initname.substring(0, _initname.length()-2); } else { initname = "$init$" + _initname; } } else { initname = "$init$" + typename; } gen.out("function ", initname, "()"); gen.beginBlock(); gen.out("if(", typename, ".$$===undefined)"); gen.beginBlock(); boolean genIniter = true; if (TypeUtils.isNativeExternal(d)) { //Allow native types to have their own initialization code genIniter = !gen.stitchInitializer(d); } if (genIniter) { final String qns = TypeUtils.qualifiedNameSkippingMethods(d); gen.out(gen.getClAlias(), initFuncName, "(", typename, ",'", qns, "'"); final List<Tree.StaticType> supers = satisfiedTypes == null ? Collections.<Tree.StaticType>emptyList() : new ArrayList<Tree.StaticType>(satisfiedTypes.getTypes().size()+1); if (extendedType != null) { if (satisfiedTypes == null) { String fname = gen.typeFunctionName(extendedType.getType(), !extendedType.getType().getDeclarationModel().isMember(), d); gen.out(",", fname); } else { supers.add(extendedType.getType()); } } else if (!isInterface) { gen.out(",", gen.getClAlias(), "Basic"); } if (satisfiedTypes != null) { supers.addAll(satisfiedTypes.getTypes()); Collections.sort(supers, new StaticTypeComparator()); for (Tree.StaticType satType : supers) { String fname = gen.typeFunctionName(satType, true, d); gen.out(",", fname); } } gen.out(");"); } //Add ref to outer type if (d.isMember()) { StringBuilder containers = new StringBuilder(); Scope _d2 = d; while (_d2 instanceof ClassOrInterface) { if (containers.length() > 0) { containers.insert(0, '.'); } containers.insert(0, gen.getNames().name((Declaration)_d2)); _d2 = _d2.getContainer(); } gen.endLine(); gen.out(containers.toString(), "=", typename, ";"); } //The class definition needs to be inside the init function if we want forwards decls to work in prototype style if (gen.opts.isOptimize()) { gen.endLine(); callback.addToPrototypeCallback(); } gen.endBlockNewLine(); gen.out("return ", typename, ";"); gen.endBlockNewLine(); //If it's nested, share the init function if (gen.outerSelf(d)) { gen.out(".", initname, "=", initname); gen.endLine(true); } gen.out(initname, "()"); gen.endLine(true); } static void interfaceDefinition(final Tree.InterfaceDefinition that, final GenerateJsVisitor gen) { //Don't even bother with nodes that have errors if (errVisitor.hasErrors(that))return; final Interface d = that.getDeclarationModel(); //If it's inside a dynamic interface, don't generate anything if (d.isClassOrInterfaceMember() && ((ClassOrInterface)d.getContainer()).isDynamic())return; gen.comment(that); gen.out(GenerateJsVisitor.function, gen.getNames().name(d)); final boolean withTargs = generateParameters(that.getTypeParameterList(), null, d, gen); gen.beginBlock(); //declareSelf(d); gen.referenceOuter(d); final List<Declaration> superDecs = new ArrayList<Declaration>(3); if (!gen.opts.isOptimize()) { new SuperVisitor(superDecs).visit(that.getInterfaceBody()); } final Tree.SatisfiedTypes sats = that.getSatisfiedTypes(); if (withTargs) { gen.out(gen.getClAlias(), "set_type_args(", gen.getNames().self(d), ",$$targs$$,", gen.getNames().name(d), ")"); gen.endLine(true); } callSupertypes(sats == null ? null : sats.getTypes(), null, d, that, superDecs, null, null, gen); if (!d.isToplevel() && d.getContainer() instanceof Method && !((Method)d.getContainer()).getTypeParameters().isEmpty()) { gen.out(gen.getClAlias(), "set_type_args(", gen.getNames().self(d), ",$$$mptypes,", gen.getNames().name(d), ")"); gen.endLine(true); } that.getInterfaceBody().visit(gen); //returnSelf(d); gen.endBlockNewLine(); if (d.isDynamic()) { //Add the list of expected members here final List<Declaration> members = d.getMembers(); gen.out(gen.getNames().name(d), ".dynmem$=["); if (members.isEmpty()) { gen.out("];"); } else { gen.out("'"); boolean first = true; for (Declaration m : members) { if (first)first=false;else gen.out("','"); gen.out(gen.getNames().name(m)); } gen.out("'];"); } } //Add reference to metamodel gen.out(gen.getNames().name(d), ".$crtmm$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), gen); gen.endLine(true); gen.share(d); initializeType(that, gen); } /** Outputs the parameter list of the type's constructor, including surrounding parens. * Returns true if the type has type parameters. */ static boolean generateParameters(final Tree.TypeParameterList tparms, final Tree.ParameterList plist, final TypeDeclaration d, final GenerateJsVisitor gen) { gen.out("("); final boolean withTargs = tparms != null && !tparms.getTypeParameterDeclarations().isEmpty(); if (plist != null) { for (Tree.Parameter p: plist.getParameters()) { p.visit(gen); gen.out(","); } } if (withTargs) { gen.out("$$targs$$,"); } gen.out(gen.getNames().self(d), ")"); return withTargs; } static void classDefinition(final Tree.ClassDefinition that, final GenerateJsVisitor gen) { //Don't even bother with nodes that have errors if (errVisitor.hasErrors(that))return; final Class d = that.getDeclarationModel(); //If it's inside a dynamic interface, don't generate anything if (d.isClassOrInterfaceMember() && ((ClassOrInterface)d.getContainer()).isDynamic())return; final Tree.ParameterList plist = that.getParameterList(); final List<Tree.Constructor> constructors; final Tree.SatisfiedTypes sats = that.getSatisfiedTypes(); //Find the constructors, if any Tree.Constructor defconstr = null; if (d.hasConstructors()) { constructors = new ArrayList<>(3); for (Tree.Statement st : that.getClassBody().getStatements()) { if (st instanceof Tree.Constructor) { Tree.Constructor constr = (Tree.Constructor)st; constructors.add(constr); if (constr.getDeclarationModel().getName() == null) { defconstr = constr; } } } } else { constructors = Collections.emptyList(); } gen.comment(that); if (gen.shouldStitch(d)) { boolean bye = false; if (d.hasConstructors() && defconstr == null) { gen.out(GenerateJsVisitor.function, gen.getNames().name(d)); gen.out("(){"); gen.generateThrow("Exception", d.getQualifiedNameString() + " has no default constructor.", that); gen.out(";}"); gen.endLine(); } if (gen.stitchNative(d, that)) { if (d.isShared()) { gen.share(d); } initializeType(that, gen); bye = true; } if (d.hasConstructors()) { for (Tree.Constructor cnstr : constructors) { classConstructor(cnstr, that, constructors, gen); } } if (bye)return; } gen.out(GenerateJsVisitor.function, gen.getNames().name(d)); //If there's a default constructor, create a different function with this code if (d.hasConstructors()) { if (defconstr == null) { gen.out("(){"); gen.generateThrow("Exception", d.getQualifiedNameString() + " has no default constructor.", that); gen.out(";}"); gen.endLine(); gen.out(GenerateJsVisitor.function, gen.getNames().name(d)); } gen.out("$$c"); } final boolean withTargs = generateParameters(that.getTypeParameterList(), plist, d, gen); gen.beginBlock(); if (!d.hasConstructors()) { //This takes care of top-level attributes defined before the class definition gen.out("$init$", gen.getNames().name(d), "();"); gen.endLine(); gen.declareSelf(d); gen.referenceOuter(d); } final String me = gen.getNames().self(d); if (withTargs) { gen.out(gen.getClAlias(), "set_type_args(", me, ",$$targs$$);"); gen.endLine(); } else { //Check if any of the satisfied types have type arguments if (sats != null) { for(Tree.StaticType sat : sats.getTypes()) { boolean first = true; Map<TypeParameter,ProducedType> targs = sat.getTypeModel().getTypeArguments(); if (targs != null && !targs.isEmpty()) { if (first) { gen.out(me, ".$$targs$$="); TypeUtils.printTypeArguments(that, targs, gen, false, null); gen.endLine(true); first = false; } else { gen.out("/*TODO: more type arguments*/"); } } } } } if (!d.isToplevel() && d.getContainer() instanceof Method && !((Method)d.getContainer()).getTypeParameters().isEmpty()) { gen.out(gen.getClAlias(), "set_type_args(", me, ",$$$mptypes)"); gen.endLine(true); } if (plist != null) { gen.initParameters(plist, d, null); } final List<Declaration> superDecs = new ArrayList<Declaration>(3); if (!gen.opts.isOptimize()) { new SuperVisitor(superDecs).visit(that.getClassBody()); } final Tree.ExtendedType extendedType = that.getExtendedType(); callSupertypes(sats == null ? null : sats.getTypes(), extendedType == null ? null : extendedType.getType(), d, that, superDecs, extendedType == null ? null : extendedType.getInvocationExpression(), extendedType == null ? null : d.getExtendedTypeDeclaration().getParameterList(), gen); if (!gen.opts.isOptimize() && plist != null) { //Fix #231 for lexical scope for (Tree.Parameter p : plist.getParameters()) { if (!p.getParameterModel().isHidden()){ gen.generateAttributeForParameter(that, d, p.getParameterModel()); } } } if (!d.hasConstructors()) { if (TypeUtils.isNativeExternal(d)) { gen.stitchConstructorHelper(that, "_cons_before"); } gen.visitStatements(that.getClassBody().getStatements()); if (d.isNative()) { gen.stitchConstructorHelper(that, "_cons_after"); } gen.out("return ", me, ";"); } gen.endBlockNewLine(); if (defconstr != null) { //Define a function as the class and call the default constructor in there String _this = "undefined"; if (!d.isToplevel()) { final ClassOrInterface coi = Util.getContainingClassOrInterface(d.getContainer()); if (coi != null) { if (d.isClassOrInterfaceMember()) { _this = "this"; } else { _this = gen.getNames().self(coi); } } } gen.out(GenerateJsVisitor.function, gen.getNames().name(d), "(){return ", gen.getNames().name(d), "_", gen.getNames().name(defconstr.getDeclarationModel()), ".apply(", _this, ",arguments);}"); gen.endLine(); } for (Tree.Constructor cnstr : constructors) { classConstructor(cnstr, that, constructors, gen); } //Add reference to metamodel gen.out(gen.getNames().name(d), ".$crtmm$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), gen); gen.endLine(true); gen.share(d); initializeType(that, gen); if (d.isSerializable()) { SerializationHelper.addDeserializer(that, d, gen); } } static void callSuperclass(final Tree.SimpleType extendedType, final Tree.InvocationExpression invocation, final Class d, final ParameterList plist, final Node that, final boolean pseudoAbstractConstructor, final List<Declaration> superDecs, final GenerateJsVisitor gen) { TypeDeclaration typeDecl = extendedType.getDeclarationModel(); if (invocation != null) { Tree.PositionalArgumentList argList = invocation.getPositionalArgumentList(); final String qpath; if (typeDecl instanceof Constructor) { final String path = gen.qualifiedPath(that, (TypeDeclaration)typeDecl.getContainer(), false); if (path.isEmpty()) { qpath = gen.getNames().name((TypeDeclaration)typeDecl.getContainer()); } else { qpath = path + "." + gen.getNames().name((TypeDeclaration)typeDecl.getContainer()); } } else { qpath = gen.qualifiedPath(that, typeDecl, false); } if (pseudoAbstractConstructor) { if (typeDecl instanceof Constructor) { gen.out(gen.memberAccessBase(extendedType, typeDecl, false, qpath), "$$a("); } else { gen.out(gen.memberAccessBase(extendedType, typeDecl, false, qpath), "_$c$$$a("); } } else { gen.out(gen.memberAccessBase(extendedType, typeDecl, false, qpath), (gen.opts.isOptimize() && (gen.getSuperMemberScope(extendedType) != null)) ? ".call(this," : "("); } gen.getInvoker().generatePositionalArguments(invocation.getPrimary(), argList, argList.getPositionalArguments(), false, false); if (argList.getPositionalArguments().size() > 0) { gen.out(","); } //There may be defaulted args we must pass as undefined if (plist != null && plist.getParameters().size() > argList.getPositionalArguments().size()) { for (int i = argList.getPositionalArguments().size(); i < plist.getParameters().size(); i++) { com.redhat.ceylon.model.typechecker.model.Parameter p = plist.getParameters().get(i); if (p.isSequenced()) { gen.out(gen.getClAlias(), "empty(),"); } else { gen.out("undefined,"); } } } //If the supertype has type arguments, add them to the call if (typeDecl.getTypeParameters() != null && !typeDecl.getTypeParameters().isEmpty()) { List<ProducedType> typeArgs = null; if (extendedType.getTypeArgumentList() != null) { typeArgs = extendedType.getTypeArgumentList().getTypeModels(); } TypeUtils.printTypeArguments(that, TypeUtils.matchTypeParametersWithArguments(typeDecl.getTypeParameters(), typeArgs), gen, false, null); gen.out(","); } if (typeDecl instanceof Constructor && ((Class)typeDecl.getContainer()).getTypeParameters()!=null && !((Class)typeDecl.getContainer()).getTypeParameters().isEmpty()) { gen.out("$$targs$$,"); } gen.out(gen.getNames().self(d), ")"); gen.endLine(true); } copySuperMembers(typeDecl, superDecs, d, gen); } static void callSupertypes(final List<Tree.StaticType> sats, final Tree.SimpleType supertype, final ClassOrInterface d, final Node that, final List<Declaration> superDecs, final Tree.InvocationExpression invoke, final ParameterList plist, final GenerateJsVisitor gen) { if (sats != null) { final ArrayList<Tree.StaticType> supers = new ArrayList<>(sats.size()+1); supers.addAll(sats); if (supertype != null) { supers.add(supertype); } Collections.sort(supers, new StaticTypeComparator()); HashSet<String> myTypeArgs = new HashSet<>(); for (TypeParameter tp : d.getTypeParameters()) { myTypeArgs.add(tp.getName()); } for (Tree.StaticType st: supers) { if (st == supertype) { callSuperclass(supertype, invoke, (Class)d, plist, that, false, superDecs, gen); } else { TypeDeclaration typeDecl = st.getTypeModel().getDeclaration(); gen.qualify(that, typeDecl); gen.out(gen.getNames().name((ClassOrInterface)typeDecl), "("); if (typeDecl.getTypeParameters() != null && !typeDecl.getTypeParameters().isEmpty()) { TypeUtils.printTypeArguments(that, st.getTypeModel().getTypeArguments(), gen, d.isToplevel(), null); gen.out(","); } gen.out(gen.getNames().self(d), ")"); gen.endLine(true); copySuperMembers(typeDecl, superDecs, d, gen); } } } else if (supertype != null) { callSuperclass(supertype, invoke, (Class)d, plist, that, false, superDecs, gen); } } private static void copySuperMembers(final TypeDeclaration typeDecl, final List<Declaration> decs, final ClassOrInterface d, final GenerateJsVisitor gen) { if (!gen.opts.isOptimize() && decs != null) { for (Declaration dec: decs) { if (!typeDecl.isMember(dec)) { continue; } String suffix = gen.getNames().scopeSuffix(dec.getContainer()); if (dec instanceof Value && ((Value)dec).isTransient()) { superGetterRef(dec,d,suffix, gen); if (((Value) dec).isVariable()) { superSetterRef(dec,d,suffix, gen); } } else { gen.out(gen.getNames().self(d), ".", gen.getNames().name(dec), suffix, "=", gen.getNames().self(d), ".", gen.getNames().name(dec)); gen.endLine(true); } } } } private static void superGetterRef(final Declaration d, final ClassOrInterface sub, final String parentSuffix, final GenerateJsVisitor gen) { if (AttributeGenerator.defineAsProperty(d)) { gen.out(gen.getClAlias(), "copySuperAttr(", gen.getNames().self(sub), ",'", gen.getNames().name(d), "','", parentSuffix, "')"); } else { gen.out(gen.getNames().self(sub), ".", gen.getNames().getter(d, false), parentSuffix, "=", gen.getNames().self(sub), ".", gen.getNames().getter(d, false)); } gen.endLine(true); } private static void superSetterRef(final Declaration d, final ClassOrInterface sub, final String parentSuffix, final GenerateJsVisitor gen) { if (!AttributeGenerator.defineAsProperty(d)) { gen.out(gen.getNames().self(sub), ".", gen.getNames().setter(d), parentSuffix, "=", gen.getNames().self(sub), ".", gen.getNames().setter(d)); gen.endLine(true); } } public static class StaticTypeComparator implements Comparator<Tree.StaticType> { @Override public int compare(StaticType o1, StaticType o2) { final ProducedType t1 = o1.getTypeModel(); final ProducedType t2 = o2.getTypeModel(); if (t1.isUnknown()) { return t2.isUnknown() ? 0 : -1; } if (t2.isUnknown()) { return t1.isUnknown() ? 0 : -1; } if (t1.isSubtypeOf(t2)) { return 1; } if (t2.isSubtypeOf(t1)) { return -1; } //Check the members for (Declaration d : t1.getDeclaration().getMembers()) { if (d instanceof TypedDeclaration || d instanceof ClassOrInterface) { Declaration d2 = t2.getDeclaration().getMember(d.getName(), null, false); if (d2 != null) { final Declaration dd2 = Util.getContainingDeclaration(d2); if (dd2 instanceof TypeDeclaration && t1.getDeclaration().inherits((TypeDeclaration)dd2)) { return 1; } } } } for (Declaration d : t2.getDeclaration().getMembers()) { if (d instanceof TypedDeclaration || d instanceof ClassOrInterface) { Declaration d2 = t1.getDeclaration().getMember(d.getName(), null, false); if (d2 != null) { final Declaration dd2 = Util.getContainingDeclaration(d2); if (dd2 instanceof TypeDeclaration && t2.getDeclaration().inherits((TypeDeclaration)dd2)) { return -1; } } } } return 0; } } static void defineObject(final Node that, final Value d, final Tree.SatisfiedTypes sats, final Tree.ExtendedType superType, final Tree.ClassBody body, final Tree.AnnotationList annots, final GenerateJsVisitor gen) { final boolean addToPrototype = gen.opts.isOptimize() && d != null && d.isClassOrInterfaceMember(); final boolean isObjExpr = that instanceof Tree.ObjectExpression; final Class c = (Class)(isObjExpr ? ((Tree.ObjectExpression)that).getAnonymousClass() : d.getTypeDeclaration()); final String className = gen.getNames().name(c); final String objectName = gen.getNames().name(d); final String selfName = gen.getNames().self(c); gen.out(GenerateJsVisitor.function, className); Map<TypeParameter, ProducedType> targs=new HashMap<TypeParameter, ProducedType>(); if (sats != null) { for (StaticType st : sats.getTypes()) { Map<TypeParameter, ProducedType> stargs = st.getTypeModel().getTypeArguments(); if (stargs != null && !stargs.isEmpty()) { targs.putAll(stargs); } } } gen.out(targs.isEmpty()?"()":"($$targs$$)"); gen.beginBlock(); if (isObjExpr) { gen.out("var ", selfName, "=new ", className, ".$$;"); final ClassOrInterface coi = Util.getContainingClassOrInterface(c.getContainer()); if (coi != null) { gen.out(selfName, ".outer$=", gen.getNames().self(coi)); gen.endLine(true); } } else { if (c.isMember()) { gen.initSelf(that); } gen.instantiateSelf(c); gen.referenceOuter(c); } final List<Declaration> superDecs = new ArrayList<Declaration>(); if (!gen.opts.isOptimize()) { new SuperVisitor(superDecs).visit(body); } if (!targs.isEmpty()) { gen.out(selfName, ".$$targs$$=$$targs$$"); gen.endLine(true); } TypeGenerator.callSupertypes(sats == null ? null : sats.getTypes(), superType == null ? null : superType.getType(), c, that, superDecs, superType == null ? null : superType.getInvocationExpression(), superType == null ? null : c.getExtendedTypeDeclaration().getParameterList(), gen); body.visit(gen); gen.out("return ", selfName, ";"); gen.endBlock(); gen.out(";", className, ".$crtmm$="); TypeUtils.encodeForRuntime(that, c, gen); gen.endLine(true); TypeGenerator.initializeType(that, gen); final String objvar = (addToPrototype ? "this.":"")+gen.getNames().createTempVariable(); if (d != null && !addToPrototype) { gen.out("var ", objvar); //If it's a property, create the object here if (AttributeGenerator.defineAsProperty(d)) { gen.out("=", className, "("); if (!targs.isEmpty()) { TypeUtils.printTypeArguments(that, targs, gen, false, null); } gen.out(")"); } gen.endLine(true); } if (d != null && AttributeGenerator.defineAsProperty(d)) { gen.out(gen.getClAlias(), "atr$("); gen.outerSelf(d); gen.out(",'", objectName, "',function(){return "); if (addToPrototype) { gen.out("this.", gen.getNames().privateName(d)); } else { gen.out(objvar); } gen.out(";},undefined,"); TypeUtils.encodeForRuntime(d, annots, gen); gen.out(")"); gen.endLine(true); } else if (d != null) { final String objectGetterName = gen.getNames().getter(d, false); gen.out(GenerateJsVisitor.function, objectGetterName, "()"); gen.beginBlock(); //Create the object lazily final String oname = gen.getNames().objectName(c); gen.out("if(", objvar, "===", gen.getClAlias(), "INIT$)"); gen.generateThrow(gen.getClAlias()+"InitializationError", "Cyclic initialization trying to read the value of '" + d.getName() + "' before it was set", that); gen.endLine(true); gen.out("if(", objvar, "===undefined){", objvar, "=", gen.getClAlias(), "INIT$;", objvar, "=$init$", oname); if (!oname.endsWith("()")) { gen.out("()"); } gen.out("("); if (!targs.isEmpty()) { TypeUtils.printTypeArguments(that, targs, gen, false, null); } gen.out(");", objvar, ".$crtmm$=", objectGetterName, ".$crtmm$;}"); gen.endLine(); gen.out("return ", objvar, ";"); gen.endBlockNewLine(); if (addToPrototype || d.isShared()) { gen.outerSelf(d); gen.out(".", objectGetterName, "=", objectGetterName); gen.endLine(true); } if (!d.isToplevel()) { if(gen.outerSelf(d))gen.out("."); } gen.out(objectGetterName, ".$crtmm$="); TypeUtils.encodeForRuntime(d, annots, gen); gen.endLine(true); gen.out(gen.getNames().getter(c, true), "=", objectGetterName); gen.endLine(true); if (d.isToplevel()) { final String objectGetterNameMM = gen.getNames().getter(d, true); gen.out("ex$.", objectGetterNameMM, "=", objectGetterNameMM); gen.endLine(true); } } else if (that instanceof Tree.ObjectExpression) { gen.out("return ", className, "();"); } } static void objectDefinition(final Tree.ObjectDefinition that, final GenerateJsVisitor gen) { //Don't even bother with nodes that have errors if (errVisitor.hasErrors(that))return; gen.comment(that); defineObject(that, that.getDeclarationModel(), that.getSatisfiedTypes(), that.getExtendedType(), that.getClassBody(), that.getAnnotationList(), gen); //Objects defined inside methods need their init sections are exec'd if (!that.getDeclarationModel().isToplevel() && !that.getDeclarationModel().isClassOrInterfaceMember()) { gen.out(gen.getNames().objectName(that.getDeclarationModel()), "();"); } } static boolean localConstructorDelegation(final TypeDeclaration that, final List<Tree.Constructor> constructors) { if (that.isAbstract()) { return true; } for (Tree.Constructor cnst : constructors) { if (cnst.getDelegatedConstructor() != null) { final TypeDeclaration superdec = cnst.getDelegatedConstructor().getType().getDeclarationModel(); if (superdec instanceof Class && that.getName()==null) { //Default constructor return true; } else if (superdec.equals(that)) { return true; } } } return false; } static void classConstructor(final Tree.Constructor that, final Tree.ClassDefinition cdef, final List<Tree.Constructor> constructors, final GenerateJsVisitor gen) { gen.comment(that); Constructor d = that.getDeclarationModel(); final Class container = cdef.getDeclarationModel(); final String fullName = gen.getNames().name(container) + "_" + gen.getNames().name(d); if (!TypeUtils.isNativeExternal(d) || !gen.stitchNative(d, that)) { final Tree.DelegatedConstructor delcons = that.getDelegatedConstructor(); final TypeDeclaration superdec; final ParameterList superplist; final boolean pseudoAbstract; if (delcons == null) { superdec = null; superplist = null; pseudoAbstract = false; } else { superdec = delcons.getType().getDeclarationModel(); pseudoAbstract = superdec instanceof Class ? superdec==container : ((Constructor)superdec).getContainer()==container; superplist = superdec instanceof Class ? ((Class)superdec).getParameterList() : ((Constructor)superdec).getParameterLists().get(0); } gen.out("function ", fullName); boolean forceAbstract = localConstructorDelegation(that.getDeclarationModel(), constructors); if (forceAbstract) { gen.out("$$a"); } final boolean withTargs = generateParameters(cdef.getTypeParameterList(), that.getParameterList(), container, gen); final String me = gen.getNames().self(container); gen.beginBlock(); if (forceAbstract) { gen.initParameters(that.getParameterList(), container, null); if (delcons != null) { callSuperclass(delcons.getType(), delcons.getInvocationExpression(), container, superplist, that, false, null, gen); } gen.generateClassStatements(cdef, that, null, 1); gen.out("return ", me, ";"); gen.endBlockNewLine(true); gen.out("function ", fullName); generateParameters(cdef.getTypeParameterList(), that.getParameterList(), container, gen); gen.beginBlock(); } if (!d.isAbstract()) { gen.out("$init$", gen.getNames().name(container), "();"); gen.endLine(); gen.declareSelf(container); gen.referenceOuter(container); } gen.initParameters(that.getParameterList(), container, null); if (!d.isAbstract()) { //Call common initializer gen.out(gen.getNames().name(container), "$$c("); if (withTargs) { gen.out("$$targs$$,"); } gen.out(me, ");"); gen.endLine(); } if (forceAbstract) { gen.out(fullName, "$$a"); generateParameters(cdef.getTypeParameterList(), that.getParameterList(), container, gen); gen.endLine(true); } else if (delcons != null) { callSuperclass(delcons.getType(), delcons.getInvocationExpression(), container, superplist, that, pseudoAbstract, null, gen); } if (d.isNative()) { gen.stitchConstructorHelper(cdef, "_cons_before"); } if (forceAbstract) { gen.generateClassStatements(cdef, that, null, 2); } else if (pseudoAbstract) { //Pass the delegated constructor Tree.Constructor pseudo1 = null; if (superdec instanceof Class) { for (Tree.Constructor _cns : constructors) { if (_cns.getDeclarationModel().getName() == null) { pseudo1 = _cns; } } } else { for (Tree.Constructor _cns : constructors) { if (_cns.getDeclarationModel() == superdec) { pseudo1 = _cns; } } } gen.generateClassStatements(cdef, pseudo1, that, 2); } else { gen.generateClassStatements(cdef, that, null, 0); } if (d.isNative()) { gen.stitchConstructorHelper(cdef, "_cons_after"); } gen.out("return ", me, ";"); gen.endBlockNewLine(true); } //Add reference to metamodel gen.out(fullName, ".$crtmm$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), gen); gen.endLine(true); gen.out(gen.getNames().name(container), ".", fullName, "=", fullName); gen.endLine(true); if (gen.outerSelf(container)) { gen.out(".", fullName, "=", fullName); gen.endLine(true); } } }
src/main/java/com/redhat/ceylon/compiler/js/TypeGenerator.java
package com.redhat.ceylon.compiler.js; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import com.redhat.ceylon.compiler.js.GenerateJsVisitor.PrototypeInitCallback; import com.redhat.ceylon.compiler.js.GenerateJsVisitor.SuperVisitor; import com.redhat.ceylon.compiler.js.util.TypeUtils; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Tree.StaticType; import com.redhat.ceylon.model.typechecker.model.Class; import com.redhat.ceylon.model.typechecker.model.ClassOrInterface; import com.redhat.ceylon.model.typechecker.model.Constructor; import com.redhat.ceylon.model.typechecker.model.Declaration; import com.redhat.ceylon.model.typechecker.model.Generic; import com.redhat.ceylon.model.typechecker.model.Interface; import com.redhat.ceylon.model.typechecker.model.Method; import com.redhat.ceylon.model.typechecker.model.ParameterList; import com.redhat.ceylon.model.typechecker.model.ProducedType; import com.redhat.ceylon.model.typechecker.model.Scope; import com.redhat.ceylon.model.typechecker.model.TypeDeclaration; import com.redhat.ceylon.model.typechecker.model.TypeParameter; import com.redhat.ceylon.model.typechecker.model.TypedDeclaration; import com.redhat.ceylon.model.typechecker.model.Util; import com.redhat.ceylon.model.typechecker.model.Value; public class TypeGenerator { private static final ErrorVisitor errVisitor = new ErrorVisitor(); /** Generates a function to initialize the specified type. */ static void initializeType(final Node type, final GenerateJsVisitor gen) { Tree.ExtendedType extendedType = null; Tree.SatisfiedTypes satisfiedTypes = null; final ClassOrInterface decl; final List<Tree.Statement> stmts; if (type instanceof Tree.ClassDefinition) { Tree.ClassDefinition classDef = (Tree.ClassDefinition) type; extendedType = classDef.getExtendedType(); satisfiedTypes = classDef.getSatisfiedTypes(); decl = classDef.getDeclarationModel(); stmts = classDef.getClassBody().getStatements(); } else if (type instanceof Tree.InterfaceDefinition) { satisfiedTypes = ((Tree.InterfaceDefinition) type).getSatisfiedTypes(); decl = ((Tree.InterfaceDefinition) type).getDeclarationModel(); stmts = ((Tree.InterfaceDefinition) type).getInterfaceBody().getStatements(); } else if (type instanceof Tree.ObjectDefinition) { Tree.ObjectDefinition objectDef = (Tree.ObjectDefinition) type; extendedType = objectDef.getExtendedType(); satisfiedTypes = objectDef.getSatisfiedTypes(); decl = (ClassOrInterface)objectDef.getDeclarationModel().getTypeDeclaration(); stmts = objectDef.getClassBody().getStatements(); } else if (type instanceof Tree.ObjectExpression) { Tree.ObjectExpression objectDef = (Tree.ObjectExpression) type; extendedType = objectDef.getExtendedType(); satisfiedTypes = objectDef.getSatisfiedTypes(); decl = (ClassOrInterface)objectDef.getAnonymousClass(); stmts = objectDef.getClassBody().getStatements(); } else { stmts = null; decl = null; } final PrototypeInitCallback callback = new PrototypeInitCallback() { @Override public void addToPrototypeCallback() { if (decl != null) { gen.addToPrototype(type, decl, stmts); } } }; typeInitialization(extendedType, satisfiedTypes, decl, callback, gen); } /** This is now the main method to generate the type initialization code. * @param extendedType The type that is being extended. * @param satisfiedTypes The types satisfied by the type being initialized. * @param d The declaration for the type being initialized * @param callback A callback to add something more to the type initializer in prototype style. */ static void typeInitialization(final Tree.ExtendedType extendedType, final Tree.SatisfiedTypes satisfiedTypes, final ClassOrInterface d, PrototypeInitCallback callback, final GenerateJsVisitor gen) { final boolean isInterface = d instanceof com.redhat.ceylon.model.typechecker.model.Interface; String initFuncName = isInterface ? "initTypeProtoI" : "initTypeProto"; final String typename = gen.getNames().name(d); final String initname; if (d.isAnonymous()) { final String _initname = gen.getNames().objectName(d); if (d.isToplevel()) { initname = "$init$" + _initname.substring(0, _initname.length()-2); } else { initname = "$init$" + _initname; } } else { initname = "$init$" + typename; } gen.out("function ", initname, "()"); gen.beginBlock(); gen.out("if(", typename, ".$$===undefined)"); gen.beginBlock(); boolean genIniter = true; if (TypeUtils.isNativeExternal(d)) { //Allow native types to have their own initialization code genIniter = !gen.stitchInitializer(d); } if (genIniter) { final String qns = TypeUtils.qualifiedNameSkippingMethods(d); gen.out(gen.getClAlias(), initFuncName, "(", typename, ",'", qns, "'"); final List<Tree.StaticType> supers = satisfiedTypes == null ? Collections.<Tree.StaticType>emptyList() : new ArrayList<Tree.StaticType>(satisfiedTypes.getTypes().size()+1); if (extendedType != null) { if (satisfiedTypes == null) { String fname = gen.typeFunctionName(extendedType.getType(), !extendedType.getType().getDeclarationModel().isMember(), d); gen.out(",", fname); } else { supers.add(extendedType.getType()); } } else if (!isInterface) { gen.out(",", gen.getClAlias(), "Basic"); } if (satisfiedTypes != null) { supers.addAll(satisfiedTypes.getTypes()); Collections.sort(supers, new StaticTypeComparator()); for (Tree.StaticType satType : supers) { String fname = gen.typeFunctionName(satType, true, d); gen.out(",", fname); } } gen.out(");"); } //Add ref to outer type if (d.isMember()) { StringBuilder containers = new StringBuilder(); Scope _d2 = d; while (_d2 instanceof ClassOrInterface) { if (containers.length() > 0) { containers.insert(0, '.'); } containers.insert(0, gen.getNames().name((Declaration)_d2)); _d2 = _d2.getContainer(); } gen.endLine(); gen.out(containers.toString(), "=", typename, ";"); } //The class definition needs to be inside the init function if we want forwards decls to work in prototype style if (gen.opts.isOptimize()) { gen.endLine(); callback.addToPrototypeCallback(); } gen.endBlockNewLine(); gen.out("return ", typename, ";"); gen.endBlockNewLine(); //If it's nested, share the init function if (gen.outerSelf(d)) { gen.out(".", initname, "=", initname); gen.endLine(true); } gen.out(initname, "()"); gen.endLine(true); } static void interfaceDefinition(final Tree.InterfaceDefinition that, final GenerateJsVisitor gen) { //Don't even bother with nodes that have errors if (errVisitor.hasErrors(that))return; final Interface d = that.getDeclarationModel(); //If it's inside a dynamic interface, don't generate anything if (d.isClassOrInterfaceMember() && ((ClassOrInterface)d.getContainer()).isDynamic())return; gen.comment(that); gen.out(GenerateJsVisitor.function, gen.getNames().name(d)); final boolean withTargs = generateParameters(that.getTypeParameterList(), null, d, gen); gen.beginBlock(); //declareSelf(d); gen.referenceOuter(d); final List<Declaration> superDecs = new ArrayList<Declaration>(3); if (!gen.opts.isOptimize()) { new SuperVisitor(superDecs).visit(that.getInterfaceBody()); } final Tree.SatisfiedTypes sats = that.getSatisfiedTypes(); if (withTargs) { gen.out(gen.getClAlias(), "set_type_args(", gen.getNames().self(d), ",$$targs$$,", gen.getNames().name(d), ")"); gen.endLine(true); } callSupertypes(sats == null ? null : sats.getTypes(), null, d, that, superDecs, null, null, gen); if (!d.isToplevel() && d.getContainer() instanceof Method && !((Method)d.getContainer()).getTypeParameters().isEmpty()) { gen.out(gen.getClAlias(), "set_type_args(", gen.getNames().self(d), ",$$$mptypes,", gen.getNames().name(d), ")"); gen.endLine(true); } that.getInterfaceBody().visit(gen); //returnSelf(d); gen.endBlockNewLine(); if (d.isDynamic()) { //Add the list of expected members here final List<Declaration> members = d.getMembers(); gen.out(gen.getNames().name(d), ".dynmem$=["); if (members.isEmpty()) { gen.out("];"); } else { gen.out("'"); boolean first = true; for (Declaration m : members) { if (first)first=false;else gen.out("','"); gen.out(gen.getNames().name(m)); } gen.out("'];"); } } //Add reference to metamodel gen.out(gen.getNames().name(d), ".$crtmm$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), gen); gen.endLine(true); gen.share(d); initializeType(that, gen); } /** Outputs the parameter list of the type's constructor, including surrounding parens. * Returns true if the type has type parameters. */ static boolean generateParameters(final Tree.TypeParameterList tparms, final Tree.ParameterList plist, final TypeDeclaration d, final GenerateJsVisitor gen) { gen.out("("); final boolean withTargs = tparms != null && !tparms.getTypeParameterDeclarations().isEmpty(); if (plist != null) { for (Tree.Parameter p: plist.getParameters()) { p.visit(gen); gen.out(","); } } if (withTargs) { gen.out("$$targs$$,"); } gen.out(gen.getNames().self(d), ")"); return withTargs; } static void classDefinition(final Tree.ClassDefinition that, final GenerateJsVisitor gen) { //Don't even bother with nodes that have errors if (errVisitor.hasErrors(that))return; final Class d = that.getDeclarationModel(); //If it's inside a dynamic interface, don't generate anything if (d.isClassOrInterfaceMember() && ((ClassOrInterface)d.getContainer()).isDynamic())return; final Tree.ParameterList plist = that.getParameterList(); final List<Tree.Constructor> constructors; final Tree.SatisfiedTypes sats = that.getSatisfiedTypes(); //Find the constructors, if any Tree.Constructor defconstr = null; if (d.hasConstructors()) { constructors = new ArrayList<>(3); for (Tree.Statement st : that.getClassBody().getStatements()) { if (st instanceof Tree.Constructor) { Tree.Constructor constr = (Tree.Constructor)st; constructors.add(constr); if (constr.getDeclarationModel().getName() == null) { defconstr = constr; } } } } else { constructors = Collections.emptyList(); } gen.comment(that); if (gen.shouldStitch(d)) { boolean bye = false; if (d.hasConstructors() && defconstr == null) { gen.out(GenerateJsVisitor.function, gen.getNames().name(d)); gen.out("(){"); gen.generateThrow("Exception", d.getQualifiedNameString() + " has no default constructor.", that); gen.out(";}"); gen.endLine(); } if (gen.stitchNative(d, that)) { if (d.isShared()) { gen.share(d); } initializeType(that, gen); bye = true; } if (d.hasConstructors()) { for (Tree.Constructor cnstr : constructors) { classConstructor(cnstr, that, constructors, gen); } } if (bye)return; } gen.out(GenerateJsVisitor.function, gen.getNames().name(d)); //If there's a default constructor, create a different function with this code if (d.hasConstructors()) { if (defconstr == null) { gen.out("(){"); gen.generateThrow("Exception", d.getQualifiedNameString() + " has no default constructor.", that); gen.out(";}"); gen.endLine(); gen.out(GenerateJsVisitor.function, gen.getNames().name(d)); } gen.out("$$c"); } final boolean withTargs = generateParameters(that.getTypeParameterList(), plist, d, gen); gen.beginBlock(); if (!d.hasConstructors()) { //This takes care of top-level attributes defined before the class definition gen.out("$init$", gen.getNames().name(d), "();"); gen.endLine(); gen.declareSelf(d); gen.referenceOuter(d); } final String me = gen.getNames().self(d); if (withTargs) { gen.out(gen.getClAlias(), "set_type_args(", me, ",$$targs$$);"); gen.endLine(); } else { //Check if any of the satisfied types have type arguments if (sats != null) { for(Tree.StaticType sat : sats.getTypes()) { boolean first = true; Map<TypeParameter,ProducedType> targs = sat.getTypeModel().getTypeArguments(); if (targs != null && !targs.isEmpty()) { if (first) { gen.out(me, ".$$targs$$="); TypeUtils.printTypeArguments(that, targs, gen, false, null); gen.endLine(true); first = false; } else { gen.out("/*TODO: more type arguments*/"); } } } } } if (!d.isToplevel() && d.getContainer() instanceof Method && !((Method)d.getContainer()).getTypeParameters().isEmpty()) { gen.out(gen.getClAlias(), "set_type_args(", me, ",$$$mptypes)"); gen.endLine(true); } if (plist != null) { gen.initParameters(plist, d, null); } final List<Declaration> superDecs = new ArrayList<Declaration>(3); if (!gen.opts.isOptimize()) { new SuperVisitor(superDecs).visit(that.getClassBody()); } final Tree.ExtendedType extendedType = that.getExtendedType(); callSupertypes(sats == null ? null : sats.getTypes(), extendedType == null ? null : extendedType.getType(), d, that, superDecs, extendedType == null ? null : extendedType.getInvocationExpression(), extendedType == null ? null : d.getExtendedTypeDeclaration().getParameterList(), gen); if (!gen.opts.isOptimize() && plist != null) { //Fix #231 for lexical scope for (Tree.Parameter p : plist.getParameters()) { if (!p.getParameterModel().isHidden()){ gen.generateAttributeForParameter(that, d, p.getParameterModel()); } } } if (!d.hasConstructors()) { if (TypeUtils.isNativeExternal(d)) { gen.stitchConstructorHelper(that, "_cons_before"); } gen.visitStatements(that.getClassBody().getStatements()); if (d.isNative()) { gen.stitchConstructorHelper(that, "_cons_after"); } gen.out("return ", me, ";"); } gen.endBlockNewLine(); if (defconstr != null) { //Define a function as the class and call the default constructor in there String _this = "undefined"; if (!d.isToplevel()) { final ClassOrInterface coi = Util.getContainingClassOrInterface(d.getContainer()); if (coi != null) { if (d.isClassOrInterfaceMember()) { _this = "this"; } else { _this = gen.getNames().self(coi); } } } gen.out(GenerateJsVisitor.function, gen.getNames().name(d), "(){return ", gen.getNames().name(d), "_", gen.getNames().name(defconstr.getDeclarationModel()), ".apply(", _this, ",arguments);}"); gen.endLine(); } for (Tree.Constructor cnstr : constructors) { classConstructor(cnstr, that, constructors, gen); } //Add reference to metamodel gen.out(gen.getNames().name(d), ".$crtmm$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), gen); gen.endLine(true); gen.share(d); initializeType(that, gen); if (d.isSerializable()) { SerializationHelper.addDeserializer(that, d, gen); } } static void callSuperclass(final Tree.SimpleType extendedType, final Tree.InvocationExpression invocation, final Class d, final ParameterList plist, final Node that, final boolean pseudoAbstractConstructor, final List<Declaration> superDecs, final GenerateJsVisitor gen) { TypeDeclaration typeDecl = extendedType.getDeclarationModel(); if (invocation != null) { Tree.PositionalArgumentList argList = invocation.getPositionalArgumentList(); final String qpath; if (typeDecl instanceof Constructor) { final String path = gen.qualifiedPath(that, (TypeDeclaration)typeDecl.getContainer(), false); if (path.isEmpty()) { qpath = gen.getNames().name((TypeDeclaration)typeDecl.getContainer()); } else { qpath = path + "." + gen.getNames().name((TypeDeclaration)typeDecl.getContainer()); } } else { qpath = gen.qualifiedPath(that, typeDecl, false); } if (pseudoAbstractConstructor) { if (typeDecl instanceof Constructor) { gen.out(gen.memberAccessBase(extendedType, typeDecl, false, qpath), "$$a("); } else { gen.out(gen.memberAccessBase(extendedType, typeDecl, false, qpath), "_$c$$$a("); } } else { gen.out(gen.memberAccessBase(extendedType, typeDecl, false, qpath), (gen.opts.isOptimize() && (gen.getSuperMemberScope(extendedType) != null)) ? ".call(this," : "("); } gen.getInvoker().generatePositionalArguments(invocation.getPrimary(), argList, argList.getPositionalArguments(), false, false); if (argList.getPositionalArguments().size() > 0) { gen.out(","); } //There may be defaulted args we must pass as undefined if (plist != null && plist.getParameters().size() > argList.getPositionalArguments().size()) { for (int i = argList.getPositionalArguments().size(); i < plist.getParameters().size(); i++) { com.redhat.ceylon.model.typechecker.model.Parameter p = plist.getParameters().get(i); if (p.isSequenced()) { gen.out(gen.getClAlias(), "empty(),"); } else { gen.out("undefined,"); } } } //If the supertype has type arguments, add them to the call if (typeDecl.getTypeParameters() != null && !typeDecl.getTypeParameters().isEmpty()) { List<ProducedType> typeArgs = null; if (extendedType.getTypeArgumentList() != null) { typeArgs = extendedType.getTypeArgumentList().getTypeModels(); } TypeUtils.printTypeArguments(that, TypeUtils.matchTypeParametersWithArguments(typeDecl.getTypeParameters(), typeArgs), gen, false, null); gen.out(","); } if (typeDecl instanceof Constructor && ((Class)typeDecl.getContainer()).getTypeParameters()!=null && !((Class)typeDecl.getContainer()).getTypeParameters().isEmpty()) { gen.out("$$targs$$,"); } gen.out(gen.getNames().self(d), ")"); gen.endLine(true); } copySuperMembers(typeDecl, superDecs, d, gen); } static void callSupertypes(final List<Tree.StaticType> sats, final Tree.SimpleType supertype, final ClassOrInterface d, final Node that, final List<Declaration> superDecs, final Tree.InvocationExpression invoke, final ParameterList plist, final GenerateJsVisitor gen) { if (sats != null) { final ArrayList<Tree.StaticType> supers = new ArrayList<>(sats.size()+1); supers.addAll(sats); if (supertype != null) { supers.add(supertype); } Collections.sort(supers, new StaticTypeComparator()); HashSet<String> myTypeArgs = new HashSet<>(); for (TypeParameter tp : d.getTypeParameters()) { myTypeArgs.add(tp.getName()); } for (Tree.StaticType st: supers) { if (st == supertype) { callSuperclass(supertype, invoke, (Class)d, plist, that, false, superDecs, gen); } else { TypeDeclaration typeDecl = st.getTypeModel().getDeclaration(); gen.qualify(that, typeDecl); gen.out(gen.getNames().name((ClassOrInterface)typeDecl), "("); if (typeDecl.getTypeParameters() != null && !typeDecl.getTypeParameters().isEmpty()) { TypeUtils.printTypeArguments(that, st.getTypeModel().getTypeArguments(), gen, d.isToplevel(), null); gen.out(","); } gen.out(gen.getNames().self(d), ")"); gen.endLine(true); copySuperMembers(typeDecl, superDecs, d, gen); } } } else if (supertype != null) { callSuperclass(supertype, invoke, (Class)d, plist, that, false, superDecs, gen); } } private static void copySuperMembers(final TypeDeclaration typeDecl, final List<Declaration> decs, final ClassOrInterface d, final GenerateJsVisitor gen) { if (!gen.opts.isOptimize() && decs != null) { for (Declaration dec: decs) { if (!typeDecl.isMember(dec)) { continue; } String suffix = gen.getNames().scopeSuffix(dec.getContainer()); if (dec instanceof Value && ((Value)dec).isTransient()) { superGetterRef(dec,d,suffix, gen); if (((Value) dec).isVariable()) { superSetterRef(dec,d,suffix, gen); } } else { gen.out(gen.getNames().self(d), ".", gen.getNames().name(dec), suffix, "=", gen.getNames().self(d), ".", gen.getNames().name(dec)); gen.endLine(true); } } } } private static void superGetterRef(final Declaration d, final ClassOrInterface sub, final String parentSuffix, final GenerateJsVisitor gen) { if (AttributeGenerator.defineAsProperty(d)) { gen.out(gen.getClAlias(), "copySuperAttr(", gen.getNames().self(sub), ",'", gen.getNames().name(d), "','", parentSuffix, "')"); } else { gen.out(gen.getNames().self(sub), ".", gen.getNames().getter(d, false), parentSuffix, "=", gen.getNames().self(sub), ".", gen.getNames().getter(d, false)); } gen.endLine(true); } private static void superSetterRef(final Declaration d, final ClassOrInterface sub, final String parentSuffix, final GenerateJsVisitor gen) { if (!AttributeGenerator.defineAsProperty(d)) { gen.out(gen.getNames().self(sub), ".", gen.getNames().setter(d), parentSuffix, "=", gen.getNames().self(sub), ".", gen.getNames().setter(d)); gen.endLine(true); } } public static class StaticTypeComparator implements Comparator<Tree.StaticType> { @Override public int compare(StaticType o1, StaticType o2) { final ProducedType t1 = o1.getTypeModel(); final ProducedType t2 = o2.getTypeModel(); if (t1.isUnknown()) { return t2.isUnknown() ? 0 : -1; } if (t2.isUnknown()) { return t1.isUnknown() ? 0 : -1; } if (t1.isSubtypeOf(t2)) { return 1; } if (t2.isSubtypeOf(t1)) { return -1; } //Check the members for (Declaration d : t1.getDeclaration().getMembers()) { if (d instanceof TypedDeclaration || d instanceof ClassOrInterface) { Declaration d2 = t2.getDeclaration().getMember(d.getName(), null, false); if (d2 != null) { final Declaration dd2 = Util.getContainingDeclaration(d2); if (dd2 instanceof TypeDeclaration && t1.getDeclaration().inherits((TypeDeclaration)dd2)) { return 1; } } } } for (Declaration d : t2.getDeclaration().getMembers()) { if (d instanceof TypedDeclaration || d instanceof ClassOrInterface) { Declaration d2 = t1.getDeclaration().getMember(d.getName(), null, false); if (d2 != null) { final Declaration dd2 = Util.getContainingDeclaration(d2); if (dd2 instanceof TypeDeclaration && t2.getDeclaration().inherits((TypeDeclaration)dd2)) { return -1; } } } } return 0; } } static void defineObject(final Node that, final Value d, final Tree.SatisfiedTypes sats, final Tree.ExtendedType superType, final Tree.ClassBody body, final Tree.AnnotationList annots, final GenerateJsVisitor gen) { final boolean addToPrototype = gen.opts.isOptimize() && d != null && d.isClassOrInterfaceMember(); final boolean isObjExpr = that instanceof Tree.ObjectExpression; final Class c = (Class)(isObjExpr ? ((Tree.ObjectExpression)that).getAnonymousClass() : d.getTypeDeclaration()); final String className = gen.getNames().name(c); final String objectName = gen.getNames().name(d); final String selfName = gen.getNames().self(c); gen.out(GenerateJsVisitor.function, className); Map<TypeParameter, ProducedType> targs=new HashMap<TypeParameter, ProducedType>(); if (sats != null) { for (StaticType st : sats.getTypes()) { Map<TypeParameter, ProducedType> stargs = st.getTypeModel().getTypeArguments(); if (stargs != null && !stargs.isEmpty()) { targs.putAll(stargs); } } } gen.out(targs.isEmpty()?"()":"($$targs$$)"); gen.beginBlock(); if (isObjExpr) { gen.out("var ", selfName, "=new ", className, ".$$;"); final ClassOrInterface coi = Util.getContainingClassOrInterface(c.getContainer()); if (coi != null) { gen.out(selfName, ".outer$=", gen.getNames().self(coi)); gen.endLine(true); } } else { if (c.isMember()) { gen.initSelf(that); } gen.instantiateSelf(c); gen.referenceOuter(c); } final List<Declaration> superDecs = new ArrayList<Declaration>(); if (!gen.opts.isOptimize()) { new SuperVisitor(superDecs).visit(body); } if (!targs.isEmpty()) { gen.out(selfName, ".$$targs$$=$$targs$$"); gen.endLine(true); } TypeGenerator.callSupertypes(sats == null ? null : sats.getTypes(), superType == null ? null : superType.getType(), c, that, superDecs, superType == null ? null : superType.getInvocationExpression(), superType == null ? null : c.getExtendedTypeDeclaration().getParameterList(), gen); body.visit(gen); gen.out("return ", selfName, ";"); gen.endBlock(); gen.out(";", className, ".$crtmm$="); TypeUtils.encodeForRuntime(that, c, gen); gen.endLine(true); TypeGenerator.initializeType(that, gen); final String objvar = (addToPrototype ? "this.":"")+gen.getNames().createTempVariable(); if (d != null && !addToPrototype) { gen.out("var ", objvar); //If it's a property, create the object here if (AttributeGenerator.defineAsProperty(d)) { gen.out("=", className, "("); if (!targs.isEmpty()) { TypeUtils.printTypeArguments(that, targs, gen, false, null); } gen.out(")"); } gen.endLine(true); } if (d != null && AttributeGenerator.defineAsProperty(d)) { gen.out(gen.getClAlias(), "atr$("); gen.outerSelf(d); gen.out(",'", objectName, "',function(){return "); if (addToPrototype) { gen.out("this.", gen.getNames().privateName(d)); } else { gen.out(objvar); } gen.out(";},undefined,"); TypeUtils.encodeForRuntime(d, annots, gen); gen.out(")"); gen.endLine(true); } else if (d != null) { final String objectGetterName = gen.getNames().getter(d, false); gen.out(GenerateJsVisitor.function, objectGetterName, "()"); gen.beginBlock(); //Create the object lazily final String oname = gen.getNames().objectName(c); gen.out("if(", objvar, "===", gen.getClAlias(), "INIT$)"); gen.generateThrow(gen.getClAlias()+"InitializationError", "Cyclic initialization trying to read the value of '" + d.getName() + "' before it was set", that); gen.endLine(true); gen.out("if(", objvar, "===undefined){", objvar, "=", gen.getClAlias(), "INIT$;", objvar, "=$init$", oname); if (!oname.endsWith("()")) { gen.out("()"); } gen.out("("); if (!targs.isEmpty()) { TypeUtils.printTypeArguments(that, targs, gen, false, null); } gen.out(");", objvar, ".$crtmm$=", objectGetterName, ".$crtmm$;}"); gen.endLine(); gen.out("return ", objvar, ";"); gen.endBlockNewLine(); if (addToPrototype || d.isShared()) { gen.outerSelf(d); gen.out(".", objectGetterName, "=", objectGetterName); gen.endLine(true); } if (!d.isToplevel()) { if(gen.outerSelf(d))gen.out("."); } gen.out(objectGetterName, ".$crtmm$="); TypeUtils.encodeForRuntime(d, annots, gen); gen.endLine(true); gen.out(gen.getNames().getter(c, true), "=", objectGetterName); gen.endLine(true); if (d.isToplevel()) { final String objectGetterNameMM = gen.getNames().getter(d, true); gen.out("ex$.", objectGetterNameMM, "=", objectGetterNameMM); gen.endLine(true); } } else if (that instanceof Tree.ObjectExpression) { gen.out("return ", className, "();"); } } static void objectDefinition(final Tree.ObjectDefinition that, final GenerateJsVisitor gen) { //Don't even bother with nodes that have errors if (errVisitor.hasErrors(that))return; gen.comment(that); defineObject(that, that.getDeclarationModel(), that.getSatisfiedTypes(), that.getExtendedType(), that.getClassBody(), that.getAnnotationList(), gen); //Objects defined inside methods need their init sections are exec'd if (!that.getDeclarationModel().isToplevel() && !that.getDeclarationModel().isClassOrInterfaceMember()) { gen.out(gen.getNames().objectName(that.getDeclarationModel()), "();"); } } static boolean localConstructorDelegation(final TypeDeclaration that, final List<Tree.Constructor> constructors) { if (that.isAbstract()) { return true; } for (Tree.Constructor cnst : constructors) { if (cnst.getDelegatedConstructor() != null) { final TypeDeclaration superdec = cnst.getDelegatedConstructor().getType().getDeclarationModel(); if (superdec instanceof Class && that.getName()==null) { //Default constructor return true; } else if (superdec.equals(that)) { return true; } } } return false; } static void classConstructor(final Tree.Constructor that, final Tree.ClassDefinition cdef, final List<Tree.Constructor> constructors, final GenerateJsVisitor gen) { gen.comment(that); Constructor d = that.getDeclarationModel(); final Class container = cdef.getDeclarationModel(); final String fullName = gen.getNames().name(container) + "_" + gen.getNames().name(d); if (!TypeUtils.isNativeExternal(d) || !gen.stitchNative(d, that)) { final Tree.DelegatedConstructor delcons = that.getDelegatedConstructor(); final TypeDeclaration superdec = delcons == null ? null : delcons.getType().getDeclarationModel(); gen.out("function ", fullName); boolean forceAbstract = localConstructorDelegation(that.getDeclarationModel(), constructors); if (forceAbstract) { gen.out("$$a"); } final boolean withTargs = generateParameters(cdef.getTypeParameterList(), that.getParameterList(), container, gen); final String me = gen.getNames().self(container); gen.beginBlock(); if (forceAbstract) { gen.initParameters(that.getParameterList(), container, null); if (delcons != null) { ParameterList plist = superdec instanceof Class ? ((Class)superdec).getParameterList() : ((Constructor)superdec).getParameterLists().get(0); callSuperclass(delcons.getType(), delcons.getInvocationExpression(), container, plist, that, false, null, gen); } gen.generateClassStatements(cdef, that, null, 1); gen.out("return ", me, ";"); gen.endBlockNewLine(true); gen.out("function ", fullName); generateParameters(cdef.getTypeParameterList(), that.getParameterList(), container, gen); gen.beginBlock(); } if (!d.isAbstract()) { gen.out("$init$", gen.getNames().name(container), "();"); gen.endLine(); gen.declareSelf(container); gen.referenceOuter(container); } boolean pseudoAbstract = false; gen.initParameters(that.getParameterList(), container, null); if (!d.isAbstract()) { //Call common initializer gen.out(gen.getNames().name(container), "$$c("); if (withTargs) { gen.out("$$targs$$,"); } gen.out(me, ");"); gen.endLine(); } if (forceAbstract) { gen.out(fullName, "$$a"); generateParameters(cdef.getTypeParameterList(), that.getParameterList(), container, gen); gen.endLine(true); } else if (delcons != null) { pseudoAbstract = superdec instanceof Class ? superdec==container : ((Constructor)superdec).getContainer()==container; ParameterList plist = superdec instanceof Class ? ((Class)superdec).getParameterList() : ((Constructor)superdec).getParameterLists().get(0); callSuperclass(delcons.getType(), delcons.getInvocationExpression(), container, plist, that, pseudoAbstract, null, gen); } if (d.isNative()) { gen.stitchConstructorHelper(cdef, "_cons_before"); } if (forceAbstract) { gen.generateClassStatements(cdef, that, null, 2); } else if (pseudoAbstract) { //Pass the delegated constructor Tree.Constructor pseudo1 = null; if (superdec instanceof Class) { for (Tree.Constructor _cns : constructors) { if (_cns.getDeclarationModel().getName() == null) { pseudo1 = _cns; } } } else { for (Tree.Constructor _cns : constructors) { if (_cns.getDeclarationModel() == superdec) { pseudo1 = _cns; } } } gen.generateClassStatements(cdef, pseudo1, that, 2); } else { gen.generateClassStatements(cdef, that, null, 0); } if (d.isNative()) { gen.stitchConstructorHelper(cdef, "_cons_after"); } gen.out("return ", me, ";"); gen.endBlockNewLine(true); } //Add reference to metamodel gen.out(fullName, ".$crtmm$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), gen); gen.endLine(true); gen.out(gen.getNames().name(container), ".", fullName, "=", fullName); gen.endLine(true); if (gen.outerSelf(container)) { gen.out(".", fullName, "=", fullName); gen.endLine(true); } } }
simplify a little
src/main/java/com/redhat/ceylon/compiler/js/TypeGenerator.java
simplify a little
<ide><path>rc/main/java/com/redhat/ceylon/compiler/js/TypeGenerator.java <ide> import com.redhat.ceylon.model.typechecker.model.ClassOrInterface; <ide> import com.redhat.ceylon.model.typechecker.model.Constructor; <ide> import com.redhat.ceylon.model.typechecker.model.Declaration; <del>import com.redhat.ceylon.model.typechecker.model.Generic; <ide> import com.redhat.ceylon.model.typechecker.model.Interface; <ide> import com.redhat.ceylon.model.typechecker.model.Method; <ide> import com.redhat.ceylon.model.typechecker.model.ParameterList; <ide> final String fullName = gen.getNames().name(container) + "_" + gen.getNames().name(d); <ide> if (!TypeUtils.isNativeExternal(d) || !gen.stitchNative(d, that)) { <ide> final Tree.DelegatedConstructor delcons = that.getDelegatedConstructor(); <del> final TypeDeclaration superdec = delcons == null ? null : delcons.getType().getDeclarationModel(); <add> final TypeDeclaration superdec; <add> final ParameterList superplist; <add> final boolean pseudoAbstract; <add> if (delcons == null) { <add> superdec = null; <add> superplist = null; <add> pseudoAbstract = false; <add> } else { <add> superdec = delcons.getType().getDeclarationModel(); <add> pseudoAbstract = superdec instanceof Class ? superdec==container : <add> ((Constructor)superdec).getContainer()==container; <add> superplist = superdec instanceof Class ? ((Class)superdec).getParameterList() : <add> ((Constructor)superdec).getParameterLists().get(0); <add> } <ide> gen.out("function ", fullName); <ide> boolean forceAbstract = localConstructorDelegation(that.getDeclarationModel(), constructors); <ide> if (forceAbstract) { <ide> if (forceAbstract) { <ide> gen.initParameters(that.getParameterList(), container, null); <ide> if (delcons != null) { <del> ParameterList plist = superdec instanceof Class ? ((Class)superdec).getParameterList() : <del> ((Constructor)superdec).getParameterLists().get(0); <ide> callSuperclass(delcons.getType(), delcons.getInvocationExpression(), <del> container, plist, that, false, null, gen); <add> container, superplist, that, false, null, gen); <ide> } <ide> gen.generateClassStatements(cdef, that, null, 1); <ide> gen.out("return ", me, ";"); <ide> gen.declareSelf(container); <ide> gen.referenceOuter(container); <ide> } <del> boolean pseudoAbstract = false; <ide> gen.initParameters(that.getParameterList(), container, null); <ide> if (!d.isAbstract()) { <ide> //Call common initializer <ide> container, gen); <ide> gen.endLine(true); <ide> } else if (delcons != null) { <del> pseudoAbstract = superdec instanceof Class ? superdec==container : <del> ((Constructor)superdec).getContainer()==container; <del> ParameterList plist = superdec instanceof Class ? ((Class)superdec).getParameterList() : <del> ((Constructor)superdec).getParameterLists().get(0); <ide> callSuperclass(delcons.getType(), delcons.getInvocationExpression(), <del> container, plist, that, pseudoAbstract, null, gen); <add> container, superplist, that, pseudoAbstract, null, gen); <ide> } <ide> if (d.isNative()) { <ide> gen.stitchConstructorHelper(cdef, "_cons_before");
Java
apache-2.0
484e8e6f460d5efb8a8c81c806ab58034feb9e5c
0
thauser/pnc,emmettu/pnc,jdcasey/pnc,michalszynkiewicz/pnc,mareknovotny/pnc,ruhan1/pnc,mareknovotny/pnc,ruhan1/pnc,dans123456/pnc,psakar/pnc,michalszynkiewicz/pnc,ahmedlawi92/pnc,matedo1/pnc,matedo1/pnc,pkocandr/pnc,mareknovotny/pnc,alexcreasy/pnc,dans123456/pnc,jbartece/pnc,thauser/pnc,alexcreasy/pnc,michalszynkiewicz/pnc,ruhan1/pnc,ahmedlawi92/pnc,pgier/pnc,emmettu/pnc,pgier/pnc,psakar/pnc,emmettu/pnc,pgier/pnc,jsenko/pnc,project-ncl/pnc,thescouser89/pnc,mareknovotny/pnc,pgier/pnc,alexcreasy/pnc,jbartece/pnc,psakar/pnc,matedo1/pnc,michalszynkiewicz/pnc,ahmedlawi92/pnc,jdcasey/pnc,emmettu/pnc,jbartece/pnc,jdcasey/pnc,dans123456/pnc,jsenko/pnc,psakar/pnc,matejonnet/pnc,rnc/pnc,jsenko/pnc,ahmedlawi92/pnc,thauser/pnc
/** * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.pnc.demo.data; import com.google.common.base.Preconditions; import org.jboss.logging.Logger; import org.jboss.pnc.datastore.repositories.*; import org.jboss.pnc.model.*; import org.jboss.pnc.model.ProductRelease.SupportLevel; import org.jboss.pnc.spi.datastore.Datastore; import javax.ejb.Singleton; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.inject.Inject; import java.lang.invoke.MethodHandles; import java.sql.Timestamp; import java.time.Instant; import java.util.Date; import java.util.HashSet; import java.util.Set; /** * Data for the DEMO. Note: The database initialization requires two separate * transactions in order for the build configuration audit record to be created * and then linked to a build record. */ @Singleton public class DatabaseDataInitializer { private static final Logger logger = Logger.getLogger(MethodHandles.lookup().lookupClass()); private static final String PNC_PRODUCT_NAME = "Project Newcastle Demo Product"; private static final String PNC_PRODUCT_VERSION = "1.0"; private static final String PNC_PRODUCT_RELEASE = "1.0.0.GA"; private static final String PNC_PRODUCT_MILESTONE = "1.0.0.Build1"; private static final String PNC_PROJECT_1_NAME = "Project Newcastle Demo Project 1"; private static final String PNC_PROJECT_BUILD_CFG_ID = "pnc-1.0.0.DR1"; @Inject ProjectRepository projectRepository; @Inject ProductRepository productRepository; @Inject BuildConfigurationRepository buildConfigurationRepository; @Inject BuildConfigurationAuditedRepository buildConfigurationAuditedRepository; @Inject ProductVersionRepository productVersionRepository; @Inject ProductMilestoneRepository productMilestoneRepository; @Inject ProductReleaseRepository productReleaseRepository; @Inject BuildConfigurationSetRepository buildConfigurationSetRepository; @Inject BuildConfigSetRecordRepository buildConfigSetRecordRepository; @Inject UserRepository userRepository; @Inject BuildRecordRepository buildRecordRepository; @Inject EnvironmentRepository environmentRepository; @Inject Datastore datastore; BuildConfiguration buildConfiguration1; BuildConfiguration buildConfiguration2; BuildConfigurationSet buildConfigurationSet1; User demoUser; public void verifyData() { // Check number of entities in DB Preconditions.checkState(projectRepository.count() > 0, "Expecting number of Projects > 0"); Preconditions.checkState(productRepository.count() > 0, "Expecting number of Products > 0"); Preconditions.checkState(buildConfigurationRepository.count() > 0, "Expecting number of BuildConfigurations > 0"); Preconditions.checkState(productVersionRepository.count() > 0, "Expecting number of ProductVersions > 0"); Preconditions.checkState(buildConfigurationSetRepository.count() > 0, "Expecting number of BuildRepositorySets > 0"); BuildConfiguration buildConfigurationDB = buildConfigurationRepository.findAll().get(0); // Check that BuildConfiguration and BuildConfigurationSet have a ProductVersion associated Preconditions.checkState(buildConfigurationDB.getBuildConfigurationSets().iterator().next().getProductVersion() != null, "Product version of buildConfiguration must be not null"); BuildConfigurationSet buildConfigurationSetDB = buildConfigurationSetRepository.findAll().get(0); Preconditions.checkState(buildConfigurationSetDB.getProductVersion() != null, "Product version of buildConfigurationSet must be not null"); // Check that mapping between Product and Build Configuration via BuildConfigurationSet is correct Preconditions.checkState(buildConfigurationSetDB.getProductVersion().getProduct().getName().equals(PNC_PRODUCT_NAME), "Product mapped to Project must be " + PNC_PRODUCT_NAME); Preconditions.checkState(buildConfigurationSetDB.getProductVersion().getVersion().equals(PNC_PRODUCT_VERSION), "Product version mapped to Project must be " + PNC_PRODUCT_VERSION); // Check that BuildConfiguration and BuildConfigurationSet have a ProductVersion associated Preconditions.checkState(buildConfigurationDB.getBuildConfigurationSets().iterator().next() .getProductVersion().getVersion().equals(PNC_PRODUCT_VERSION), "Product version mapped to BuildConfiguration must be " + PNC_PRODUCT_VERSION); Preconditions.checkState(buildConfigurationDB.getBuildConfigurationSets().iterator().next() .getProductVersion().getProduct().getName().equals(PNC_PRODUCT_NAME), "Product mapped to BuildConfiguration must be " + PNC_PRODUCT_NAME); // Check data of BuildConfiguration Preconditions.checkState(buildConfigurationDB.getProject().getName().equals(PNC_PROJECT_1_NAME), "Project mapped to BuildConfiguration must be " + PNC_PROJECT_1_NAME); } @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void initiliazeProjectProductData() { Environment environment1 = createAndPersistDefultEnvironment(); Environment environment2 = createAndPersistDefultEnvironment(); /* * All the bi-directional mapping settings are managed inside the Builders */ // Example product and product version Product product = Product.Builder.newBuilder().name(PNC_PRODUCT_NAME).abbreviation("PNC").description( "Example Product for Project Newcastle Demo").productCode("PNC").pgmSystemName("newcastle") .build(); product = productRepository.save(product); // Example product version, release, and milestone of the product ProductVersion productVersion = ProductVersion.Builder.newBuilder().version(PNC_PRODUCT_VERSION).product(product) .build(); productVersion = productVersionRepository.save(productVersion); ProductMilestone productMilestone = ProductMilestone.Builder.newBuilder().version(PNC_PRODUCT_MILESTONE) .productVersion(productVersion).build(); productMilestone = productMilestoneRepository.save(productMilestone); ProductRelease productRelease = ProductRelease.Builder.newBuilder().version(PNC_PRODUCT_RELEASE) .productVersion(productVersion).productMilestone(productMilestone).supportLevel(SupportLevel.EARLYACCESS) .build(); productRelease = productReleaseRepository.save(productRelease); productVersion.setCurrentProductMilestone(productMilestone); productVersion = productVersionRepository.save(productVersion); // Example projects Project project1 = Project.Builder.newBuilder() .name(PNC_PROJECT_1_NAME).description("Example Project for Newcastle Demo") .projectUrl("https://github.com/project-ncl/pnc") .build(); Project project2 = Project.Builder.newBuilder() .name("JBoss Modules").description("JBoss Modules Project") .projectUrl("https://github.com/jboss-modules/jboss-modules") .issueTrackerUrl("https://issues.jboss.org/browse/MODULES").build(); Project project3 = Project.Builder.newBuilder() .name("JBoss JavaEE Servlet Spec API").description("JavaEE Servlet Spec API") .projectUrl("https://github.com/jboss/jboss-servlet-api_spec") .issueTrackerUrl("https://issues.jboss.org/browse/JBEE").build(); Project project4 = Project.Builder.newBuilder() .name("Fabric8").description( "Integration platform for working with Apache ActiveMQ, Camel, CXF and Karaf in the cloud") .projectUrl("https://github.com/fabric8io/fabric8") .issueTrackerUrl("https://github.com/fabric8io/fabric8/issues").build(); projectRepository.save(project1); projectRepository.save(project2); projectRepository.save(project3); projectRepository.save(project4); // Example build configurations buildConfiguration1 = BuildConfiguration.Builder.newBuilder() .name(PNC_PROJECT_BUILD_CFG_ID) .project(project1) .description("Test build config for project newcastle") .environment(environment1) .buildScript("mvn clean deploy -DskipTests=true") .scmRepoURL("https://github.com/project-ncl/pnc.git") .scmRevision("*/v0.2") .build(); buildConfiguration1 = buildConfigurationRepository.save(buildConfiguration1); buildConfiguration2 = BuildConfiguration.Builder.newBuilder() .name("jboss-modules-1.5.0") .project(project2) .description("Test config for JBoss modules build master branch.") .environment(environment2) .buildScript("mvn clean deploy -DskipTests=true") .scmRepoURL("https://github.com/jboss-modules/jboss-modules.git") .scmRevision("9e7115771a791feaa5be23b1255416197f2cda38") .build(); buildConfiguration2 = buildConfigurationRepository.save(buildConfiguration2); BuildConfiguration buildConfiguration3 = BuildConfiguration.Builder.newBuilder() .name("jboss-servlet-spec-api-1.0.1") .project(project3) .description("Test build for jboss java servlet api") .environment(environment1) .buildScript("mvn clean deploy -DskipTests=true") .scmRepoURL("https://github.com/jboss/jboss-servlet-api_spec.git") .dependency(buildConfiguration2) .build(); buildConfiguration3 = buildConfigurationRepository.save(buildConfiguration3); BuildConfiguration buildConfiguration4 = BuildConfiguration.Builder.newBuilder() .name("io-fabric8-2.2-SNAPSHOT") .project(project4) .description("Test build for Fabric8") .environment(environment1) .buildScript("mvn clean deploy -DskipTests=true") .scmRepoURL("https://github.com/fabric8io/fabric8.git") .build(); buildConfiguration4 = buildConfigurationRepository.save(buildConfiguration4); // Build config set containing the three example build configs buildConfigurationSet1 = BuildConfigurationSet.Builder.newBuilder().name("Build Config Set 1") .buildConfiguration(buildConfiguration1) .buildConfiguration(buildConfiguration2) .buildConfiguration(buildConfiguration3) .productVersion(productVersion).build(); BuildConfigurationSet buildConfigurationSet2 = BuildConfigurationSet.Builder.newBuilder().name( "Fabric Configuration Set") .buildConfiguration(buildConfiguration4).build(); demoUser = User.Builder.newBuilder().username("demo-user").firstName("Demo First Name") .lastName("Demo Last Name").email("[email protected]").build(); buildConfigurationSetRepository.save(buildConfigurationSet1); buildConfigurationSetRepository.save(buildConfigurationSet2); demoUser = userRepository.save(demoUser); } /** * Build record needs to be initialized in a separate transaction * so that the audited build configuration can be set. */ @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void initiliazeBuildRecordDemoData() { Artifact builtArtifact1 = Artifact.Builder.newBuilder().identifier("test").deployUrl("http://google.pl/built1") .status(ArtifactStatus.BINARY_BUILT).build(); Artifact builtArtifact2 = Artifact.Builder.newBuilder().identifier("test").deployUrl("http://google.pl/built2") .status(ArtifactStatus.BINARY_BUILT).build(); Artifact importedArtifact1 = Artifact.Builder.newBuilder().identifier("test").deployUrl("http://google.pl/imported1") .status(ArtifactStatus.BINARY_IMPORTED).build(); Artifact importedArtifact2 = Artifact.Builder.newBuilder().identifier("test").deployUrl("http://google.pl/imported2") .status(ArtifactStatus.BINARY_IMPORTED).build(); Set<BuildRecord> buildRecords = new HashSet<BuildRecord> (); final int INITIAL_REVISION = 1; IdRev buildConfig1AuditIdRev = new IdRev(buildConfiguration1.getId(), INITIAL_REVISION); BuildConfigurationAudited buildConfigAudited1 = buildConfigurationAuditedRepository.findOne(buildConfig1AuditIdRev); if (buildConfigAudited1 != null) { BuildRecord buildRecord = BuildRecord.Builder.newBuilder() .id(datastore.getNextBuildRecordId()) .latestBuildConfiguration(buildConfiguration1) .buildConfigurationAudited(buildConfigAudited1) .startTime(Timestamp.from(Instant.now())) .endTime(Timestamp.from(Instant.now())) .builtArtifact(builtArtifact1) .builtArtifact(builtArtifact2) .builtArtifact(importedArtifact1) .builtArtifact(importedArtifact2) .user(demoUser) .buildLog("Very short demo log: The quick brown fox jumps over the lazy dog.").build(); buildRecordRepository.save(buildRecord); buildRecords.add(buildRecord); } Artifact builtArtifact3 = Artifact.Builder.newBuilder().identifier("test").deployUrl("http://google.pl/built3") .status(ArtifactStatus.BINARY_BUILT).build(); Artifact builtArtifact4 = Artifact.Builder.newBuilder().identifier("test").deployUrl("http://google.pl/built4") .status(ArtifactStatus.BINARY_BUILT).build(); IdRev buildConfig2AuditIdRev = new IdRev(buildConfiguration2.getId(), INITIAL_REVISION); BuildConfigurationAudited buildConfigAudited2 = buildConfigurationAuditedRepository.findOne(buildConfig2AuditIdRev); if (buildConfigAudited2 != null) { BuildRecord buildRecord = BuildRecord.Builder.newBuilder() .id(datastore.getNextBuildRecordId()) .latestBuildConfiguration(buildConfiguration2) .buildConfigurationAudited(buildConfigAudited2) .startTime(Timestamp.from(Instant.now())) .endTime(Timestamp.from(Instant.now())) .builtArtifact(builtArtifact3) .builtArtifact(builtArtifact4) .user(demoUser) .buildLog("Very short demo log: The quick brown fox jumps over the lazy dog.") .build(); buildRecordRepository.save(buildRecord); buildRecords.add(buildRecord); } BuildConfigSetRecord buildConfigSetRecord1 = BuildConfigSetRecord.Builder.newBuilder() .buildConfigurationSet(buildConfigurationSet1) .startTime(new Date()) .endTime(new Date()) .user(demoUser) .status(BuildStatus.FAILED) .build(); buildConfigSetRecordRepository.save(buildConfigSetRecord1); BuildConfigSetRecord buildConfigSetRecord2 = BuildConfigSetRecord.Builder.newBuilder() .buildConfigurationSet(buildConfigurationSet1) .buildRecords(buildRecords) .startTime(new Date()) .endTime(new Date()) .user(demoUser) .status(BuildStatus.SUCCESS) .build(); buildConfigSetRecordRepository.save(buildConfigSetRecord2); } private Environment createAndPersistDefultEnvironment() { Environment environment = Environment.Builder.defaultEnvironment().build(); return environmentRepository.save(environment); } }
demo-data/src/main/java/org/jboss/pnc/demo/data/DatabaseDataInitializer.java
/** * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.pnc.demo.data; import com.google.common.base.Preconditions; import org.jboss.logging.Logger; import org.jboss.pnc.datastore.repositories.*; import org.jboss.pnc.model.*; import org.jboss.pnc.model.ProductRelease.SupportLevel; import javax.ejb.Singleton; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.inject.Inject; import java.lang.invoke.MethodHandles; import java.sql.Timestamp; import java.time.Instant; import java.util.Date; import java.util.HashSet; import java.util.Set; /** * Data for the DEMO. Note: The database initialization requires two separate * transactions in order for the build configuration audit record to be created * and then linked to a build record. */ @Singleton public class DatabaseDataInitializer { private static final Logger logger = Logger.getLogger(MethodHandles.lookup().lookupClass()); private static final String PNC_PRODUCT_NAME = "Project Newcastle Demo Product"; private static final String PNC_PRODUCT_VERSION = "1.0"; private static final String PNC_PRODUCT_RELEASE = "1.0.0.GA"; private static final String PNC_PRODUCT_MILESTONE = "1.0.0.Build1"; private static final String PNC_PROJECT_1_NAME = "Project Newcastle Demo Project 1"; private static final String PNC_PROJECT_BUILD_CFG_ID = "pnc-1.0.0.DR1"; @Inject ProjectRepository projectRepository; @Inject ProductRepository productRepository; @Inject BuildConfigurationRepository buildConfigurationRepository; @Inject BuildConfigurationAuditedRepository buildConfigurationAuditedRepository; @Inject ProductVersionRepository productVersionRepository; @Inject ProductMilestoneRepository productMilestoneRepository; @Inject ProductReleaseRepository productReleaseRepository; @Inject BuildConfigurationSetRepository buildConfigurationSetRepository; @Inject BuildConfigSetRecordRepository buildConfigSetRecordRepository; @Inject UserRepository userRepository; @Inject BuildRecordRepository buildRecordRepository; @Inject EnvironmentRepository environmentRepository; BuildConfiguration buildConfiguration1; BuildConfiguration buildConfiguration2; BuildConfigurationSet buildConfigurationSet1; User demoUser; public void verifyData() { // Check number of entities in DB Preconditions.checkState(projectRepository.count() > 0, "Expecting number of Projects > 0"); Preconditions.checkState(productRepository.count() > 0, "Expecting number of Products > 0"); Preconditions.checkState(buildConfigurationRepository.count() > 0, "Expecting number of BuildConfigurations > 0"); Preconditions.checkState(productVersionRepository.count() > 0, "Expecting number of ProductVersions > 0"); Preconditions.checkState(buildConfigurationSetRepository.count() > 0, "Expecting number of BuildRepositorySets > 0"); BuildConfiguration buildConfigurationDB = buildConfigurationRepository.findAll().get(0); // Check that BuildConfiguration and BuildConfigurationSet have a ProductVersion associated Preconditions.checkState(buildConfigurationDB.getBuildConfigurationSets().iterator().next().getProductVersion() != null, "Product version of buildConfiguration must be not null"); BuildConfigurationSet buildConfigurationSetDB = buildConfigurationSetRepository.findAll().get(0); Preconditions.checkState(buildConfigurationSetDB.getProductVersion() != null, "Product version of buildConfigurationSet must be not null"); // Check that mapping between Product and Build Configuration via BuildConfigurationSet is correct Preconditions.checkState(buildConfigurationSetDB.getProductVersion().getProduct().getName().equals(PNC_PRODUCT_NAME), "Product mapped to Project must be " + PNC_PRODUCT_NAME); Preconditions.checkState(buildConfigurationSetDB.getProductVersion().getVersion().equals(PNC_PRODUCT_VERSION), "Product version mapped to Project must be " + PNC_PRODUCT_VERSION); // Check that BuildConfiguration and BuildConfigurationSet have a ProductVersion associated Preconditions.checkState(buildConfigurationDB.getBuildConfigurationSets().iterator().next() .getProductVersion().getVersion().equals(PNC_PRODUCT_VERSION), "Product version mapped to BuildConfiguration must be " + PNC_PRODUCT_VERSION); Preconditions.checkState(buildConfigurationDB.getBuildConfigurationSets().iterator().next() .getProductVersion().getProduct().getName().equals(PNC_PRODUCT_NAME), "Product mapped to BuildConfiguration must be " + PNC_PRODUCT_NAME); // Check data of BuildConfiguration Preconditions.checkState(buildConfigurationDB.getProject().getName().equals(PNC_PROJECT_1_NAME), "Project mapped to BuildConfiguration must be " + PNC_PROJECT_1_NAME); } @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void initiliazeProjectProductData() { Environment environment1 = createAndPersistDefultEnvironment(); Environment environment2 = createAndPersistDefultEnvironment(); /* * All the bi-directional mapping settings are managed inside the Builders */ // Example product and product version Product product = Product.Builder.newBuilder().name(PNC_PRODUCT_NAME).abbreviation("PNC").description( "Example Product for Project Newcastle Demo").productCode("PNC").pgmSystemName("newcastle") .build(); product = productRepository.save(product); // Example product version, release, and milestone of the product ProductVersion productVersion = ProductVersion.Builder.newBuilder().version(PNC_PRODUCT_VERSION).product(product) .build(); productVersion = productVersionRepository.save(productVersion); ProductMilestone productMilestone = ProductMilestone.Builder.newBuilder().version(PNC_PRODUCT_MILESTONE) .productVersion(productVersion).build(); productMilestone = productMilestoneRepository.save(productMilestone); ProductRelease productRelease = ProductRelease.Builder.newBuilder().version(PNC_PRODUCT_RELEASE) .productVersion(productVersion).productMilestone(productMilestone).supportLevel(SupportLevel.EARLYACCESS) .build(); productRelease = productReleaseRepository.save(productRelease); productVersion.setCurrentProductMilestone(productMilestone); productVersion = productVersionRepository.save(productVersion); // Example projects Project project1 = Project.Builder.newBuilder() .name(PNC_PROJECT_1_NAME).description("Example Project for Newcastle Demo") .projectUrl("https://github.com/project-ncl/pnc") .build(); Project project2 = Project.Builder.newBuilder() .name("JBoss Modules").description("JBoss Modules Project") .projectUrl("https://github.com/jboss-modules/jboss-modules") .issueTrackerUrl("https://issues.jboss.org/browse/MODULES").build(); Project project3 = Project.Builder.newBuilder() .name("JBoss JavaEE Servlet Spec API").description("JavaEE Servlet Spec API") .projectUrl("https://github.com/jboss/jboss-servlet-api_spec") .issueTrackerUrl("https://issues.jboss.org/browse/JBEE").build(); Project project4 = Project.Builder.newBuilder() .name("Fabric8").description( "Integration platform for working with Apache ActiveMQ, Camel, CXF and Karaf in the cloud") .projectUrl("https://github.com/fabric8io/fabric8") .issueTrackerUrl("https://github.com/fabric8io/fabric8/issues").build(); projectRepository.save(project1); projectRepository.save(project2); projectRepository.save(project3); projectRepository.save(project4); // Example build configurations buildConfiguration1 = BuildConfiguration.Builder.newBuilder() .name(PNC_PROJECT_BUILD_CFG_ID) .project(project1) .description("Test build config for project newcastle") .environment(environment1) .buildScript("mvn clean deploy -DskipTests=true") .scmRepoURL("https://github.com/project-ncl/pnc.git") .scmRevision("*/v0.2") .build(); buildConfiguration1 = buildConfigurationRepository.save(buildConfiguration1); buildConfiguration2 = BuildConfiguration.Builder.newBuilder() .name("jboss-modules-1.5.0") .project(project2) .description("Test config for JBoss modules build master branch.") .environment(environment2) .buildScript("mvn clean deploy -DskipTests=true") .scmRepoURL("https://github.com/jboss-modules/jboss-modules.git") .scmRevision("9e7115771a791feaa5be23b1255416197f2cda38") .build(); buildConfiguration2 = buildConfigurationRepository.save(buildConfiguration2); BuildConfiguration buildConfiguration3 = BuildConfiguration.Builder.newBuilder() .name("jboss-servlet-spec-api-1.0.1") .project(project3) .description("Test build for jboss java servlet api") .environment(environment1) .buildScript("mvn clean deploy -DskipTests=true") .scmRepoURL("https://github.com/jboss/jboss-servlet-api_spec.git") .dependency(buildConfiguration2) .build(); buildConfiguration3 = buildConfigurationRepository.save(buildConfiguration3); BuildConfiguration buildConfiguration4 = BuildConfiguration.Builder.newBuilder() .name("io-fabric8-2.2-SNAPSHOT") .project(project4) .description("Test build for Fabric8") .environment(environment1) .buildScript("mvn clean deploy -DskipTests=true") .scmRepoURL("https://github.com/fabric8io/fabric8.git") .build(); buildConfiguration4 = buildConfigurationRepository.save(buildConfiguration4); // Build config set containing the three example build configs buildConfigurationSet1 = BuildConfigurationSet.Builder.newBuilder().name("Build Config Set 1") .buildConfiguration(buildConfiguration1) .buildConfiguration(buildConfiguration2) .buildConfiguration(buildConfiguration3) .productVersion(productVersion).build(); BuildConfigurationSet buildConfigurationSet2 = BuildConfigurationSet.Builder.newBuilder().name( "Fabric Configuration Set") .buildConfiguration(buildConfiguration4).build(); demoUser = User.Builder.newBuilder().username("demo-user").firstName("Demo First Name") .lastName("Demo Last Name").email("[email protected]").build(); buildConfigurationSetRepository.save(buildConfigurationSet1); buildConfigurationSetRepository.save(buildConfigurationSet2); demoUser = userRepository.save(demoUser); } /** * Build record needs to be initialized in a separate transaction * so that the audited build configuration can be set. */ @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void initiliazeBuildRecordDemoData() { Artifact builtArtifact1 = Artifact.Builder.newBuilder().identifier("test").deployUrl("http://google.pl/built1") .status(ArtifactStatus.BINARY_BUILT).build(); Artifact builtArtifact2 = Artifact.Builder.newBuilder().identifier("test").deployUrl("http://google.pl/built2") .status(ArtifactStatus.BINARY_BUILT).build(); Artifact importedArtifact1 = Artifact.Builder.newBuilder().identifier("test").deployUrl("http://google.pl/imported1") .status(ArtifactStatus.BINARY_IMPORTED).build(); Artifact importedArtifact2 = Artifact.Builder.newBuilder().identifier("test").deployUrl("http://google.pl/imported2") .status(ArtifactStatus.BINARY_IMPORTED).build(); Set<BuildRecord> buildRecords = new HashSet<BuildRecord> (); final int INITIAL_REVISION = 1; IdRev buildConfig1AuditIdRev = new IdRev(buildConfiguration1.getId(), INITIAL_REVISION); BuildConfigurationAudited buildConfigAudited1 = buildConfigurationAuditedRepository.findOne(buildConfig1AuditIdRev); if (buildConfigAudited1 != null) { BuildRecord buildRecord = BuildRecord.Builder.newBuilder() .latestBuildConfiguration(buildConfiguration1) .buildConfigurationAudited(buildConfigAudited1) .startTime(Timestamp.from(Instant.now())) .endTime(Timestamp.from(Instant.now())) .builtArtifact(builtArtifact1) .builtArtifact(builtArtifact2) .builtArtifact(importedArtifact1) .builtArtifact(importedArtifact2) .user(demoUser) .buildLog("Very short demo log: The quick brown fox jumps over the lazy dog.").build(); buildRecordRepository.save(buildRecord); buildRecords.add(buildRecord); } Artifact builtArtifact3 = Artifact.Builder.newBuilder().identifier("test").deployUrl("http://google.pl/built3") .status(ArtifactStatus.BINARY_BUILT).build(); Artifact builtArtifact4 = Artifact.Builder.newBuilder().identifier("test").deployUrl("http://google.pl/built4") .status(ArtifactStatus.BINARY_BUILT).build(); IdRev buildConfig2AuditIdRev = new IdRev(buildConfiguration2.getId(), INITIAL_REVISION); BuildConfigurationAudited buildConfigAudited2 = buildConfigurationAuditedRepository.findOne(buildConfig2AuditIdRev); if (buildConfigAudited2 != null) { BuildRecord buildRecord = BuildRecord.Builder.newBuilder() .latestBuildConfiguration(buildConfiguration2) .buildConfigurationAudited(buildConfigAudited2) .startTime(Timestamp.from(Instant.now())) .endTime(Timestamp.from(Instant.now())) .builtArtifact(builtArtifact3) .builtArtifact(builtArtifact4) .user(demoUser) .buildLog("Very short demo log: The quick brown fox jumps over the lazy dog.") .build(); buildRecordRepository.save(buildRecord); buildRecords.add(buildRecord); } BuildConfigSetRecord buildConfigSetRecord1 = BuildConfigSetRecord.Builder.newBuilder() .buildConfigurationSet(buildConfigurationSet1) .startTime(new Date()) .endTime(new Date()) .user(demoUser) .status(BuildStatus.FAILED) .build(); buildConfigSetRecordRepository.save(buildConfigSetRecord1); BuildConfigSetRecord buildConfigSetRecord2 = BuildConfigSetRecord.Builder.newBuilder() .buildConfigurationSet(buildConfigurationSet1) .buildRecords(buildRecords) .startTime(new Date()) .endTime(new Date()) .user(demoUser) .status(BuildStatus.SUCCESS) .build(); buildConfigSetRecordRepository.save(buildConfigSetRecord2); } private Environment createAndPersistDefultEnvironment() { Environment environment = Environment.Builder.defaultEnvironment().build(); return environmentRepository.save(environment); } }
Fix setting buildRecord and buildRecordSet id.
demo-data/src/main/java/org/jboss/pnc/demo/data/DatabaseDataInitializer.java
Fix setting buildRecord and buildRecordSet id.
<ide><path>emo-data/src/main/java/org/jboss/pnc/demo/data/DatabaseDataInitializer.java <ide> import org.jboss.pnc.datastore.repositories.*; <ide> import org.jboss.pnc.model.*; <ide> import org.jboss.pnc.model.ProductRelease.SupportLevel; <add>import org.jboss.pnc.spi.datastore.Datastore; <ide> <ide> import javax.ejb.Singleton; <ide> import javax.ejb.TransactionAttribute; <ide> <ide> @Inject <ide> EnvironmentRepository environmentRepository; <add> <add> @Inject <add> Datastore datastore; <ide> <ide> BuildConfiguration buildConfiguration1; <ide> <ide> BuildConfigurationAudited buildConfigAudited1 = buildConfigurationAuditedRepository.findOne(buildConfig1AuditIdRev); <ide> if (buildConfigAudited1 != null) { <ide> BuildRecord buildRecord = BuildRecord.Builder.newBuilder() <add> .id(datastore.getNextBuildRecordId()) <ide> .latestBuildConfiguration(buildConfiguration1) <ide> .buildConfigurationAudited(buildConfigAudited1) <ide> .startTime(Timestamp.from(Instant.now())) <ide> BuildConfigurationAudited buildConfigAudited2 = buildConfigurationAuditedRepository.findOne(buildConfig2AuditIdRev); <ide> if (buildConfigAudited2 != null) { <ide> BuildRecord buildRecord = BuildRecord.Builder.newBuilder() <add> .id(datastore.getNextBuildRecordId()) <ide> .latestBuildConfiguration(buildConfiguration2) <ide> .buildConfigurationAudited(buildConfigAudited2) <ide> .startTime(Timestamp.from(Instant.now()))
Java
apache-2.0
3e6661f75545d9235d86b76ced12a4f51f50470b
0
nate-rcl/irplus,nate-rcl/irplus
/** Copyright 2008 University of Rochester 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 edu.ur.ir.web.action.user; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.apache.log4j.Logger; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.Validateable; import edu.ur.ir.FileSystem; import edu.ur.ir.user.IrUser; import edu.ur.ir.user.PersonalFile; import edu.ur.ir.user.PersonalFolder; import edu.ur.ir.user.UserFileSystemService; import edu.ur.ir.user.UserService; import edu.ur.ir.user.UserWorkspaceIndexService; import edu.ur.ir.web.action.UserIdAware; /** * Show a set of files and folders for a given user. * * @author Nathan Sarr * */ public class ViewPersonalFolders extends ActionSupport implements UserIdAware, Validateable { /**Eclipse gernerated id */ private static final long serialVersionUID = 6684102482237911784L; /** Id of the suer who has folders */ private Long userId; /** The user who owns the folders */ private IrUser user; /** User information data access */ private UserService userService; /** Service for dealing with user file system */ private UserFileSystemService userFileSystemService; /** Service for dealing with indexing user information*/ private UserWorkspaceIndexService userWorkspaceIndexService; /** A collection of folders and files for a user in a given location of ther personal directory.*/ private List<FileSystem> fileSystem; /** set of folders that are the path for the current folder */ private Collection <PersonalFolder> folderPath; /** The folder that owns the listed files and folders */ private Long parentFolderId; /** list of folder ids to perform actions on*/ private Long[] folderIds; /** list of file ids to perform actions on*/ private Long[] fileIds; /** True indicates the folders were deleted */ private boolean foldersDeleted = true; /** Message used to indicate there is a problem with deleting the folders. */ private String foldersDeletedMessage; /** type of sort [ ascending | descending ] * this is for incoming requests */ private String sortType = "desc"; /** name of the element to sort on * this is for incoming requests */ private String sortElement = "type"; /** use the type sort this is information for the page */ private String folderTypeSort = "none"; /** use the name sort this is information for the page */ private String folderNameSort = "none"; /** Size of file system for user */ private Long fileSystemSize; /** Logger for vierw workspace action */ private static final Logger log = Logger.getLogger(ViewPersonalFolders.class); /** * Get folder table * * @return */ public String getTable() { if(parentFolderId != null && parentFolderId > 0) { PersonalFolder parent = userFileSystemService.getPersonalFolder(parentFolderId, false); if( !parent.getOwner().getId().equals(userId)) { return "accessDenied"; } } log.debug("getTableCalled"); createFileSystem(); return SUCCESS; } /** * Removes the select files and folders. * * @return */ public String deleteFileSystemObjects() { log.debug("Delete folders called"); user = userService.getUser(userId, false); if( folderIds != null ) { for(int index = 0; index < folderIds.length; index++) { log.debug("Deleting folder with id " + folderIds[index]); PersonalFolder pf = userFileSystemService.getPersonalFolder(folderIds[index], false); if( !pf.getOwner().getId().equals(userId)) { return "accessDenied"; } //un-index all the files List<PersonalFile> allFiles = userFileSystemService.getAllFilesInFolderAndSubFolder(pf.getId(), pf.getOwner().getId()); for(PersonalFile aFile : allFiles) { deleteFileFromIndex(aFile, user); } userWorkspaceIndexService.deleteFromIndex(pf); userFileSystemService.deletePersonalFolder(pf); } } if(fileIds != null) { for(int index = 0; index < fileIds.length; index++) { log.debug("Deleting file with id " + fileIds[index]); PersonalFile pf = userFileSystemService.getPersonalFile( fileIds[index], false); if( !pf.getOwner().getId().equals(userId)) { return "accessDenied"; } deleteFileFromIndex(pf, user); userFileSystemService.deletePersonalFile(pf); } } createFileSystem(); return SUCCESS; } /** * Deletes the file from the users index. If the user is the owner of the file * the file is removed from the indexes of all users. * * @param aFile - file to remove * @param aUser - user to remove the file from */ private void deleteFileFromIndex(PersonalFile aFile, IrUser aUser) { if(aFile.getOwner().equals(aUser)) { userWorkspaceIndexService.deleteFromAllIndexes(aFile); } else { userWorkspaceIndexService.deleteFromIndex(aFile); } } /** * Create the file system to view. */ private void createFileSystem() { user = userService.getUser(userId, false); if(parentFolderId != null && parentFolderId > 0) { folderPath = userFileSystemService.getPersonalFolderPath(parentFolderId); } Collection<PersonalFolder> myPersonalFolders = userFileSystemService.getPersonalFoldersForUser(userId, parentFolderId); Collection<PersonalFile> myPersonalFiles = userFileSystemService.getPersonalFilesInFolder(userId, parentFolderId); fileSystem = new LinkedList<FileSystem>(); fileSystem.addAll(myPersonalFolders); fileSystem.addAll(myPersonalFiles); FileSystemSortHelper sortHelper = new FileSystemSortHelper(); if( sortElement.equals("type")) { if(sortType.equals("asc")) { sortHelper.sort(fileSystem, FileSystemSortHelper.TYPE_ASC); folderTypeSort = "asc"; } else if( sortType.equals("desc")) { sortHelper.sort(fileSystem, FileSystemSortHelper.TYPE_DESC); folderTypeSort = "desc"; } else { folderTypeSort = "none"; } } if( sortElement.equals("name")) { if(sortType.equals("asc")) { sortHelper.sort(fileSystem, FileSystemSortHelper.NAME_ASC); folderNameSort = "asc"; } else if( sortType.equals("desc")) { sortHelper.sort(fileSystem, FileSystemSortHelper.NAME_DESC); folderNameSort = "desc"; } else { folderNameSort = "none"; } } fileSystemSize = userFileSystemService.getFileSystemSizeForUser(getUser()); } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } public Long getParentFolderId() { return parentFolderId; } public void setParentFolderId(Long parentFolderId) { this.parentFolderId = parentFolderId; } public Long[] getFolderIds() { return folderIds; } public void setFolderIds(Long[] folderIds) { this.folderIds = folderIds; } public boolean isFoldersDeleted() { return foldersDeleted; } public void setFoldersDeleted(boolean foldersDeleted) { this.foldersDeleted = foldersDeleted; } public String getFoldersDeletedMessage() { return foldersDeletedMessage; } public void setFoldersDeletedMessage(String foldersDeletedMessage) { this.foldersDeletedMessage = foldersDeletedMessage; } @SuppressWarnings("unchecked") public Collection getFileSystem() { return fileSystem; } public Long[] getFileIds() { return fileIds; } public void setFileIds(Long[] fileIds) { this.fileIds = fileIds; } public void validate() { log.debug("Validate called"); } public Collection<PersonalFolder> getFolderPath() { return folderPath; } public IrUser getUser() { return user; } public UserFileSystemService getUserFileSystemService() { return userFileSystemService; } public void setUserFileSystemService(UserFileSystemService userFileSystemService) { this.userFileSystemService = userFileSystemService; } public UserWorkspaceIndexService getUserWorkspaceIndexService() { return userWorkspaceIndexService; } public void setUserWorkspaceIndexService(UserWorkspaceIndexService userIndexService) { this.userWorkspaceIndexService = userIndexService; } public String getSortType() { return sortType; } public void setSortType(String sortType) { this.sortType = sortType; } public String getSortElement() { return sortElement; } public void setSortElement(String sortElement) { this.sortElement = sortElement; } public String getFolderTypeSort() { return folderTypeSort; } public void setFolderTypeSort(String typeHeaderSort) { this.folderTypeSort = typeHeaderSort; } public String getFolderNameSort() { return folderNameSort; } public void setFolderNameSort(String folderIdSort) { this.folderNameSort = folderIdSort; } public Long getFileSystemSize() { return fileSystemSize; } public void setUserId(Long userId) { this.userId = userId; } }
ir_web/src/edu/ur/ir/web/action/user/ViewPersonalFolders.java
/** Copyright 2008 University of Rochester 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 edu.ur.ir.web.action.user; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.apache.log4j.Logger; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.Validateable; import edu.ur.ir.FileSystem; import edu.ur.ir.user.IrUser; import edu.ur.ir.user.PersonalFile; import edu.ur.ir.user.PersonalFolder; import edu.ur.ir.user.UserFileSystemService; import edu.ur.ir.user.UserService; import edu.ur.ir.user.UserWorkspaceIndexService; import edu.ur.ir.web.action.UserIdAware; /** * Show a set of files and folders for a given user. * * @author Nathan Sarr * */ public class ViewPersonalFolders extends ActionSupport implements UserIdAware, Validateable { /**Eclipse gernerated id */ private static final long serialVersionUID = 6684102482237911784L; /** Id of the suer who has folders */ private Long userId; /** The user who owns the folders */ private IrUser user; /** User information data access */ private UserService userService; /** Service for dealing with user file system */ private UserFileSystemService userFileSystemService; /** Service for dealing with indexing user information*/ private UserWorkspaceIndexService userWorkspaceIndexService; /** A collection of folders and files for a user in a given location of ther personal directory.*/ private List<FileSystem> fileSystem; /** set of folders that are the path for the current folder */ private Collection <PersonalFolder> folderPath; /** The folder that owns the listed files and folders */ private Long parentFolderId; /** list of folder ids to perform actions on*/ private Long[] folderIds; /** list of file ids to perform actions on*/ private Long[] fileIds; /** True indicates the folders were deleted */ private boolean foldersDeleted = true; /** Message used to indicate there is a problem with deleting the folders. */ private String foldersDeletedMessage; /** type of sort [ ascending | descending ] * this is for incoming requests */ private String sortType = "desc"; /** name of the element to sort on * this is for incoming requests */ private String sortElement = "type"; /** use the type sort this is information for the page */ private String folderTypeSort = "none"; /** use the name sort this is information for the page */ private String folderNameSort = "none"; /** Size of file system for user */ private Long fileSystemSize; /** Logger for vierw workspace action */ private static final Logger log = Logger.getLogger(ViewPersonalFolders.class); /** * Get folder table * * @return */ public String getTable() { log.debug("getTableCalled"); createFileSystem(); return SUCCESS; } /** * Removes the select files and folders. * * @return */ public String deleteFileSystemObjects() { log.debug("Delete folders called"); user = userService.getUser(userId, false); if( folderIds != null ) { for(int index = 0; index < folderIds.length; index++) { log.debug("Deleting folder with id " + folderIds[index]); PersonalFolder pf = userFileSystemService.getPersonalFolder(folderIds[index], false); if( !pf.getOwner().getId().equals(userId)) { return "accessDenied"; } //un-index all the files List<PersonalFile> allFiles = userFileSystemService.getAllFilesInFolderAndSubFolder(pf.getId(), pf.getOwner().getId()); for(PersonalFile aFile : allFiles) { deleteFileFromIndex(aFile, user); } userWorkspaceIndexService.deleteFromIndex(pf); userFileSystemService.deletePersonalFolder(pf); } } if(fileIds != null) { for(int index = 0; index < fileIds.length; index++) { log.debug("Deleting file with id " + fileIds[index]); PersonalFile pf = userFileSystemService.getPersonalFile( fileIds[index], false); if( !pf.getOwner().getId().equals(userId)) { return "accessDenied"; } deleteFileFromIndex(pf, user); userFileSystemService.deletePersonalFile(pf); } } createFileSystem(); return SUCCESS; } /** * Deletes the file from the users index. If the user is the owner of the file * the file is removed from the indexes of all users. * * @param aFile - file to remove * @param aUser - user to remove the file from */ private void deleteFileFromIndex(PersonalFile aFile, IrUser aUser) { if(aFile.getOwner().equals(aUser)) { userWorkspaceIndexService.deleteFromAllIndexes(aFile); } else { userWorkspaceIndexService.deleteFromIndex(aFile); } } /** * Create the file system to view. */ private void createFileSystem() { user = userService.getUser(userId, false); if(parentFolderId != null && parentFolderId > 0) { folderPath = userFileSystemService.getPersonalFolderPath(parentFolderId); } Collection<PersonalFolder> myPersonalFolders = userFileSystemService.getPersonalFoldersForUser(userId, parentFolderId); Collection<PersonalFile> myPersonalFiles = userFileSystemService.getPersonalFilesInFolder(userId, parentFolderId); fileSystem = new LinkedList<FileSystem>(); fileSystem.addAll(myPersonalFolders); fileSystem.addAll(myPersonalFiles); FileSystemSortHelper sortHelper = new FileSystemSortHelper(); if( sortElement.equals("type")) { if(sortType.equals("asc")) { sortHelper.sort(fileSystem, FileSystemSortHelper.TYPE_ASC); folderTypeSort = "asc"; } else if( sortType.equals("desc")) { sortHelper.sort(fileSystem, FileSystemSortHelper.TYPE_DESC); folderTypeSort = "desc"; } else { folderTypeSort = "none"; } } if( sortElement.equals("name")) { if(sortType.equals("asc")) { sortHelper.sort(fileSystem, FileSystemSortHelper.NAME_ASC); folderNameSort = "asc"; } else if( sortType.equals("desc")) { sortHelper.sort(fileSystem, FileSystemSortHelper.NAME_DESC); folderNameSort = "desc"; } else { folderNameSort = "none"; } } fileSystemSize = userFileSystemService.getFileSystemSizeForUser(getUser()); } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } public Long getParentFolderId() { return parentFolderId; } public void setParentFolderId(Long parentFolderId) { this.parentFolderId = parentFolderId; } public Long[] getFolderIds() { return folderIds; } public void setFolderIds(Long[] folderIds) { this.folderIds = folderIds; } public boolean isFoldersDeleted() { return foldersDeleted; } public void setFoldersDeleted(boolean foldersDeleted) { this.foldersDeleted = foldersDeleted; } public String getFoldersDeletedMessage() { return foldersDeletedMessage; } public void setFoldersDeletedMessage(String foldersDeletedMessage) { this.foldersDeletedMessage = foldersDeletedMessage; } @SuppressWarnings("unchecked") public Collection getFileSystem() { return fileSystem; } public Long[] getFileIds() { return fileIds; } public void setFileIds(Long[] fileIds) { this.fileIds = fileIds; } public void validate() { log.debug("Validate called"); } public Collection<PersonalFolder> getFolderPath() { return folderPath; } public IrUser getUser() { return user; } public UserFileSystemService getUserFileSystemService() { return userFileSystemService; } public void setUserFileSystemService(UserFileSystemService userFileSystemService) { this.userFileSystemService = userFileSystemService; } public UserWorkspaceIndexService getUserWorkspaceIndexService() { return userWorkspaceIndexService; } public void setUserWorkspaceIndexService(UserWorkspaceIndexService userIndexService) { this.userWorkspaceIndexService = userIndexService; } public String getSortType() { return sortType; } public void setSortType(String sortType) { this.sortType = sortType; } public String getSortElement() { return sortElement; } public void setSortElement(String sortElement) { this.sortElement = sortElement; } public String getFolderTypeSort() { return folderTypeSort; } public void setFolderTypeSort(String typeHeaderSort) { this.folderTypeSort = typeHeaderSort; } public String getFolderNameSort() { return folderNameSort; } public void setFolderNameSort(String folderIdSort) { this.folderNameSort = folderIdSort; } public Long getFileSystemSize() { return fileSystemSize; } public void setUserId(Long userId) { this.userId = userId; } }
updated to prevent users from seeing folder path
ir_web/src/edu/ur/ir/web/action/user/ViewPersonalFolders.java
updated to prevent users from seeing folder path
<ide><path>r_web/src/edu/ur/ir/web/action/user/ViewPersonalFolders.java <ide> */ <ide> public String getTable() <ide> { <add> if(parentFolderId != null && parentFolderId > 0) <add> { <add> PersonalFolder parent = userFileSystemService.getPersonalFolder(parentFolderId, false); <add> if( !parent.getOwner().getId().equals(userId)) <add> { <add> return "accessDenied"; <add> } <add> } <ide> log.debug("getTableCalled"); <ide> createFileSystem(); <ide>
Java
apache-2.0
bcc8de19c571c17b7e11205a848b086e87318e76
0
SUPERCILEX/FirebaseUI-Android,SUPERCILEX/FirebaseUI-Android,SUPERCILEX/FirebaseUI-Android,SUPERCILEX/FirebaseUI-Android
/* * Copyright 2016 Google Inc. 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 * * 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.firebase.uidemo.database; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.firebase.ui.database.FirebaseIndexRecyclerAdapter; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.firebase.uidemo.R; import com.firebase.uidemo.util.SignInResultNotifier; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class ChatActivity extends AppCompatActivity implements FirebaseAuth.AuthStateListener { private static final String TAG = "RecyclerViewDemo"; private FirebaseAuth mAuth; private DatabaseReference mChatIndicesRef; private DatabaseReference mChatRef; private Button mSendButton; private EditText mMessageEdit; private RecyclerView mMessages; private LinearLayoutManager mManager; private FirebaseRecyclerAdapter<Chat, ChatHolder> mAdapter; private TextView mEmptyListMessage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat); mAuth = FirebaseAuth.getInstance(); mAuth.addAuthStateListener(this); mSendButton = (Button) findViewById(R.id.sendButton); mMessageEdit = (EditText) findViewById(R.id.messageEdit); mEmptyListMessage = (TextView) findViewById(R.id.emptyTextView); DatabaseReference ref = FirebaseDatabase.getInstance().getReference(); mChatIndicesRef = ref.child("chatIndices"); mChatRef = ref.child("chats"); mSendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String uid = mAuth.getCurrentUser().getUid(); String name = "User " + uid.substring(0, 6); Chat chat = new Chat(name, mMessageEdit.getText().toString(), uid); DatabaseReference chatRef = mChatRef.push(); mChatIndicesRef.child(chatRef.getKey()).setValue(true); chatRef.setValue(chat, new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError error, DatabaseReference reference) { if (error != null) { Log.e(TAG, "Failed to write message", error.toException()); } } }); mMessageEdit.setText(""); } }); mManager = new LinearLayoutManager(this); mManager.setReverseLayout(false); mMessages = (RecyclerView) findViewById(R.id.messagesList); mMessages.setHasFixedSize(false); mMessages.setLayoutManager(mManager); } @Override public void onStart() { super.onStart(); // Default Database rules do not allow unauthenticated reads, so we need to // sign in before attaching the RecyclerView adapter otherwise the Adapter will // not be able to read any data from the Database. if (isSignedIn()) { attachRecyclerViewAdapter(); } else { signInAnonymously(); } } @Override public void onStop() { super.onStop(); if (mAdapter != null) { mAdapter.cleanup(); } } @Override public void onDestroy() { super.onDestroy(); if (mAuth != null) { mAuth.removeAuthStateListener(this); } } @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { updateUI(); } private void attachRecyclerViewAdapter() { mAdapter = new FirebaseIndexRecyclerAdapter<Chat, ChatHolder>( Chat.class, R.layout.message, ChatHolder.class, mChatIndicesRef.limitToLast(50), mChatRef) { @Override public void populateViewHolder(final ChatHolder holder, Chat chat, int position) { holder.bind(chat); holder.itemView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() { @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { menu.add("Delete") .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { DatabaseReference ref = getRef(holder.getAdapterPosition()); mChatIndicesRef.child(ref.getKey()).removeValue(); ref.removeValue(); return true; } }); } }); } @Override public void onChildChanged(EventType type, int index, int oldIndex) { super.onChildChanged(type, index, oldIndex); // TODO temporary fix for https://github.com/firebase/FirebaseUI-Android/issues/546 onDataChanged(); } @Override public void onDataChanged() { // If there are no chat messages, show a view that invites the user to add a message. mEmptyListMessage.setVisibility(getItemCount() == 0 ? View.VISIBLE : View.GONE); } }; // Scroll to bottom on new messages mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { @Override public void onItemRangeInserted(int positionStart, int itemCount) { mManager.smoothScrollToPosition(mMessages, null, mAdapter.getItemCount()); } }); mMessages.setAdapter(mAdapter); } private void signInAnonymously() { Toast.makeText(this, "Signing in...", Toast.LENGTH_SHORT).show(); mAuth.signInAnonymously() .addOnSuccessListener(this, new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult result) { attachRecyclerViewAdapter(); } }) .addOnCompleteListener(new SignInResultNotifier(this)); } private boolean isSignedIn() { return mAuth.getCurrentUser() != null; } private void updateUI() { // Sending only allowed when signed in mSendButton.setEnabled(isSignedIn()); mMessageEdit.setEnabled(isSignedIn()); } }
app/src/main/java/com/firebase/uidemo/database/ChatActivity.java
/* * Copyright 2016 Google Inc. 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 * * 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.firebase.uidemo.database; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.firebase.ui.database.adapter.FirebaseIndexRecyclerAdapter; import com.firebase.ui.database.adapter.FirebaseRecyclerAdapter; import com.firebase.uidemo.R; import com.firebase.uidemo.util.SignInResultNotifier; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class ChatActivity extends AppCompatActivity implements FirebaseAuth.AuthStateListener { private static final String TAG = "RecyclerViewDemo"; private FirebaseAuth mAuth; private DatabaseReference mChatIndicesRef; private DatabaseReference mChatRef; private Button mSendButton; private EditText mMessageEdit; private RecyclerView mMessages; private LinearLayoutManager mManager; private FirebaseRecyclerAdapter<Chat, ChatHolder> mAdapter; private TextView mEmptyListMessage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat); mAuth = FirebaseAuth.getInstance(); mAuth.addAuthStateListener(this); mSendButton = (Button) findViewById(R.id.sendButton); mMessageEdit = (EditText) findViewById(R.id.messageEdit); mEmptyListMessage = (TextView) findViewById(R.id.emptyTextView); DatabaseReference ref = FirebaseDatabase.getInstance().getReference(); mChatIndicesRef = ref.child("chatIndices"); mChatRef = ref.child("chats"); mSendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String uid = mAuth.getCurrentUser().getUid(); String name = "User " + uid.substring(0, 6); Chat chat = new Chat(name, mMessageEdit.getText().toString(), uid); DatabaseReference chatRef = mChatRef.push(); mChatIndicesRef.child(chatRef.getKey()).setValue(true); chatRef.setValue(chat, new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError error, DatabaseReference reference) { if (error != null) { Log.e(TAG, "Failed to write message", error.toException()); } } }); mMessageEdit.setText(""); } }); mManager = new LinearLayoutManager(this); mManager.setReverseLayout(false); mMessages = (RecyclerView) findViewById(R.id.messagesList); mMessages.setHasFixedSize(false); mMessages.setLayoutManager(mManager); } @Override public void onStart() { super.onStart(); // Default Database rules do not allow unauthenticated reads, so we need to // sign in before attaching the RecyclerView adapter otherwise the Adapter will // not be able to read any data from the Database. if (isSignedIn()) { attachRecyclerViewAdapter(); } else { signInAnonymously(); } } @Override public void onStop() { super.onStop(); if (mAdapter != null) { mAdapter.cleanup(); } } @Override public void onDestroy() { super.onDestroy(); if (mAuth != null) { mAuth.removeAuthStateListener(this); } } @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { updateUI(); } private void attachRecyclerViewAdapter() { mAdapter = new FirebaseIndexRecyclerAdapter<Chat, ChatHolder>( Chat.class, R.layout.message, ChatHolder.class, mChatIndicesRef.limitToLast(50), mChatRef) { @Override public void populateViewHolder(final ChatHolder holder, Chat chat, int position) { holder.bind(chat); holder.itemView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() { @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { menu.add("Delete") .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { DatabaseReference ref = getRef(holder.getAdapterPosition()); mChatIndicesRef.child(ref.getKey()).removeValue(); ref.removeValue(); return true; } }); } }); } @Override public void onChildChanged(EventType type, int index, int oldIndex) { super.onChildChanged(type, index, oldIndex); // TODO temporary fix for https://github.com/firebase/FirebaseUI-Android/issues/546 onDataChanged(); } @Override public void onDataChanged() { // If there are no chat messages, show a view that invites the user to add a message. mEmptyListMessage.setVisibility(getItemCount() == 0 ? View.VISIBLE : View.GONE); } }; // Scroll to bottom on new messages mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { @Override public void onItemRangeInserted(int positionStart, int itemCount) { mManager.smoothScrollToPosition(mMessages, null, mAdapter.getItemCount()); } }); mMessages.setAdapter(mAdapter); } private void signInAnonymously() { Toast.makeText(this, "Signing in...", Toast.LENGTH_SHORT).show(); mAuth.signInAnonymously() .addOnSuccessListener(this, new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult result) { attachRecyclerViewAdapter(); } }) .addOnCompleteListener(new SignInResultNotifier(this)); } private boolean isSignedIn() { return mAuth.getCurrentUser() != null; } private void updateUI() { // Sending only allowed when signed in mSendButton.setEnabled(isSignedIn()); mMessageEdit.setEnabled(isSignedIn()); } }
Fix compile errors Signed-off-by: Alex Saveau <[email protected]>
app/src/main/java/com/firebase/uidemo/database/ChatActivity.java
Fix compile errors
<ide><path>pp/src/main/java/com/firebase/uidemo/database/ChatActivity.java <ide> import android.widget.TextView; <ide> import android.widget.Toast; <ide> <del>import com.firebase.ui.database.adapter.FirebaseIndexRecyclerAdapter; <del>import com.firebase.ui.database.adapter.FirebaseRecyclerAdapter; <add>import com.firebase.ui.database.FirebaseIndexRecyclerAdapter; <add>import com.firebase.ui.database.FirebaseRecyclerAdapter; <ide> import com.firebase.uidemo.R; <ide> import com.firebase.uidemo.util.SignInResultNotifier; <ide> import com.google.android.gms.tasks.OnSuccessListener;
Java
apache-2.0
d8d7110b89708e8187474cb476747c306157f593
0
andrey-kuznetsov/ignite,samaitra/ignite,ilantukh/ignite,samaitra/ignite,andrey-kuznetsov/ignite,daradurvs/ignite,xtern/ignite,ilantukh/ignite,xtern/ignite,daradurvs/ignite,SomeFire/ignite,samaitra/ignite,samaitra/ignite,daradurvs/ignite,SomeFire/ignite,daradurvs/ignite,andrey-kuznetsov/ignite,NSAmelchev/ignite,apache/ignite,SomeFire/ignite,andrey-kuznetsov/ignite,SomeFire/ignite,xtern/ignite,nizhikov/ignite,ascherbakoff/ignite,chandresh-pancholi/ignite,shroman/ignite,daradurvs/ignite,samaitra/ignite,andrey-kuznetsov/ignite,andrey-kuznetsov/ignite,chandresh-pancholi/ignite,ascherbakoff/ignite,chandresh-pancholi/ignite,NSAmelchev/ignite,nizhikov/ignite,NSAmelchev/ignite,xtern/ignite,SomeFire/ignite,apache/ignite,chandresh-pancholi/ignite,NSAmelchev/ignite,ascherbakoff/ignite,daradurvs/ignite,andrey-kuznetsov/ignite,ascherbakoff/ignite,nizhikov/ignite,ilantukh/ignite,ilantukh/ignite,xtern/ignite,daradurvs/ignite,ascherbakoff/ignite,ilantukh/ignite,andrey-kuznetsov/ignite,ilantukh/ignite,nizhikov/ignite,NSAmelchev/ignite,ascherbakoff/ignite,andrey-kuznetsov/ignite,ascherbakoff/ignite,NSAmelchev/ignite,apache/ignite,shroman/ignite,nizhikov/ignite,SomeFire/ignite,xtern/ignite,ilantukh/ignite,nizhikov/ignite,ilantukh/ignite,chandresh-pancholi/ignite,shroman/ignite,shroman/ignite,ascherbakoff/ignite,chandresh-pancholi/ignite,daradurvs/ignite,samaitra/ignite,shroman/ignite,apache/ignite,shroman/ignite,shroman/ignite,SomeFire/ignite,apache/ignite,shroman/ignite,apache/ignite,xtern/ignite,shroman/ignite,NSAmelchev/ignite,andrey-kuznetsov/ignite,nizhikov/ignite,SomeFire/ignite,chandresh-pancholi/ignite,NSAmelchev/ignite,SomeFire/ignite,samaitra/ignite,NSAmelchev/ignite,nizhikov/ignite,shroman/ignite,daradurvs/ignite,SomeFire/ignite,ilantukh/ignite,samaitra/ignite,nizhikov/ignite,samaitra/ignite,ascherbakoff/ignite,daradurvs/ignite,apache/ignite,chandresh-pancholi/ignite,samaitra/ignite,apache/ignite,xtern/ignite,chandresh-pancholi/ignite,xtern/ignite,apache/ignite,ilantukh/ignite
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.spi.discovery.tcp; import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.util.Collections; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.spi.IgniteSpiOperationTimeoutException; import org.apache.ignite.spi.IgniteSpiOperationTimeoutHelper; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder; import org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryAbstractMessage; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.junit.Test; /** * Test checks that if node cannot accept incoming connections it will be * kicked off and stopped. * * Older versions will infinitely retry to connect, but this will not lead * to node join and, as a consequence, to start exchange process. */ public class TcpDiscoveryFailedJoinTest extends GridCommonAbstractTest { /** */ private static final int FAIL_PORT = 47503; /** */ private SpiFailType failType = SpiFailType.REFUSE; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); TcpDiscoverySpi discoSpi = failType == SpiFailType.REFUSE ? new FailTcpDiscoverySpi() : new DropTcpDiscoverySpi(); discoSpi.setLocalPort(Integer.parseInt(gridName.split("-")[1])); TcpDiscoveryVmIpFinder finder = new TcpDiscoveryVmIpFinder(true); finder.setAddresses(Collections.singleton("127.0.0.1:47500..47503")); discoSpi.setIpFinder(finder); discoSpi.setNetworkTimeout(2_000); cfg.setDiscoverySpi(discoSpi); if (gridName.contains("client")) { cfg.setClientMode(true); discoSpi.setForceServerMode(gridName.contains("server")); } return cfg; } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { stopAllGrids(); } /** * @throws Exception If failed. */ @Test public void testDiscoveryRefuse() throws Exception { failType = SpiFailType.REFUSE; startGrid("server-47500"); startGrid("server-47501"); startGrid("server-47502"); assertStartFailed("server-47503"); // Client in server mode. assertStartFailed("client_server-47503"); // Regular client starts normally. startGrid("client-47503"); } /** * @throws Exception If failed. */ @Test public void testDiscoveryDrop() throws Exception { failType = SpiFailType.DROP; startGrid("server-47500"); startGrid("server-47501"); startGrid("server-47502"); assertStartFailed("server-47503"); // Client in server mode. assertStartFailed("client_server-47503"); // Regular client starts normally. startGrid("client-47503"); } /** * @param name Name. */ private void assertStartFailed(final String name) { //noinspection ThrowableNotThrown GridTestUtils.assertThrows(log, () -> { startGrid(name); return null; }, IgniteCheckedException.class, null); } /** * */ private static class FailTcpDiscoverySpi extends TcpDiscoverySpi { /** {@inheritDoc} */ @Override protected Socket openSocket(InetSocketAddress sockAddr, IgniteSpiOperationTimeoutHelper timeoutHelper) throws IOException, IgniteSpiOperationTimeoutException { if (sockAddr.getPort() == FAIL_PORT) throw new SocketException("Connection refused"); return super.openSocket(sockAddr, timeoutHelper); } /** {@inheritDoc} */ @Override protected Socket openSocket(Socket sock, InetSocketAddress remAddr, IgniteSpiOperationTimeoutHelper timeoutHelper) throws IOException, IgniteSpiOperationTimeoutException { if (remAddr.getPort() == FAIL_PORT) throw new SocketException("Connection refused"); return super.openSocket(sock, remAddr, timeoutHelper); } } /** * Emulates situation when network drops packages. */ private static class DropTcpDiscoverySpi extends TcpDiscoverySpi { /** {@inheritDoc} */ @Override protected void writeToSocket(Socket sock, TcpDiscoveryAbstractMessage msg, byte[] data, long timeout) throws IOException { if (sock.getPort() != FAIL_PORT) super.writeToSocket(sock, msg, data, timeout); } /** {@inheritDoc} */ @Override protected void writeToSocket(Socket sock, TcpDiscoveryAbstractMessage msg, long timeout) throws IOException, IgniteCheckedException { if (sock.getPort() != FAIL_PORT) super.writeToSocket(sock, msg, timeout); } /** {@inheritDoc} */ @Override protected void writeToSocket(ClusterNode node, Socket sock, OutputStream out, TcpDiscoveryAbstractMessage msg, long timeout) throws IOException, IgniteCheckedException { if (sock.getPort() != FAIL_PORT) super.writeToSocket(node, sock, out, msg, timeout); } /** {@inheritDoc} */ @Override protected void writeToSocket(Socket sock, OutputStream out, TcpDiscoveryAbstractMessage msg, long timeout) throws IOException, IgniteCheckedException { if (sock.getPort() != FAIL_PORT) super.writeToSocket(sock, out, msg, timeout); } /** {@inheritDoc} */ @Override protected void writeToSocket(TcpDiscoveryAbstractMessage msg, Socket sock, int res, long timeout) throws IOException { if (sock.getPort() != FAIL_PORT) super.writeToSocket(msg, sock, res, timeout); } } /** * */ private enum SpiFailType { /** */ REFUSE, /** */ DROP } }
modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoveryFailedJoinTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.spi.discovery.tcp; import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.util.Collections; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.spi.IgniteSpiOperationTimeoutException; import org.apache.ignite.spi.IgniteSpiOperationTimeoutHelper; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder; import org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryAbstractMessage; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.junit.After; import org.junit.Test; /** * Test checks that if node cannot accept incoming connections it will be * kicked off and stopped. * * Older versions will infinitely retry to connect, but this will not lead * to node join and, as a consequence, to start exchange process. */ public class TcpDiscoveryFailedJoinTest extends GridCommonAbstractTest { /** */ private static final int FAIL_PORT = 47503; /** */ private SpiFailType failType = SpiFailType.REFUSE; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); TcpDiscoverySpi discoSpi = failType == SpiFailType.REFUSE ? new FailTcpDiscoverySpi() : new DropTcpDiscoverySpi(); discoSpi.setLocalPort(Integer.parseInt(gridName.split("-")[1])); TcpDiscoveryVmIpFinder finder = new TcpDiscoveryVmIpFinder(true); finder.setAddresses(Collections.singleton("127.0.0.1:47500..47503")); discoSpi.setIpFinder(finder); discoSpi.setNetworkTimeout(2_000); cfg.setDiscoverySpi(discoSpi); if (gridName.contains("client")) { cfg.setClientMode(true); discoSpi.setForceServerMode(gridName.contains("server")); } return cfg; } /** */ @After public void afterTest() throws Exception { stopAllGrids(); } /** * @throws Exception If failed. */ @Test public void testDiscoveryRefuse() throws Exception { failType = SpiFailType.REFUSE; startGrid("server-47500"); startGrid("server-47501"); startGrid("server-47502"); assertStartFailed("server-47503"); // Client in server mode. assertStartFailed("client_server-47503"); // Regular client starts normally. startGrid("client-47503"); } /** * @throws Exception If failed. */ @Test public void testDiscoveryDrop() throws Exception { failType = SpiFailType.DROP; startGrid("server-47500"); startGrid("server-47501"); startGrid("server-47502"); assertStartFailed("server-47503"); // Client in server mode. assertStartFailed("client_server-47503"); // Regular client starts normally. startGrid("client-47503"); } /** * @param name Name. */ private void assertStartFailed(final String name) { //noinspection ThrowableNotThrown GridTestUtils.assertThrows(log, () -> { startGrid(name); return null; }, IgniteCheckedException.class, null); } /** * */ private static class FailTcpDiscoverySpi extends TcpDiscoverySpi { /** {@inheritDoc} */ @Override protected Socket openSocket(InetSocketAddress sockAddr, IgniteSpiOperationTimeoutHelper timeoutHelper) throws IOException, IgniteSpiOperationTimeoutException { if (sockAddr.getPort() == FAIL_PORT) throw new SocketException("Connection refused"); return super.openSocket(sockAddr, timeoutHelper); } /** {@inheritDoc} */ @Override protected Socket openSocket(Socket sock, InetSocketAddress remAddr, IgniteSpiOperationTimeoutHelper timeoutHelper) throws IOException, IgniteSpiOperationTimeoutException { if (remAddr.getPort() == FAIL_PORT) throw new SocketException("Connection refused"); return super.openSocket(sock, remAddr, timeoutHelper); } } /** * Emulates situation when network drops packages. */ private static class DropTcpDiscoverySpi extends TcpDiscoverySpi { /** {@inheritDoc} */ @Override protected void writeToSocket(Socket sock, TcpDiscoveryAbstractMessage msg, byte[] data, long timeout) throws IOException { if (sock.getPort() != FAIL_PORT) super.writeToSocket(sock, msg, data, timeout); } /** {@inheritDoc} */ @Override protected void writeToSocket(Socket sock, TcpDiscoveryAbstractMessage msg, long timeout) throws IOException, IgniteCheckedException { if (sock.getPort() != FAIL_PORT) super.writeToSocket(sock, msg, timeout); } /** {@inheritDoc} */ @Override protected void writeToSocket(ClusterNode node, Socket sock, OutputStream out, TcpDiscoveryAbstractMessage msg, long timeout) throws IOException, IgniteCheckedException { if (sock.getPort() != FAIL_PORT) super.writeToSocket(node, sock, out, msg, timeout); } /** {@inheritDoc} */ @Override protected void writeToSocket(Socket sock, OutputStream out, TcpDiscoveryAbstractMessage msg, long timeout) throws IOException, IgniteCheckedException { if (sock.getPort() != FAIL_PORT) super.writeToSocket(sock, out, msg, timeout); } /** {@inheritDoc} */ @Override protected void writeToSocket(TcpDiscoveryAbstractMessage msg, Socket sock, int res, long timeout) throws IOException { if (sock.getPort() != FAIL_PORT) super.writeToSocket(msg, sock, res, timeout); } } /** * */ private enum SpiFailType { /** */ REFUSE, /** */ DROP } }
IGNITE-11568 Change afterTest() annotation in TcpDiscoveryFailedJoinTest (#6303)
modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoveryFailedJoinTest.java
IGNITE-11568 Change afterTest() annotation in TcpDiscoveryFailedJoinTest (#6303)
<ide><path>odules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoveryFailedJoinTest.java <ide> import org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryAbstractMessage; <ide> import org.apache.ignite.testframework.GridTestUtils; <ide> import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; <del>import org.junit.After; <ide> import org.junit.Test; <ide> <ide> /** <ide> return cfg; <ide> } <ide> <del> /** */ <del> @After <del> public void afterTest() throws Exception { <add> /** {@inheritDoc} */ <add> @Override protected void afterTest() throws Exception { <ide> stopAllGrids(); <ide> } <ide>
Java
apache-2.0
ff920be0fe4b1469da075989033cce17ab4e8005
0
google-code-export/xtandem-parser,google-code-export/xtandem-parser
package de.proteinms.xtandemparser.xtandem; import de.proteinms.xtandemparser.interfaces.Ion; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; /** * This class holds the peptide informatin in a map. * * @author Thilo Muth */ public class PeptideMap implements Serializable { /** * This variable holds the second dimension hash map for the peptide object as value. */ private HashMap<String, Peptide> iPeptideMap = null; /** * This variable holds the first dimension hash map for the peptide hash map as value. */ private HashMap<String, HashMap> iSpectrumAndPeptideMap = null; /** * Builds the peptide map * * @param aRawPeptideMap * @param aProteinMap * @param aNumberOfSpectra */ public PeptideMap(HashMap aRawPeptideMap, ProteinMap aProteinMap, int aNumberOfSpectra) { buildPeptideMap(aRawPeptideMap, aProteinMap, aNumberOfSpectra); } /** * Constructs the 2-dim hashmap, the first dimension is the map with the spectrum-number * as key and another hash map as value. The second dimension has the peptideID (e.g. * s171_p2 for spectrum number 171 and the second peptide) and the peptide object as value. * * @param aRawPeptideMap * @param aProteinMap * @param aNumberOfSpectra * @return spectrumAndPeptideMap */ private HashMap buildPeptideMap(HashMap aRawPeptideMap, ProteinMap aProteinMap, int aNumberOfSpectra) { // First dimension of the map, which contains the spectra as key and the peptide hash maps as values iSpectrumAndPeptideMap = new HashMap(aNumberOfSpectra); // Hashmap for the peptide objects iPeptideMap = new HashMap<String, Peptide>(); if (aRawPeptideMap != null) { for (int i = 1; i <= aNumberOfSpectra; i++) { // The counter for the peptides int counter = 1; // Check if there are any values given out of the map while (aRawPeptideMap.get("s" + i + "_p" + counter) != null) { // The peptide id is consists of s + spectrum# + _p + peptide# String peptideID = ("s" + i + "_p" + counter).toString(); int peptideStart = Integer.parseInt(aRawPeptideMap.get("start" + "_s" + i + "_p" + counter).toString()); int peptideEnd = Integer.parseInt(aRawPeptideMap.get("end" + "_s" + i + "_p" + counter).toString()); String sequence = aRawPeptideMap.get("seq" + "_s" + i + "_p" + counter).toString().trim(); // Create an instance of a protein. Peptide peptide = new Peptide(peptideID, peptideStart, peptideEnd, sequence); // Set the domain values peptide.setSpectrumNumber(i); peptide.setDomainID(aRawPeptideMap.get("domainid" + "_s" + i + "_p" + counter).toString()); peptide.setDomainStart(Integer.parseInt(aRawPeptideMap.get("domainstart" + "_s" + i + "_p" + counter).toString())); peptide.setDomainEnd(Integer.parseInt(aRawPeptideMap.get("domainend" + "_s" + i + "_p" + counter).toString())); peptide.setDomainExpect(Double.parseDouble(aRawPeptideMap.get("expect" + "_s" + i + "_p" + counter).toString())); peptide.setDomainMh(Double.parseDouble(aRawPeptideMap.get("mh" + "_s" + i + "_p" + counter).toString())); peptide.setDomainDeltaMh(Double.parseDouble(aRawPeptideMap.get("delta" + "_s" + i + "_p" + counter).toString())); peptide.setDomainHyperScore(Double.parseDouble(aRawPeptideMap.get("hyperscore" + "_s" + i + "_p" + counter).toString())); peptide.setDomainNextScore(Double.parseDouble(aRawPeptideMap.get("nextscore" + "_s" + i + "_p" + counter).toString())); ArrayList<Ion> ionList = new ArrayList<Ion>(); // if(aRawPeptideMap.get("a_score" + "_s" + i +"_p" + counter) != null ){ // double aScore = Double.parseDouble(aRawPeptideMap.get("a_score" + "_s" + i +"_p" + counter).toString()); // int aNumber = Integer.parseInt(aRawPeptideMap.get("a_ions" + "_s" + i +"_p" + counter).toString()); // Ion aIon = new Ion (aNumber, aScore); // aIon.setType(interfaces.aION_TYPE); // ionList.add(aIon); // } // // if (aRawPeptideMap.get("b_score" + "_s" + i +"_p" + counter) != null){ // double bScore = Double.parseDouble(aRawPeptideMap.get("b_score" + "_s" + i +"_p" + counter).toString()); // int bNumber = Integer.parseInt(aRawPeptideMap.get("b_ions" + "_s" + i +"_p" + counter).toString()); // Ion bIon = new Ion (bNumber, bScore); // bIon.setType(interfaces.bION_TYPE); // ionList.add(bIon); // } // // if(aRawPeptideMap.get("c_score" + "_s" + i +"_p" + counter) != null){ // double cScore = Double.parseDouble(aRawPeptideMap.get("c_score" + "_s" + i +"_p" + counter).toString()); // int cNumber = Integer.parseInt(aRawPeptideMap.get("c_ions" + "_s" + i +"_p" + counter).toString()); // Ion cIon = new Ion (cNumber, cScore); // cIon.setType(interfaces.cION_TYPE); // ionList.add(cIon); // } // // if(aRawPeptideMap.get("x_score" + "_s" + i +"_p" + counter) != null){ // double xScore = Double.parseDouble(aRawPeptideMap.get("x_score" + "_s" + i +"_p" + counter).toString()); // int xNumber = Integer.parseInt(aRawPeptideMap.get("x_ions" + "_s" + i +"_p" + counter).toString()); // Ion xIon = new Ion (xNumber, xScore); // xIon.setType(interfaces.xION_TYPE); // ionList.add(xIon); // } // // if(aRawPeptideMap.get("y_score" + "_s" + i +"_p" + counter) != null){ // double yScore = Double.parseDouble(aRawPeptideMap.get("y_score" + "_s" + i +"_p" + counter).toString()); // int yNumber = Integer.parseInt(aRawPeptideMap.get("y_ions" + "_s" + i +"_p" + counter).toString()); // Ion yIon = new Ion (yNumber, yScore); // yIon.setType(interfaces.yION_TYPE); // ionList.add(yIon); // } // // if(aRawPeptideMap.get("z_score" + "_s" + i +"_p" + counter) != null){ // double zScore = Double.parseDouble(aRawPeptideMap.get("z_score" + "_s" + i +"_p" + counter).toString()); // int zNumber = Integer.parseInt(aRawPeptideMap.get("z_ions" + "_s" + i +"_p" + counter).toString()); // Ion zIon = new Ion (zNumber, zScore); // zIon.setType(interfaces.zION_TYPE); // ionList.add(zIon); // } peptide.setIons(ionList); peptide.setUpFlankSequence(aRawPeptideMap.get("pre" + "_s" + i + "_p" + counter).toString()); peptide.setDownFlankSequence(aRawPeptideMap.get("post" + "_s" + i + "_p" + counter).toString()); peptide.setDomainSequence(aRawPeptideMap.get("domainseq" + "_s" + i + "_p" + counter).toString()); peptide.setMissedCleavages(Integer.parseInt(aRawPeptideMap.get("missed_cleavages" + "_s" + i + "_p" + counter).toString())); // Put the peptide into the map, value is the id. iPeptideMap.put(peptideID, peptide); counter++; } iSpectrumAndPeptideMap.put("s" + i, iPeptideMap); } } return iSpectrumAndPeptideMap; } /** * Returns the 2-dim spectrum and peptide map. * * @return iSpectrumAndPeptideMap HashMap */ public HashMap<String, HashMap> getSpectrumAndPeptideMap() { return iSpectrumAndPeptideMap; } /** * Retrieve all possible peptide objects for a given spectrum. * * @param aSpectrumNumber * @return peptideList ArrayList */ public ArrayList<Peptide> getAllPeptides(int aSpectrumNumber) { ArrayList<Peptide> peptideList = new ArrayList<Peptide>(); HashMap<String, Peptide> peptideMap = iSpectrumAndPeptideMap.get("s" + aSpectrumNumber); int pepCount = 1; while (peptideMap.get("s" + aSpectrumNumber + "_p" + pepCount) != null) { peptideList.add(peptideMap.get("s" + aSpectrumNumber + "_p" + pepCount)); pepCount++; } return peptideList; } /** * Returns a specific peptide by an index. * * @param aSpectrumNumber * @param index * @return peptide Peptide */ public Peptide getPeptideByIndex(int aSpectrumNumber, int index) { ArrayList<Peptide> peptideList = this.getAllPeptides(aSpectrumNumber); Peptide peptide = null; if (peptideList.get(index - 1) != null) { peptide = peptideList.get(index - 1); } return peptide; } /** * Returns the number of peptides for a given spectrum * * @param aSpectrumNumber * @return The total number of peptides */ public int getNumberOfPeptides(int aSpectrumNumber) { return this.getAllPeptides(aSpectrumNumber).size(); } }
src/main/java/de/proteinms/xtandemparser/xtandem/PeptideMap.java
package de.proteinms.xtandemparser.xtandem; import de.proteinms.xtandemparser.interfaces.Ion; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; /** * This class holds the peptide informatin in a map. * * @author Thilo Muth */ public class PeptideMap implements Serializable { /** * This variable holds the second dimension hash map for the peptide object as value. */ private HashMap<String, Peptide> iPeptideMap = null; /** * This variable holds the first dimension hash map for the peptide hash map as value. */ private HashMap<String, HashMap> iSpectrumAndPeptideMap = null; /** * Builds the peptide map * * @param aRawPeptideMap * @param aProteinMap * @param aNumberOfSpectra */ public PeptideMap(HashMap aRawPeptideMap, ProteinMap aProteinMap, int aNumberOfSpectra) { buildPeptideMap(aRawPeptideMap, aProteinMap, aNumberOfSpectra); } /** * Constructs the 2-dim hashmap, the first dimension is the map with the spectrum-number * as key and another hash map as value. The second dimension has the peptideID (e.g. * s171_p2 for spectrum number 171 and the second peptide) and the peptide object as value. * * @param aRawPeptideMap * @param aProteinMap * @param aNumberOfSpectra * @return spectrumAndPeptideMap */ private HashMap buildPeptideMap(HashMap aRawPeptideMap, ProteinMap aProteinMap, int aNumberOfSpectra) { // First dimension of the map, which contains the spectra as key and the peptide hash maps as values iSpectrumAndPeptideMap = new HashMap(aNumberOfSpectra); // Hashmap for the peptide objects iPeptideMap = new HashMap<String, Peptide>(); if (aRawPeptideMap != null) { for (int i = 1; i <= aNumberOfSpectra; i++) { // The counter for the peptides int counter = 1; // Check if there are any values given out of the map while (aRawPeptideMap.get("s" + i + "_p" + counter) != null) { // The peptide id is consists of s + spectrum# + _p + peptide# String peptideID = ("s" + i + "_p" + counter).toString(); int peptideStart = Integer.parseInt(aRawPeptideMap.get("start" + "_s" + i + "_p" + counter).toString()); int peptideEnd = Integer.parseInt(aRawPeptideMap.get("end" + "_s" + i + "_p" + counter).toString()); String sequence = aRawPeptideMap.get("seq" + "_s" + i + "_p" + counter).toString().trim(); // Create an instance of a protein. Peptide peptide = new Peptide(peptideID, peptideStart, peptideEnd, sequence); // Set the domain values peptide.setSpectrumNumber(i); peptide.setDomainID(aRawPeptideMap.get("domainid" + "_s" + i + "_p" + counter).toString()); peptide.setDomainStart(Integer.parseInt(aRawPeptideMap.get("domainstart" + "_s" + i + "_p" + counter).toString())); peptide.setDomainEnd(Integer.parseInt(aRawPeptideMap.get("domainend" + "_s" + i + "_p" + counter).toString())); peptide.setDomainExpect(Double.parseDouble(aRawPeptideMap.get("expect" + "_s" + i + "_p" + counter).toString())); peptide.setDomainMh(Double.parseDouble(aRawPeptideMap.get("mh" + "_s" + i + "_p" + counter).toString())); peptide.setDomainDeltaMh(Double.parseDouble(aRawPeptideMap.get("delta" + "_s" + i + "_p" + counter).toString())); peptide.setDomainHyperScore(Double.parseDouble(aRawPeptideMap.get("hyperscore" + "_s" + i + "_p" + counter).toString())); peptide.setDomainNextScore(Double.parseDouble(aRawPeptideMap.get("nextscore" + "_s" + i + "_p" + counter).toString())); ArrayList<Ion> ionList = new ArrayList<Ion>(); // if(aRawPeptideMap.get("a_score" + "_s" + i +"_p" + counter) != null ){ // double aScore = Double.parseDouble(aRawPeptideMap.get("a_score" + "_s" + i +"_p" + counter).toString()); // int aNumber = Integer.parseInt(aRawPeptideMap.get("a_ions" + "_s" + i +"_p" + counter).toString()); // Ion aIon = new Ion (aNumber, aScore); // aIon.setType(interfaces.aION_TYPE); // ionList.add(aIon); // } // // if (aRawPeptideMap.get("b_score" + "_s" + i +"_p" + counter) != null){ // double bScore = Double.parseDouble(aRawPeptideMap.get("b_score" + "_s" + i +"_p" + counter).toString()); // int bNumber = Integer.parseInt(aRawPeptideMap.get("b_ions" + "_s" + i +"_p" + counter).toString()); // Ion bIon = new Ion (bNumber, bScore); // bIon.setType(interfaces.bION_TYPE); // ionList.add(bIon); // } // // if(aRawPeptideMap.get("c_score" + "_s" + i +"_p" + counter) != null){ // double cScore = Double.parseDouble(aRawPeptideMap.get("c_score" + "_s" + i +"_p" + counter).toString()); // int cNumber = Integer.parseInt(aRawPeptideMap.get("c_ions" + "_s" + i +"_p" + counter).toString()); // Ion cIon = new Ion (cNumber, cScore); // cIon.setType(interfaces.cION_TYPE); // ionList.add(cIon); // } // // if(aRawPeptideMap.get("x_score" + "_s" + i +"_p" + counter) != null){ // double xScore = Double.parseDouble(aRawPeptideMap.get("x_score" + "_s" + i +"_p" + counter).toString()); // int xNumber = Integer.parseInt(aRawPeptideMap.get("x_ions" + "_s" + i +"_p" + counter).toString()); // Ion xIon = new Ion (xNumber, xScore); // xIon.setType(interfaces.xION_TYPE); // ionList.add(xIon); // } // // if(aRawPeptideMap.get("y_score" + "_s" + i +"_p" + counter) != null){ // double yScore = Double.parseDouble(aRawPeptideMap.get("y_score" + "_s" + i +"_p" + counter).toString()); // int yNumber = Integer.parseInt(aRawPeptideMap.get("y_ions" + "_s" + i +"_p" + counter).toString()); // Ion yIon = new Ion (yNumber, yScore); // yIon.setType(interfaces.yION_TYPE); // ionList.add(yIon); // } // // if(aRawPeptideMap.get("z_score" + "_s" + i +"_p" + counter) != null){ // double zScore = Double.parseDouble(aRawPeptideMap.get("z_score" + "_s" + i +"_p" + counter).toString()); // int zNumber = Integer.parseInt(aRawPeptideMap.get("z_ions" + "_s" + i +"_p" + counter).toString()); // Ion zIon = new Ion (zNumber, zScore); // zIon.setType(interfaces.zION_TYPE); // ionList.add(zIon); // } peptide.setIons(ionList); peptide.setUpFlankSequence(aRawPeptideMap.get("pre" + "_s" + i + "_p" + counter).toString()); peptide.setDownFlankSequence(aRawPeptideMap.get("post" + "_s" + i + "_p" + counter).toString()); peptide.setDomainSequence(aRawPeptideMap.get("domainseq" + "_s" + i + "_p" + counter).toString()); peptide.setMissedCleavages(Integer.parseInt(aRawPeptideMap.get("missed_cleavages" + "_s" + i + "_p" + counter).toString())); // Put the peptide into the map, value is the id. iPeptideMap.put(peptideID, peptide); // Update the PeptideHit in the ProteinMap. // PeptideHit lPeptideHit = (PeptideHit) lSecondDimension.get(lCount - 1); // int lNumberOfProteinHits = lPeptideHit.getProteinHits().size(); // for (int k = 0; k < lNumberOfProteinHits; k++) { // ProteinHit lProteinHit = (ProteinHit) lPeptideHit.getProteinHits().get(k); // aProteinMap.addProteinSource(lProteinHit.getAccession(), i, lCount); // } counter++; } iSpectrumAndPeptideMap.put("s" + i, iPeptideMap); } } return iSpectrumAndPeptideMap; } /** * Returns the 2-dim spectrum and peptide map. * * @return iSpectrumAndPeptideMap HashMap */ public HashMap<String, HashMap> getSpectrumAndPeptideMap() { return iSpectrumAndPeptideMap; } /** * Retrieve all possible peptide objects for a given spectrum. * * @param aSpectrumNumber * @return peptideList ArrayList */ public ArrayList<Peptide> getAllPeptides(int aSpectrumNumber) { ArrayList<Peptide> peptideList = new ArrayList<Peptide>(); HashMap<String, Peptide> peptideMap = iSpectrumAndPeptideMap.get("s" + aSpectrumNumber); int pepCount = 1; while (peptideMap.get("s" + aSpectrumNumber + "_p" + pepCount) != null) { peptideList.add(peptideMap.get("s" + aSpectrumNumber + "_p" + pepCount)); pepCount++; } return peptideList; } /** * Returns a specific peptide by an index. * * @param aSpectrumNumber * @param index * @return peptide Peptide */ public Peptide getPeptideByIndex(int aSpectrumNumber, int index) { ArrayList<Peptide> peptideList = this.getAllPeptides(aSpectrumNumber); Peptide peptide = null; if (peptideList.get(index - 1) != null) { peptide = peptideList.get(index - 1); } return peptide; } /** * Returns the number of peptides for a given spectrum * * @param aSpectrumNumber * @return The total number of peptides */ public int getNumberOfPeptides(int aSpectrumNumber) { return this.getAllPeptides(aSpectrumNumber).size(); } }
Deleted comments
src/main/java/de/proteinms/xtandemparser/xtandem/PeptideMap.java
Deleted comments
<ide><path>rc/main/java/de/proteinms/xtandemparser/xtandem/PeptideMap.java <ide> // Put the peptide into the map, value is the id. <ide> iPeptideMap.put(peptideID, peptide); <ide> <del> // Update the PeptideHit in the ProteinMap. <del>// PeptideHit lPeptideHit = (PeptideHit) lSecondDimension.get(lCount - 1); <del>// int lNumberOfProteinHits = lPeptideHit.getProteinHits().size(); <del>// for (int k = 0; k < lNumberOfProteinHits; k++) { <del>// ProteinHit lProteinHit = (ProteinHit) lPeptideHit.getProteinHits().get(k); <del>// aProteinMap.addProteinSource(lProteinHit.getAccession(), i, lCount); <del>// } <ide> counter++; <ide> } <ide>
Java
epl-1.0
4abb6aaf8e5cc619ad164fd04b053622504a6dbe
0
paulvi/egit,rickard-von-essen/egit,wdliu/egit,SmithAndr/egit,collaborative-modeling/egit,spearce/egit,jdcasey/EGit,rickard-von-essen/egit,chalstrick/egit,SmithAndr/egit,bols-blue/eclipse_maven_autobuild_sample,jdcasey/EGit,paulvi/egit,mdoninger/egit,bols-blue/eclipse_maven_autobuild_sample,wdliu/egit,blizzy78/egit,spearce/egit,collaborative-modeling/egit
/******************************************************************************* * Copyright (C) 2008, Roger C. Soares <[email protected]> * Copyright (C) 2008, Shawn O. Pearce <[email protected]> * * 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 *******************************************************************************/ package org.eclipse.egit.ui.internal.history; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.compare.CompareEditorInput; import org.eclipse.compare.CompareUI; import org.eclipse.compare.ITypedElement; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Preferences; import org.eclipse.core.runtime.Preferences.IPropertyChangeListener; import org.eclipse.core.runtime.Preferences.PropertyChangeEvent; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.egit.core.ResourceList; import org.eclipse.egit.core.internal.storage.GitFileRevision; import org.eclipse.egit.core.project.RepositoryMapping; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.UIIcons; import org.eclipse.egit.ui.UIPreferences; import org.eclipse.egit.ui.UIText; import org.eclipse.egit.ui.internal.GitCompareFileRevisionEditorInput; import org.eclipse.egit.ui.internal.trace.GitTraceLocation; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.ActionContributionItem; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IContributionItem; 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.jface.resource.ImageDescriptor; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.util.OpenStrategy; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jgit.lib.AnyObjectId; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.IndexChangedEvent; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.RefsChangedEvent; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.RepositoryListener; import org.eclipse.jgit.revplot.PlotCommit; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevFlag; import org.eclipse.jgit.revwalk.RevSort; import org.eclipse.jgit.revwalk.filter.RevFilter; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.filter.AndTreeFilter; import org.eclipse.jgit.treewalk.filter.PathFilterGroup; import org.eclipse.jgit.treewalk.filter.TreeFilter; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.MenuDetectEvent; import org.eclipse.swt.events.MenuDetectListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.team.core.history.IFileRevision; import org.eclipse.team.internal.ui.IPreferenceIds; import org.eclipse.team.internal.ui.TeamUIPlugin; import org.eclipse.team.internal.ui.Utils; import org.eclipse.team.internal.ui.history.FileRevisionTypedElement; import org.eclipse.team.ui.history.HistoryPage; import org.eclipse.team.ui.synchronize.SaveableCompareEditorInput; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IReusableEditor; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction; import org.eclipse.ui.part.IPageSite; import org.eclipse.ui.progress.IWorkbenchSiteProgressService; /** Graphical commit history viewer. */ public class GitHistoryPage extends HistoryPage implements RepositoryListener { private static final String PREF_COMMENT_WRAP = UIPreferences.RESOURCEHISTORY_SHOW_COMMENT_WRAP; private static final String PREF_COMMENT_FILL = UIPreferences.RESOURCEHISTORY_SHOW_COMMENT_FILL; private static final String SHOW_COMMENT = UIPreferences.RESOURCEHISTORY_SHOW_REV_COMMENT; private static final String SHOW_FILES = UIPreferences.RESOURCEHISTORY_SHOW_REV_DETAIL; private static final String SPLIT_GRAPH = UIPreferences.RESOURCEHISTORY_GRAPH_SPLIT; private static final String SPLIT_INFO = UIPreferences.RESOURCEHISTORY_REV_SPLIT; private static final String SHOW_FIND_TOOLBAR = UIPreferences.RESOURCEHISTORY_SHOW_FINDTOOLBAR; private static final String POPUP_ID = "org.eclipse.egit.ui.historyPageContributions"; //$NON-NLS-1$ private IAction compareAction = new CompareWithWorkingTreeAction(); private IAction compareVersionsAction = new CompareVersionsAction(); private IAction viewVersionsAction = new ViewVersionsAction(); /** * Determine if the input can be shown in this viewer. * * @param object * an object that is hopefully of type ResourceList or IResource, * but may be anything (including null). * @return true if the input is a ResourceList or an IResource of type FILE, * FOLDER or PROJECT and we can show it; false otherwise. */ public static boolean canShowHistoryFor(final Object object) { if (object instanceof ResourceList) { final IResource[] array = ((ResourceList) object).getItems(); if (array.length == 0) return false; for (final IResource r : array) { if (!typeOk(r)) return false; } return true; } if (object instanceof IResource) { return typeOk((IResource) object); } return false; } private static boolean typeOk(final IResource object) { switch (object.getType()) { case IResource.FILE: case IResource.FOLDER: case IResource.PROJECT: return true; } return false; } /** Plugin private preference store for the current workspace. */ private Preferences prefs; /** Overall composite hosting all of our controls. */ private Composite ourControl; /** Split between {@link #graph} and {@link #revInfoSplit}. */ private SashForm graphDetailSplit; /** Split between {@link #commentViewer} and {@link #fileViewer}. */ private SashForm revInfoSplit; /** The table showing the DAG, first "paragraph", author, author date. */ private CommitGraphTable graph; /** Viewer displaying the currently selected commit of {@link #graph}. */ private CommitMessageViewer commentViewer; /** Viewer displaying file difference implied by {@link #graph}'s commit. */ private CommitFileDiffViewer fileViewer; /** Toolbar to find commits in the history view. */ private FindToolbar findToolbar; /** Our context menu manager for the entire page. */ private MenuManager popupMgr; /** Job that is updating our history view, if we are refreshing. */ private GenerateHistoryJob job; /** Revision walker that allocated our graph's commit nodes. */ private SWTWalk currentWalk; /** Last HEAD */ private AnyObjectId currentHeadId; /** We need to remember the current repository */ private Repository db; /** * Highlight flag that can be applied to commits to make them stand out. * <p> * Allocated at the same time as {@link #currentWalk}. If the walk * rebuilds, so must this flag. */ private RevFlag highlightFlag; /** * List of paths we used to limit {@link #currentWalk}; null if no paths. * <p> * Note that a change in this list requires that {@link #currentWalk} and * all of its associated commits. */ private List<String> pathFilters; /** * The selection provider tracks the selected revisions for the context menu */ private RevObjectSelectionProvider revObjectSelectionProvider; private static final String PREF_SHOWALLFILTER = "org.eclipse.egit.ui.githistorypage.showallfilter"; //$NON-NLS-1$ enum ShowFilter { SHOWALLRESOURCE, SHOWALLFOLDER, SHOWALLPROJECT, SHOWALLREPO, } class ShowFilterAction extends Action { private final ShowFilter filter; ShowFilterAction(ShowFilter filter, ImageDescriptor icon, String toolTipText) { super(null, IAction.AS_CHECK_BOX); this.filter = filter; setImageDescriptor(icon); setToolTipText(toolTipText); } @Override public void run() { String oldName = getName(); if (!isChecked()) { if (showAllFilter == filter) { showAllFilter = ShowFilter.SHOWALLRESOURCE; refresh(); } } if (isChecked() && showAllFilter != filter) { showAllFilter = filter; if (this != showAllRepoVersionsAction) showAllRepoVersionsAction.setChecked(false); if (this != showAllProjectVersionsAction) showAllProjectVersionsAction.setChecked(false); if (this != showAllFolderVersionsAction) showAllFolderVersionsAction.setChecked(false); refresh(); } GitHistoryPage.this.firePropertyChange(GitHistoryPage.this, P_NAME, oldName, getName()); Activator.getDefault().getPreferenceStore().setValue( PREF_SHOWALLFILTER, showAllFilter.toString()); } @Override public String toString() { return "ShowFilter[" + filter.toString() + "]"; //$NON-NLS-1$ //$NON-NLS-2$ } } private ShowFilter showAllFilter = ShowFilter.SHOWALLRESOURCE; private ShowFilterAction showAllRepoVersionsAction; private ShowFilterAction showAllProjectVersionsAction; private ShowFilterAction showAllFolderVersionsAction; private void createResourceFilterActions() { try { showAllFilter = ShowFilter.valueOf(Activator.getDefault() .getPreferenceStore().getString(PREF_SHOWALLFILTER)); } catch (IllegalArgumentException e) { showAllFilter = ShowFilter.SHOWALLRESOURCE; } showAllRepoVersionsAction = new ShowFilterAction( ShowFilter.SHOWALLREPO, UIIcons.FILTERREPO, UIText.HistoryPage_ShowAllVersionsForRepo); showAllProjectVersionsAction = new ShowFilterAction( ShowFilter.SHOWALLPROJECT, UIIcons.FILTERPROJECT, UIText.HistoryPage_ShowAllVersionsForProject); showAllFolderVersionsAction = new ShowFilterAction( ShowFilter.SHOWALLFOLDER, UIIcons.FILTERFOLDER, UIText.HistoryPage_ShowAllVersionsForFolder); showAllRepoVersionsAction .setChecked(showAllFilter == showAllRepoVersionsAction.filter); showAllProjectVersionsAction .setChecked(showAllFilter == showAllProjectVersionsAction.filter); showAllFolderVersionsAction .setChecked(showAllFilter == showAllFolderVersionsAction.filter); getSite().getActionBars().getToolBarManager().add(new Separator()); getSite().getActionBars().getToolBarManager().add( showAllRepoVersionsAction); getSite().getActionBars().getToolBarManager().add( showAllProjectVersionsAction); getSite().getActionBars().getToolBarManager().add( showAllFolderVersionsAction); } @Override public void createControl(final Composite parent) { GridData gd; prefs = Activator.getDefault().getPluginPreferences(); ourControl = createMainPanel(parent); gd = new GridData(); gd.verticalAlignment = SWT.FILL; gd.horizontalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; gd.grabExcessVerticalSpace = true; ourControl.setLayoutData(gd); gd = new GridData(); gd.verticalAlignment = SWT.FILL; gd.horizontalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; gd.grabExcessVerticalSpace = true; graphDetailSplit = new SashForm(ourControl, SWT.VERTICAL); graphDetailSplit.setLayoutData(gd); graph = new CommitGraphTable(graphDetailSplit); graph.getTableView().addOpenListener(new IOpenListener() { public void open(OpenEvent event) { final Object input = getInput(); // if multiple resources (IResourceList) or something not a file is selected we do nothing if (!(input instanceof IFile)) { return; } final IFile resource = (IFile) input; final RepositoryMapping mapping = RepositoryMapping.getMapping(resource.getProject()); final String gitPath = mapping.getRepoRelativePath(resource); IStructuredSelection selection = (IStructuredSelection) event.getSelection(); SWTCommit commit = (SWTCommit) selection.getFirstElement(); ITypedElement right = getFileRevisionTypedElement(resource, gitPath, commit); final GitCompareFileRevisionEditorInput in = new GitCompareFileRevisionEditorInput( SaveableCompareEditorInput.createFileElement(resource), right, null); openInCompare(in); } }); revInfoSplit = new SashForm(graphDetailSplit, SWT.HORIZONTAL); commentViewer = new CommitMessageViewer(revInfoSplit); fileViewer = new CommitFileDiffViewer(revInfoSplit); findToolbar = new FindToolbar(ourControl); layoutSashForm(graphDetailSplit, SPLIT_GRAPH); layoutSashForm(revInfoSplit, SPLIT_INFO); revObjectSelectionProvider = new RevObjectSelectionProvider(); popupMgr = new MenuManager(null, POPUP_ID); attachCommitSelectionChanged(); createLocalToolbarActions(); createResourceFilterActions(); createStandardActions(); createViewMenu(); finishContextMenu(); attachContextMenu(graph.getControl()); attachContextMenu(commentViewer.getControl()); attachContextMenu(fileViewer.getControl()); layout(); Repository.addAnyRepositoryChangedListener(this); } private ITypedElement getFileRevisionTypedElement(final IFile resource, final String gitPath, SWTCommit commit) { ITypedElement right = new GitCompareFileRevisionEditorInput.EmptyTypedElement( NLS.bind(UIText.GitHistoryPage_FileNotInCommit, resource .getName(), commit)); try { IFileRevision nextFile = getFileRevision(resource, gitPath, commit); if (nextFile != null) right = new FileRevisionTypedElement(nextFile); } catch (IOException e) { Activator.error(NLS.bind(UIText.GitHistoryPage_errorLookingUpPath, gitPath, commit.getId()), e); } return right; } private IFileRevision getFileRevision(final IFile resource, final String gitPath, SWTCommit commit) throws IOException { TreeWalk w = TreeWalk.forPath(db, gitPath, commit.getTree()); // check if file is contained in commit if (w != null) { final IFileRevision fileRevision = GitFileRevision.inCommit(db, commit, gitPath, null); return fileRevision; } return null; } private void openInCompare(CompareEditorInput input) { IWorkbenchPage workBenchPage = getSite().getPage(); IEditorPart editor = findReusableCompareEditor(input, workBenchPage); if (editor != null) { IEditorInput otherInput = editor.getEditorInput(); if (otherInput.equals(input)) { // simply provide focus to editor if (OpenStrategy.activateOnOpen()) workBenchPage.activate(editor); else workBenchPage.bringToTop(editor); } else { // if editor is currently not open on that input either re-use // existing CompareUI.reuseCompareEditor(input, (IReusableEditor) editor); if (OpenStrategy.activateOnOpen()) workBenchPage.activate(editor); else workBenchPage.bringToTop(editor); } } else { CompareUI.openCompareEditor(input); } } /** * Returns an editor that can be re-used. An open compare editor that * has un-saved changes cannot be re-used. * @param input the input being opened * @param page * @return an EditorPart or <code>null</code> if none can be found */ private IEditorPart findReusableCompareEditor(CompareEditorInput input, IWorkbenchPage page) { IEditorReference[] editorRefs = page.getEditorReferences(); // first loop looking for an editor with the same input for (int i = 0; i < editorRefs.length; i++) { IEditorPart part = editorRefs[i].getEditor(false); if (part != null && (part.getEditorInput() instanceof GitCompareFileRevisionEditorInput) && part instanceof IReusableEditor && part.getEditorInput().equals(input)) { return part; } } // if none found and "Reuse open compare editors" preference is on use // a non-dirty editor if (isReuseOpenEditor()) { for (int i = 0; i < editorRefs.length; i++) { IEditorPart part = editorRefs[i].getEditor(false); if (part != null && (part.getEditorInput() instanceof SaveableCompareEditorInput) && part instanceof IReusableEditor && !part.isDirty()) { return part; } } } // no re-usable editor found return null; } private static boolean isReuseOpenEditor() { return TeamUIPlugin.getPlugin().getPreferenceStore().getBoolean(IPreferenceIds.REUSE_OPEN_COMPARE_EDITOR); } private Runnable refschangedRunnable; public void refsChanged(final RefsChangedEvent e) { if (e.getRepository() != db) return; if (getControl().isDisposed()) return; synchronized (this) { if (refschangedRunnable == null) { refschangedRunnable = new Runnable() { public void run() { if (!getControl().isDisposed()) { // TODO is this the right location? if (GitTraceLocation.UI.isActive()) GitTraceLocation .getTrace() .trace( GitTraceLocation.UI .getLocation(), "Executing async repository changed event"); //$NON-NLS-1$ refschangedRunnable = null; inputSet(); } } }; getControl().getDisplay().asyncExec(refschangedRunnable); } } } public void indexChanged(final IndexChangedEvent e) { // We do not use index information here now } private void finishContextMenu() { popupMgr.add(new Separator()); popupMgr.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); getSite().registerContextMenu(POPUP_ID, popupMgr, revObjectSelectionProvider); getHistoryPageSite().getPart().getSite().setSelectionProvider( revObjectSelectionProvider); } private void attachContextMenu(final Control c) { c.setMenu(popupMgr.createContextMenu(c)); if (c == graph.getControl()) { c.addMenuDetectListener(new MenuDetectListener() { public void menuDetected(MenuDetectEvent e) { popupMgr.remove(new ActionContributionItem(compareAction)); popupMgr.remove(new ActionContributionItem( compareVersionsAction)); popupMgr.remove(new ActionContributionItem( viewVersionsAction)); int size = ((IStructuredSelection) revObjectSelectionProvider .getSelection()).size(); if (IFile.class.isAssignableFrom(getInput().getClass())) { popupMgr.add(new Separator()); if (size == 1) { popupMgr.add(compareAction); } else if (size == 2) { popupMgr.add(compareVersionsAction); } if (size >= 1) popupMgr.add(viewVersionsAction); } } }); } else { c.addMenuDetectListener(new MenuDetectListener() { public void menuDetected(MenuDetectEvent e) { popupMgr.remove(new ActionContributionItem(compareAction)); popupMgr.remove(new ActionContributionItem( compareVersionsAction)); popupMgr.remove(new ActionContributionItem( viewVersionsAction)); } }); } } private void layoutSashForm(final SashForm sf, final String key) { sf.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { final int[] w = sf.getWeights(); UIPreferences.setValue(prefs, key, w); } }); sf.setWeights(UIPreferences.getIntArray(prefs, key, 2)); } private Composite createMainPanel(final Composite parent) { final Composite c = new Composite(parent, SWT.NULL); final GridLayout parentLayout = new GridLayout(); parentLayout.marginHeight = 0; parentLayout.marginWidth = 0; parentLayout.verticalSpacing = 0; c.setLayout(parentLayout); return c; } private void layout() { final boolean showComment = prefs.getBoolean(SHOW_COMMENT); final boolean showFiles = prefs.getBoolean(SHOW_FILES); final boolean showFindToolbar = prefs.getBoolean(SHOW_FIND_TOOLBAR); if (showComment && showFiles) { graphDetailSplit.setMaximizedControl(null); revInfoSplit.setMaximizedControl(null); } else if (showComment && !showFiles) { graphDetailSplit.setMaximizedControl(null); revInfoSplit.setMaximizedControl(commentViewer.getControl()); } else if (!showComment && showFiles) { graphDetailSplit.setMaximizedControl(null); revInfoSplit.setMaximizedControl(fileViewer.getControl()); } else if (!showComment && !showFiles) { graphDetailSplit.setMaximizedControl(graph.getControl()); } if (showFindToolbar) { ((GridData) findToolbar.getLayoutData()).heightHint = SWT.DEFAULT; } else { ((GridData) findToolbar.getLayoutData()).heightHint = 0; findToolbar.clear(); } ourControl.layout(); } private void attachCommitSelectionChanged() { graph.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(final SelectionChangedEvent event) { final ISelection s = event.getSelection(); if (s.isEmpty() || !(s instanceof IStructuredSelection)) { commentViewer.setInput(null); fileViewer.setInput(null); return; } final IStructuredSelection sel; final PlotCommit<?> c; sel = ((IStructuredSelection) s); c = (PlotCommit<?>) sel.getFirstElement(); commentViewer.setInput(c); fileViewer.setInput(c); revObjectSelectionProvider.setSelection(s); } }); commentViewer .addCommitNavigationListener(new CommitNavigationListener() { public void showCommit(final RevCommit c) { graph.selectCommit(c); } }); findToolbar.addSelectionListener(new Listener() { public void handleEvent(Event event) { graph.selectCommit((RevCommit) event.data); } }); } private void createLocalToolbarActions() { final IToolBarManager barManager = getSite().getActionBars() .getToolBarManager(); IAction a; a = createFindToolbarAction(); barManager.add(a); } private IAction createFindToolbarAction() { final IAction r = new Action(UIText.GitHistoryPage_find, UIIcons.ELCL16_FIND) { public void run() { prefs.setValue(SHOW_FIND_TOOLBAR, isChecked()); layout(); } }; r.setChecked(prefs.getBoolean(SHOW_FIND_TOOLBAR)); r.setToolTipText(UIText.HistoryPage_findbar_findTooltip); return r; } private void createViewMenu() { final IActionBars actionBars = getSite().getActionBars(); final IMenuManager menuManager = actionBars.getMenuManager(); IAction a; a = createCommentWrap(); menuManager.add(a); popupMgr.add(a); a = createCommentFill(); menuManager.add(a); popupMgr.add(a); menuManager.add(new Separator()); popupMgr.add(new Separator()); a = createShowComment(); menuManager.add(a); popupMgr.add(a); a = createShowFiles(); menuManager.add(a); popupMgr.add(a); menuManager.add(new Separator()); popupMgr.add(new Separator()); } private IAction createCommentWrap() { final BooleanPrefAction a = new BooleanPrefAction(PREF_COMMENT_WRAP, UIText.ResourceHistory_toggleCommentWrap) { void apply(boolean wrap) { commentViewer.setWrap(wrap); } }; a.apply(a.isChecked()); return a; } private IAction createCommentFill() { final BooleanPrefAction a = new BooleanPrefAction(PREF_COMMENT_FILL, UIText.ResourceHistory_toggleCommentFill) { void apply(boolean fill) { commentViewer.setFill(fill); } }; a.apply(a.isChecked()); return a; } private IAction createShowComment() { return new BooleanPrefAction(SHOW_COMMENT, UIText.ResourceHistory_toggleRevComment) { void apply(final boolean value) { layout(); } }; } private IAction createShowFiles() { return new BooleanPrefAction(SHOW_FILES, UIText.ResourceHistory_toggleRevDetail) { void apply(final boolean value) { layout(); } }; } private void createStandardActions() { final TextAction copy = new TextAction(ITextOperationTarget.COPY); final TextAction sAll = new TextAction(ITextOperationTarget.SELECT_ALL); graph.getControl().addFocusListener(copy); graph.getControl().addFocusListener(sAll); graph.addSelectionChangedListener(copy); graph.addSelectionChangedListener(sAll); commentViewer.getControl().addFocusListener(copy); commentViewer.getControl().addFocusListener(sAll); commentViewer.addSelectionChangedListener(copy); commentViewer.addSelectionChangedListener(sAll); fileViewer.getControl().addFocusListener(copy); fileViewer.getControl().addFocusListener(sAll); fileViewer.addSelectionChangedListener(copy); fileViewer.addSelectionChangedListener(sAll); final IActionBars b = getSite().getActionBars(); b.setGlobalActionHandler(ActionFactory.COPY.getId(), copy); b.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), sAll); popupMgr.add(createStandardAction(ActionFactory.COPY)); popupMgr.add(createStandardAction(ActionFactory.SELECT_ALL)); popupMgr.add(new Separator()); } private IAction createStandardAction(final ActionFactory af) { final IPageSite s = getSite(); final IWorkbenchAction a = af.create(s.getWorkbenchWindow()); if (af instanceof IPartListener) ((IPartListener) a).partActivated(s.getPage().getActivePart()); return a; } public void dispose() { Repository.removeAnyRepositoryChangedListener(this); cancelRefreshJob(); if (popupMgr != null) { for (final IContributionItem i : popupMgr.getItems()) { if (i instanceof ActionFactory.IWorkbenchAction) ((ActionFactory.IWorkbenchAction) i).dispose(); } for (final IContributionItem i : getSite().getActionBars() .getMenuManager().getItems()) { if (i instanceof ActionFactory.IWorkbenchAction) ((ActionFactory.IWorkbenchAction) i).dispose(); } } Activator.getDefault().savePluginPreferences(); super.dispose(); } public void refresh() { inputSet(); } @Override public void setFocus() { graph.getControl().setFocus(); } @Override public Control getControl() { return ourControl; } public Object getInput() { final ResourceList r = (ResourceList) super.getInput(); if (r == null) return null; final IResource[] in = r.getItems(); if (in == null || in.length == 0) return null; if (in.length == 1) return in[0]; return r; } public boolean setInput(final Object o) { final Object in; if (o instanceof IResource) in = new ResourceList(new IResource[] { (IResource) o }); else if (o instanceof ResourceList) in = o; else in = null; return super.setInput(in); } @Override public boolean inputSet() { if (revObjectSelectionProvider != null) revObjectSelectionProvider.setActiveRepository(null); cancelRefreshJob(); if (graph == null) return false; final IResource[] in = ((ResourceList) super.getInput()).getItems(); if (in == null || in.length == 0) return false; db = null; final ArrayList<String> paths = new ArrayList<String>(in.length); for (final IResource r : in) { final RepositoryMapping map = RepositoryMapping.getMapping(r); if (map == null) continue; if (db == null) db = map.getRepository(); else if (db != map.getRepository()) return false; if (showAllFilter == ShowFilter.SHOWALLFOLDER) { final String name = map.getRepoRelativePath(r.getParent()); if (name != null && name.length() > 0) paths.add(name); } else if (showAllFilter == ShowFilter.SHOWALLPROJECT) { final String name = map.getRepoRelativePath(r.getProject()); if (name != null && name.length() > 0) paths.add(name); } else if (showAllFilter == ShowFilter.SHOWALLREPO) { // nothing } else /*if (showAllFilter == ShowFilter.SHOWALLRESOURCE)*/ { final String name = map.getRepoRelativePath(r); if (name != null && name.length() > 0) paths.add(name); } } if (db == null) return false; final AnyObjectId headId; try { headId = db.resolve(Constants.HEAD); } catch (IOException e) { Activator.logError(NLS.bind(UIText.GitHistoryPage_errorParsingHead, db.getDirectory().getAbsolutePath()), e); return false; } if (currentWalk == null || currentWalk.getRepository() != db || pathChange(pathFilters, paths) || headId != null && !headId.equals(currentHeadId)) { // TODO Do not dispose SWTWalk just because HEAD changed // In theory we should be able to update the graph and // not dispose of the SWTWalk, even if HEAD was reset to // HEAD^1 and the old HEAD commit should not be visible. // currentWalk = new SWTWalk(db); currentWalk.sort(RevSort.COMMIT_TIME_DESC, true); currentWalk.sort(RevSort.BOUNDARY, true); highlightFlag = currentWalk.newFlag("highlight"); //$NON-NLS-1$ } else { currentWalk.reset(); } if (headId == null) return false; try { currentWalk.markStart(currentWalk.parseCommit(headId)); } catch (IOException e) { Activator.logError(NLS.bind(UIText.GitHistoryPage_errorReadingHeadCommit, headId, db.getDirectory().getAbsolutePath()), e); return false; } final TreeWalk fileWalker = new TreeWalk(db); fileWalker.setRecursive(true); if (paths.size() > 0) { pathFilters = paths; currentWalk.setTreeFilter(AndTreeFilter.create(PathFilterGroup .createFromStrings(paths), TreeFilter.ANY_DIFF)); fileWalker.setFilter(currentWalk.getTreeFilter().clone()); } else { pathFilters = null; currentWalk.setTreeFilter(TreeFilter.ALL); fileWalker.setFilter(TreeFilter.ANY_DIFF); } fileViewer.setTreeWalk(fileWalker); fileViewer.addSelectionChangedListener(commentViewer); commentViewer.setTreeWalk(fileWalker); commentViewer.setDb(db); findToolbar.clear(); graph.setInput(highlightFlag, null, null); final SWTCommitList list; list = new SWTCommitList(graph.getControl().getDisplay()); list.source(currentWalk); final GenerateHistoryJob rj = new GenerateHistoryJob(this, list); final Repository fdb = db; rj.addJobChangeListener(new JobChangeAdapter() { @Override public void done(final IJobChangeEvent event) { revObjectSelectionProvider.setActiveRepository(fdb); final Control graphctl = graph.getControl(); if (job != rj || graphctl.isDisposed()) return; graphctl.getDisplay().asyncExec(new Runnable() { public void run() { if (job == rj) job = null; } }); } }); job = rj; schedule(rj); return true; } private void cancelRefreshJob() { if (job != null && job.getState() != Job.NONE) { job.cancel(); // As the job had to be canceled but was working on // the data connected with the currentWalk we cannot // be sure it really finished. Since the walk is not // thread safe we must throw it away and build a new // one to start another walk. Clearing our field will // ensure that happens. // job = null; currentWalk = null; highlightFlag = null; pathFilters = null; } } private boolean pathChange(final List<String> o, final List<String> n) { if (o == null) return !n.isEmpty(); return !o.equals(n); } private void schedule(final Job j) { final IWorkbenchPartSite site = getWorkbenchSite(); if (site != null) { final IWorkbenchSiteProgressService p; p = (IWorkbenchSiteProgressService) site .getAdapter(IWorkbenchSiteProgressService.class); if (p != null) { p.schedule(j, 0, true /* use half-busy cursor */); return; } } j.schedule(); } void showCommitList(final Job j, final SWTCommitList list, final SWTCommit[] asArray) { if (job != j || graph.getControl().isDisposed()) return; graph.getControl().getDisplay().asyncExec(new Runnable() { public void run() { if (!graph.getControl().isDisposed() && job == j) { graph.setInput(highlightFlag, list, asArray); findToolbar.setInput(highlightFlag, graph.getTableView().getTable(), asArray); } } }); } private IWorkbenchPartSite getWorkbenchSite() { final IWorkbenchPart part = getHistoryPageSite().getPart(); return part != null ? part.getSite() : null; } public boolean isValidInput(final Object object) { return canShowHistoryFor(object); } public Object getAdapter(final Class adapter) { return null; } public String getName() { final ResourceList in = (ResourceList) super.getInput(); if (currentWalk == null || in == null) return ""; //$NON-NLS-1$ final IResource[] items = in.getItems(); if (items.length == 0) return ""; //$NON-NLS-1$ final StringBuilder b = new StringBuilder(); b.append(items[0].getProject().getName()); if (currentWalk.getRevFilter() != RevFilter.ALL) { b.append(": "); //$NON-NLS-1$ b.append(currentWalk.getRevFilter()); } if (currentWalk.getTreeFilter() != TreeFilter.ALL) { b.append(":"); //$NON-NLS-1$ for (final String p : pathFilters) { b.append(' '); b.append(p); } } return b.toString(); } public String getDescription() { return getName(); } private abstract class BooleanPrefAction extends Action implements IPropertyChangeListener, ActionFactory.IWorkbenchAction { private final String prefName; BooleanPrefAction(final String pn, final String text) { setText(text); prefName = pn; prefs.addPropertyChangeListener(this); setChecked(prefs.getBoolean(prefName)); } public void run() { prefs.setValue(prefName, isChecked()); apply(isChecked()); } abstract void apply(boolean value); public void propertyChange(final PropertyChangeEvent event) { if (prefName.equals(event.getProperty())) { setChecked(prefs.getBoolean(prefName)); apply(isChecked()); } } public void dispose() { prefs.removePropertyChangeListener(this); } } private class TextAction extends Action implements FocusListener, ISelectionChangedListener { private final int op; TextAction(final int operationCode) { op = operationCode; setEnabled(false); } public void run() { if (commentViewer.getTextWidget().isFocusControl()) { if (commentViewer.canDoOperation(op)) commentViewer.doOperation(op); } else if (fileViewer.getTable().isFocusControl()) { switch (op) { case ITextOperationTarget.COPY: fileViewer.doCopy(); break; case ITextOperationTarget.SELECT_ALL: fileViewer.doSelectAll(); break; } } else if (graph.getControl().isFocusControl()) { switch (op) { case ITextOperationTarget.COPY: graph.doCopy(); break; } } } private void update() { if (commentViewer.getTextWidget().isFocusControl()) { setEnabled(commentViewer.canDoOperation(op)); } else if (fileViewer.getTable().isFocusControl()) { switch (op) { case ITextOperationTarget.COPY: setEnabled(!fileViewer.getSelection().isEmpty()); break; case ITextOperationTarget.SELECT_ALL: setEnabled(fileViewer.getTable().getItemCount() > 0); break; } } else if (graph.getControl().isFocusControl()) { switch (op) { case ITextOperationTarget.COPY: setEnabled(graph.canDoCopy()); break; case ITextOperationTarget.SELECT_ALL: setEnabled(false); break; } } } public void focusGained(final FocusEvent e) { update(); } public void selectionChanged(final SelectionChangedEvent event) { update(); } public void focusLost(final FocusEvent e) { // Ignore lost events. If focus leaves our page then the // workbench will update the global action away from us. // If focus stays in our page someone else should have // gained it from us. } } private class CompareWithWorkingTreeAction extends Action { public CompareWithWorkingTreeAction() { super(UIText.GitHistoryPage_CompareWithWorking); } @Override public void run() { IStructuredSelection selection = ((IStructuredSelection) revObjectSelectionProvider .getSelection()); if (selection.size() == 1) { Iterator<?> it = selection.iterator(); SWTCommit commit = (SWTCommit) it.next(); if (getInput() instanceof IFile){ IFile file = (IFile) getInput(); final RepositoryMapping mapping = RepositoryMapping.getMapping(file.getProject()); final String gitPath = mapping.getRepoRelativePath(file); ITypedElement right = getFileRevisionTypedElement(file, gitPath, commit); final GitCompareFileRevisionEditorInput in = new GitCompareFileRevisionEditorInput( SaveableCompareEditorInput.createFileElement(file), right, null); openInCompare(in); } } } @Override public boolean isEnabled() { int size = ((IStructuredSelection) revObjectSelectionProvider .getSelection()).size(); return IFile.class.isAssignableFrom(getInput().getClass()) && size == 1; } } private class CompareVersionsAction extends Action { public CompareVersionsAction() { super(UIText.GitHistoryPage_CompareVersions); } @Override public void run() { IStructuredSelection selection = ((IStructuredSelection) revObjectSelectionProvider .getSelection()); if (selection.size() == 2) { Iterator<?> it = selection.iterator(); SWTCommit commit1 = (SWTCommit) it.next(); SWTCommit commit2 = (SWTCommit) it.next(); if (getInput() instanceof IFile){ IFile resource = (IFile) getInput(); final RepositoryMapping map = RepositoryMapping .getMapping(resource); final String gitPath = map .getRepoRelativePath(resource); final ITypedElement base = getFileRevisionTypedElement(resource, gitPath, commit1); final ITypedElement next = getFileRevisionTypedElement(resource, gitPath, commit2); CompareEditorInput in = new GitCompareFileRevisionEditorInput(base, next, null); openInCompare(in); } } } @Override public boolean isEnabled() { int size = ((IStructuredSelection) revObjectSelectionProvider .getSelection()).size(); return IFile.class.isAssignableFrom(getInput().getClass()) && size == 2; } } private class ViewVersionsAction extends Action { public ViewVersionsAction() { super(UIText.GitHistoryPage_open); } @Override public void run() { IStructuredSelection selection = ((IStructuredSelection) revObjectSelectionProvider .getSelection()); if (selection.size() < 1) return; if (!(getInput() instanceof IFile)) return; IFile resource = (IFile) getInput(); final RepositoryMapping map = RepositoryMapping .getMapping(resource); final String gitPath = map.getRepoRelativePath(resource); Iterator<?> it = selection.iterator(); boolean errorOccured = false; List<ObjectId> ids = new ArrayList<ObjectId>(); while (it.hasNext()) { SWTCommit commit = (SWTCommit) it.next(); IFileRevision rev = null; try { rev = getFileRevision(resource, gitPath, commit); } catch (IOException e) { Activator.logError(NLS.bind( UIText.GitHistoryPage_errorLookingUpPath, gitPath, commit.getId()), e); errorOccured = true; } if (rev != null) { try { Utils.openEditor(getSite().getPage(), rev, new NullProgressMonitor()); } catch (CoreException e) { Activator.logError(UIText.GitHistoryPage_openFailed, e); errorOccured = true; } } else { ids.add(commit.getId()); } } if (errorOccured) MessageDialog.openError(getSite().getShell(), UIText.GitHistoryPage_openFailed, UIText.GitHistoryPage_seeLog); if (ids.size() > 0) { String idList = ""; //$NON-NLS-1$ for (ObjectId objectId : ids) { idList += objectId.getName() + " "; //$NON-NLS-1$ } MessageDialog.openError(getSite().getShell(), UIText.GitHistoryPage_fileNotFound, NLS.bind( UIText.GitHistoryPage_notContainedInCommits, gitPath, idList)); } } @Override public boolean isEnabled() { int size = ((IStructuredSelection) revObjectSelectionProvider .getSelection()).size(); return IFile.class.isAssignableFrom(getInput().getClass()) && size >= 1; } } }
org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/history/GitHistoryPage.java
/******************************************************************************* * Copyright (C) 2008, Roger C. Soares <[email protected]> * Copyright (C) 2008, Shawn O. Pearce <[email protected]> * * 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 *******************************************************************************/ package org.eclipse.egit.ui.internal.history; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.compare.CompareEditorInput; import org.eclipse.compare.CompareUI; import org.eclipse.compare.ITypedElement; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Preferences; import org.eclipse.core.runtime.Preferences.IPropertyChangeListener; import org.eclipse.core.runtime.Preferences.PropertyChangeEvent; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.egit.core.ResourceList; import org.eclipse.egit.core.internal.storage.GitFileRevision; import org.eclipse.egit.core.project.RepositoryMapping; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.UIIcons; import org.eclipse.egit.ui.UIPreferences; import org.eclipse.egit.ui.UIText; import org.eclipse.egit.ui.internal.GitCompareFileRevisionEditorInput; import org.eclipse.egit.ui.internal.trace.GitTraceLocation; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.ActionContributionItem; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IContributionItem; 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.jface.resource.ImageDescriptor; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.util.OpenStrategy; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jgit.lib.AnyObjectId; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.IndexChangedEvent; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.RefsChangedEvent; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.RepositoryListener; import org.eclipse.jgit.revplot.PlotCommit; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevFlag; import org.eclipse.jgit.revwalk.RevSort; import org.eclipse.jgit.revwalk.filter.RevFilter; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.filter.AndTreeFilter; import org.eclipse.jgit.treewalk.filter.PathFilterGroup; import org.eclipse.jgit.treewalk.filter.TreeFilter; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.MenuDetectEvent; import org.eclipse.swt.events.MenuDetectListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.team.core.history.IFileRevision; import org.eclipse.team.internal.ui.IPreferenceIds; import org.eclipse.team.internal.ui.TeamUIPlugin; import org.eclipse.team.internal.ui.Utils; import org.eclipse.team.internal.ui.history.FileRevisionTypedElement; import org.eclipse.team.ui.history.HistoryPage; import org.eclipse.team.ui.synchronize.SaveableCompareEditorInput; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IReusableEditor; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction; import org.eclipse.ui.part.IPageSite; import org.eclipse.ui.progress.IWorkbenchSiteProgressService; /** Graphical commit history viewer. */ public class GitHistoryPage extends HistoryPage implements RepositoryListener { private static final String PREF_COMMENT_WRAP = UIPreferences.RESOURCEHISTORY_SHOW_COMMENT_WRAP; private static final String PREF_COMMENT_FILL = UIPreferences.RESOURCEHISTORY_SHOW_COMMENT_FILL; private static final String SHOW_COMMENT = UIPreferences.RESOURCEHISTORY_SHOW_REV_COMMENT; private static final String SHOW_FILES = UIPreferences.RESOURCEHISTORY_SHOW_REV_DETAIL; private static final String SPLIT_GRAPH = UIPreferences.RESOURCEHISTORY_GRAPH_SPLIT; private static final String SPLIT_INFO = UIPreferences.RESOURCEHISTORY_REV_SPLIT; private static final String SHOW_FIND_TOOLBAR = UIPreferences.RESOURCEHISTORY_SHOW_FINDTOOLBAR; private static final String POPUP_ID = "org.eclipse.egit.ui.historyPageContributions"; //$NON-NLS-1$ private IAction compareAction = new CompareWithWorkingTreeAction(); private IAction compareVersionsAction = new CompareVersionsAction(); private IAction viewVersionsAction = new ViewVersionsAction(); /** * Determine if the input can be shown in this viewer. * * @param object * an object that is hopefully of type ResourceList or IResource, * but may be anything (including null). * @return true if the input is a ResourceList or an IResource of type FILE, * FOLDER or PROJECT and we can show it; false otherwise. */ public static boolean canShowHistoryFor(final Object object) { if (object instanceof ResourceList) { final IResource[] array = ((ResourceList) object).getItems(); if (array.length == 0) return false; for (final IResource r : array) { if (!typeOk(r)) return false; } return true; } if (object instanceof IResource) { return typeOk((IResource) object); } return false; } private static boolean typeOk(final IResource object) { switch (object.getType()) { case IResource.FILE: case IResource.FOLDER: case IResource.PROJECT: return true; } return false; } /** Plugin private preference store for the current workspace. */ private Preferences prefs; /** Overall composite hosting all of our controls. */ private Composite ourControl; /** Split between {@link #graph} and {@link #revInfoSplit}. */ private SashForm graphDetailSplit; /** Split between {@link #commentViewer} and {@link #fileViewer}. */ private SashForm revInfoSplit; /** The table showing the DAG, first "paragraph", author, author date. */ private CommitGraphTable graph; /** Viewer displaying the currently selected commit of {@link #graph}. */ private CommitMessageViewer commentViewer; /** Viewer displaying file difference implied by {@link #graph}'s commit. */ private CommitFileDiffViewer fileViewer; /** Toolbar to find commits in the history view. */ private FindToolbar findToolbar; /** Our context menu manager for the entire page. */ private MenuManager popupMgr; /** Job that is updating our history view, if we are refreshing. */ private GenerateHistoryJob job; /** Revision walker that allocated our graph's commit nodes. */ private SWTWalk currentWalk; /** Last HEAD */ private AnyObjectId currentHeadId; /** We need to remember the current repository */ private Repository db; /** * Highlight flag that can be applied to commits to make them stand out. * <p> * Allocated at the same time as {@link #currentWalk}. If the walk * rebuilds, so must this flag. */ private RevFlag highlightFlag; /** * List of paths we used to limit {@link #currentWalk}; null if no paths. * <p> * Note that a change in this list requires that {@link #currentWalk} and * all of its associated commits. */ private List<String> pathFilters; /** * The selection provider tracks the selected revisions for the context menu */ private RevObjectSelectionProvider revObjectSelectionProvider; private static final String PREF_SHOWALLFILTER = "org.eclipse.egit.ui.githistorypage.showallfilter"; //$NON-NLS-1$ enum ShowFilter { SHOWALLRESOURCE, SHOWALLFOLDER, SHOWALLPROJECT, SHOWALLREPO, } class ShowFilterAction extends Action { private final ShowFilter filter; ShowFilterAction(ShowFilter filter, ImageDescriptor icon, String toolTipText) { super(null, IAction.AS_CHECK_BOX); this.filter = filter; setImageDescriptor(icon); setToolTipText(toolTipText); } @Override public void run() { if (!isChecked()) { if (showAllFilter == filter) { showAllFilter = ShowFilter.SHOWALLRESOURCE; refresh(); } } if (isChecked() && showAllFilter != filter) { showAllFilter = filter; if (this != showAllRepoVersionsAction) showAllRepoVersionsAction.setChecked(false); if (this != showAllProjectVersionsAction) showAllProjectVersionsAction.setChecked(false); if (this != showAllFolderVersionsAction) showAllFolderVersionsAction.setChecked(false); refresh(); } Activator.getDefault().getPreferenceStore().setValue( PREF_SHOWALLFILTER, showAllFilter.toString()); } @Override public String toString() { return "ShowFilter[" + filter.toString() + "]"; //$NON-NLS-1$ //$NON-NLS-2$ } } private ShowFilter showAllFilter = ShowFilter.SHOWALLRESOURCE; private ShowFilterAction showAllRepoVersionsAction; private ShowFilterAction showAllProjectVersionsAction; private ShowFilterAction showAllFolderVersionsAction; private void createResourceFilterActions() { try { showAllFilter = ShowFilter.valueOf(Activator.getDefault() .getPreferenceStore().getString(PREF_SHOWALLFILTER)); } catch (IllegalArgumentException e) { showAllFilter = ShowFilter.SHOWALLRESOURCE; } showAllRepoVersionsAction = new ShowFilterAction( ShowFilter.SHOWALLREPO, UIIcons.FILTERREPO, UIText.HistoryPage_ShowAllVersionsForRepo); showAllProjectVersionsAction = new ShowFilterAction( ShowFilter.SHOWALLPROJECT, UIIcons.FILTERPROJECT, UIText.HistoryPage_ShowAllVersionsForProject); showAllFolderVersionsAction = new ShowFilterAction( ShowFilter.SHOWALLFOLDER, UIIcons.FILTERFOLDER, UIText.HistoryPage_ShowAllVersionsForFolder); showAllRepoVersionsAction .setChecked(showAllFilter == showAllRepoVersionsAction.filter); showAllProjectVersionsAction .setChecked(showAllFilter == showAllProjectVersionsAction.filter); showAllFolderVersionsAction .setChecked(showAllFilter == showAllFolderVersionsAction.filter); getSite().getActionBars().getToolBarManager().add(new Separator()); getSite().getActionBars().getToolBarManager().add( showAllRepoVersionsAction); getSite().getActionBars().getToolBarManager().add( showAllProjectVersionsAction); getSite().getActionBars().getToolBarManager().add( showAllFolderVersionsAction); } @Override public void createControl(final Composite parent) { GridData gd; prefs = Activator.getDefault().getPluginPreferences(); ourControl = createMainPanel(parent); gd = new GridData(); gd.verticalAlignment = SWT.FILL; gd.horizontalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; gd.grabExcessVerticalSpace = true; ourControl.setLayoutData(gd); gd = new GridData(); gd.verticalAlignment = SWT.FILL; gd.horizontalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; gd.grabExcessVerticalSpace = true; graphDetailSplit = new SashForm(ourControl, SWT.VERTICAL); graphDetailSplit.setLayoutData(gd); graph = new CommitGraphTable(graphDetailSplit); graph.getTableView().addOpenListener(new IOpenListener() { public void open(OpenEvent event) { final Object input = getInput(); // if multiple resources (IResourceList) or something not a file is selected we do nothing if (!(input instanceof IFile)) { return; } final IFile resource = (IFile) input; final RepositoryMapping mapping = RepositoryMapping.getMapping(resource.getProject()); final String gitPath = mapping.getRepoRelativePath(resource); IStructuredSelection selection = (IStructuredSelection) event.getSelection(); SWTCommit commit = (SWTCommit) selection.getFirstElement(); ITypedElement right = getFileRevisionTypedElement(resource, gitPath, commit); final GitCompareFileRevisionEditorInput in = new GitCompareFileRevisionEditorInput( SaveableCompareEditorInput.createFileElement(resource), right, null); openInCompare(in); } }); revInfoSplit = new SashForm(graphDetailSplit, SWT.HORIZONTAL); commentViewer = new CommitMessageViewer(revInfoSplit); fileViewer = new CommitFileDiffViewer(revInfoSplit); findToolbar = new FindToolbar(ourControl); layoutSashForm(graphDetailSplit, SPLIT_GRAPH); layoutSashForm(revInfoSplit, SPLIT_INFO); revObjectSelectionProvider = new RevObjectSelectionProvider(); popupMgr = new MenuManager(null, POPUP_ID); attachCommitSelectionChanged(); createLocalToolbarActions(); createResourceFilterActions(); createStandardActions(); createViewMenu(); finishContextMenu(); attachContextMenu(graph.getControl()); attachContextMenu(commentViewer.getControl()); attachContextMenu(fileViewer.getControl()); layout(); Repository.addAnyRepositoryChangedListener(this); } private ITypedElement getFileRevisionTypedElement(final IFile resource, final String gitPath, SWTCommit commit) { ITypedElement right = new GitCompareFileRevisionEditorInput.EmptyTypedElement( NLS.bind(UIText.GitHistoryPage_FileNotInCommit, resource .getName(), commit)); try { IFileRevision nextFile = getFileRevision(resource, gitPath, commit); if (nextFile != null) right = new FileRevisionTypedElement(nextFile); } catch (IOException e) { Activator.error(NLS.bind(UIText.GitHistoryPage_errorLookingUpPath, gitPath, commit.getId()), e); } return right; } private IFileRevision getFileRevision(final IFile resource, final String gitPath, SWTCommit commit) throws IOException { TreeWalk w = TreeWalk.forPath(db, gitPath, commit.getTree()); // check if file is contained in commit if (w != null) { final IFileRevision fileRevision = GitFileRevision.inCommit(db, commit, gitPath, null); return fileRevision; } return null; } private void openInCompare(CompareEditorInput input) { IWorkbenchPage workBenchPage = getSite().getPage(); IEditorPart editor = findReusableCompareEditor(input, workBenchPage); if (editor != null) { IEditorInput otherInput = editor.getEditorInput(); if (otherInput.equals(input)) { // simply provide focus to editor if (OpenStrategy.activateOnOpen()) workBenchPage.activate(editor); else workBenchPage.bringToTop(editor); } else { // if editor is currently not open on that input either re-use // existing CompareUI.reuseCompareEditor(input, (IReusableEditor) editor); if (OpenStrategy.activateOnOpen()) workBenchPage.activate(editor); else workBenchPage.bringToTop(editor); } } else { CompareUI.openCompareEditor(input); } } /** * Returns an editor that can be re-used. An open compare editor that * has un-saved changes cannot be re-used. * @param input the input being opened * @param page * @return an EditorPart or <code>null</code> if none can be found */ private IEditorPart findReusableCompareEditor(CompareEditorInput input, IWorkbenchPage page) { IEditorReference[] editorRefs = page.getEditorReferences(); // first loop looking for an editor with the same input for (int i = 0; i < editorRefs.length; i++) { IEditorPart part = editorRefs[i].getEditor(false); if (part != null && (part.getEditorInput() instanceof GitCompareFileRevisionEditorInput) && part instanceof IReusableEditor && part.getEditorInput().equals(input)) { return part; } } // if none found and "Reuse open compare editors" preference is on use // a non-dirty editor if (isReuseOpenEditor()) { for (int i = 0; i < editorRefs.length; i++) { IEditorPart part = editorRefs[i].getEditor(false); if (part != null && (part.getEditorInput() instanceof SaveableCompareEditorInput) && part instanceof IReusableEditor && !part.isDirty()) { return part; } } } // no re-usable editor found return null; } private static boolean isReuseOpenEditor() { return TeamUIPlugin.getPlugin().getPreferenceStore().getBoolean(IPreferenceIds.REUSE_OPEN_COMPARE_EDITOR); } private Runnable refschangedRunnable; public void refsChanged(final RefsChangedEvent e) { if (e.getRepository() != db) return; if (getControl().isDisposed()) return; synchronized (this) { if (refschangedRunnable == null) { refschangedRunnable = new Runnable() { public void run() { if (!getControl().isDisposed()) { // TODO is this the right location? if (GitTraceLocation.UI.isActive()) GitTraceLocation .getTrace() .trace( GitTraceLocation.UI .getLocation(), "Executing async repository changed event"); //$NON-NLS-1$ refschangedRunnable = null; inputSet(); } } }; getControl().getDisplay().asyncExec(refschangedRunnable); } } } public void indexChanged(final IndexChangedEvent e) { // We do not use index information here now } private void finishContextMenu() { popupMgr.add(new Separator()); popupMgr.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); getSite().registerContextMenu(POPUP_ID, popupMgr, revObjectSelectionProvider); getHistoryPageSite().getPart().getSite().setSelectionProvider( revObjectSelectionProvider); } private void attachContextMenu(final Control c) { c.setMenu(popupMgr.createContextMenu(c)); if (c == graph.getControl()) { c.addMenuDetectListener(new MenuDetectListener() { public void menuDetected(MenuDetectEvent e) { popupMgr.remove(new ActionContributionItem(compareAction)); popupMgr.remove(new ActionContributionItem( compareVersionsAction)); popupMgr.remove(new ActionContributionItem( viewVersionsAction)); int size = ((IStructuredSelection) revObjectSelectionProvider .getSelection()).size(); if (IFile.class.isAssignableFrom(getInput().getClass())) { popupMgr.add(new Separator()); if (size == 1) { popupMgr.add(compareAction); } else if (size == 2) { popupMgr.add(compareVersionsAction); } if (size >= 1) popupMgr.add(viewVersionsAction); } } }); } else { c.addMenuDetectListener(new MenuDetectListener() { public void menuDetected(MenuDetectEvent e) { popupMgr.remove(new ActionContributionItem(compareAction)); popupMgr.remove(new ActionContributionItem( compareVersionsAction)); popupMgr.remove(new ActionContributionItem( viewVersionsAction)); } }); } } private void layoutSashForm(final SashForm sf, final String key) { sf.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { final int[] w = sf.getWeights(); UIPreferences.setValue(prefs, key, w); } }); sf.setWeights(UIPreferences.getIntArray(prefs, key, 2)); } private Composite createMainPanel(final Composite parent) { final Composite c = new Composite(parent, SWT.NULL); final GridLayout parentLayout = new GridLayout(); parentLayout.marginHeight = 0; parentLayout.marginWidth = 0; parentLayout.verticalSpacing = 0; c.setLayout(parentLayout); return c; } private void layout() { final boolean showComment = prefs.getBoolean(SHOW_COMMENT); final boolean showFiles = prefs.getBoolean(SHOW_FILES); final boolean showFindToolbar = prefs.getBoolean(SHOW_FIND_TOOLBAR); if (showComment && showFiles) { graphDetailSplit.setMaximizedControl(null); revInfoSplit.setMaximizedControl(null); } else if (showComment && !showFiles) { graphDetailSplit.setMaximizedControl(null); revInfoSplit.setMaximizedControl(commentViewer.getControl()); } else if (!showComment && showFiles) { graphDetailSplit.setMaximizedControl(null); revInfoSplit.setMaximizedControl(fileViewer.getControl()); } else if (!showComment && !showFiles) { graphDetailSplit.setMaximizedControl(graph.getControl()); } if (showFindToolbar) { ((GridData) findToolbar.getLayoutData()).heightHint = SWT.DEFAULT; } else { ((GridData) findToolbar.getLayoutData()).heightHint = 0; findToolbar.clear(); } ourControl.layout(); } private void attachCommitSelectionChanged() { graph.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(final SelectionChangedEvent event) { final ISelection s = event.getSelection(); if (s.isEmpty() || !(s instanceof IStructuredSelection)) { commentViewer.setInput(null); fileViewer.setInput(null); return; } final IStructuredSelection sel; final PlotCommit<?> c; sel = ((IStructuredSelection) s); c = (PlotCommit<?>) sel.getFirstElement(); commentViewer.setInput(c); fileViewer.setInput(c); revObjectSelectionProvider.setSelection(s); } }); commentViewer .addCommitNavigationListener(new CommitNavigationListener() { public void showCommit(final RevCommit c) { graph.selectCommit(c); } }); findToolbar.addSelectionListener(new Listener() { public void handleEvent(Event event) { graph.selectCommit((RevCommit) event.data); } }); } private void createLocalToolbarActions() { final IToolBarManager barManager = getSite().getActionBars() .getToolBarManager(); IAction a; a = createFindToolbarAction(); barManager.add(a); } private IAction createFindToolbarAction() { final IAction r = new Action(UIText.GitHistoryPage_find, UIIcons.ELCL16_FIND) { public void run() { prefs.setValue(SHOW_FIND_TOOLBAR, isChecked()); layout(); } }; r.setChecked(prefs.getBoolean(SHOW_FIND_TOOLBAR)); r.setToolTipText(UIText.HistoryPage_findbar_findTooltip); return r; } private void createViewMenu() { final IActionBars actionBars = getSite().getActionBars(); final IMenuManager menuManager = actionBars.getMenuManager(); IAction a; a = createCommentWrap(); menuManager.add(a); popupMgr.add(a); a = createCommentFill(); menuManager.add(a); popupMgr.add(a); menuManager.add(new Separator()); popupMgr.add(new Separator()); a = createShowComment(); menuManager.add(a); popupMgr.add(a); a = createShowFiles(); menuManager.add(a); popupMgr.add(a); menuManager.add(new Separator()); popupMgr.add(new Separator()); } private IAction createCommentWrap() { final BooleanPrefAction a = new BooleanPrefAction(PREF_COMMENT_WRAP, UIText.ResourceHistory_toggleCommentWrap) { void apply(boolean wrap) { commentViewer.setWrap(wrap); } }; a.apply(a.isChecked()); return a; } private IAction createCommentFill() { final BooleanPrefAction a = new BooleanPrefAction(PREF_COMMENT_FILL, UIText.ResourceHistory_toggleCommentFill) { void apply(boolean fill) { commentViewer.setFill(fill); } }; a.apply(a.isChecked()); return a; } private IAction createShowComment() { return new BooleanPrefAction(SHOW_COMMENT, UIText.ResourceHistory_toggleRevComment) { void apply(final boolean value) { layout(); } }; } private IAction createShowFiles() { return new BooleanPrefAction(SHOW_FILES, UIText.ResourceHistory_toggleRevDetail) { void apply(final boolean value) { layout(); } }; } private void createStandardActions() { final TextAction copy = new TextAction(ITextOperationTarget.COPY); final TextAction sAll = new TextAction(ITextOperationTarget.SELECT_ALL); graph.getControl().addFocusListener(copy); graph.getControl().addFocusListener(sAll); graph.addSelectionChangedListener(copy); graph.addSelectionChangedListener(sAll); commentViewer.getControl().addFocusListener(copy); commentViewer.getControl().addFocusListener(sAll); commentViewer.addSelectionChangedListener(copy); commentViewer.addSelectionChangedListener(sAll); fileViewer.getControl().addFocusListener(copy); fileViewer.getControl().addFocusListener(sAll); fileViewer.addSelectionChangedListener(copy); fileViewer.addSelectionChangedListener(sAll); final IActionBars b = getSite().getActionBars(); b.setGlobalActionHandler(ActionFactory.COPY.getId(), copy); b.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), sAll); popupMgr.add(createStandardAction(ActionFactory.COPY)); popupMgr.add(createStandardAction(ActionFactory.SELECT_ALL)); popupMgr.add(new Separator()); } private IAction createStandardAction(final ActionFactory af) { final IPageSite s = getSite(); final IWorkbenchAction a = af.create(s.getWorkbenchWindow()); if (af instanceof IPartListener) ((IPartListener) a).partActivated(s.getPage().getActivePart()); return a; } public void dispose() { Repository.removeAnyRepositoryChangedListener(this); cancelRefreshJob(); if (popupMgr != null) { for (final IContributionItem i : popupMgr.getItems()) { if (i instanceof ActionFactory.IWorkbenchAction) ((ActionFactory.IWorkbenchAction) i).dispose(); } for (final IContributionItem i : getSite().getActionBars() .getMenuManager().getItems()) { if (i instanceof ActionFactory.IWorkbenchAction) ((ActionFactory.IWorkbenchAction) i).dispose(); } } Activator.getDefault().savePluginPreferences(); super.dispose(); } public void refresh() { inputSet(); } @Override public void setFocus() { graph.getControl().setFocus(); } @Override public Control getControl() { return ourControl; } public Object getInput() { final ResourceList r = (ResourceList) super.getInput(); if (r == null) return null; final IResource[] in = r.getItems(); if (in == null || in.length == 0) return null; if (in.length == 1) return in[0]; return r; } public boolean setInput(final Object o) { final Object in; if (o instanceof IResource) in = new ResourceList(new IResource[] { (IResource) o }); else if (o instanceof ResourceList) in = o; else in = null; return super.setInput(in); } @Override public boolean inputSet() { if (revObjectSelectionProvider != null) revObjectSelectionProvider.setActiveRepository(null); cancelRefreshJob(); if (graph == null) return false; final IResource[] in = ((ResourceList) super.getInput()).getItems(); if (in == null || in.length == 0) return false; db = null; final ArrayList<String> paths = new ArrayList<String>(in.length); for (final IResource r : in) { final RepositoryMapping map = RepositoryMapping.getMapping(r); if (map == null) continue; if (db == null) db = map.getRepository(); else if (db != map.getRepository()) return false; if (showAllFilter == ShowFilter.SHOWALLFOLDER) { final String name = map.getRepoRelativePath(r.getParent()); if (name != null && name.length() > 0) paths.add(name); } else if (showAllFilter == ShowFilter.SHOWALLPROJECT) { final String name = map.getRepoRelativePath(r.getProject()); if (name != null && name.length() > 0) paths.add(name); } else if (showAllFilter == ShowFilter.SHOWALLREPO) { // nothing } else /*if (showAllFilter == ShowFilter.SHOWALLRESOURCE)*/ { final String name = map.getRepoRelativePath(r); if (name != null && name.length() > 0) paths.add(name); } } if (db == null) return false; final AnyObjectId headId; try { headId = db.resolve(Constants.HEAD); } catch (IOException e) { Activator.logError(NLS.bind(UIText.GitHistoryPage_errorParsingHead, db.getDirectory().getAbsolutePath()), e); return false; } if (currentWalk == null || currentWalk.getRepository() != db || pathChange(pathFilters, paths) || headId != null && !headId.equals(currentHeadId)) { // TODO Do not dispose SWTWalk just because HEAD changed // In theory we should be able to update the graph and // not dispose of the SWTWalk, even if HEAD was reset to // HEAD^1 and the old HEAD commit should not be visible. // currentWalk = new SWTWalk(db); currentWalk.sort(RevSort.COMMIT_TIME_DESC, true); currentWalk.sort(RevSort.BOUNDARY, true); highlightFlag = currentWalk.newFlag("highlight"); //$NON-NLS-1$ } else { currentWalk.reset(); } if (headId == null) return false; try { currentWalk.markStart(currentWalk.parseCommit(headId)); } catch (IOException e) { Activator.logError(NLS.bind(UIText.GitHistoryPage_errorReadingHeadCommit, headId, db.getDirectory().getAbsolutePath()), e); return false; } final TreeWalk fileWalker = new TreeWalk(db); fileWalker.setRecursive(true); if (paths.size() > 0) { pathFilters = paths; currentWalk.setTreeFilter(AndTreeFilter.create(PathFilterGroup .createFromStrings(paths), TreeFilter.ANY_DIFF)); fileWalker.setFilter(currentWalk.getTreeFilter().clone()); } else { pathFilters = null; currentWalk.setTreeFilter(TreeFilter.ALL); fileWalker.setFilter(TreeFilter.ANY_DIFF); } fileViewer.setTreeWalk(fileWalker); fileViewer.addSelectionChangedListener(commentViewer); commentViewer.setTreeWalk(fileWalker); commentViewer.setDb(db); findToolbar.clear(); graph.setInput(highlightFlag, null, null); final SWTCommitList list; list = new SWTCommitList(graph.getControl().getDisplay()); list.source(currentWalk); final GenerateHistoryJob rj = new GenerateHistoryJob(this, list); final Repository fdb = db; rj.addJobChangeListener(new JobChangeAdapter() { @Override public void done(final IJobChangeEvent event) { revObjectSelectionProvider.setActiveRepository(fdb); final Control graphctl = graph.getControl(); if (job != rj || graphctl.isDisposed()) return; graphctl.getDisplay().asyncExec(new Runnable() { public void run() { if (job == rj) job = null; } }); } }); job = rj; schedule(rj); return true; } private void cancelRefreshJob() { if (job != null && job.getState() != Job.NONE) { job.cancel(); // As the job had to be canceled but was working on // the data connected with the currentWalk we cannot // be sure it really finished. Since the walk is not // thread safe we must throw it away and build a new // one to start another walk. Clearing our field will // ensure that happens. // job = null; currentWalk = null; highlightFlag = null; pathFilters = null; } } private boolean pathChange(final List<String> o, final List<String> n) { if (o == null) return !n.isEmpty(); return !o.equals(n); } private void schedule(final Job j) { final IWorkbenchPartSite site = getWorkbenchSite(); if (site != null) { final IWorkbenchSiteProgressService p; p = (IWorkbenchSiteProgressService) site .getAdapter(IWorkbenchSiteProgressService.class); if (p != null) { p.schedule(j, 0, true /* use half-busy cursor */); return; } } j.schedule(); } void showCommitList(final Job j, final SWTCommitList list, final SWTCommit[] asArray) { if (job != j || graph.getControl().isDisposed()) return; graph.getControl().getDisplay().asyncExec(new Runnable() { public void run() { if (!graph.getControl().isDisposed() && job == j) { graph.setInput(highlightFlag, list, asArray); findToolbar.setInput(highlightFlag, graph.getTableView().getTable(), asArray); } } }); } private IWorkbenchPartSite getWorkbenchSite() { final IWorkbenchPart part = getHistoryPageSite().getPart(); return part != null ? part.getSite() : null; } public boolean isValidInput(final Object object) { return canShowHistoryFor(object); } public Object getAdapter(final Class adapter) { return null; } public String getName() { final ResourceList in = (ResourceList) super.getInput(); if (currentWalk == null || in == null) return ""; //$NON-NLS-1$ final IResource[] items = in.getItems(); if (items.length == 0) return ""; //$NON-NLS-1$ final StringBuilder b = new StringBuilder(); b.append(items[0].getProject().getName()); if (currentWalk.getRevFilter() != RevFilter.ALL) { b.append(": "); //$NON-NLS-1$ b.append(currentWalk.getRevFilter()); } if (currentWalk.getTreeFilter() != TreeFilter.ALL) { b.append(":"); //$NON-NLS-1$ for (final String p : pathFilters) { b.append(' '); b.append(p); } } return b.toString(); } public String getDescription() { return getName(); } private abstract class BooleanPrefAction extends Action implements IPropertyChangeListener, ActionFactory.IWorkbenchAction { private final String prefName; BooleanPrefAction(final String pn, final String text) { setText(text); prefName = pn; prefs.addPropertyChangeListener(this); setChecked(prefs.getBoolean(prefName)); } public void run() { prefs.setValue(prefName, isChecked()); apply(isChecked()); } abstract void apply(boolean value); public void propertyChange(final PropertyChangeEvent event) { if (prefName.equals(event.getProperty())) { setChecked(prefs.getBoolean(prefName)); apply(isChecked()); } } public void dispose() { prefs.removePropertyChangeListener(this); } } private class TextAction extends Action implements FocusListener, ISelectionChangedListener { private final int op; TextAction(final int operationCode) { op = operationCode; setEnabled(false); } public void run() { if (commentViewer.getTextWidget().isFocusControl()) { if (commentViewer.canDoOperation(op)) commentViewer.doOperation(op); } else if (fileViewer.getTable().isFocusControl()) { switch (op) { case ITextOperationTarget.COPY: fileViewer.doCopy(); break; case ITextOperationTarget.SELECT_ALL: fileViewer.doSelectAll(); break; } } else if (graph.getControl().isFocusControl()) { switch (op) { case ITextOperationTarget.COPY: graph.doCopy(); break; } } } private void update() { if (commentViewer.getTextWidget().isFocusControl()) { setEnabled(commentViewer.canDoOperation(op)); } else if (fileViewer.getTable().isFocusControl()) { switch (op) { case ITextOperationTarget.COPY: setEnabled(!fileViewer.getSelection().isEmpty()); break; case ITextOperationTarget.SELECT_ALL: setEnabled(fileViewer.getTable().getItemCount() > 0); break; } } else if (graph.getControl().isFocusControl()) { switch (op) { case ITextOperationTarget.COPY: setEnabled(graph.canDoCopy()); break; case ITextOperationTarget.SELECT_ALL: setEnabled(false); break; } } } public void focusGained(final FocusEvent e) { update(); } public void selectionChanged(final SelectionChangedEvent event) { update(); } public void focusLost(final FocusEvent e) { // Ignore lost events. If focus leaves our page then the // workbench will update the global action away from us. // If focus stays in our page someone else should have // gained it from us. } } private class CompareWithWorkingTreeAction extends Action { public CompareWithWorkingTreeAction() { super(UIText.GitHistoryPage_CompareWithWorking); } @Override public void run() { IStructuredSelection selection = ((IStructuredSelection) revObjectSelectionProvider .getSelection()); if (selection.size() == 1) { Iterator<?> it = selection.iterator(); SWTCommit commit = (SWTCommit) it.next(); if (getInput() instanceof IFile){ IFile file = (IFile) getInput(); final RepositoryMapping mapping = RepositoryMapping.getMapping(file.getProject()); final String gitPath = mapping.getRepoRelativePath(file); ITypedElement right = getFileRevisionTypedElement(file, gitPath, commit); final GitCompareFileRevisionEditorInput in = new GitCompareFileRevisionEditorInput( SaveableCompareEditorInput.createFileElement(file), right, null); openInCompare(in); } } } @Override public boolean isEnabled() { int size = ((IStructuredSelection) revObjectSelectionProvider .getSelection()).size(); return IFile.class.isAssignableFrom(getInput().getClass()) && size == 1; } } private class CompareVersionsAction extends Action { public CompareVersionsAction() { super(UIText.GitHistoryPage_CompareVersions); } @Override public void run() { IStructuredSelection selection = ((IStructuredSelection) revObjectSelectionProvider .getSelection()); if (selection.size() == 2) { Iterator<?> it = selection.iterator(); SWTCommit commit1 = (SWTCommit) it.next(); SWTCommit commit2 = (SWTCommit) it.next(); if (getInput() instanceof IFile){ IFile resource = (IFile) getInput(); final RepositoryMapping map = RepositoryMapping .getMapping(resource); final String gitPath = map .getRepoRelativePath(resource); final ITypedElement base = getFileRevisionTypedElement(resource, gitPath, commit1); final ITypedElement next = getFileRevisionTypedElement(resource, gitPath, commit2); CompareEditorInput in = new GitCompareFileRevisionEditorInput(base, next, null); openInCompare(in); } } } @Override public boolean isEnabled() { int size = ((IStructuredSelection) revObjectSelectionProvider .getSelection()).size(); return IFile.class.isAssignableFrom(getInput().getClass()) && size == 2; } } private class ViewVersionsAction extends Action { public ViewVersionsAction() { super(UIText.GitHistoryPage_open); } @Override public void run() { IStructuredSelection selection = ((IStructuredSelection) revObjectSelectionProvider .getSelection()); if (selection.size() < 1) return; if (!(getInput() instanceof IFile)) return; IFile resource = (IFile) getInput(); final RepositoryMapping map = RepositoryMapping .getMapping(resource); final String gitPath = map.getRepoRelativePath(resource); Iterator<?> it = selection.iterator(); boolean errorOccured = false; List<ObjectId> ids = new ArrayList<ObjectId>(); while (it.hasNext()) { SWTCommit commit = (SWTCommit) it.next(); IFileRevision rev = null; try { rev = getFileRevision(resource, gitPath, commit); } catch (IOException e) { Activator.logError(NLS.bind( UIText.GitHistoryPage_errorLookingUpPath, gitPath, commit.getId()), e); errorOccured = true; } if (rev != null) { try { Utils.openEditor(getSite().getPage(), rev, new NullProgressMonitor()); } catch (CoreException e) { Activator.logError(UIText.GitHistoryPage_openFailed, e); errorOccured = true; } } else { ids.add(commit.getId()); } } if (errorOccured) MessageDialog.openError(getSite().getShell(), UIText.GitHistoryPage_openFailed, UIText.GitHistoryPage_seeLog); if (ids.size() > 0) { String idList = ""; //$NON-NLS-1$ for (ObjectId objectId : ids) { idList += objectId.getName() + " "; //$NON-NLS-1$ } MessageDialog.openError(getSite().getShell(), UIText.GitHistoryPage_fileNotFound, NLS.bind( UIText.GitHistoryPage_notContainedInCommits, gitPath, idList)); } } @Override public boolean isEnabled() { int size = ((IStructuredSelection) revObjectSelectionProvider .getSelection()).size(); return IFile.class.isAssignableFrom(getInput().getClass()) && size >= 1; } } }
Fix refresh bug in name of GitHistoryView When the filter was changed in the GitHistoryView the label was not updated accordingly. Change-Id: I5cd79b90e74cb25fc7af6ce4b038bf33720a970a Signed-off-by: Stefan Lay <[email protected]>
org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/history/GitHistoryPage.java
Fix refresh bug in name of GitHistoryView
<ide><path>rg.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/history/GitHistoryPage.java <ide> } <ide> @Override <ide> public void run() { <add> String oldName = getName(); <ide> if (!isChecked()) { <ide> if (showAllFilter == filter) { <ide> showAllFilter = ShowFilter.SHOWALLRESOURCE; <ide> showAllFolderVersionsAction.setChecked(false); <ide> refresh(); <ide> } <add> GitHistoryPage.this.firePropertyChange(GitHistoryPage.this, P_NAME, oldName, getName()); <ide> Activator.getDefault().getPreferenceStore().setValue( <ide> PREF_SHOWALLFILTER, showAllFilter.toString()); <ide> }
Java
apache-2.0
c5b1edaec4e52145f84627fed9600c64c4c48f39
0
esoco/gewt
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // This file is a part of the 'gewt' project. // Copyright 2017 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany // // 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 de.esoco.ewt.component; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.HasClickHandlers; import com.google.gwt.user.client.ui.Widget; /******************************************************************** * A panel that can contain arbitrary child widgets. * * @author eso */ public class Panel extends Container { //~ Methods ---------------------------------------------------------------- /*************************************** * Overridden to sink GWT events so that events will be created. * * @see Container#createEventDispatcher() */ @Override ComponentEventDispatcher createEventDispatcher() { ComponentEventDispatcher rEventDispatcher = super.createEventDispatcher(); Widget rWidget = getWidget(); if (!(rWidget instanceof HasClickHandlers)) { // enable click events for panel widgets that without native support rWidget.addDomHandler(rEventDispatcher, ClickEvent.getType()); } return rEventDispatcher; } }
src/main/java/de/esoco/ewt/component/Panel.java
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // This file is a part of the 'gewt' project. // Copyright 2016 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany // // 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 de.esoco.ewt.component; import com.google.gwt.event.dom.client.ClickEvent; /******************************************************************** * A panel that can contain arbitrary child widgets. * * @author eso */ public class Panel extends Container { //~ Methods ---------------------------------------------------------------- /*************************************** * Overridden to sink GWT events so that events will be created. * * @see Container#createEventDispatcher() */ @Override ComponentEventDispatcher createEventDispatcher() { ComponentEventDispatcher rEventDispatcher = super.createEventDispatcher(); getWidget().addDomHandler(rEventDispatcher, ClickEvent.getType()); return rEventDispatcher; } }
BF: DOM click event handling only for panels without click handler support (as in gwtmaterial)
src/main/java/de/esoco/ewt/component/Panel.java
BF: DOM click event handling only for panels without click handler support (as in gwtmaterial)
<ide><path>rc/main/java/de/esoco/ewt/component/Panel.java <ide> //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ <ide> // This file is a part of the 'gewt' project. <del>// Copyright 2016 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany <add>// Copyright 2017 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany <ide> // <ide> // Licensed under the Apache License, Version 2.0 (the "License"); <ide> // you may not use this file except in compliance with the License. <ide> package de.esoco.ewt.component; <ide> <ide> import com.google.gwt.event.dom.client.ClickEvent; <add>import com.google.gwt.event.dom.client.HasClickHandlers; <add>import com.google.gwt.user.client.ui.Widget; <ide> <ide> <ide> /******************************************************************** <ide> ComponentEventDispatcher rEventDispatcher = <ide> super.createEventDispatcher(); <ide> <del> getWidget().addDomHandler(rEventDispatcher, ClickEvent.getType()); <add> Widget rWidget = getWidget(); <add> <add> if (!(rWidget instanceof HasClickHandlers)) <add> { <add> // enable click events for panel widgets that without native support <add> rWidget.addDomHandler(rEventDispatcher, ClickEvent.getType()); <add> } <ide> <ide> return rEventDispatcher; <ide> }
Java
apache-2.0
bd801a9bc0482ae2bc89e602dd293d29843f6b61
0
harti2006/neo4j-server-maven-plugin,harti2006/neo4j-server-maven-plugin
/* * Copyright 2015 André Hartmann (github.com/harti2006) * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.harti2006.neo4j; import static java.lang.String.format; import static java.nio.file.Files.createDirectories; import static java.nio.file.Files.exists; import static java.nio.file.Files.newBufferedWriter; import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; import static java.nio.file.StandardOpenOption.WRITE; import static java.util.concurrent.TimeUnit.SECONDS; import static org.apache.commons.io.FileUtils.copyURLToFile; import static org.apache.maven.plugins.annotations.LifecyclePhase.PRE_INTEGRATION_TEST; import static org.rauschig.jarchivelib.ArchiverFactory.createArchiver; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Properties; import org.apache.commons.io.FileUtils; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugins.annotations.Mojo; import org.codehaus.plexus.util.PropertyUtils; import org.neo4j.driver.v1.AuthTokens; import org.neo4j.driver.v1.Driver; import org.neo4j.driver.v1.GraphDatabase; import org.neo4j.driver.v1.Session; import org.neo4j.driver.v1.exceptions.ServiceUnavailableException; @Mojo(name = "start", defaultPhase = PRE_INTEGRATION_TEST) public class StartNeo4jServerMojo extends Neo4jServerMojoSupport { private static final int INITIAL_WAIT_MILLIS = 1500; private static final int WAIT_MILLIS = 1000; public void execute() throws MojoExecutionException { installNeo4jServer(); configureNeo4jServer(); startNeo4jServer(); } private void installNeo4jServer() throws MojoExecutionException { final Path serverLocation = getServerLocation(); if (!exists(serverLocation)) { final Path downloadDestination = Paths.get(System.getProperty("java.io.tmpdir"), "neo4j-server-maven-plugin", "downloads", "server", version, "neo4j-server" + urlSuffix); if (!exists(downloadDestination)) { try { final URL source = new URL(BASE_URL + version + urlSuffix); createDirectories(downloadDestination.getParent()); getLog().info(format("Downloading Neo4j Server from %s", source)); getLog().debug(format("...and saving it to '%s'", downloadDestination)); copyURLToFile(source, downloadDestination.toFile()); } catch (IOException e) { throw new MojoExecutionException("Error downloading server artifact", e); } } try { getLog().info(format("Extracting %s", downloadDestination)); createArchiver("tar", "gz").extract(downloadDestination.toFile(), serverLocation.getParent().toFile()); } catch (IOException e) { throw new MojoExecutionException("Error extracting server archive", e); } } } private void configureNeo4jServer() throws MojoExecutionException { final Path serverLocation = getServerLocation(); final Path serverPropertiesPath = serverLocation.resolve(Paths.get("conf", "neo4j.conf")); Properties serverProperties = PropertyUtils.loadProperties(serverPropertiesPath.toFile()); serverProperties.setProperty("dbms.connector.http.listen_address", "localhost:" + port); serverProperties.setProperty("dbms.connector.bolt.listen_address", "localhost:" + boltPort); serverProperties.setProperty("dbms.connector.https.enabled", "false"); try { serverProperties.store(newBufferedWriter(serverPropertiesPath, TRUNCATE_EXISTING, WRITE), "Generated by Neo4j Server Maven Plugin"); } catch (IOException e) { throw new MojoExecutionException("Could not configure Neo4j server", e); } } private void startNeo4jServer() throws MojoExecutionException { final Log log = getLog(); try { final Path serverLocation = getServerLocation(); // Delete existing DB if required if (deleteDb) { Path dataDir = serverLocation.resolve("data"); log.info("Deleting Database directory: '" + dataDir.toAbsolutePath().toString() + "'"); FileUtils.deleteQuietly(dataDir.toFile()); } final String[] neo4jCommand = new String[]{ serverLocation.resolve(Paths.get("bin", "neo4j")).toString(), "start"}; final File workingDir = serverLocation.toFile(); final Process neo4jStartProcess = Runtime.getRuntime().exec(neo4jCommand, null, workingDir); try (BufferedReader br = new BufferedReader( new InputStreamReader(neo4jStartProcess.getInputStream()))) { String line; while ((line = br.readLine()) != null) { log.info("NEO4J SERVER > " + line); } } if (neo4jStartProcess.waitFor(5, SECONDS) && neo4jStartProcess.exitValue() == 0) { log.info("Started Neo4j server"); } else { throw new MojoExecutionException("Neo4j server did not start up properly"); } // Now we need to wait it replies checkServerReady(); // Went up! If it's a new DB, let's change the password. setNewPassword(); } catch (IOException | InterruptedException e) { throw new MojoExecutionException("Could not start neo4j server", e); } } /** * @see Neo4jServerMojoSupport#serverReadyAttempts */ private void checkServerReady() throws MojoExecutionException, InterruptedException { // If the deleteDb parameter is true, at this point we have created a new server, which have the // default // password, and we're about to change this. // String pwd = deleteDb ? "neo4j" : password; Thread.sleep(INITIAL_WAIT_MILLIS); // It takes some time anyway for (int attempts = 1; attempts <= serverReadyAttempts; attempts++) { getLog().debug("Trying to connect Neo4j, attempt " + attempts); try (Driver ignored = GraphDatabase.driver("bolt://127.0.0.1:" + boltPort, AuthTokens.basic("neo4j", pwd))) { return; } catch (ServiceUnavailableException ignored) { Thread.sleep(WAIT_MILLIS); } } throw new MojoExecutionException( format("Server doesn't result started after waiting %sms for its boot", INITIAL_WAIT_MILLIS + serverReadyAttempts * WAIT_MILLIS)); } private void setNewPassword() { if (!deleteDb) { return; } try (Driver driver = GraphDatabase.driver("bolt://127.0.0.1:" + boltPort, AuthTokens.basic("neo4j", "neo4j")); Session session = driver.session()) { session.run("CALL dbms.changePassword( '" + password + "' )"); } } }
src/main/java/com/github/harti2006/neo4j/StartNeo4jServerMojo.java
/* * Copyright 2015 André Hartmann (github.com/harti2006) * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.harti2006.neo4j; import static java.lang.String.format; import static java.nio.file.Files.createDirectories; import static java.nio.file.Files.exists; import static java.nio.file.Files.newBufferedWriter; import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; import static java.nio.file.StandardOpenOption.WRITE; import static java.util.concurrent.TimeUnit.SECONDS; import static org.apache.commons.io.FileUtils.copyURLToFile; import static org.apache.maven.plugins.annotations.LifecyclePhase.PRE_INTEGRATION_TEST; import static org.rauschig.jarchivelib.ArchiverFactory.createArchiver; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Properties; import org.apache.commons.io.FileUtils; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugins.annotations.Mojo; import org.codehaus.plexus.util.PropertyUtils; import org.neo4j.driver.v1.AuthTokens; import org.neo4j.driver.v1.Driver; import org.neo4j.driver.v1.GraphDatabase; import org.neo4j.driver.v1.Session; import org.neo4j.driver.v1.exceptions.ServiceUnavailableException; @Mojo(name = "start", defaultPhase = PRE_INTEGRATION_TEST) public class StartNeo4jServerMojo extends Neo4jServerMojoSupport { public void execute() throws MojoExecutionException { installNeo4jServer(); configureNeo4jServer(); startNeo4jServer(); } private void installNeo4jServer() throws MojoExecutionException { final Path serverLocation = getServerLocation(); if (!exists(serverLocation)) { final Path downloadDestination = Paths.get(System.getProperty("java.io.tmpdir"), "neo4j-server-maven-plugin", "downloads", "server", version, "neo4j-server" + urlSuffix); if (!exists(downloadDestination)) { try { final URL source = new URL(BASE_URL + version + urlSuffix); createDirectories(downloadDestination.getParent()); getLog().info(format("Downloading Neo4j Server from %s", source)); getLog().debug(format("...and saving it to '%s'", downloadDestination)); copyURLToFile(source, downloadDestination.toFile()); } catch (IOException e) { throw new MojoExecutionException("Error downloading server artifact", e); } } try { getLog().info(format("Extracting %s", downloadDestination)); createArchiver("tar", "gz").extract(downloadDestination.toFile(), serverLocation.getParent().toFile()); } catch (IOException e) { throw new MojoExecutionException("Error extracting server archive", e); } } } private void configureNeo4jServer() throws MojoExecutionException { final Path serverLocation = getServerLocation(); final Path serverPropertiesPath = serverLocation.resolve(Paths.get("conf", "neo4j.conf")); Properties serverProperties = PropertyUtils.loadProperties(serverPropertiesPath.toFile()); serverProperties.setProperty("dbms.connector.http.listen_address", "localhost:" + port); serverProperties.setProperty("dbms.connector.bolt.listen_address", "localhost:" + boltPort); serverProperties.setProperty("dbms.connector.https.enabled", "false"); try { serverProperties.store(newBufferedWriter(serverPropertiesPath, TRUNCATE_EXISTING, WRITE), "Generated by Neo4j Server Maven Plugin"); } catch (IOException e) { throw new MojoExecutionException("Could not configure Neo4j server", e); } } private void startNeo4jServer() throws MojoExecutionException { final Log log = getLog(); try { final Path serverLocation = getServerLocation(); // Delete existing DB if required if (deleteDb) { Path dataDir = serverLocation.resolve("data"); log.info("Deleting Database directory: '" + dataDir.toAbsolutePath().toString() + "'"); FileUtils.deleteQuietly(dataDir.toFile()); } final String[] neo4jCommand = new String[]{ serverLocation.resolve(Paths.get("bin", "neo4j")).toString(), "start"}; final File workingDir = serverLocation.toFile(); final Process neo4jStartProcess = Runtime.getRuntime().exec(neo4jCommand, null, workingDir); try (BufferedReader br = new BufferedReader( new InputStreamReader(neo4jStartProcess.getInputStream()))) { String line; while ((line = br.readLine()) != null) { log.info("NEO4J SERVER > " + line); } } if (neo4jStartProcess.waitFor(5, SECONDS) && neo4jStartProcess.exitValue() == 0) { log.info("Started Neo4j server"); } else { throw new MojoExecutionException("Neo4j server did not start up properly"); } // Now we need to wait it replies checkServerReady(); // Went up! If it's a new DB, let's change the password. setNewPassword(); } catch (IOException | InterruptedException e) { throw new MojoExecutionException("Could not start neo4j server", e); } } /** * @see Neo4jServerMojoSupport#serverReadyAttempts. */ private void checkServerReady() throws MojoExecutionException, InterruptedException { // If the deleteDb parameter is true, at this point we have created a new server, which have the // default // password, and we're about to change this. // String pwd = deleteDb ? "neo4j" : password; Thread.sleep(1500); // It takes some time anyway for (int attempts = 1; attempts <= serverReadyAttempts; attempts++) { getLog().debug("Trying to connect Neo4j, attempt " + attempts); try (Driver driver = GraphDatabase.driver("bolt://127.0.0.1:" + boltPort, AuthTokens.basic("neo4j", pwd));) { return; } catch (ServiceUnavailableException ex) { Thread.sleep(1000); } } throw new MojoExecutionException(String.format ( "Server doesn't result started after waiting %ss for its boot", 1.5 + serverReadyAttempts )); } private void setNewPassword() { if (!deleteDb) { return; } try (Driver driver = GraphDatabase.driver("bolt://127.0.0.1:" + boltPort, AuthTokens.basic("neo4j", "neo4j")); Session session = driver.session();) { session.run("CALL dbms.changePassword( '" + password + "' )"); } } }
removed magic numbers
src/main/java/com/github/harti2006/neo4j/StartNeo4jServerMojo.java
removed magic numbers
<ide><path>rc/main/java/com/github/harti2006/neo4j/StartNeo4jServerMojo.java <ide> <ide> @Mojo(name = "start", defaultPhase = PRE_INTEGRATION_TEST) <ide> public class StartNeo4jServerMojo extends Neo4jServerMojoSupport { <add> <add> private static final int INITIAL_WAIT_MILLIS = 1500; <add> private static final int WAIT_MILLIS = 1000; <ide> <ide> public void execute() throws MojoExecutionException { <ide> installNeo4jServer(); <ide> } <ide> <ide> /** <del> * @see Neo4jServerMojoSupport#serverReadyAttempts. <add> * @see Neo4jServerMojoSupport#serverReadyAttempts <ide> */ <ide> private void checkServerReady() throws MojoExecutionException, InterruptedException { <ide> // If the deleteDb parameter is true, at this point we have created a new server, which have the <ide> // password, and we're about to change this. <ide> // <ide> String pwd = deleteDb ? "neo4j" : password; <del> Thread.sleep(1500); // It takes some time anyway <add> Thread.sleep(INITIAL_WAIT_MILLIS); // It takes some time anyway <ide> <ide> for (int attempts = 1; attempts <= serverReadyAttempts; attempts++) { <ide> getLog().debug("Trying to connect Neo4j, attempt " + attempts); <ide> <del> try (Driver driver = GraphDatabase.driver("bolt://127.0.0.1:" + boltPort, <del> AuthTokens.basic("neo4j", pwd));) { <add> try (Driver ignored = GraphDatabase.driver("bolt://127.0.0.1:" + boltPort, <add> AuthTokens.basic("neo4j", pwd))) { <ide> return; <del> } catch (ServiceUnavailableException ex) { <del> Thread.sleep(1000); <add> } catch (ServiceUnavailableException ignored) { <add> Thread.sleep(WAIT_MILLIS); <ide> } <ide> } <del> throw new MojoExecutionException(String.format ( <del> "Server doesn't result started after waiting %ss for its boot", <del> 1.5 + serverReadyAttempts <del> )); <add> throw new MojoExecutionException( <add> format("Server doesn't result started after waiting %sms for its boot", <add> INITIAL_WAIT_MILLIS + serverReadyAttempts * WAIT_MILLIS)); <ide> } <ide> <ide> private void setNewPassword() { <ide> <ide> try (Driver driver = GraphDatabase.driver("bolt://127.0.0.1:" + boltPort, <ide> AuthTokens.basic("neo4j", "neo4j")); <del> Session session = driver.session();) { <add> Session session = driver.session()) { <ide> session.run("CALL dbms.changePassword( '" + password + "' )"); <ide> } <ide> }
JavaScript
apache-2.0
b38615eff7abdc2aa6edb5fa003b4e9117ecf458
0
snahelou/awx,snahelou/awx,wwitzel3/awx,wwitzel3/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx,snahelou/awx
export default function Init($location, DeleteSurvey, EditSurvey, AddSurvey, GenerateForm, SurveyQuestionForm, Wait, Alert, GetBasePath, Rest, ProcessErrors, $compile, FinalizeQuestion, EditQuestion, $sce) { return function(params) { var scope = params.scope, id = params.id, i, url, html, element, questions = [], form = SurveyQuestionForm, sce = params.sce; scope.sce = sce; scope.survey_questions = []; scope.answer_types=[ {name: 'Text' , type: 'text'}, {name: 'Textarea', type: 'textarea'}, {name: 'Password', type: 'password'}, {name: 'Multiple Choice (single select)', type: 'multiplechoice'}, {name: 'Multiple Choice (multiple select)', type: 'multiselect'}, {name: 'Integer', type: 'integer'}, {name: 'Float', type: 'float'} ]; scope.serialize = function(expression){ return $sce.getTrustedHtml(expression); }; scope.deleteSurvey = function() { DeleteSurvey({ scope: scope, id: id, // callback: 'SchedulesRefresh' }); }; scope.editSurvey = function() { if(scope.mode==='add'){ for(i=0; i<scope.survey_questions.length; i++){ questions.push(scope.survey_questions[i]); } } EditSurvey({ scope: scope, id: id, // callback: 'SchedulesRefresh' }); }; scope.addSurvey = function() { AddSurvey({ scope: scope }); }; scope.cancelSurvey = function(me){ if(scope.mode === 'add'){ questions = []; } else { scope.survey_questions = []; } $(me).dialog('close'); }; scope.addQuestion = function(){ var tmpMode = scope.mode; GenerateForm.inject(form, { id:'new_question', mode: 'add' , scope: scope, related: false, breadCrumbs: false}); scope.mode = tmpMode; scope.required = true; //set the required checkbox to true via the ngmodel attached to scope.required. scope.text_min = null; scope.text_max = null; scope.int_min = null; scope.int_max = null; scope.float_min = null; scope.float_max = null; scope.duplicate = false; scope.invalidChoice = false; scope.minTextError = false; scope.maxTextError = false; }; scope.addNewQuestion = function(){ // $('#add_question_btn').on("click" , function(){ scope.addQuestion(); $('#survey_question_question_name').focus(); $('#add_question_btn').attr('disabled', 'disabled'); $('#add_question_btn').hide(); $('#survey-save-button').attr('disabled' , 'disabled'); // }); }; scope.editQuestion = function(index){ scope.duplicate = false; EditQuestion({ index: index, scope: scope, question: (scope.mode==='add') ? questions[index] : scope.survey_questions[index] }); }; scope.deleteQuestion = function(index){ element = $('.question_final:eq('+index+')'); element.remove(); if(scope.mode === 'add'){ questions.splice(index, 1); scope.reorder(); if(questions.length<1){ $('#survey-save-button').attr('disabled', 'disabled'); } } else { scope.survey_questions.splice(index, 1); scope.reorder(); if(scope.survey_questions.length<1){ $('#survey-save-button').attr('disabled', 'disabled'); } } }; scope.cancelQuestion = function(event){ var elementID, key; if(event.target.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.id==="new_question"){ $('#new_question .aw-form-well').remove(); $('#add_question_btn').show(); $('#add_question_btn').removeAttr('disabled'); if(scope.mode === 'add' && questions.length>0){ $('#survey-save-button').removeAttr('disabled'); } if(scope.mode === 'edit' && scope.survey_questions.length>0 && scope.can_edit===true){ $('#survey-save-button').removeAttr('disabled'); } } else { elementID = event.target.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.id; key = elementID.split('_')[1]; $('#'+elementID).empty(); if(scope.mode === 'add'){ if(questions.length>0){ $('#survey-save-button').removeAttr('disabled'); } scope.finalizeQuestion(questions[key], Number(key)); } else if(scope.mode=== 'edit' ){ if(scope.survey_questions.length>0 && scope.can_edit === true){ $('#survey-save-button').removeAttr('disabled'); } scope.finalizeQuestion(scope.survey_questions[key] , Number(key)); } } }; scope.questionUp = function(index){ var animating = false, clickedDiv = $('#question_'+index), prevDiv = clickedDiv.prev(), distance = clickedDiv.outerHeight(); if (animating) { return; } if (prevDiv.length) { animating = true; $.when(clickedDiv.animate({ top: -distance }, 600), prevDiv.animate({ top: distance }, 600)).done(function () { prevDiv.css('top', '0px'); clickedDiv.css('top', '0px'); clickedDiv.insertBefore(prevDiv); animating = false; if ( scope.mode === 'add'){ i = questions[index]; questions[index] = questions[index-1]; questions[index-1] = i; } else { i = scope.survey_questions[index]; scope.survey_questions[index] = scope.survey_questions[index-1]; scope.survey_questions[index-1] = i; } scope.reorder(); }); } }; scope.questionDown = function(index){ var clickedDiv = $('#question_'+index), nextDiv = clickedDiv.next(), distance = clickedDiv.outerHeight(), animating = false; if (animating) { return; } if (nextDiv.length) { animating = true; $.when(clickedDiv.animate({ top: distance }, 600), nextDiv.animate({ top: -distance }, 600)).done(function () { nextDiv.css('top', '0px'); clickedDiv.css('top', '0px'); nextDiv.insertBefore(clickedDiv); animating = false; if(scope.mode === 'add'){ i = questions[index]; questions[index] = questions[Number(index)+1]; questions[Number(index)+1] = i; } else { i = scope.survey_questions[index]; scope.survey_questions[index] = scope.survey_questions[Number(index)+1]; scope.survey_questions[Number(index)+1] = i; } scope.reorder(); }); } }; scope.reorder = function(){ if(scope.mode==='add'){ for(i=0; i<questions.length; i++){ questions[i].index=i; $('.question_final:eq('+i+')').attr('id', 'question_'+i); } } else { for(i=0; i<scope.survey_questions.length; i++){ scope.survey_questions[i].index=i; $('.question_final:eq('+i+')').attr('id', 'question_'+i); } } }; scope.finalizeQuestion= function(data, index){ FinalizeQuestion({ scope: scope, question: data, id: id, index: index }); }; scope.typeChange = function() { scope.minTextError = false; scope.maxTextError = false; scope.default = ""; scope.default_multiselect = ""; scope.default_float = ""; scope.default_int = ""; scope.default_textarea = ""; scope.default_password = "" ; scope.choices = ""; scope.text_min = ""; scope.text_max = "" ; scope.textarea_min = ""; scope.textarea_max = "" ; scope.password_min = "" ; scope.password_max = "" ; scope.int_min = ""; scope.int_max = ""; scope.float_min = ""; scope.float_max = ""; scope.survey_question_form.default.$setPristine(); scope.survey_question_form.default_multiselect.$setPristine(); scope.survey_question_form.default_float.$setPristine(); scope.survey_question_form.default_int.$setPristine(); scope.survey_question_form.default_textarea.$setPristine(); scope.survey_question_form.default_password.$setPristine(); scope.survey_question_form.choices.$setPristine(); scope.survey_question_form.int_min.$setPristine(); scope.survey_question_form.int_max.$setPristine(); }; scope.submitQuestion = function(event){ var data = {}, fld, i, choiceArray, answerArray, key, elementID; scope.invalidChoice = false; scope.duplicate = false; scope.minTextError = false; scope.maxTextError = false; if(scope.type.type==="text"){ if(scope.default.trim() !== ""){ if(scope.default.trim().length < scope.text_min && scope.text_min !== "" ){ scope.minTextError = true; } if(scope.text_max < scope.default.trim().length && scope.text_max !== "" ){ scope.maxTextError = true; } } } if(scope.type.type==="textarea"){ if(scope.default_textarea.trim() !== ""){ if(scope.default_textarea.trim().length < scope.textarea_min && scope.textarea_min !== "" ){ scope.minTextError = true; } if(scope.textarea_max < scope.default_textarea.trim().length && scope.textarea_max !== "" ){ scope.maxTextError = true; } } } if(scope.type.type==="password"){ if(scope.default_password.trim() !== ""){ if(scope.default_password.trim().length < scope.password_min && scope.password_min !== "" ){ scope.minTextError = true; } if(scope.password_max < scope.default_password.trim().length && scope.password_max !== "" ){ scope.maxTextError = true; } } } if(scope.type.type==="multiselect" && scope.default_multiselect.trim() !== ""){ choiceArray = scope.choices.split(/\n/); answerArray = scope.default_multiselect.split(/\n/); if(answerArray.length>0){ for(i=0; i<answerArray.length; i++){ if($.inArray(answerArray[i], choiceArray)===-1){ scope.invalidChoice = true; } } } } if(scope.type.type==="multiplechoice" && scope.default.trim() !== ""){ choiceArray = scope.choices.split(/\n/); if($.inArray(scope.default, choiceArray)===-1){ scope.invalidChoice = true; } } // validate that there aren't any questions using this var name. if(GenerateForm.mode === 'add'){ if(scope.mode === 'add'){ for(fld in questions){ if(questions[fld].variable === scope.variable){ scope.duplicate = true; } } } else if (scope.mode === 'edit'){ for(fld in scope.survey_questions){ if(scope.survey_questions[fld].variable === scope.variable){ scope.duplicate = true; } } } } if(GenerateForm.mode === 'edit'){ elementID = event.target.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.id; key = elementID.split('_')[1]; if(scope.mode==='add'){ for(fld in questions){ if(questions[fld].variable === scope.variable && fld!==key){ scope.duplicate = true; } } } else if(scope.mode === 'edit'){ for(fld in scope.survey_questions){ if(scope.survey_questions[fld].variable === scope.variable && fld!==key){ scope.duplicate = true; } } } } if(scope.duplicate===true || scope.invalidChoice===true || scope.minTextError === true || scope.maxTextError === true){ return; } try { //create data object for each submitted question data.question_name = scope.question_name; data.question_description = (scope.question_description) ? scope.question_description : "" ; data.required = scope.required; data.type = scope.type.type; data.variable = scope.variable; //set the data.min depending on which type of question if (scope.type.type === 'text') { data.min = scope.text_min; } else if (scope.type.type === 'textarea') { data.min = scope.textarea_min; } else if (scope.type.type === 'password') { data.min = scope.password_min; } else if (scope.type.type === 'float') { data.min = scope.float_min; } else if (scope.type.type === 'integer') { data.min = scope.int_min; } else { data.min = ""; } // set hte data max depending on which type if (scope.type.type === 'text') { data.max = scope.text_max; } else if (scope.type.type === 'textarea') { data.max = scope.textarea_max; } else if (scope.type.type === 'password') { data.max = scope.password_max; } else if (scope.type.type === 'float') { data.max = scope.float_max; } else if (scope.type.type === 'integer') { data.max = scope.int_max; } else { data.max = ""; } //set the data.default depending on which type if (scope.type.type === 'text' || scope.type.type === 'multiplechoice') { data.default = scope.default; } else if (scope.type.type === 'textarea') { data.default = scope.default_textarea; } else if (scope.type.type === 'password') { data.default = scope.default_password; } else if (scope.type.type === 'multiselect') { data.default = scope.default_multiselect; } else if (scope.type.type === 'float') { data.default = scope.default_float; } else if (scope.type.type === 'integer') { data.default = scope.default_int; } else { data.default = ""; } data.choices = (scope.type.type === "multiplechoice") ? scope.choices : (scope.type.type === 'multiselect') ? scope.choices : "" ; if (data.choices !== "") { // remove duplicates from the choices data.choices = _.uniq(data.choices.split("\n")).join("\n"); } Wait('stop'); if(scope.mode === 'add' || scope.mode==="edit" && scope.can_edit === true){ $('#survey-save-button').removeAttr('disabled'); } if(GenerateForm.mode === 'add'){ if(scope.mode === 'add'){ questions.push(data); $('#new_question .aw-form-well').remove(); $('#add_question_btn').show(); scope.finalizeQuestion(data , questions.length-1); } else if (scope.mode === 'edit'){ scope.survey_questions.push(data); $('#new_question .aw-form-well').remove(); $('#add_question_btn').show(); scope.finalizeQuestion(data , scope.survey_questions.length-1); } } if(GenerateForm.mode === 'edit'){ elementID = event.target.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.id; key = elementID.split('_')[1]; if(scope.mode==='add'){ questions[key] = data; } else if(scope.mode === 'edit'){ scope.survey_questions[key] = data; } $('#'+elementID).empty(); scope.finalizeQuestion(data , Number(key)); } } catch (err) { Wait('stop'); Alert("Error", "Error parsing extra variables. Parser returned: " + err); } }; scope.resetForm = function(){ html = '<div class="row">'+ '<div class="col-sm-12">'+ '<label for="survey"><span class="label-text prepend-asterisk"> Questions</span></label>'+ '<div id="survey_maker_question_area"></div>'+ '<div id="finalized_questions"></div>'+ '<button style="display:none" type="button" class="btn btn-sm btn-primary" id="add_question_btn" ng-click="addNewQuestion()" aw-tool-tip="Create a new question" data-placement="top" data-original-title="" title="" disabled><i class="fa fa-plus fa-lg"></i> New Question</button>'+ '<div id="new_question"></div>'+ '</div>'+ '</div>'; $('#survey-modal-dialog').html(html); element = angular.element(document.getElementById('add_question_btn')); $compile(element)(scope); }; scope.saveSurvey = function() { Wait('start'); if(scope.mode ==="add"){ $('#survey-modal-dialog').dialog('close'); if(questions.length>0){ scope.survey_questions = questions; } scope.survey_name = ""; scope.survey_description = ""; questions = [] ; scope.$emit('SurveySaved'); } else{ scope.survey_name = ""; scope.survey_description = ""; url = GetBasePath('job_templates') + id + '/survey_spec/'; Rest.setUrl(url); Rest.post({ name: scope.survey_name, description: scope.survey_description, spec: scope.survey_questions }) .success(function () { // Wait('stop'); $('#survey-modal-dialog').dialog('close'); scope.$emit('SurveySaved'); }) .error(function (data, status) { ProcessErrors(scope, data, status, null, { hdr: 'Error!', msg: 'Failed to add new survey. POST returned status: ' + status }); }); } }; //for toggling the input on password inputs scope.toggleInput = function(id) { var buttonId = id + "_show_input_button", inputId = id, buttonInnerHTML = $(buttonId).html(); if (buttonInnerHTML.indexOf("Show") > -1) { $(buttonId).html("Hide"); $(inputId).attr("type", "text"); } else { $(buttonId).html("Show"); $(inputId).attr("type", "password"); } }; }; } Init.$inject = [ '$location', 'deleteSurvey', 'editSurvey', 'addSurvey', 'GenerateForm', 'questionDefinitionForm', 'Wait', 'Alert', 'GetBasePath', 'Rest', 'ProcessErrors', '$compile', 'finalizeQuestion', 'editQuestion', '$sce' ];
awx/ui/client/src/job-templates/survey-maker/surveys/init.factory.js
export default function Init($location, DeleteSurvey, EditSurvey, AddSurvey, GenerateForm, SurveyQuestionForm, Wait, Alert, GetBasePath, Rest, ProcessErrors, $compile, FinalizeQuestion, EditQuestion, $sce) { return function(params) { var scope = params.scope, id = params.id, i, url, html, element, questions = [], form = SurveyQuestionForm, sce = params.sce; scope.sce = sce; scope.survey_questions = []; scope.answer_types=[ {name: 'Text' , type: 'text'}, {name: 'Textarea', type: 'textarea'}, {name: 'Password', type: 'password'}, {name: 'Multiple Choice (single select)', type: 'multiplechoice'}, {name: 'Multiple Choice (multiple select)', type: 'multiselect'}, {name: 'Integer', type: 'integer'}, {name: 'Float', type: 'float'} ]; scope.serialize = function(expression){ return $sce.getTrustedHtml(expression); }; scope.deleteSurvey = function() { DeleteSurvey({ scope: scope, id: id, // callback: 'SchedulesRefresh' }); }; scope.editSurvey = function() { if(scope.mode==='add'){ for(i=0; i<scope.survey_questions.length; i++){ questions.push(scope.survey_questions[i]); } } EditSurvey({ scope: scope, id: id, // callback: 'SchedulesRefresh' }); }; scope.addSurvey = function() { AddSurvey({ scope: scope }); }; scope.cancelSurvey = function(me){ if(scope.mode === 'add'){ questions = []; } else { scope.survey_questions = []; } $(me).dialog('close'); }; scope.addQuestion = function(){ var tmpMode = scope.mode; GenerateForm.inject(form, { id:'new_question', mode: 'add' , scope: scope, related: false, breadCrumbs: false}); scope.mode = tmpMode; scope.required = true; //set the required checkbox to true via the ngmodel attached to scope.required. scope.text_min = null; scope.text_max = null; scope.int_min = null; scope.int_max = null; scope.float_min = null; scope.float_max = null; scope.duplicate = false; scope.invalidChoice = false; scope.minTextError = false; scope.maxTextError = false; }; scope.addNewQuestion = function(){ // $('#add_question_btn').on("click" , function(){ scope.addQuestion(); $('#survey_question_question_name').focus(); $('#add_question_btn').attr('disabled', 'disabled'); $('#add_question_btn').hide(); $('#survey-save-button').attr('disabled' , 'disabled'); // }); }; scope.editQuestion = function(index){ scope.duplicate = false; EditQuestion({ index: index, scope: scope, question: (scope.mode==='add') ? questions[index] : scope.survey_questions[index] }); }; scope.deleteQuestion = function(index){ element = $('.question_final:eq('+index+')'); element.remove(); if(scope.mode === 'add'){ questions.splice(index, 1); scope.reorder(); if(questions.length<1){ $('#survey-save-button').attr('disabled', 'disabled'); } } else { scope.survey_questions.splice(index, 1); scope.reorder(); if(scope.survey_questions.length<1){ $('#survey-save-button').attr('disabled', 'disabled'); } } }; scope.cancelQuestion = function(event){ var elementID, key; if(event.target.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.id==="new_question"){ $('#new_question .aw-form-well').remove(); $('#add_question_btn').show(); $('#add_question_btn').removeAttr('disabled'); if(scope.mode === 'add' && questions.length>0){ $('#survey-save-button').removeAttr('disabled'); } if(scope.mode === 'edit' && scope.survey_questions.length>0 && scope.can_edit===true){ $('#survey-save-button').removeAttr('disabled'); } } else { elementID = event.target.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.id; key = elementID.split('_')[1]; $('#'+elementID).empty(); if(scope.mode === 'add'){ if(questions.length>0){ $('#survey-save-button').removeAttr('disabled'); } scope.finalizeQuestion(questions[key], Number(key)); } else if(scope.mode=== 'edit' ){ if(scope.survey_questions.length>0 && scope.can_edit === true){ $('#survey-save-button').removeAttr('disabled'); } scope.finalizeQuestion(scope.survey_questions[key] , Number(key)); } } }; scope.questionUp = function(index){ var animating = false, clickedDiv = $('#question_'+index), prevDiv = clickedDiv.prev(), distance = clickedDiv.outerHeight(); if (animating) { return; } if (prevDiv.length) { animating = true; $.when(clickedDiv.animate({ top: -distance }, 600), prevDiv.animate({ top: distance }, 600)).done(function () { prevDiv.css('top', '0px'); clickedDiv.css('top', '0px'); clickedDiv.insertBefore(prevDiv); animating = false; if ( scope.mode === 'add'){ i = questions[index]; questions[index] = questions[index-1]; questions[index-1] = i; } else { i = scope.survey_questions[index]; scope.survey_questions[index] = scope.survey_questions[index-1]; scope.survey_questions[index-1] = i; } scope.reorder(); }); } }; scope.questionDown = function(index){ var clickedDiv = $('#question_'+index), nextDiv = clickedDiv.next(), distance = clickedDiv.outerHeight(), animating = false; if (animating) { return; } if (nextDiv.length) { animating = true; $.when(clickedDiv.animate({ top: distance }, 600), nextDiv.animate({ top: -distance }, 600)).done(function () { nextDiv.css('top', '0px'); clickedDiv.css('top', '0px'); nextDiv.insertBefore(clickedDiv); animating = false; if(scope.mode === 'add'){ i = questions[index]; questions[index] = questions[Number(index)+1]; questions[Number(index)+1] = i; } else { i = scope.survey_questions[index]; scope.survey_questions[index] = scope.survey_questions[Number(index)+1]; scope.survey_questions[Number(index)+1] = i; } scope.reorder(); }); } }; scope.reorder = function(){ if(scope.mode==='add'){ for(i=0; i<questions.length; i++){ questions[i].index=i; $('.question_final:eq('+i+')').attr('id', 'question_'+i); } } else { for(i=0; i<scope.survey_questions.length; i++){ scope.survey_questions[i].index=i; $('.question_final:eq('+i+')').attr('id', 'question_'+i); } } }; scope.finalizeQuestion= function(data, index){ FinalizeQuestion({ scope: scope, question: data, id: id, index: index }); }; scope.typeChange = function() { scope.minTextError = false; scope.maxTextError = false; scope.default = ""; scope.default_multiselect = ""; scope.default_float = ""; scope.default_int = ""; scope.default_textarea = ""; scope.default_password = "" ; scope.choices = ""; scope.text_min = ""; scope.text_max = "" ; scope.textarea_min = ""; scope.textarea_max = "" ; scope.password_min = "" ; scope.password_max = "" ; scope.int_min = ""; scope.int_max = ""; scope.float_min = ""; scope.float_max = ""; scope.survey_question_form.default.$setPristine(); scope.survey_question_form.default_multiselect.$setPristine(); scope.survey_question_form.default_float.$setPristine(); scope.survey_question_form.default_int.$setPristine(); scope.survey_question_form.default_textarea.$setPristine(); scope.survey_question_form.default_password.$setPristine(); scope.survey_question_form.choices.$setPristine(); scope.survey_question_form.int_min.$setPristine(); scope.survey_question_form.int_max.$setPristine(); }; scope.submitQuestion = function(event){ var data = {}, fld, i, choiceArray, answerArray, key, elementID; scope.invalidChoice = false; scope.duplicate = false; scope.minTextError = false; scope.maxTextError = false; if(scope.type.type==="text"){ if(scope.default.trim() !== ""){ if(scope.default.trim().length < scope.text_min && scope.text_min !== "" ){ scope.minTextError = true; } if(scope.text_max < scope.default.trim().length && scope.text_max !== "" ){ scope.maxTextError = true; } } } if(scope.type.type==="textarea"){ if(scope.default_textarea.trim() !== ""){ if(scope.default_textarea.trim().length < scope.textarea_min && scope.textarea_min !== "" ){ scope.minTextError = true; } if(scope.textarea_max < scope.default_textarea.trim().length && scope.textarea_max !== "" ){ scope.maxTextError = true; } } } if(scope.type.type==="password"){ if(scope.default_password.trim() !== ""){ if(scope.default_password.trim().length < scope.password_min && scope.password_min !== "" ){ scope.minTextError = true; } if(scope.password_max < scope.default_password.trim().length && scope.password_max !== "" ){ scope.maxTextError = true; } } } if(scope.type.type==="multiselect" && scope.default_multiselect.trim() !== ""){ choiceArray = scope.choices.split(/\n/); answerArray = scope.default_multiselect.split(/\n/); if(answerArray.length>0){ for(i=0; i<answerArray.length; i++){ if($.inArray(answerArray[i], choiceArray)===-1){ scope.invalidChoice = true; } } } } if(scope.type.type==="multiplechoice" && scope.default.trim() !== ""){ choiceArray = scope.choices.split(/\n/); if($.inArray(scope.default, choiceArray)===-1){ scope.invalidChoice = true; } } // validate that there aren't any questions using this var name. if(GenerateForm.mode === 'add'){ if(scope.mode === 'add'){ for(fld in questions){ if(questions[fld].variable === scope.variable){ scope.duplicate = true; } } } else if (scope.mode === 'edit'){ for(fld in scope.survey_questions){ if(scope.survey_questions[fld].variable === scope.variable){ scope.duplicate = true; } } } } if(GenerateForm.mode === 'edit'){ elementID = event.target.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.id; key = elementID.split('_')[1]; if(scope.mode==='add'){ for(fld in questions){ if(questions[fld].variable === scope.variable && fld!==key){ scope.duplicate = true; } } } else if(scope.mode === 'edit'){ for(fld in scope.survey_questions){ if(scope.survey_questions[fld].variable === scope.variable && fld!==key){ scope.duplicate = true; } } } } if(scope.duplicate===true || scope.invalidChoice===true || scope.minTextError === true || scope.maxTextError === true){ return; } try { //create data object for each submitted question data.question_name = scope.question_name; data.question_description = (scope.question_description) ? scope.question_description : "" ; data.required = scope.required; data.type = scope.type.type; data.variable = scope.variable; //set the data.min depending on which type of question if (scope.type.type === 'text') { data.min = scope.text_min; } else if (scope.type.type === 'textarea') { data.min = scope.textarea_min; } else if (scope.type.type === 'password') { data.min = scope.password_min; } else if (scope.type.type === 'float') { data.min = scope.float_min; } else if (scope.type.type === 'integer') { data.min = scope.int_min; } else { data.min = ""; } // set hte data max depending on which type if (scope.type.type === 'text') { data.max = scope.text_max; } else if (scope.type.type === 'textarea') { data.max = scope.textarea_max; } else if (scope.type.type === 'password') { data.max = scope.password_max; } else if (scope.type.type === 'float') { data.max = scope.float_max; } else if (scope.type.type === 'integer') { data.max = scope.int_max; } else { data.max = ""; } //set the data.default depending on which type if (scope.type.type === 'text' || scope.type.type === 'multiplechoice') { data.default = scope.default; } else if (scope.type.type === 'textarea') { data.default = scope.default_textarea; } else if (scope.type.type === 'password') { data.default = scope.default_password; } else if (scope.type.type === 'multiselect') { data.default = scope.default_multiselect; } else if (scope.type.type === 'float') { data.default = scope.default_float; } else if (scope.type.type === 'integer') { data.default = scope.default_int; } else { data.default = ""; } data.choices = (scope.type.type === "multiplechoice") ? scope.choices : (scope.type.type === 'multiselect') ? scope.choices : "" ; Wait('stop'); if(scope.mode === 'add' || scope.mode==="edit" && scope.can_edit === true){ $('#survey-save-button').removeAttr('disabled'); } if(GenerateForm.mode === 'add'){ if(scope.mode === 'add'){ questions.push(data); $('#new_question .aw-form-well').remove(); $('#add_question_btn').show(); scope.finalizeQuestion(data , questions.length-1); } else if (scope.mode === 'edit'){ scope.survey_questions.push(data); $('#new_question .aw-form-well').remove(); $('#add_question_btn').show(); scope.finalizeQuestion(data , scope.survey_questions.length-1); } } if(GenerateForm.mode === 'edit'){ elementID = event.target.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.id; key = elementID.split('_')[1]; if(scope.mode==='add'){ questions[key] = data; } else if(scope.mode === 'edit'){ scope.survey_questions[key] = data; } $('#'+elementID).empty(); scope.finalizeQuestion(data , Number(key)); } } catch (err) { Wait('stop'); Alert("Error", "Error parsing extra variables. Parser returned: " + err); } }; scope.resetForm = function(){ html = '<div class="row">'+ '<div class="col-sm-12">'+ '<label for="survey"><span class="label-text prepend-asterisk"> Questions</span></label>'+ '<div id="survey_maker_question_area"></div>'+ '<div id="finalized_questions"></div>'+ '<button style="display:none" type="button" class="btn btn-sm btn-primary" id="add_question_btn" ng-click="addNewQuestion()" aw-tool-tip="Create a new question" data-placement="top" data-original-title="" title="" disabled><i class="fa fa-plus fa-lg"></i> New Question</button>'+ '<div id="new_question"></div>'+ '</div>'+ '</div>'; $('#survey-modal-dialog').html(html); element = angular.element(document.getElementById('add_question_btn')); $compile(element)(scope); }; scope.saveSurvey = function() { Wait('start'); if(scope.mode ==="add"){ $('#survey-modal-dialog').dialog('close'); if(questions.length>0){ scope.survey_questions = questions; } scope.survey_name = ""; scope.survey_description = ""; questions = [] ; scope.$emit('SurveySaved'); } else{ scope.survey_name = ""; scope.survey_description = ""; url = GetBasePath('job_templates') + id + '/survey_spec/'; Rest.setUrl(url); Rest.post({ name: scope.survey_name, description: scope.survey_description, spec: scope.survey_questions }) .success(function () { // Wait('stop'); $('#survey-modal-dialog').dialog('close'); scope.$emit('SurveySaved'); }) .error(function (data, status) { ProcessErrors(scope, data, status, null, { hdr: 'Error!', msg: 'Failed to add new survey. POST returned status: ' + status }); }); } }; //for toggling the input on password inputs scope.toggleInput = function(id) { var buttonId = id + "_show_input_button", inputId = id, buttonInnerHTML = $(buttonId).html(); if (buttonInnerHTML.indexOf("Show") > -1) { $(buttonId).html("Hide"); $(inputId).attr("type", "text"); } else { $(buttonId).html("Show"); $(inputId).attr("type", "password"); } }; }; } Init.$inject = [ '$location', 'deleteSurvey', 'editSurvey', 'addSurvey', 'GenerateForm', 'questionDefinitionForm', 'Wait', 'Alert', 'GetBasePath', 'Rest', 'ProcessErrors', '$compile', 'finalizeQuestion', 'editQuestion', '$sce' ];
fixed duplicate choices from being passed to select2
awx/ui/client/src/job-templates/survey-maker/surveys/init.factory.js
fixed duplicate choices from being passed to select2
<ide><path>wx/ui/client/src/job-templates/survey-maker/surveys/init.factory.js <ide> } <ide> data.choices = (scope.type.type === "multiplechoice") ? scope.choices : (scope.type.type === 'multiselect') ? scope.choices : "" ; <ide> <add> if (data.choices !== "") { <add> // remove duplicates from the choices <add> data.choices = _.uniq(data.choices.split("\n")).join("\n"); <add> } <add> <ide> Wait('stop'); <ide> if(scope.mode === 'add' || scope.mode==="edit" && scope.can_edit === true){ <ide> $('#survey-save-button').removeAttr('disabled');
Java
apache-2.0
6ce9a9eb55f14868085efe7e7543ca3480fe6634
0
vjuranek/JGroups,pruivo/JGroups,belaban/JGroups,ligzy/JGroups,danberindei/JGroups,pferraro/JGroups,dimbleby/JGroups,Sanne/JGroups,ibrahimshbat/JGroups,dimbleby/JGroups,vjuranek/JGroups,rvansa/JGroups,ibrahimshbat/JGroups,slaskawi/JGroups,ligzy/JGroups,dimbleby/JGroups,rpelisse/JGroups,deepnarsay/JGroups,kedzie/JGroups,Sanne/JGroups,ibrahimshbat/JGroups,ligzy/JGroups,rhusar/JGroups,deepnarsay/JGroups,rhusar/JGroups,belaban/JGroups,tristantarrant/JGroups,danberindei/JGroups,pferraro/JGroups,TarantulaTechnology/JGroups,deepnarsay/JGroups,vjuranek/JGroups,belaban/JGroups,TarantulaTechnology/JGroups,rpelisse/JGroups,ibrahimshbat/JGroups,pruivo/JGroups,rhusar/JGroups,slaskawi/JGroups,rpelisse/JGroups,Sanne/JGroups,pruivo/JGroups,slaskawi/JGroups,tristantarrant/JGroups,rvansa/JGroups,kedzie/JGroups,kedzie/JGroups,pferraro/JGroups,danberindei/JGroups,TarantulaTechnology/JGroups
package org.jgroups.util; import java.io.ByteArrayOutputStream; /** * Extends ByteArrayOutputStream, but exposes the internal buffer. This way we don't need to call * toByteArray() which copies the internal buffer * @author Bela Ban * @version $Id: ExposedByteArrayOutputStream.java,v 1.3 2008/03/27 11:16:15 belaban Exp $ */ public class ExposedByteArrayOutputStream extends ByteArrayOutputStream { public ExposedByteArrayOutputStream() { super(); } public ExposedByteArrayOutputStream(int size) { super(size); } /** Resets count and creates a new buf if the current buf is > max_size. This method is not synchronized */ public void reset(int max_size) { super.reset(); if(buf.length > max_size) { buf=new byte[max_size]; } } public byte[] getRawBuffer() { return buf; } public int getCapacity() { return buf.length; } }
src/org/jgroups/util/ExposedByteArrayOutputStream.java
package org.jgroups.util; import java.io.ByteArrayOutputStream; /** * Extends ByteArrayOutputStream, but exposes the internal buffer. This way we don't need to call * toByteArray() which copies the internal buffer * @author Bela Ban * @version $Id: ExposedByteArrayOutputStream.java,v 1.2 2005/07/25 15:53:36 belaban Exp $ */ public class ExposedByteArrayOutputStream extends ByteArrayOutputStream { public ExposedByteArrayOutputStream() { } public ExposedByteArrayOutputStream(int size) { super(size); } public byte[] getRawBuffer() { return buf; } public int getCapacity() { return buf.length; } }
added reset() method (http://jira.jboss.com/jira/browse/JGRP-725)
src/org/jgroups/util/ExposedByteArrayOutputStream.java
added reset() method (http://jira.jboss.com/jira/browse/JGRP-725)
<ide><path>rc/org/jgroups/util/ExposedByteArrayOutputStream.java <ide> * Extends ByteArrayOutputStream, but exposes the internal buffer. This way we don't need to call <ide> * toByteArray() which copies the internal buffer <ide> * @author Bela Ban <del> * @version $Id: ExposedByteArrayOutputStream.java,v 1.2 2005/07/25 15:53:36 belaban Exp $ <add> * @version $Id: ExposedByteArrayOutputStream.java,v 1.3 2008/03/27 11:16:15 belaban Exp $ <ide> */ <ide> public class ExposedByteArrayOutputStream extends ByteArrayOutputStream { <ide> <ide> public ExposedByteArrayOutputStream() { <add> super(); <ide> } <ide> <ide> public ExposedByteArrayOutputStream(int size) { <ide> super(size); <add> } <add> <add> /** Resets count and creates a new buf if the current buf is > max_size. This method is not synchronized */ <add> public void reset(int max_size) { <add> super.reset(); <add> if(buf.length > max_size) { <add> buf=new byte[max_size]; <add> } <ide> } <ide> <ide> public byte[] getRawBuffer() {
Java
apache-2.0
3e15771d016677207249542ac7f4c5aa99cc2c6b
0
diennea/herddb,diennea/herddb,eolivelli/herddb,eolivelli/herddb,eolivelli/herddb,diennea/herddb,diennea/herddb,eolivelli/herddb
/* Licensed to Diennea S.r.l. under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Diennea S.r.l. 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 herddb.core; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.LongAdder; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.Stream; import herddb.codec.RecordSerializer; import herddb.core.PageSet.DataPageMetaData; import herddb.core.stats.TableManagerStats; import herddb.index.IndexOperation; import herddb.index.KeyToPageIndex; import herddb.index.PrimaryIndexSeek; import herddb.log.CommitLog; import herddb.log.CommitLogResult; import herddb.log.LogEntry; import herddb.log.LogEntryFactory; import herddb.log.LogEntryType; import herddb.log.LogNotAvailableException; import herddb.log.LogSequenceNumber; import herddb.model.Column; import herddb.model.ColumnTypes; import herddb.model.DDLException; import herddb.model.DMLStatementExecutionResult; import herddb.model.DataScanner; import herddb.model.DuplicatePrimaryKeyException; import herddb.model.GetResult; import herddb.model.Index; import herddb.model.Predicate; import herddb.model.Projection; import herddb.model.Record; import herddb.model.RecordFunction; import herddb.model.RecordTooBigException; import herddb.model.ScanLimits; import herddb.model.Statement; import herddb.model.StatementEvaluationContext; import herddb.model.StatementExecutionException; import herddb.model.StatementExecutionResult; import herddb.model.Table; import herddb.model.TableContext; import herddb.model.Transaction; import herddb.model.commands.DeleteStatement; import herddb.model.commands.GetStatement; import herddb.model.commands.InsertStatement; import herddb.model.commands.ScanStatement; import herddb.model.commands.TruncateTableStatement; import herddb.model.commands.UpdateStatement; import herddb.server.ServerConfiguration; import herddb.storage.DataPageDoesNotExistException; import herddb.storage.DataStorageManager; import herddb.storage.DataStorageManagerException; import herddb.storage.FullTableScanConsumer; import herddb.storage.TableStatus; import herddb.utils.BatchOrderedExecutor; import herddb.utils.Bytes; import herddb.utils.DataAccessor; import herddb.utils.EnsureLongIncrementAccumulator; import herddb.utils.Holder; import herddb.utils.LocalLockManager; import herddb.utils.LockHandle; import herddb.utils.SystemProperties; /** * Handles Data of a Table * * @author enrico.olivelli * @author diego.salvi */ public final class TableManager implements AbstractTableManager, Page.Owner { private static final Logger LOGGER = Logger.getLogger(TableManager.class.getName()); private static final int SORTED_PAGE_ACCESS_WINDOW_SIZE = SystemProperties. getIntSystemProperty(TableManager.class.getName() + ".sortedPageAccessWindowSize", 2000); private static final boolean ENABLE_LOCAL_SCAN_PAGE_CACHE = SystemProperties. getBooleanSystemProperty(TableManager.class.getName() + ".enableLocalScanPageCache", true); private final ConcurrentMap<Long, DataPage> newPages; private final ConcurrentMap<Long, DataPage> pages; /** * A structure which maps each key to the ID of the page (map<byte[], long>) (this can be quite large) */ private final KeyToPageIndex keyToPage; private final PageSet pageSet = new PageSet(); private long nextPageId = 1; private final Lock nextPageLock = new ReentrantLock(); private final AtomicLong currentDirtyRecordsPage = new AtomicLong(); /** * Counts how many pages had been unloaded */ private final LongAdder loadedPagesCount = new LongAdder(); /** * Counts how many pages had been loaded */ private final LongAdder unloadedPagesCount = new LongAdder(); /** * Local locks */ private final LocalLockManager locksManager = new LocalLockManager(); /** * Set to {@code true} when this {@link TableManage} is fully started */ private volatile boolean started = false; private volatile boolean checkPointRunning = false; /** * Allow checkpoint */ private final ReentrantReadWriteLock checkpointLock = new ReentrantReadWriteLock(false); /** * auto_increment support */ private final AtomicLong nextPrimaryKeyValue = new AtomicLong(1); private final TableContext tableContext; /** * Phisical ID of the TableSpace */ private final String tableSpaceUUID; /** * Definition of the table */ private Table table; private final CommitLog log; private final DataStorageManager dataStorageManager; private final TableSpaceManager tableSpaceManager; private final PageReplacementPolicy pageReplacementPolicy; /** * Max logical size of a page (raw key size + raw value size) */ private final long maxLogicalPageSize; private final Semaphore maxCurrentPagesLoads = new Semaphore(4, true); /** * This value is not empty until the transaction who creates the table does not commit */ private long createdInTransaction; /** * Default dirty threshold for page rebuild during checkpoints */ private final double dirtyThreshold; /** * Default fill threshold for page rebuild during checkpoints */ private final double fillThreshold; /** * Checkpoint target max milliseconds */ private final long checkpointTargetTime; /** * Compaction (small pages) target max milliseconds */ private final long compactionTargetTime; private final TableManagerStats stats; void prepareForRestore(LogSequenceNumber dumpLogSequenceNumber) { LOGGER.log(Level.SEVERE, "Table " + table.name + ", receiving dump," + "done at external logPosition " + dumpLogSequenceNumber); this.dumpLogSequenceNumber = dumpLogSequenceNumber; } void restoreFinished() { dumpLogSequenceNumber = null; LOGGER.log(Level.SEVERE, "Table " + table.name + ", received dump"); } private final class TableManagerStatsImpl implements TableManagerStats { @Override public int getLoadedpages() { return pages.size(); } @Override public long getLoadedPagesCount() { return loadedPagesCount.sum(); } @Override public long getUnloadedPagesCount() { return unloadedPagesCount.sum(); } @Override public long getTablesize() { return keyToPage.size(); } @Override public int getDirtypages() { return pageSet.getDirtyPagesCount(); } @Override public int getDirtyrecords() { int size = 0; for (DataPage newPage : newPages.values()) { size += newPage.size(); } return size; } @Override public long getDirtyUsedMemory() { long used = 0; for (DataPage newPage : newPages.values()) { used += newPage.getUsedMemory(); } return used; } @Override public long getMaxLogicalPageSize() { return maxLogicalPageSize; } @Override public long getBuffersUsedMemory() { long value = 0; for (DataPage page : pages.values()) { value += page.getUsedMemory(); } return value; } @Override public long getKeysUsedMemory() { return keyToPage.getUsedMemory(); } } TableManager(Table table, CommitLog log, MemoryManager memoryManager, DataStorageManager dataStorageManager, TableSpaceManager tableSpaceManager, String tableSpaceUUID, long createdInTransaction) throws DataStorageManagerException { this.stats = new TableManagerStatsImpl(); this.log = log; this.table = table; this.tableSpaceManager = tableSpaceManager; this.dataStorageManager = dataStorageManager; this.createdInTransaction = createdInTransaction; this.tableSpaceUUID = tableSpaceUUID; this.tableContext = buildTableContext(); this.maxLogicalPageSize = memoryManager.getMaxLogicalPageSize(); this.keyToPage = dataStorageManager.createKeyToPageMap(tableSpaceUUID, table.uuid, memoryManager); this.pageReplacementPolicy = memoryManager.getDataPageReplacementPolicy(); this.pages = new ConcurrentHashMap<>(); this.newPages = new ConcurrentHashMap<>(); this.dirtyThreshold = tableSpaceManager.getDbmanager().getServerConfiguration().getDouble( ServerConfiguration.PROPERTY_DIRTY_PAGE_THRESHOLD, ServerConfiguration.PROPERTY_DIRTY_PAGE_THRESHOLD_DEFAULT); this.fillThreshold = tableSpaceManager.getDbmanager().getServerConfiguration().getDouble( ServerConfiguration.PROPERTY_FILL_PAGE_THRESHOLD, ServerConfiguration.PROPERTY_FILL_PAGE_THRESHOLD_DEFAULT); long checkpointTargetTime = tableSpaceManager.getDbmanager().getServerConfiguration().getLong( ServerConfiguration.PROPERTY_CHECKPOINT_DURATION, ServerConfiguration.PROPERTY_CHECKPOINT_DURATION_DEFAULT); this.checkpointTargetTime = checkpointTargetTime < 0 ? Long.MAX_VALUE : checkpointTargetTime; long compactionTargetTime = tableSpaceManager.getDbmanager().getServerConfiguration().getLong( ServerConfiguration.PROPERTY_COMPACTION_DURATION, ServerConfiguration.PROPERTY_COMPACTION_DURATION_DEFAULT); this.compactionTargetTime = compactionTargetTime < 0 ? Long.MAX_VALUE : compactionTargetTime; } private TableContext buildTableContext() { TableContext tableContext; if (!table.auto_increment) { tableContext = new TableContext() { @Override public byte[] computeNewPrimaryKeyValue() { throw new UnsupportedOperationException("no auto_increment function on this table"); } @Override public Table getTable() { return table; } }; } else if (table.getColumn(table.primaryKey[0]).type == ColumnTypes.INTEGER) { tableContext = new TableContext() { @Override public byte[] computeNewPrimaryKeyValue() { return Bytes.from_int((int) nextPrimaryKeyValue.getAndIncrement()).data; } @Override public Table getTable() { return table; } }; } else if (table.getColumn(table.primaryKey[0]).type == ColumnTypes.LONG) { tableContext = new TableContext() { @Override public byte[] computeNewPrimaryKeyValue() { return Bytes.from_long((int) nextPrimaryKeyValue.getAndIncrement()).data; } @Override public Table getTable() { return table; } }; } else { tableContext = new TableContext() { @Override public byte[] computeNewPrimaryKeyValue() { throw new UnsupportedOperationException("no auto_increment function on this table"); } @Override public Table getTable() { return table; } }; } return tableContext; } @Override public Table getTable() { return table; } private LogSequenceNumber bootSequenceNumber; private LogSequenceNumber dumpLogSequenceNumber; @Override public LogSequenceNumber getBootSequenceNumber() { return bootSequenceNumber; } @Override public void start() throws DataStorageManagerException { Map<Long, DataPageMetaData> activePagesAtBoot = new HashMap<>(); bootSequenceNumber = LogSequenceNumber.START_OF_TIME; boolean requireLoadAtStartup = keyToPage.requireLoadAtStartup(); if (requireLoadAtStartup) { // non persistent primary key index, we need a full table scan LOGGER.log(Level.SEVERE, "loading in memory all the keys for table {0}", new Object[]{table.name}); dataStorageManager.fullTableScan(tableSpaceUUID, table.uuid, new FullTableScanConsumer() { Long currentPage; @Override public void acceptTableStatus(TableStatus tableStatus) { LOGGER.log(Level.SEVERE, "recovery table at " + tableStatus.sequenceNumber); nextPrimaryKeyValue.set(Bytes.toLong(tableStatus.nextPrimaryKeyValue, 0, 8)); nextPageId = tableStatus.nextPageId; bootSequenceNumber = tableStatus.sequenceNumber; activePagesAtBoot.putAll(tableStatus.activePages); } @Override public void startPage(long pageId) { currentPage = pageId; } @Override public void acceptRecord(Record record) { if (currentPage < 0) { throw new IllegalStateException(); } keyToPage.put(record.key, currentPage); } @Override public void endPage() { currentPage = null; } @Override public void endTable() { } }); } else { LOGGER.log(Level.SEVERE, "loading table {0}, uuid {1}", new Object[]{table.name, table.uuid}); TableStatus tableStatus = dataStorageManager.getLatestTableStatus(tableSpaceUUID, table.uuid); LOGGER.log(Level.SEVERE, "recovery table at " + tableStatus.sequenceNumber); nextPrimaryKeyValue.set(Bytes.toLong(tableStatus.nextPrimaryKeyValue, 0, 8)); nextPageId = tableStatus.nextPageId; bootSequenceNumber = tableStatus.sequenceNumber; activePagesAtBoot.putAll(tableStatus.activePages); } keyToPage.start(bootSequenceNumber); dataStorageManager.cleanupAfterBoot(tableSpaceUUID, table.uuid, activePagesAtBoot.keySet()); pageSet.setActivePagesAtBoot(activePagesAtBoot); initNewPage(); LOGGER.log(Level.SEVERE, "loaded {0} keys for table {1}, newPageId {2}, nextPrimaryKeyValue {3}, activePages {4}", new Object[]{keyToPage.size(), table.name, nextPageId, nextPrimaryKeyValue.get(), pageSet.getActivePages() + ""}); started = true; } @Override public StatementExecutionResult executeStatement(Statement statement, Transaction transaction, StatementEvaluationContext context) throws StatementExecutionException { checkpointLock.readLock().lock(); try { if (statement instanceof UpdateStatement) { UpdateStatement update = (UpdateStatement) statement; return executeUpdate(update, transaction, context); } if (statement instanceof InsertStatement) { InsertStatement insert = (InsertStatement) statement; return executeInsert(insert, transaction, context); } if (statement instanceof GetStatement) { GetStatement get = (GetStatement) statement; return executeGet(get, transaction, context); } if (statement instanceof DeleteStatement) { DeleteStatement delete = (DeleteStatement) statement; return executeDelete(delete, transaction, context); } if (statement instanceof TruncateTableStatement) { TruncateTableStatement truncate = (TruncateTableStatement) statement; return executeTruncate(truncate, transaction, context); } } catch (DataStorageManagerException err) { throw new StatementExecutionException("internal data error: " + err, err); } finally { checkpointLock.readLock().unlock(); if (statement instanceof TruncateTableStatement) { try { flush(); } catch (DataStorageManagerException err) { throw new StatementExecutionException("internal data error: " + err, err); } } } throw new StatementExecutionException("unsupported statement " + statement); } /** * Create a new page with given data, save it and update keyToPage records * <p> * Will not place any lock, this method should be invoked at startup time or during checkpoint: <b>during * "stop-the-world" procedures!</b> * </p> */ private long createImmutablePage(Map<Bytes, Record> newPage, long newPageSize) throws DataStorageManagerException { final Long pageId = nextPageId++; final DataPage dataPage = buildImmutableDataPage(pageId, newPage, newPageSize); LOGGER.log(Level.FINER, "createNewPage table {0}, pageId={1} with {2} records, {3} logical page size", new Object[]{table.name, pageId, newPage.size(), newPageSize}); dataStorageManager.writePage(tableSpaceUUID, table.uuid, pageId, newPage.values()); pageSet.pageCreated(pageId, dataPage); pages.put(pageId, dataPage); /* We mustn't update currentDirtyRecordsPage. This page isn't created to host live dirty data */ final Page.Metadata unload = pageReplacementPolicy.add(dataPage); if (unload != null) { unload.owner.unload(unload.pageId); } for (Bytes key : newPage.keySet()) { keyToPage.put(key, pageId); } return pageId; } private Long allocateLivePage(Long lastKnownPageId) { /* This method expect that a new page actually exists! */ nextPageLock.lock(); final Long newId; Page.Metadata unload = null; try { /* * Use currentDirtyRecordsPage to check because nextPageId could be advanced for other needings * like rebuild a dirty page during checkpoint */ if (lastKnownPageId == currentDirtyRecordsPage.get()) { final DataPage lastKnownPage; /* Is really a new page! */ newId = nextPageId++; if (pages.containsKey(newId)) { throw new IllegalStateException("invalid newpage id " + newId + ", " + newPages.keySet() + "/" + pages.keySet()); } /* * If really was the last new page id it MUST be in pages. It cannot be unloaded before the * creation of a new page! */ lastKnownPage = pages.get(lastKnownPageId); if (lastKnownPage == null) { throw new IllegalStateException("invalid last known new page id " + lastKnownPageId + ", " + newPages.keySet() + "/" + pages.keySet()); } final DataPage newPage = new DataPage(this, newId, maxLogicalPageSize, 0, new ConcurrentHashMap<>(), false); newPages.put(newId, newPage); pages.put(newId, newPage); /* From this moment on the page has been published */ /* The lock is needed to block other threads up to this point */ currentDirtyRecordsPage.set(newId); /* * Now we must add the "lastKnownPage" to page replacement policy. There is only one page living * outside replacement policy (the currentDirtyRecordsPage) */ unload = pageReplacementPolicy.add(lastKnownPage); } else { /* The page has been published for sure */ newId = currentDirtyRecordsPage.get(); } } finally { nextPageLock.unlock(); } /* Dereferenced page unload. Out of locking */ if (unload != null) { unload.owner.unload(unload.pageId); } /* Both created now or already created */ return newId; } /** * Create a new page and set it as the target page for dirty records. * <p> * Will not place any lock, this method should be invoked at startup time: <b>during "stop-the-world" * procedures!</b> * </p> */ private void initNewPage() { final Long newId = nextPageId++; final DataPage newPage = new DataPage(this, newId, maxLogicalPageSize, 0, new ConcurrentHashMap<>(), false); if (!newPages.isEmpty()) { throw new IllegalStateException("invalid new page initialization, other new pages already exist: " + newPages.keySet()); } newPages.put(newId, newPage); pages.put(newId, newPage); /* From this moment on the page has been published */ /* The lock is needed to block other threads up to this point */ currentDirtyRecordsPage.set(newId); } @Override public void unload(long pageId) { pages.computeIfPresent(pageId, (k, remove) -> { unloadedPagesCount.increment(); LOGGER.log(Level.FINER, "table {0} removed page {1}, {2}", new Object[]{table.name, pageId, remove.getUsedMemory() / (1024 * 1024) + " MB"}); if (!remove.readonly) { flushNewPage(remove, Collections.emptyMap()); LOGGER.log(Level.FINER, "table {0} remove and save 'new' page {1}, {2}", new Object[]{table.name, remove.pageId, remove.getUsedMemory() / (1024 * 1024) + " MB"}); } else { LOGGER.log(Level.FINER, "table {0} unload page {1}, {2}", new Object[]{table.name, pageId, remove.getUsedMemory() / (1024 * 1024) + " MB"}); } return null; }); } /** * Remove the page from {@link #newPages}, set it as "unloaded" and write it to disk * <p> * Add as much spare data as possible to fillup the page. If added must change key to page pointers too for spare * data * </p> * * @param page new page to flush * @param spareData old spare data to fit in the new page if possible * @return spare memory size used (and removed) */ private long flushNewPage(DataPage page, Map<Bytes, Record> spareData) { /* Set the new page as a fully active page */ pageSet.pageCreated(page.pageId, page); /* Remove it from "new" pages */ newPages.remove(page.pageId); /* * We need to keep the page lock just to write the unloaded flag... after that write any other * thread that check the page will avoid writes (thus using page data is safe) */ final Lock lock = page.pageLock.writeLock(); lock.lock(); try { page.unloaded = true; } finally { lock.unlock(); } long usedMemory = page.getUsedMemory(); /* Flag to enable spare data addition to currently flushed page */ boolean add = true; final Iterator<Record> records = spareData.values().iterator(); while (add && records.hasNext()) { Record record = records.next(); add = page.put(record); if (add) { keyToPage.put(record.key, page.pageId); records.remove(); } } long spareUsedMemory = page.getUsedMemory() - usedMemory; dataStorageManager.writePage(tableSpaceUUID, table.uuid, page.pageId, page.data.values()); return spareUsedMemory; } private LockHandle lockForWrite(Bytes key, Transaction transaction) { if (transaction != null) { LockHandle lock = transaction.lookupLock(table.name, key); if (lock != null) { if (lock.write) { // transaction already locked the key for writes return lock; } else { // transaction already locked the key, but we need to upgrade the lock locksManager.releaseLock(lock); transaction.unregisterUpgradedLocksOnTable(table.name, lock); lock = locksManager.acquireWriteLockForKey(key); transaction.registerLockOnTable(this.table.name, lock); return lock; } } else { lock = locksManager.acquireWriteLockForKey(key); transaction.registerLockOnTable(this.table.name, lock); return lock; } } else { return locksManager.acquireWriteLockForKey(key); } } private LockHandle lockForRead(Bytes key, Transaction transaction) { if (transaction != null) { LockHandle lock = transaction.lookupLock(table.name, key); if (lock != null) { // transaction already locked the key return lock; } else { lock = locksManager.acquireReadLockForKey(key); transaction.registerLockOnTable(this.table.name, lock); return lock; } } else { return locksManager.acquireReadLockForKey(key); } } private StatementExecutionResult executeInsert(InsertStatement insert, Transaction transaction, StatementEvaluationContext context) throws StatementExecutionException, DataStorageManagerException { /* an insert can succeed only if the row is valid and the "keys" structure does not contain the requested key the insert will add the row in the 'buffer' without assigning a page to it locks: the insert uses global 'insert' lock on the table the insert will update the 'maxKey' for auto_increment primary keys */ Bytes key = new Bytes(insert.getKeyFunction().computeNewValue(null, context, tableContext)); byte[] value = insert.getValuesFunction().computeNewValue(new Record(key, null), context, tableContext); final long size = DataPage.estimateEntrySize(key, value); if (size > maxLogicalPageSize) { throw new RecordTooBigException("New record " + key + " is to big to be inserted: size " + size + ", max size " + maxLogicalPageSize); } LockHandle lock = lockForWrite(key, transaction); try { if (transaction != null) { if (transaction.recordDeleted(table.name, key)) { // OK, INSERT on a DELETED record inside this transaction } else if (transaction.recordInserted(table.name, key) != null) { // ERROR, INSERT on a INSERTED record inside this transaction throw new DuplicatePrimaryKeyException(key, "key " + key + ", decoded as " + RecordSerializer.deserializePrimaryKey(key.data, table) + ", already exists in table " + table.name + " inside transaction " + transaction.transactionId); } else if (keyToPage.containsKey(key)) { throw new DuplicatePrimaryKeyException(key, "key " + key + ", decoded as " + RecordSerializer.deserializePrimaryKey(key.data, table) + ", already exists in table " + table.name + " during transaction " + transaction.transactionId); } } else if (keyToPage.containsKey(key)) { throw new DuplicatePrimaryKeyException(key, "key " + key + ", decoded as " + RecordSerializer.deserializePrimaryKey(key.data, table) + ", already exists in table " + table.name); } LogEntry entry = LogEntryFactory.insert(table, key.data, value, transaction); CommitLogResult pos = log.log(entry, entry.transactionId <= 0); apply(pos, entry, false); return new DMLStatementExecutionResult(entry.transactionId, 1, key, insert.isReturnValues() ? Bytes.from_array(value) : null); } catch (LogNotAvailableException err) { throw new StatementExecutionException(err); } finally { if (transaction == null) { locksManager.releaseWriteLockForKey(key, lock); } } } @SuppressWarnings("serial") private static class ExitLoop extends RuntimeException { private final boolean continueWithTransactionData; public ExitLoop(boolean continueWithTransactionData) { this.continueWithTransactionData = continueWithTransactionData; } } private static class ScanResultOperation { public void accept(Record record) throws StatementExecutionException, DataStorageManagerException, LogNotAvailableException { } public void beginNewRecordsInTransactionBlock() { } } private StatementExecutionResult executeUpdate(UpdateStatement update, Transaction transaction, StatementEvaluationContext context) throws StatementExecutionException, DataStorageManagerException { AtomicInteger updateCount = new AtomicInteger(); Holder<Bytes> lastKey = new Holder<>(); Holder<byte[]> lastValue = new Holder<>(); /* an update can succeed only if the row is valid, the key is contains in the "keys" structure the update will simply override the value of the row, assigning a null page to the row the update can have a 'where' predicate which is to be evaluated against the decoded row, the update will be executed only if the predicate returns boolean 'true' value (CAS operation) locks: the update uses a lock on the the key */ RecordFunction function = update.getFunction(); long transactionId = transaction != null ? transaction.transactionId : 0; Predicate predicate = update.getPredicate(); ScanStatement scan = new ScanStatement(table.tablespace, table, predicate); accessTableData(scan, context, new ScanResultOperation() { @Override public void accept(Record actual) throws StatementExecutionException, LogNotAvailableException, DataStorageManagerException { byte[] newValue = function.computeNewValue(actual, context, tableContext); final long size = DataPage.estimateEntrySize(actual.key, newValue); if (size > maxLogicalPageSize) { throw new RecordTooBigException("New version of record " + actual.key + " is to big to be update: new size " + size + ", actual size " + DataPage.estimateEntrySize(actual) + ", max size " + maxLogicalPageSize); } LogEntry entry = LogEntryFactory.update(table, actual.key.data, newValue, transaction); CommitLogResult pos = log.log(entry, entry.transactionId <= 0); apply(pos, entry, false); lastKey.value = actual.key; lastValue.value = newValue; updateCount.incrementAndGet(); } }, transaction, true, true); return new DMLStatementExecutionResult(transactionId, updateCount.get(), lastKey.value, update.isReturnValues() ? (lastValue.value != null ? Bytes.from_array(lastValue.value) : null) : null); } private StatementExecutionResult executeDelete(DeleteStatement delete, Transaction transaction, StatementEvaluationContext context) throws StatementExecutionException, DataStorageManagerException { AtomicInteger updateCount = new AtomicInteger(); Holder<Bytes> lastKey = new Holder<>(); Holder<byte[]> lastValue = new Holder<>(); long transactionId = transaction != null ? transaction.transactionId : 0; Predicate predicate = delete.getPredicate(); ScanStatement scan = new ScanStatement(table.tablespace, table, predicate); accessTableData(scan, context, new ScanResultOperation() { @Override public void accept(Record actual) throws StatementExecutionException, LogNotAvailableException, DataStorageManagerException { LogEntry entry = LogEntryFactory.delete(table, actual.key.data, transaction); CommitLogResult pos = log.log(entry, entry.transactionId <= 0); apply(pos, entry, false); lastKey.value = actual.key; lastValue.value = actual.value.data; updateCount.incrementAndGet(); } }, transaction, true, true); return new DMLStatementExecutionResult(transactionId, updateCount.get(), lastKey.value, delete.isReturnValues() ? (lastValue.value != null ? Bytes.from_array(lastValue.value) : null) : null); } private StatementExecutionResult executeTruncate(TruncateTableStatement truncate, Transaction transaction, StatementEvaluationContext context) throws StatementExecutionException, DataStorageManagerException { if (transaction != null) { throw new StatementExecutionException("TRUNCATE TABLE cannot be executed within the context of a Transaction"); } try { long estimatedSize = keyToPage.size(); LogEntry entry = LogEntryFactory.truncate(table, null); CommitLogResult pos = log.log(entry, entry.transactionId <= 0); apply(pos, entry, false); return new DMLStatementExecutionResult(0, estimatedSize > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) estimatedSize, null, null); } catch (LogNotAvailableException error) { throw new StatementExecutionException(error); } } private void applyTruncate() throws DataStorageManagerException { if (createdInTransaction > 0) { throw new DataStorageManagerException("TRUNCATE TABLE cannot be executed on an uncommitted table"); } if (checkPointRunning) { throw new DataStorageManagerException("TRUNCATE TABLE cannot be executed during a checkpoint"); } if (tableSpaceManager.isTransactionRunningOnTable(table.name)) { throw new DataStorageManagerException("TRUNCATE TABLE cannot be executed table " + table.name + ": at least one transaction is pending on it"); } Map<String, AbstractIndexManager> indexes = tableSpaceManager.getIndexesOnTable(table.name); if (indexes != null) { for (AbstractIndexManager index : indexes.values()) { if (!index.isAvailable()) { throw new DataStorageManagerException("index " + index.getIndexName() + " in not full available. Cannot TRUNCATE table " + table.name); } } } /* Do not unload the current working page not known to replacement policy */ final long currentDirtyPageId = currentDirtyRecordsPage.get(); final List<DataPage> unload = pages.values().stream() .filter(page -> page.pageId != currentDirtyPageId) .collect(Collectors.toList()); pageReplacementPolicy.remove(unload); pageSet.truncate(); pages.clear(); newPages.clear(); initNewPage(); locksManager.clear(); keyToPage.truncate(); if (indexes != null) { for (AbstractIndexManager index : indexes.values()) { index.truncate(); } } } @Override public void onTransactionCommit(Transaction transaction, boolean recovery) throws DataStorageManagerException { if (transaction == null) { throw new DataStorageManagerException("transaction cannot be null"); } boolean forceFlushTableData = false; if (createdInTransaction > 0) { if (transaction.transactionId != createdInTransaction) { throw new DataStorageManagerException("this tableManager is available only on transaction " + createdInTransaction); } createdInTransaction = 0; forceFlushTableData = true; } checkpointLock.readLock().lock(); try { Map<Bytes, Record> changedRecords = transaction.changedRecords.get(table.name); // transaction is still holding locks on each record, so we can change records Map<Bytes, Record> newRecords = transaction.newRecords.get(table.name); if (newRecords != null) { for (Record record : newRecords.values()) { applyInsert(record.key, record.value, true); } } if (changedRecords != null) { for (Record r : changedRecords.values()) { applyUpdate(r.key, r.value); } } Set<Bytes> deletedRecords = transaction.deletedRecords.get(table.name); if (deletedRecords != null) { for (Bytes key : deletedRecords) { applyDelete(key); } } } finally { checkpointLock.readLock().unlock(); } transaction.releaseLocksOnTable(table.name, locksManager); if (forceFlushTableData) { LOGGER.log(Level.SEVERE, "forcing local checkpoint, table " + table.name + " will be visible to all transactions now"); checkpoint(false); } } @Override public void onTransactionRollback(Transaction transaction) { transaction.releaseLocksOnTable(table.name, locksManager); } @Override public void apply(CommitLogResult writeResult, LogEntry entry, boolean recovery) throws DataStorageManagerException, LogNotAvailableException { if (recovery) { if (writeResult.deferred) { throw new DataStorageManagerException("impossibile to have a deferred CommitLogResult during recovery"); } LogSequenceNumber position = writeResult.getLogSequenceNumber(); if (dumpLogSequenceNumber != null && !position.after(dumpLogSequenceNumber)) { // in "restore mode" the 'position" parameter is from the 'old' transaction log Transaction transaction = null; if (entry.transactionId > 0) { transaction = tableSpaceManager.getTransaction(entry.transactionId); } if (transaction != null) { LOGGER.log(Level.FINER, "{0}.{1} keep {2} at {3}, table restored from position {4}, it belongs to transaction {5} which was in progress during the dump of the table", new Object[]{table.tablespace, table.name, entry, position, dumpLogSequenceNumber, entry.transactionId}); } else { LOGGER.log(Level.FINER, "{0}.{1} skip {2} at {3}, table restored from position {4}", new Object[]{table.tablespace, table.name, entry, position, dumpLogSequenceNumber}); return; } } else if (!position.after(bootSequenceNumber)) { // recovery mode Transaction transaction = null; if (entry.transactionId > 0) { transaction = tableSpaceManager.getTransaction(entry.transactionId); } if (transaction != null) { LOGGER.log(Level.FINER, "{0}.{1} keep {2} at {3}, table booted at {4}, it belongs to transaction {5} which was in progress during the flush of the table", new Object[]{table.tablespace, table.name, entry, position, bootSequenceNumber, entry.transactionId}); } else { LOGGER.log(Level.FINER, "{0}.{1} skip {2} at {3}, table booted at {4}", new Object[]{table.tablespace, table.name, entry, position, bootSequenceNumber}); return; } } } switch (entry.type) { case LogEntryType.DELETE: { // remove the record from the set of existing records Bytes key = new Bytes(entry.key); if (entry.transactionId > 0) { Transaction transaction = tableSpaceManager.getTransaction(entry.transactionId); if (transaction == null) { throw new DataStorageManagerException("no such transaction " + entry.transactionId); } transaction.registerDeleteOnTable(this.table.name, key, writeResult); } else { applyDelete(key); } break; } case LogEntryType.UPDATE: { Bytes key = new Bytes(entry.key); Bytes value = new Bytes(entry.value); if (entry.transactionId > 0) { Transaction transaction = tableSpaceManager.getTransaction(entry.transactionId); if (transaction == null) { throw new DataStorageManagerException("no such transaction " + entry.transactionId); } transaction.registerRecordUpdate(this.table.name, key, value, writeResult); } else { applyUpdate(key, value); } break; } case LogEntryType.INSERT: { Bytes key = new Bytes(entry.key); Bytes value = new Bytes(entry.value); if (entry.transactionId > 0) { Transaction transaction = tableSpaceManager.getTransaction(entry.transactionId); if (transaction == null) { throw new DataStorageManagerException("no such transaction " + entry.transactionId); } transaction.registerInsertOnTable(table.name, key, value, writeResult); } else { applyInsert(key, value, false); } break; } case LogEntryType.TRUNCATE_TABLE: { applyTruncate(); } ; break; default: throw new IllegalArgumentException("unhandled entry type " + entry.type); } } private void applyDelete(Bytes key) throws DataStorageManagerException { /* This could be a normal or a temporary modifiable page */ final Long pageId = keyToPage.remove(key); if (pageId == null) { throw new IllegalStateException("corrupted transaction log: key " + key + " is not present in table " + table.name); } if (LOGGER.isLoggable(Level.FINEST)) LOGGER.log(Level.FINEST, "Deleted key " + key + " from page " + pageId); /* * We'll try to remove the record if in a writable page, otherwise we'll simply set the old page * as dirty. */ final Map<String, AbstractIndexManager> indexes = tableSpaceManager.getIndexesOnTable(table.name); /* * When index is enabled we need the old value to update them, we'll force the page load only if that * record is really needed. */ final DataPage page; final Record previous; if (indexes == null) { /* We don't need the page if isn't loaded or isn't a mutable new page */ page = newPages.get(pageId); previous = null; if (page != null) { pageReplacementPolicy.pageHit(page); } } else { /* We really need the page for update index old values */ page = loadPageToMemory(pageId, false); previous = page.get(key); if (previous == null) { throw new RuntimeException("deleted record at " + key + " was not found?"); } } if (page == null || page.readonly) { /* Unloaded or immutable, set it as dirty */ pageSet.setPageDirty(pageId, previous); } else { /* Mutable page, need to check if still modifiable or already unloaded */ final Lock lock = page.pageLock.readLock(); lock.lock(); try { if (page.unloaded) { /* Unfortunately unloaded, set it as dirty */ pageSet.setPageDirty(pageId, previous); } else { /* We can modify the page directly */ page.remove(key); } } finally { lock.unlock(); } } if (indexes != null) { /* If there are indexes e have already forced a page load and previous record has been loaded */ DataAccessor values = previous.getDataAccessor(table); for (AbstractIndexManager index : indexes.values()) { index.recordDeleted(key, values); } } } private void applyUpdate(Bytes key, Bytes value) throws DataStorageManagerException { /* * New record to be updated, it will always updated if there aren't errors thus is simpler to create * the record now */ final Record record = new Record(key, value); /* This could be a normal or a temporary modifiable page */ final Long prevPageId = keyToPage.get(key); if (prevPageId == null) { throw new IllegalStateException("corrupted transaction log: key " + key + " is not present in table " + table.name); } /* * We'll try to replace the record if in a writable page, otherwise we'll simply set the old page * as dirty and continue like a normal insertion */ final Map<String, AbstractIndexManager> indexes = tableSpaceManager.getIndexesOnTable(table.name); /* * When index is enabled we need the old value to update them, we'll force the page load only if that * record is really needed. */ final DataPage prevPage; final Record previous; boolean insertedInSamePage = false; if (indexes == null) { /* We don't need the page if isn't loaded or isn't a mutable new page*/ prevPage = newPages.get(prevPageId); previous = null; if (prevPage != null) { pageReplacementPolicy.pageHit(prevPage); } } else { /* We really need the page for update index old values */ prevPage = loadPageToMemory(prevPageId, false); previous = prevPage.get(key); if (previous == null) { throw new RuntimeException("updated record at " + key + " was not found?"); } } if (prevPage == null || prevPage.readonly) { /* Unloaded or immutable, set it as dirty */ pageSet.setPageDirty(prevPageId, previous); } else { /* Mutable page, need to check if still modifiable or already unloaded */ final Lock lock = prevPage.pageLock.readLock(); lock.lock(); try { if (prevPage.unloaded) { /* Unfortunately unloaded, set it as dirty */ pageSet.setPageDirty(prevPageId, previous); } else { /* We can try to modify the page directly */ insertedInSamePage = prevPage.put(record); } } finally { lock.unlock(); } } /* Insertion page */ Long insertionPageId; if (insertedInSamePage) { /* Inserted in temporary mutable previous page, no need to alter keyToPage too: no record page change */ insertionPageId = prevPageId; } else { /* Do real insertion */ insertionPageId = currentDirtyRecordsPage.get(); while (true) { final DataPage newPage = newPages.get(insertionPageId); if (newPage != null) { pageReplacementPolicy.pageHit(newPage); /* The temporary memory page could have been unloaded and loaded again in meantime */ if (!newPage.readonly) { /* Mutable page, need to check if still modifiable or already unloaded */ final Lock lock = newPage.pageLock.readLock(); lock.lock(); try { if (!newPage.unloaded) { /* We can try to modify the page directly */ if (newPage.put(record)) { break; } } } finally { lock.unlock(); } } } /* Try allocate a new page if no already done */ insertionPageId = allocateLivePage(insertionPageId); } /* Update the value on keyToPage */ keyToPage.put(key, insertionPageId); } if (LOGGER.isLoggable(Level.FINEST)) LOGGER.log(Level.FINEST, "Updated key " + key + " from page " + prevPageId + " to page " + insertionPageId); if (indexes != null) { /* If there are indexes e have already forced a page load and previous record has been loaded */ DataAccessor prevValues = previous.getDataAccessor(table); DataAccessor newValues = record.getDataAccessor(table); for (AbstractIndexManager index : indexes.values()) { index.recordUpdated(key, prevValues, newValues); } } } @Override public void dropTableData() throws DataStorageManagerException { dataStorageManager.dropTable(tableSpaceUUID, table.uuid); } @Override public void scanForIndexRebuild(Consumer<Record> records) throws DataStorageManagerException { LocalScanPageCache localPageCache = new LocalScanPageCache(); Consumer<Map.Entry<Bytes, Long>> scanExecutor = (Map.Entry<Bytes, Long> entry) -> { Bytes key = entry.getKey(); LockHandle lock = lockForRead(key, null); try { Long pageId = entry.getValue(); if (pageId != null) { Record record = fetchRecord(key, pageId, localPageCache); if (record != null) { records.accept(record); } } } catch (DataStorageManagerException | StatementExecutionException error) { throw new RuntimeException(error); } finally { locksManager.releaseReadLockForKey(key, lock); } }; Stream<Map.Entry<Bytes, Long>> scanner = keyToPage.scanner(null, StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), tableContext, null); scanner.forEach(scanExecutor); } @Override public void dump(LogSequenceNumber sequenceNumber, FullTableScanConsumer receiver) throws DataStorageManagerException { dataStorageManager.fullTableScan(tableSpaceUUID, table.uuid, sequenceNumber, receiver); } public void writeFromDump(List<Record> record) throws DataStorageManagerException { LOGGER.log(Level.SEVERE, table.name + " received " + record.size() + " records"); checkpointLock.readLock().lock(); try { for (Record r : record) { applyInsert(r.key, r.value, false); } } finally { checkpointLock.readLock().unlock(); } } private void rebuildNextPrimaryKeyValue() throws DataStorageManagerException { LOGGER.log(Level.SEVERE, "rebuildNextPrimaryKeyValue"); Stream<Entry<Bytes, Long>> scanner = keyToPage.scanner(null, StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), tableContext, null); scanner.forEach((Entry<Bytes, Long> t) -> { Bytes key = t.getKey(); long pk_logical_value; if (table.getColumn(table.primaryKey[0]).type == ColumnTypes.INTEGER) { pk_logical_value = key.to_int(); } else { pk_logical_value = key.to_long(); } nextPrimaryKeyValue.accumulateAndGet(pk_logical_value + 1, EnsureLongIncrementAccumulator.INSTANCE); }); LOGGER.log(Level.SEVERE, "rebuildNextPrimaryKeyValue, newPkValue : " + nextPrimaryKeyValue.get()); } private void applyInsert(Bytes key, Bytes value, boolean onTransaction) throws DataStorageManagerException { if (table.auto_increment) { // the next auto_increment value MUST be greater than every other explict value long pk_logical_value; if (table.getColumn(table.primaryKey[0]).type == ColumnTypes.INTEGER) { pk_logical_value = key.to_int(); } else { pk_logical_value = key.to_long(); } nextPrimaryKeyValue.accumulateAndGet(pk_logical_value + 1, EnsureLongIncrementAccumulator.INSTANCE); } /* * New record to be added, it will always added if there aren't DataStorageManagerException thus is * simpler to create the record now */ final Record record = new Record(key, value); /* Normally we expect this value null or pointing to a temporary modifiable page */ final Long prevPageId = keyToPage.get(key); final Map<String, AbstractIndexManager> indexes = tableSpaceManager.getIndexesOnTable(table.name); /* * When index is enabled we need the old value to update them, we'll force the page load only if that * record is really needed. */ final DataPage prevPage; final Record previous; boolean insertedInSamePage = false; if (prevPageId != null) { /* Very strage but possible inside a transaction which executes DELETE THEN INSERT */ if (!onTransaction) { throw new DataStorageManagerException("new record " + key + " already present in keyToPage?"); } if (indexes == null) { /* We don't need the page if isn't loaded or isn't a mutable new page*/ prevPage = newPages.get(prevPageId); previous = null; if (prevPage != null) { pageReplacementPolicy.pageHit(prevPage); } } else { /* We really need the page for update index old values */ prevPage = loadPageToMemory(prevPageId, false); previous = prevPage.get(key); if (previous == null) { throw new RuntimeException("insert upon delete record at " + key + " was not found?"); } } if (prevPage == null || prevPage.readonly) { /* Unloaded or immutable, set it as dirty */ pageSet.setPageDirty(prevPageId, previous); } else { /* Mutable page, need to check if still modifiable or already unloaded */ final Lock lock = prevPage.pageLock.readLock(); lock.lock(); try { if (prevPage.unloaded) { /* Unfortunately unloaded, set it as dirty */ pageSet.setPageDirty(prevPageId, previous); } else { /* We can try to modify the page directly */ insertedInSamePage = prevPage.put(record); } } finally { lock.unlock(); } } } else { /* * Initialize previous record to null... Non really needed but otherwise compiler cannot compile * indexing instructions below. */ previous = null; } /* Insertion page */ Long insertionPageId; if (insertedInSamePage) { /* Inserted in temporary mutable previous page, no need to alter keyToPage too: no record page change */ insertionPageId = prevPageId; } else { /* Do real insertion */ insertionPageId = currentDirtyRecordsPage.get(); while (true) { final DataPage newPage = newPages.get(insertionPageId); if (newPage != null) { pageReplacementPolicy.pageHit(newPage); /* The temporary memory page could have been unloaded and loaded again in meantime */ if (!newPage.readonly) { /* Mutable page, need to check if still modifiable or already unloaded */ final Lock lock = newPage.pageLock.readLock(); lock.lock(); try { if (!newPage.unloaded) { /* We can try to modify the page directly */ if (newPage.put(record)) { break; } } } finally { lock.unlock(); } } } /* Try allocate a new page if no already done */ insertionPageId = allocateLivePage(insertionPageId); } /* Insert/update the value on keyToPage */ keyToPage.put(key, insertionPageId); } if (LOGGER.isLoggable(Level.FINEST)) { if (prevPageId == null) LOGGER.log(Level.FINEST, "Inserted key " + key + " into page " + insertionPageId); else LOGGER.log(Level.FINEST, "Inserted key " + key + " into page " + insertionPageId + " previously was in page " + prevPageId); } if (indexes != null) { if (previous == null) { /* Standard insert */ DataAccessor values = record.getDataAccessor(table); for (AbstractIndexManager index : indexes.values()) { index.recordInserted(key, values); } } else { /* If there is a previous page this is a delete and insert, we really need to update indexes * from old "deleted" values to the new ones. Previus record has already been loaded */ DataAccessor prevValues = previous.getDataAccessor(table); DataAccessor newValues = record.getDataAccessor(table); for (AbstractIndexManager index : indexes.values()) { index.recordUpdated(key, prevValues, newValues); } } } } @Override public void flush() throws DataStorageManagerException { TableCheckpoint checkpoint = checkpoint(false); if (checkpoint != null) { for (PostCheckpointAction action : checkpoint.actions) { action.run(); } } } @Override public void close() { dataStorageManager.releaseKeyToPageMap(tableSpaceUUID, table.uuid, keyToPage); } private StatementExecutionResult executeGet(GetStatement get, Transaction transaction, StatementEvaluationContext context) throws StatementExecutionException, DataStorageManagerException { Bytes key = new Bytes(get.getKey().computeNewValue(null, context, tableContext)); Predicate predicate = get.getPredicate(); boolean requireLock = get.isRequireLock(); long transactionId = transaction != null ? transaction.transactionId : 0; LockHandle lock = (transaction != null || requireLock) ? lockForRead(key, transaction) : null; try { if (transaction != null) { if (transaction.recordDeleted(table.name, key)) { return GetResult.NOT_FOUND(transactionId); } Record loadedInTransaction = transaction.recordUpdated(table.name, key); if (loadedInTransaction != null) { if (predicate != null && !predicate.evaluate(loadedInTransaction, context)) { return GetResult.NOT_FOUND(transactionId); } return new GetResult(transactionId, loadedInTransaction, table); } loadedInTransaction = transaction.recordInserted(table.name, key); if (loadedInTransaction != null) { if (predicate != null && !predicate.evaluate(loadedInTransaction, context)) { return GetResult.NOT_FOUND(transactionId); } return new GetResult(transactionId, loadedInTransaction, table); } } Long pageId = keyToPage.get(key); if (pageId == null) { return GetResult.NOT_FOUND(transactionId); } Record loaded = fetchRecord(key, pageId, null); if (loaded == null || (predicate != null && !predicate.evaluate(loaded, context))) { return GetResult.NOT_FOUND(transactionId); } return new GetResult(transactionId, loaded, table); } finally { if (transaction == null && lock != null) { locksManager.releaseReadLockForKey(key, lock); } } } private DataPage temporaryLoadPageToMemory(Long pageId) throws DataStorageManagerException { long _start = System.currentTimeMillis(); List<Record> page; maxCurrentPagesLoads.acquireUninterruptibly(); try { page = dataStorageManager.readPage(tableSpaceUUID, table.uuid, pageId); } catch (DataPageDoesNotExistException ex) { return null; } finally { maxCurrentPagesLoads.release(); } long _io = System.currentTimeMillis(); DataPage result = buildImmutableDataPage(pageId, page); if (LOGGER.isLoggable(Level.FINEST)) { long _stop = System.currentTimeMillis(); LOGGER.log(Level.FINEST, "tmp table " + table.name + "," + "loaded " + result.size() + " records from page " + pageId + " in " + (_stop - _start) + " ms" + ", (" + (_io - _start) + " ms read)"); } return result; } private DataPage loadPageToMemory(Long pageId, boolean recovery) throws DataStorageManagerException { DataPage result = pages.get(pageId); if (result != null) { pageReplacementPolicy.pageHit(result); return result; } long _start = System.currentTimeMillis(); long _ioAndLock = 0; AtomicBoolean computed = new AtomicBoolean(); try { result = pages.computeIfAbsent(pageId, (id) -> { try { computed.set(true); List<Record> page; maxCurrentPagesLoads.acquireUninterruptibly(); try { page = dataStorageManager.readPage(tableSpaceUUID, table.uuid, pageId); } finally { maxCurrentPagesLoads.release(); } loadedPagesCount.increment(); return buildImmutableDataPage(pageId, page); } catch (DataStorageManagerException err) { throw new RuntimeException(err); } }); if (computed.get()) { _ioAndLock = System.currentTimeMillis(); final Page.Metadata unload = pageReplacementPolicy.add(result); if (unload != null) { unload.owner.unload(unload.pageId); } } } catch (RuntimeException error) { if (error.getCause() != null) { Throwable cause = error.getCause(); if (cause instanceof DataStorageManagerException) { if (cause instanceof DataPageDoesNotExistException) { return null; } throw (DataStorageManagerException) cause; } } throw new DataStorageManagerException(error); } if (computed.get()) { long _stop = System.currentTimeMillis(); LOGGER.log(Level.FINE, "table " + table.name + "," + "loaded " + result.size() + " records from page " + pageId + " in " + (_stop - _start) + " ms" + ", (" + (_ioAndLock - _start) + " ms read + plock" + ", " + (_stop - _ioAndLock) + " ms unlock)"); } return result; } private DataPage buildImmutableDataPage(long pageId, List<Record> page) { Map<Bytes, Record> newPageMap = new HashMap<>(); long estimatedPageSize = 0; for (Record r : page) { newPageMap.put(r.key, r); estimatedPageSize += DataPage.estimateEntrySize(r); } return buildImmutableDataPage(pageId, newPageMap, estimatedPageSize); } private DataPage buildImmutableDataPage(long pageId, Map<Bytes, Record> page, long estimatedPageSize) { DataPage res = new DataPage(this, pageId, maxLogicalPageSize, estimatedPageSize, page, true); return res; } @Override public TableCheckpoint fullCheckpoint(boolean pin) throws DataStorageManagerException { return checkpoint(Double.NEGATIVE_INFINITY, fillThreshold, Long.MAX_VALUE, Long.MAX_VALUE, pin); } @Override public TableCheckpoint checkpoint(boolean pin) throws DataStorageManagerException { return checkpoint(dirtyThreshold, fillThreshold, checkpointTargetTime, compactionTargetTime, pin); } @Override public void unpinCheckpoint(LogSequenceNumber sequenceNumber) throws DataStorageManagerException { /* Unpin secondary indexes too */ final Map<String, AbstractIndexManager> indexes = tableSpaceManager.getIndexesOnTable(table.name); if (indexes != null) { for (AbstractIndexManager indexManager : indexes.values()) { // Checkpointed at the same position of current TableManager indexManager.unpinCheckpoint(sequenceNumber); } } keyToPage.unpinCheckpoint(sequenceNumber); dataStorageManager.unPinTableCheckpoint(tableSpaceUUID, table.uuid, sequenceNumber); } private static final class WeightedPage { public static final Comparator<WeightedPage> ASCENDING_ORDER = (a, b) -> Long.compare(a.weight, b.weight); public static final Comparator<WeightedPage> DESCENDING_ORDER = (a, b) -> Long.compare(b.weight, a.weight); private final Long pageId; private final long weight; public WeightedPage(Long pageId, long weight) { super(); this.pageId = pageId; this.weight = weight; } @Override public String toString() { return pageId + ":" + weight; } } /** * Sums two long values caring of overflows. Assumes that both values are positive! */ private static final long sumOverflowWise(long a, long b) { long total = a + b; return total < 0 ? Long.MAX_VALUE : total; } /** * * @param sequenceNumber * @param dirtyThreshold * @param fillThreshold * @param checkpointTargetTime checkpoint target max milliseconds * @param compactionTargetTime compaction target max milliseconds * @return * @throws DataStorageManagerException */ private TableCheckpoint checkpoint(double dirtyThreshold, double fillThreshold, long checkpointTargetTime, long compactionTargetTime, boolean pin) throws DataStorageManagerException { if (createdInTransaction > 0) { LOGGER.log(Level.SEVERE, "checkpoint for table " + table.name + " skipped," + "this table is created on transaction " + createdInTransaction + " which is not committed"); return null; } final long fillPageThreshold = (long) (fillThreshold * maxLogicalPageSize); final long dirtyPageThreshold = (long) (dirtyThreshold * maxLogicalPageSize); long start = System.currentTimeMillis(); long end; long getlock; long pageAnalysis; long dirtyPagesFlush; long smallPagesFlush; long newPagesFlush; long keytopagecheckpoint; long indexcheckpoint; long tablecheckpoint; final List<PostCheckpointAction> actions = new ArrayList<>(); TableCheckpoint result; checkpointLock.writeLock().lock(); try { LogSequenceNumber sequenceNumber = log.getLastSequenceNumber(); getlock = System.currentTimeMillis(); checkPointRunning = true; final long checkpointLimitInstant = sumOverflowWise(getlock, checkpointTargetTime); final Map<Long, DataPageMetaData> activePages = pageSet.getActivePages(); Map<Bytes, Record> buffer = new HashMap<>(); long bufferPageSize = 0; long flushedRecords = 0; final List<WeightedPage> flushingDirtyPages = new ArrayList<>(); final List<WeightedPage> flushingSmallPages = new ArrayList<>(); final List<Long> flushedPages = new ArrayList<>(); int flushedDirtyPages = 0; int flushedSmallPages = 0; for (Entry<Long, DataPageMetaData> ref : activePages.entrySet()) { final Long pageId = ref.getKey(); final DataPageMetaData metadata = ref.getValue(); final long dirt = metadata.dirt.sum(); /* * Check dirtiness (flush here even small pages if dirty. Small pages flush IGNORES dirty data * handling). */ if (dirt > 0 && (dirt >= dirtyPageThreshold || metadata.size <= fillPageThreshold)) { flushingDirtyPages.add(new WeightedPage(pageId, dirt)); continue; } /* Check emptiness (with a really dirty check to avoid to rewrite an unfillable page) */ if (metadata.size <= fillPageThreshold && maxLogicalPageSize - metadata.avgRecordSize >= fillPageThreshold) { flushingSmallPages.add(new WeightedPage(pageId, metadata.size)); continue; } } /* Clean dirtier first */ flushingDirtyPages.sort(WeightedPage.DESCENDING_ORDER); /* Clean smaller first */ flushingSmallPages.sort(WeightedPage.ASCENDING_ORDER); pageAnalysis = System.currentTimeMillis(); /* Rebuild dirty pages with only records to be kept */ for (WeightedPage weighted : flushingDirtyPages) { /* Page flushed */ flushedPages.add(weighted.pageId); ++flushedDirtyPages; final DataPage dataPage = pages.get(weighted.pageId); final Collection<Record> records; if (dataPage == null) { records = dataStorageManager.readPage(tableSpaceUUID, table.uuid, weighted.pageId); LOGGER.log(Level.FINEST, "loaded dirty page {0} on tmp buffer: {1} records", new Object[]{weighted.pageId, records.size()}); } else { records = dataPage.data.values(); } for (Record record : records) { /* Avoid the record if has been modified or deleted */ final Long currentPageId = keyToPage.get(record.key); if (currentPageId == null || !weighted.pageId.equals(currentPageId)) { continue; } /* Flush the page if it would exceed max page size */ if (bufferPageSize + DataPage.estimateEntrySize(record) > maxLogicalPageSize) { createImmutablePage(buffer, bufferPageSize); flushedRecords += buffer.size(); bufferPageSize = 0; /* Do not clean old buffer! It will used in generated pages to avoid too many copies! */ buffer = new HashMap<>(buffer.size()); } buffer.put(record.key, record); bufferPageSize += DataPage.estimateEntrySize(record); } /* Do not continue if we have used up all configured checkpoint time */ if (checkpointLimitInstant <= System.currentTimeMillis()) { break; } } dirtyPagesFlush = System.currentTimeMillis(); /* * If there is only one without additional data to add * rebuilding the page make no sense: is too probable to rebuild an identical page! */ if (flushingSmallPages.size() == 1 && buffer.isEmpty()) { boolean hasNewPagesData = newPages.values().stream().filter(p -> !p.isEmpty()).findAny().isPresent(); if (!hasNewPagesData) { flushingSmallPages.clear(); } } final long compactionLimitInstant = sumOverflowWise(dirtyPagesFlush, compactionTargetTime); /* Rebuild too small pages */ for (WeightedPage weighted : flushingSmallPages) { /* Page flushed */ flushedPages.add(weighted.pageId); ++flushedSmallPages; final DataPage dataPage = pages.get(weighted.pageId); final Collection<Record> records; if (dataPage == null) { records = dataStorageManager.readPage(tableSpaceUUID, table.uuid, weighted.pageId); LOGGER.log(Level.FINEST, "loaded small page {0} on tmp buffer: {1} records", new Object[]{weighted.pageId, records.size()}); } else { records = dataPage.data.values(); } for (Record record : records) { /* Flush the page if it would exceed max page size */ if (bufferPageSize + DataPage.estimateEntrySize(record) > maxLogicalPageSize) { createImmutablePage(buffer, bufferPageSize); flushedRecords += buffer.size(); bufferPageSize = 0; /* Do not clean old buffer! It will used in generated pages to avoid too many copies! */ buffer = new HashMap<>(buffer.size()); } buffer.put(record.key, record); bufferPageSize += DataPage.estimateEntrySize(record); } final long now = System.currentTimeMillis(); /* * Do not continue if we have used up all configured compaction or checkpoint time (but still compact at * least the smaller page (normally the leftover from last checkpoint) */ if (compactionLimitInstant <= now || checkpointLimitInstant <= now) { break; } } flushingSmallPages.clear(); smallPagesFlush = System.currentTimeMillis(); /* * Flush dirty records (and remaining records from previous step). * * Any newpage remaining here is unflushed and is not set as dirty (if "dirty" were unloaded!). * Just write the pages as they are. * * New empty pages won't be written */ long flushedNewPages = 0; for (DataPage dataPage : newPages.values()) { if (!dataPage.isEmpty()) { bufferPageSize -= flushNewPage(dataPage, buffer); ++flushedNewPages; flushedRecords += dataPage.size(); } } /* Flush remaining records */ if (!buffer.isEmpty()) { createImmutablePage(buffer, bufferPageSize); flushedRecords += buffer.size(); bufferPageSize = 0; /* Do not clean old buffer! It will used in generated pages to avoid too many copies! */ } newPagesFlush = System.currentTimeMillis(); LOGGER.log(Level.INFO, "checkpoint {0}, logpos {1}, flushed: {2} dirty pages, {3} small pages, {4} new pages, {5} records", new Object[]{table.name, sequenceNumber, flushedDirtyPages, flushedSmallPages, flushedNewPages, flushedRecords}); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "checkpoint {0}, logpos {1}, flushed pages: {2}", new Object[]{table.name, sequenceNumber, flushedPages.toString()}); } /* Checkpoint the key to page too */ actions.addAll(keyToPage.checkpoint(sequenceNumber, pin)); keytopagecheckpoint = System.currentTimeMillis(); /* Checkpoint secondary indexes too */ final Map<String, AbstractIndexManager> indexes = tableSpaceManager.getIndexesOnTable(table.name); if (indexes != null) { for (AbstractIndexManager indexManager : indexes.values()) { // Checkpoint at the same position of current TableManager actions.addAll(indexManager.checkpoint(sequenceNumber, pin)); } } indexcheckpoint = System.currentTimeMillis(); pageSet.checkpointDone(flushedPages); TableStatus tableStatus = new TableStatus(table.name, sequenceNumber, Bytes.from_long(nextPrimaryKeyValue.get()).data, nextPageId, pageSet.getActivePages()); actions.addAll(dataStorageManager.tableCheckpoint(tableSpaceUUID, table.uuid, tableStatus, pin)); tablecheckpoint = System.currentTimeMillis(); /* Writes done! Unloading and removing not needed pages and keys */ /* Remove flushed pages handled */ for (Long pageId : flushedPages) { final DataPage page = pages.remove(pageId); /* Current dirty record page isn't known to page replacement policy */ if (page != null && currentDirtyRecordsPage.get() != page.pageId) { pageReplacementPolicy.remove(page); } } /* * Can happen when at checkpoint start all pages are set as dirty or immutable (readonly or * unloaded) due do a deletion: all pages will be removed and no page will remain alive. */ if (newPages.isEmpty()) { /* Allocate live handles the correct policy load/unload of last dirty page */ allocateLivePage(currentDirtyRecordsPage.get()); } checkPointRunning = false; result = new TableCheckpoint(table.name, sequenceNumber, actions); end = System.currentTimeMillis(); LOGGER.log(Level.INFO, "checkpoint {0} finished, logpos {1}, {2} active pages, {3} dirty pages, " + "flushed {4} records, total time {5} ms", new Object[] {table.name, sequenceNumber, pageSet.getActivePagesCount(), pageSet.getDirtyPagesCount(), flushedRecords, Long.toString(end - start)}); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "checkpoint {0} finished, logpos {1}, pageSet: {2}", new Object[]{table.name, sequenceNumber, pageSet.toString()}); } } finally { checkpointLock.writeLock().unlock(); } long delta = end - start; if (delta > 1000) { long delta_lock = getlock - start; long delta_pageAnalysis = pageAnalysis - getlock; long delta_dirtyPagesFlush = dirtyPagesFlush - pageAnalysis; long delta_smallPagesFlush = smallPagesFlush - dirtyPagesFlush; long delta_newPagesFlush = newPagesFlush - smallPagesFlush; long delta_keytopagecheckpoint = keytopagecheckpoint - newPagesFlush; long delta_indexcheckpoint = indexcheckpoint - keytopagecheckpoint; long delta_tablecheckpoint = tablecheckpoint - indexcheckpoint; long delta_unload = end - keytopagecheckpoint; LOGGER.log(Level.INFO, "long checkpoint for {0}, time {1}", new Object[]{table.name, delta + " ms (" + delta_lock + "+" + delta_pageAnalysis + "+" + delta_dirtyPagesFlush + "+" + delta_smallPagesFlush + "+" + delta_newPagesFlush + "+" + delta_keytopagecheckpoint + "+" + delta_indexcheckpoint + "+" + delta_tablecheckpoint + "+" + delta_unload + ")"}); } return result; } @Override public DataScanner scan(ScanStatement statement, StatementEvaluationContext context, Transaction transaction) throws StatementExecutionException { boolean sorted = statement.getComparator() != null; boolean sortedByClusteredIndex = statement.getComparator() != null && statement.getComparator().isOnlyPrimaryKeyAndAscending() && keyToPage.isSortedAscending(); final Projection projection = statement.getProjection(); boolean applyProjectionDuringScan = !sorted && projection != null; MaterializedRecordSet recordSet; if (applyProjectionDuringScan) { recordSet = tableSpaceManager.getDbmanager().getRecordSetFactory() .createRecordSet(projection.getFieldNames(), projection.getColumns()); } else { recordSet = tableSpaceManager.getDbmanager().getRecordSetFactory() .createRecordSet(table.columnNames, table.columns); } ScanLimits limits = statement.getLimits(); int maxRows = limits == null ? 0 : limits.computeMaxRows(context); int offset = limits == null ? 0 : limits.getOffset(); boolean sortDone = false; if (maxRows > 0) { if (sortedByClusteredIndex) { // leverage the sorted nature of the clustered primary key index AtomicInteger remaining = new AtomicInteger(maxRows); if (offset > 0) { remaining.getAndAdd(offset); } accessTableData(statement, context, new ScanResultOperation() { private boolean inTransactionData; @Override public void beginNewRecordsInTransactionBlock() { inTransactionData = true; } @Override public void accept(Record record) throws StatementExecutionException { if (applyProjectionDuringScan) { DataAccessor tuple = projection.map(record.getDataAccessor(table), context); recordSet.add(tuple); } else { recordSet.add(record.getDataAccessor(table)); } if (!inTransactionData) { // we have scanned the table and kept top K record already sorted by the PK // we can exit now from the loop on the primary key // we have to keep all data from the transaction buffer, because it is not sorted // in the same order as the clustered index if (remaining.decrementAndGet() == 0) { // we want to receive transaction data uncommitted records too throw new ExitLoop(true); } } } }, transaction, false, false); // we have to sort data any way, because accessTableData will return partially sorted data sortDone = false; } else if (sorted) { InStreamTupleSorter sorter = new InStreamTupleSorter(offset + maxRows, statement.getComparator()); accessTableData(statement, context, new ScanResultOperation() { @Override public void accept(Record record) throws StatementExecutionException { if (applyProjectionDuringScan) { DataAccessor tuple = projection.map(record.getDataAccessor(table), context); sorter.collect(tuple); } else { sorter.collect(record.getDataAccessor(table)); } } }, transaction, false, false); sorter.flushToRecordSet(recordSet); sortDone = true; } else { // if no sort is present the limits can be applying during the scan and perform an early exit AtomicInteger remaining = new AtomicInteger(maxRows); if (offset > 0) { remaining.getAndAdd(offset); } accessTableData(statement, context, new ScanResultOperation() { @Override public void accept(Record record) throws StatementExecutionException { if (applyProjectionDuringScan) { DataAccessor tuple = projection.map(record.getDataAccessor(table), context); recordSet.add(tuple); } else { recordSet.add(record.getDataAccessor(table)); } if (remaining.decrementAndGet() == 0) { throw new ExitLoop(false); } } }, transaction, false, false); } } else { accessTableData(statement, context, new ScanResultOperation() { @Override public void accept(Record record) throws StatementExecutionException { if (applyProjectionDuringScan) { DataAccessor tuple = projection.map(record.getDataAccessor(table), context); recordSet.add(tuple); } else { recordSet.add(record.getDataAccessor(table)); } } }, transaction, false, false); } recordSet.writeFinished(); if (!sortDone) { recordSet.sort(statement.getComparator()); } recordSet.applyLimits(statement.getLimits(), context); if (!applyProjectionDuringScan) { recordSet.applyProjection(statement.getProjection(), context); } return new SimpleDataScanner(transaction != null ? transaction.transactionId : 0, recordSet); } private void accessTableData(ScanStatement statement, StatementEvaluationContext context, ScanResultOperation consumer, Transaction transaction, boolean lockRequired, boolean forWrite) throws StatementExecutionException { Predicate predicate = statement.getPredicate(); long _start = System.currentTimeMillis(); boolean acquireLock = transaction != null || forWrite || lockRequired; LocalScanPageCache lastPageRead = acquireLock ? null : new LocalScanPageCache(); try { IndexOperation indexOperation = predicate != null ? predicate.getIndexOperation() : null; boolean primaryIndexSeek = indexOperation instanceof PrimaryIndexSeek; AbstractIndexManager useIndex = getIndexForTbleAccess(indexOperation); BatchOrderedExecutor.Executor<Map.Entry<Bytes, Long>> scanExecutor = (List<Map.Entry<Bytes, Long>> batch) -> { for (Map.Entry<Bytes, Long> entry : batch) { Bytes key = entry.getKey(); boolean keep_lock = false; boolean already_locked = transaction != null && transaction.lookupLock(table.name, key) != null; LockHandle lock = acquireLock ? (forWrite ? lockForWrite(key, transaction) : lockForRead(key, transaction)) : null; try { if (transaction != null) { if (transaction.recordDeleted(table.name, key)) { // skip this record. inside current transaction it has been deleted continue; } Record record = transaction.recordUpdated(table.name, key); if (record != null) { // use current transaction version of the record if (predicate == null || predicate.evaluate(record, context)) { consumer.accept(record); keep_lock = true; } continue; } } Long pageId = entry.getValue(); if (pageId != null) { boolean pkFilterCompleteMatch = false; if (!primaryIndexSeek && predicate != null) { Predicate.PrimaryKeyMatchOutcome outcome = predicate.matchesRawPrimaryKey(key, context); if (outcome == Predicate.PrimaryKeyMatchOutcome.FAILED) { continue; } else if (outcome == Predicate.PrimaryKeyMatchOutcome.FULL_CONDITION_VERIFIED) { pkFilterCompleteMatch = true; } } Record record = fetchRecord(key, pageId, lastPageRead); if (record != null && (pkFilterCompleteMatch || predicate == null || predicate.evaluate(record, context))) { consumer.accept(record); keep_lock = true; } } } finally { // release the lock on the key if it did not match scan criteria if (transaction == null) { if (lock != null) { if (forWrite) { locksManager.releaseWriteLockForKey(key, lock); } else { locksManager.releaseReadLockForKey(key, lock); } } } else if (!keep_lock && !already_locked) { transaction.releaseLockOnKey(table.name, key, locksManager); } } } }; BatchOrderedExecutor<Map.Entry<Bytes, Long>> executor = new BatchOrderedExecutor<>(SORTED_PAGE_ACCESS_WINDOW_SIZE, scanExecutor, SORTED_PAGE_ACCESS_COMPARATOR); Stream<Map.Entry<Bytes, Long>> scanner = keyToPage.scanner(indexOperation, context, tableContext, useIndex); boolean exit = false; try { scanner.forEach(executor); executor.finish(); } catch (ExitLoop exitLoop) { exit = !exitLoop.continueWithTransactionData; if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "exit loop during scan {0}, started at {1}: {2}", new Object[]{statement, new java.sql.Timestamp(_start), exitLoop.toString()}); } } catch (final HerdDBInternalException error) { LOGGER.log(Level.SEVERE, "error during scan", error); if (error.getCause() instanceof StatementExecutionException) { throw (StatementExecutionException) error.getCause(); } else if (error.getCause() instanceof DataStorageManagerException) { throw (DataStorageManagerException) error.getCause(); } else if (error instanceof StatementExecutionException) { throw (StatementExecutionException) error; } else if (error instanceof DataStorageManagerException) { throw (DataStorageManagerException) error; } else { throw new StatementExecutionException(error); } } if (!exit && transaction != null) { consumer.beginNewRecordsInTransactionBlock(); Collection<Record> newRecordsForTable = transaction.getNewRecordsForTable(table.name); for (Record record : newRecordsForTable) { if (!transaction.recordDeleted(table.name, record.key) && (predicate == null || predicate.evaluate(record, context))) { consumer.accept(record); } } } } catch (ExitLoop exitLoop) { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "exit loop during scan {0}, started at {1}: {2}", new Object[]{statement, new java.sql.Timestamp(_start), exitLoop.toString()}); } } catch (StatementExecutionException err) { LOGGER.log(Level.SEVERE, "error during scan {0}, started at {1}: {2}", new Object[]{statement, new java.sql.Timestamp(_start), err.toString()}); throw err; } catch (HerdDBInternalException err) { LOGGER.log(Level.SEVERE, "error during scan {0}, started at {1}: {2}", new Object[]{statement, new java.sql.Timestamp(_start), err.toString()}); throw new StatementExecutionException(err); } } private AbstractIndexManager getIndexForTbleAccess(IndexOperation indexOperation) { AbstractIndexManager useIndex = null; if (indexOperation != null) { Map<String, AbstractIndexManager> indexes = tableSpaceManager.getIndexesOnTable(table.name); if (indexes != null) { useIndex = indexes.get(indexOperation.getIndexName()); if (useIndex != null && !useIndex.isAvailable()) { useIndex = null; } } } return useIndex; } @Override public List<Index> getAvailableIndexes() { Map<String, AbstractIndexManager> indexes = tableSpaceManager.getIndexesOnTable(table.name); if (indexes == null) { return Collections.emptyList(); } return indexes.values().stream().filter(AbstractIndexManager::isAvailable).map(AbstractIndexManager::getIndex) .collect(Collectors.toList()); } @Override public KeyToPageIndex getKeyToPageIndex() { return keyToPage; } private Record fetchRecord(Bytes key, Long pageId, LocalScanPageCache localScanPageCache) throws StatementExecutionException, DataStorageManagerException { int maxTrials = 2; while (true) { DataPage dataPage = fetchDataPage(pageId, localScanPageCache); if (dataPage != null) { Record record = dataPage.get(key); if (record != null) { return record; } } Long relocatedPageId = keyToPage.get(key); LOGGER.log(Level.SEVERE, table.name + " fetchRecord " + key + " failed," + "checkPointRunning:" + checkPointRunning + " pageId:" + pageId + " relocatedPageId:" + relocatedPageId); if (relocatedPageId == null) { // deleted LOGGER.log(Level.SEVERE, "table " + table.name + ", activePages " + pageSet.getActivePages() + ", record " + key + " deleted during data access"); return null; } pageId = relocatedPageId; if (maxTrials-- == 0) { throw new DataStorageManagerException("inconsistency! table " + table.name + " no record in memory for " + key + " page " + pageId + ", activePages " + pageSet.getActivePages() + " after many trials"); } } } private DataPage fetchDataPage(Long pageId, LocalScanPageCache localScanPageCache) throws DataStorageManagerException { DataPage dataPage; if (localScanPageCache == null || !ENABLE_LOCAL_SCAN_PAGE_CACHE || pages.containsKey(pageId)) { dataPage = loadPageToMemory(pageId, false); } else { if (pageId.equals(localScanPageCache.pageId)) { // same page needed twice dataPage = localScanPageCache.value; } else { // TODO: add good heuristics and choose whether to load // the page in the main buffer dataPage = pages.get(pageId); if (dataPage == null) { if (ThreadLocalRandom.current().nextInt(10) < 4) { // 25% of pages will be loaded to main buffer dataPage = loadPageToMemory(pageId, false); } else { // 75% of pages will be loaded only to current scan buffer dataPage = temporaryLoadPageToMemory(pageId); localScanPageCache.value = dataPage; localScanPageCache.pageId = pageId; } } else { pageReplacementPolicy.pageHit(dataPage); } } } return dataPage; } @Override public TableManagerStats getStats() { return stats; } @Override public long getNextPrimaryKeyValue() { return nextPrimaryKeyValue.get(); } @Override public boolean isSystemTable() { return false; } @Override public boolean isStarted() { return started; } @Override public void tableAltered(Table table, Transaction transaction) throws DDLException { // compute diff, if some column as been dropped we need to remove the value from each record List<String> droppedColumns = new ArrayList<>(); for (Column c : this.table.columns) { if (table.getColumn(c.name) == null) { droppedColumns.add(c.name); } } this.table = table; if (!droppedColumns.isEmpty()) { // no lock is necessary pages.values().forEach(p -> { p.data.values().forEach(r -> r.clearCache()); }); } if (this.table.auto_increment) { rebuildNextPrimaryKeyValue(); } } @Override public long getCreatedInTransaction() { return createdInTransaction; } private static final Comparator<Map.Entry<Bytes, Long>> SORTED_PAGE_ACCESS_COMPARATOR = (a, b) -> { return a.getValue().compareTo(b.getValue()); }; }
herddb-core/src/main/java/herddb/core/TableManager.java
/* Licensed to Diennea S.r.l. under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Diennea S.r.l. 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 herddb.core; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.LongAdder; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.Stream; import herddb.codec.RecordSerializer; import herddb.core.PageSet.DataPageMetaData; import herddb.core.stats.TableManagerStats; import herddb.index.IndexOperation; import herddb.index.KeyToPageIndex; import herddb.index.PrimaryIndexSeek; import herddb.log.CommitLog; import herddb.log.CommitLogResult; import herddb.log.LogEntry; import herddb.log.LogEntryFactory; import herddb.log.LogEntryType; import herddb.log.LogNotAvailableException; import herddb.log.LogSequenceNumber; import herddb.model.Column; import herddb.model.ColumnTypes; import herddb.model.DDLException; import herddb.model.DMLStatementExecutionResult; import herddb.model.DataScanner; import herddb.model.DuplicatePrimaryKeyException; import herddb.model.GetResult; import herddb.model.Index; import herddb.model.Predicate; import herddb.model.Projection; import herddb.model.Record; import herddb.model.RecordFunction; import herddb.model.RecordTooBigException; import herddb.model.ScanLimits; import herddb.model.Statement; import herddb.model.StatementEvaluationContext; import herddb.model.StatementExecutionException; import herddb.model.StatementExecutionResult; import herddb.model.Table; import herddb.model.TableContext; import herddb.model.Transaction; import herddb.model.commands.DeleteStatement; import herddb.model.commands.GetStatement; import herddb.model.commands.InsertStatement; import herddb.model.commands.ScanStatement; import herddb.model.commands.TruncateTableStatement; import herddb.model.commands.UpdateStatement; import herddb.server.ServerConfiguration; import herddb.storage.DataPageDoesNotExistException; import herddb.storage.DataStorageManager; import herddb.storage.DataStorageManagerException; import herddb.storage.FullTableScanConsumer; import herddb.storage.TableStatus; import herddb.utils.BatchOrderedExecutor; import herddb.utils.Bytes; import herddb.utils.DataAccessor; import herddb.utils.EnsureLongIncrementAccumulator; import herddb.utils.Holder; import herddb.utils.LocalLockManager; import herddb.utils.LockHandle; import herddb.utils.SystemProperties; /** * Handles Data of a Table * * @author enrico.olivelli * @author diego.salvi */ public final class TableManager implements AbstractTableManager, Page.Owner { private static final Logger LOGGER = Logger.getLogger(TableManager.class.getName()); private static final int SORTED_PAGE_ACCESS_WINDOW_SIZE = SystemProperties. getIntSystemProperty(TableManager.class.getName() + ".sortedPageAccessWindowSize", 2000); private static final boolean ENABLE_LOCAL_SCAN_PAGE_CACHE = SystemProperties. getBooleanSystemProperty(TableManager.class.getName() + ".enableLocalScanPageCache", true); private final ConcurrentMap<Long, DataPage> newPages; private final ConcurrentMap<Long, DataPage> pages; /** * A structure which maps each key to the ID of the page (map<byte[], long>) (this can be quite large) */ private final KeyToPageIndex keyToPage; private final PageSet pageSet = new PageSet(); private long nextPageId = 1; private final Lock nextPageLock = new ReentrantLock(); private final AtomicLong currentDirtyRecordsPage = new AtomicLong(); /** * Counts how many pages had been unloaded */ private final LongAdder loadedPagesCount = new LongAdder(); /** * Counts how many pages had been loaded */ private final LongAdder unloadedPagesCount = new LongAdder(); /** * Local locks */ private final LocalLockManager locksManager = new LocalLockManager(); /** * Set to {@code true} when this {@link TableManage} is fully started */ private volatile boolean started = false; private volatile boolean checkPointRunning = false; /** * Allow checkpoint */ private final ReentrantReadWriteLock checkpointLock = new ReentrantReadWriteLock(false); /** * auto_increment support */ private final AtomicLong nextPrimaryKeyValue = new AtomicLong(1); private final TableContext tableContext; /** * Phisical ID of the TableSpace */ private final String tableSpaceUUID; /** * Definition of the table */ private Table table; private final CommitLog log; private final DataStorageManager dataStorageManager; private final TableSpaceManager tableSpaceManager; private final PageReplacementPolicy pageReplacementPolicy; /** * Max logical size of a page (raw key size + raw value size) */ private final long maxLogicalPageSize; private final Semaphore maxCurrentPagesLoads = new Semaphore(4, true); /** * This value is not empty until the transaction who creates the table does not commit */ private long createdInTransaction; /** * Default dirty threshold for page rebuild during checkpoints */ private final double dirtyThreshold; /** * Default fill threshold for page rebuild during checkpoints */ private final double fillThreshold; /** * Checkpoint target max milliseconds */ private final long checkpointTargetTime; /** * Compaction (small pages) target max milliseconds */ private final long compactionTargetTime; private final TableManagerStats stats; void prepareForRestore(LogSequenceNumber dumpLogSequenceNumber) { LOGGER.log(Level.SEVERE, "Table " + table.name + ", receiving dump," + "done at external logPosition " + dumpLogSequenceNumber); this.dumpLogSequenceNumber = dumpLogSequenceNumber; } void restoreFinished() { dumpLogSequenceNumber = null; LOGGER.log(Level.SEVERE, "Table " + table.name + ", received dump"); } private final class TableManagerStatsImpl implements TableManagerStats { @Override public int getLoadedpages() { return pages.size(); } @Override public long getLoadedPagesCount() { return loadedPagesCount.sum(); } @Override public long getUnloadedPagesCount() { return unloadedPagesCount.sum(); } @Override public long getTablesize() { return keyToPage.size(); } @Override public int getDirtypages() { return pageSet.getDirtyPagesCount(); } @Override public int getDirtyrecords() { int size = 0; for (DataPage newPage : newPages.values()) { size += newPage.size(); } return size; } @Override public long getDirtyUsedMemory() { long used = 0; for (DataPage newPage : newPages.values()) { used += newPage.getUsedMemory(); } return used; } @Override public long getMaxLogicalPageSize() { return maxLogicalPageSize; } @Override public long getBuffersUsedMemory() { long value = 0; for (DataPage page : pages.values()) { value += page.getUsedMemory(); } return value; } @Override public long getKeysUsedMemory() { return keyToPage.getUsedMemory(); } } TableManager(Table table, CommitLog log, MemoryManager memoryManager, DataStorageManager dataStorageManager, TableSpaceManager tableSpaceManager, String tableSpaceUUID, long createdInTransaction) throws DataStorageManagerException { this.stats = new TableManagerStatsImpl(); this.log = log; this.table = table; this.tableSpaceManager = tableSpaceManager; this.dataStorageManager = dataStorageManager; this.createdInTransaction = createdInTransaction; this.tableSpaceUUID = tableSpaceUUID; this.tableContext = buildTableContext(); this.maxLogicalPageSize = memoryManager.getMaxLogicalPageSize(); this.keyToPage = dataStorageManager.createKeyToPageMap(tableSpaceUUID, table.uuid, memoryManager); this.pageReplacementPolicy = memoryManager.getDataPageReplacementPolicy(); this.pages = new ConcurrentHashMap<>(); this.newPages = new ConcurrentHashMap<>(); this.dirtyThreshold = tableSpaceManager.getDbmanager().getServerConfiguration().getDouble( ServerConfiguration.PROPERTY_DIRTY_PAGE_THRESHOLD, ServerConfiguration.PROPERTY_DIRTY_PAGE_THRESHOLD_DEFAULT); this.fillThreshold = tableSpaceManager.getDbmanager().getServerConfiguration().getDouble( ServerConfiguration.PROPERTY_FILL_PAGE_THRESHOLD, ServerConfiguration.PROPERTY_FILL_PAGE_THRESHOLD_DEFAULT); long checkpointTargetTime = tableSpaceManager.getDbmanager().getServerConfiguration().getLong( ServerConfiguration.PROPERTY_CHECKPOINT_DURATION, ServerConfiguration.PROPERTY_CHECKPOINT_DURATION_DEFAULT); this.checkpointTargetTime = checkpointTargetTime < 0 ? Long.MAX_VALUE : checkpointTargetTime; long compactionTargetTime = tableSpaceManager.getDbmanager().getServerConfiguration().getLong( ServerConfiguration.PROPERTY_COMPACTION_DURATION, ServerConfiguration.PROPERTY_COMPACTION_DURATION_DEFAULT); this.compactionTargetTime = compactionTargetTime < 0 ? Long.MAX_VALUE : compactionTargetTime; } private TableContext buildTableContext() { TableContext tableContext; if (!table.auto_increment) { tableContext = new TableContext() { @Override public byte[] computeNewPrimaryKeyValue() { throw new UnsupportedOperationException("no auto_increment function on this table"); } @Override public Table getTable() { return table; } }; } else if (table.getColumn(table.primaryKey[0]).type == ColumnTypes.INTEGER) { tableContext = new TableContext() { @Override public byte[] computeNewPrimaryKeyValue() { return Bytes.from_int((int) nextPrimaryKeyValue.getAndIncrement()).data; } @Override public Table getTable() { return table; } }; } else if (table.getColumn(table.primaryKey[0]).type == ColumnTypes.LONG) { tableContext = new TableContext() { @Override public byte[] computeNewPrimaryKeyValue() { return Bytes.from_long((int) nextPrimaryKeyValue.getAndIncrement()).data; } @Override public Table getTable() { return table; } }; } else { tableContext = new TableContext() { @Override public byte[] computeNewPrimaryKeyValue() { throw new UnsupportedOperationException("no auto_increment function on this table"); } @Override public Table getTable() { return table; } }; } return tableContext; } @Override public Table getTable() { return table; } private LogSequenceNumber bootSequenceNumber; private LogSequenceNumber dumpLogSequenceNumber; @Override public LogSequenceNumber getBootSequenceNumber() { return bootSequenceNumber; } @Override public void start() throws DataStorageManagerException { Map<Long, DataPageMetaData> activePagesAtBoot = new HashMap<>(); bootSequenceNumber = LogSequenceNumber.START_OF_TIME; boolean requireLoadAtStartup = keyToPage.requireLoadAtStartup(); if (requireLoadAtStartup) { // non persistent primary key index, we need a full table scan LOGGER.log(Level.SEVERE, "loading in memory all the keys for table {0}", new Object[]{table.name}); dataStorageManager.fullTableScan(tableSpaceUUID, table.uuid, new FullTableScanConsumer() { Long currentPage; @Override public void acceptTableStatus(TableStatus tableStatus) { LOGGER.log(Level.SEVERE, "recovery table at " + tableStatus.sequenceNumber); nextPrimaryKeyValue.set(Bytes.toLong(tableStatus.nextPrimaryKeyValue, 0, 8)); nextPageId = tableStatus.nextPageId; bootSequenceNumber = tableStatus.sequenceNumber; activePagesAtBoot.putAll(tableStatus.activePages); } @Override public void startPage(long pageId) { currentPage = pageId; } @Override public void acceptRecord(Record record) { if (currentPage < 0) { throw new IllegalStateException(); } keyToPage.put(record.key, currentPage); } @Override public void endPage() { currentPage = null; } @Override public void endTable() { } }); } else { LOGGER.log(Level.SEVERE, "loading table {0}, uuid {1}", new Object[]{table.name, table.uuid}); TableStatus tableStatus = dataStorageManager.getLatestTableStatus(tableSpaceUUID, table.uuid); LOGGER.log(Level.SEVERE, "recovery table at " + tableStatus.sequenceNumber); nextPrimaryKeyValue.set(Bytes.toLong(tableStatus.nextPrimaryKeyValue, 0, 8)); nextPageId = tableStatus.nextPageId; bootSequenceNumber = tableStatus.sequenceNumber; activePagesAtBoot.putAll(tableStatus.activePages); } keyToPage.start(bootSequenceNumber); dataStorageManager.cleanupAfterBoot(tableSpaceUUID, table.uuid, activePagesAtBoot.keySet()); pageSet.setActivePagesAtBoot(activePagesAtBoot); initNewPage(); LOGGER.log(Level.SEVERE, "loaded {0} keys for table {1}, newPageId {2}, nextPrimaryKeyValue {3}, activePages {4}", new Object[]{keyToPage.size(), table.name, nextPageId, nextPrimaryKeyValue.get(), pageSet.getActivePages() + ""}); started = true; } @Override public StatementExecutionResult executeStatement(Statement statement, Transaction transaction, StatementEvaluationContext context) throws StatementExecutionException { checkpointLock.readLock().lock(); try { if (statement instanceof UpdateStatement) { UpdateStatement update = (UpdateStatement) statement; return executeUpdate(update, transaction, context); } if (statement instanceof InsertStatement) { InsertStatement insert = (InsertStatement) statement; return executeInsert(insert, transaction, context); } if (statement instanceof GetStatement) { GetStatement get = (GetStatement) statement; return executeGet(get, transaction, context); } if (statement instanceof DeleteStatement) { DeleteStatement delete = (DeleteStatement) statement; return executeDelete(delete, transaction, context); } if (statement instanceof TruncateTableStatement) { TruncateTableStatement truncate = (TruncateTableStatement) statement; return executeTruncate(truncate, transaction, context); } } catch (DataStorageManagerException err) { throw new StatementExecutionException("internal data error: " + err, err); } finally { checkpointLock.readLock().unlock(); if (statement instanceof TruncateTableStatement) { try { flush(); } catch (DataStorageManagerException err) { throw new StatementExecutionException("internal data error: " + err, err); } } } throw new StatementExecutionException("unsupported statement " + statement); } /** * Create a new page with given data, save it and update keyToPage records * <p> * Will not place any lock, this method should be invoked at startup time or during checkpoint: <b>during * "stop-the-world" procedures!</b> * </p> */ private long createImmutablePage(Map<Bytes, Record> newPage, long newPageSize) throws DataStorageManagerException { final Long pageId = nextPageId++; final DataPage dataPage = buildImmutableDataPage(pageId, newPage, newPageSize); LOGGER.log(Level.FINER, "createNewPage table {0}, pageId={1} with {2} records, {3} logical page size", new Object[]{table.name, pageId, newPage.size(), newPageSize}); dataStorageManager.writePage(tableSpaceUUID, table.uuid, pageId, newPage.values()); pageSet.pageCreated(pageId, dataPage); pages.put(pageId, dataPage); /* We mustn't update currentDirtyRecordsPage. This page isn't created to host live dirty data */ final Page.Metadata unload = pageReplacementPolicy.add(dataPage); if (unload != null) { unload.owner.unload(unload.pageId); } for (Bytes key : newPage.keySet()) { keyToPage.put(key, pageId); } return pageId; } private Long allocateLivePage(Long lastKnownPageId) { /* This method expect that a new page actually exists! */ nextPageLock.lock(); final Long newId; Page.Metadata unload = null; try { /* * Use currentDirtyRecordsPage to check because nextPageId could be advanced for other needings * like rebuild a dirty page during checkpoint */ if (lastKnownPageId == currentDirtyRecordsPage.get()) { final DataPage lastKnownPage; /* Is really a new page! */ newId = nextPageId++; if (pages.containsKey(newId)) { throw new IllegalStateException("invalid newpage id " + newId + ", " + newPages.keySet() + "/" + pages.keySet()); } /* * If really was the last new page id it MUST be in pages. It cannot be unloaded before the * creation of a new page! */ lastKnownPage = pages.get(lastKnownPageId); if (lastKnownPage == null) { throw new IllegalStateException("invalid last known new page id " + lastKnownPageId + ", " + newPages.keySet() + "/" + pages.keySet()); } final DataPage newPage = new DataPage(this, newId, maxLogicalPageSize, 0, new ConcurrentHashMap<>(), false); newPages.put(newId, newPage); pages.put(newId, newPage); /* From this moment on the page has been published */ /* The lock is needed to block other threads up to this point */ currentDirtyRecordsPage.set(newId); /* * Now we must add the "lastKnownPage" to page replacement policy. There is only one page living * outside replacement policy (the currentDirtyRecordsPage) */ unload = pageReplacementPolicy.add(lastKnownPage); } else { /* The page has been published for sure */ newId = currentDirtyRecordsPage.get(); } } finally { nextPageLock.unlock(); } /* Dereferenced page unload. Out of locking */ if (unload != null) { unload.owner.unload(unload.pageId); } /* Both created now or already created */ return newId; } /** * Create a new page and set it as the target page for dirty records. * <p> * Will not place any lock, this method should be invoked at startup time: <b>during "stop-the-world" * procedures!</b> * </p> */ private void initNewPage() { final Long newId = nextPageId++; final DataPage newPage = new DataPage(this, newId, maxLogicalPageSize, 0, new ConcurrentHashMap<>(), false); if (!newPages.isEmpty()) { throw new IllegalStateException("invalid new page initialization, other new pages already exist: " + newPages.keySet()); } newPages.put(newId, newPage); pages.put(newId, newPage); /* From this moment on the page has been published */ /* The lock is needed to block other threads up to this point */ currentDirtyRecordsPage.set(newId); } @Override public void unload(long pageId) { pages.computeIfPresent(pageId, (k, remove) -> { unloadedPagesCount.increment(); LOGGER.log(Level.FINER, "table {0} removed page {1}, {2}", new Object[]{table.name, pageId, remove.getUsedMemory() / (1024 * 1024) + " MB"}); if (!remove.readonly) { flushNewPage(remove, Collections.emptyMap()); LOGGER.log(Level.FINER, "table {0} remove and save 'new' page {1}, {2}", new Object[]{table.name, remove.pageId, remove.getUsedMemory() / (1024 * 1024) + " MB"}); } else { LOGGER.log(Level.FINER, "table {0} unload page {1}, {2}", new Object[]{table.name, pageId, remove.getUsedMemory() / (1024 * 1024) + " MB"}); } return null; }); } /** * Remove the page from {@link #newPages}, set it as "unloaded" and write it to disk * <p> * Add as much spare data as possible to fillup the page. If added must change key to page pointers too for spare * data * </p> * * @param page new page to flush * @param spareData old spare data to fit in the new page if possible * @return spare memory size used (and removed) */ private long flushNewPage(DataPage page, Map<Bytes, Record> spareData) { /* Set the new page as a fully active page */ pageSet.pageCreated(page.pageId, page); /* Remove it from "new" pages */ newPages.remove(page.pageId); /* * We need to keep the page lock just to write the unloaded flag... after that write any other * thread that check the page will avoid writes (thus using page data is safe) */ final Lock lock = page.pageLock.writeLock(); lock.lock(); try { page.unloaded = true; } finally { lock.unlock(); } long usedMemory = page.getUsedMemory(); /* Flag to enable spare data addition to currently flushed page */ boolean add = true; final Iterator<Record> records = spareData.values().iterator(); while (add && records.hasNext()) { Record record = records.next(); add = page.put(record); if (add) { keyToPage.put(record.key, page.pageId); records.remove(); } } long spareUsedMemory = page.getUsedMemory() - usedMemory; dataStorageManager.writePage(tableSpaceUUID, table.uuid, page.pageId, page.data.values()); return spareUsedMemory; } private LockHandle lockForWrite(Bytes key, Transaction transaction) { if (transaction != null) { LockHandle lock = transaction.lookupLock(table.name, key); if (lock != null) { if (lock.write) { // transaction already locked the key for writes return lock; } else { // transaction already locked the key, but we need to upgrade the lock locksManager.releaseLock(lock); transaction.unregisterUpgradedLocksOnTable(table.name, lock); lock = locksManager.acquireWriteLockForKey(key); transaction.registerLockOnTable(this.table.name, lock); return lock; } } else { lock = locksManager.acquireWriteLockForKey(key); transaction.registerLockOnTable(this.table.name, lock); return lock; } } else { return locksManager.acquireWriteLockForKey(key); } } private LockHandle lockForRead(Bytes key, Transaction transaction) { if (transaction != null) { LockHandle lock = transaction.lookupLock(table.name, key); if (lock != null) { // transaction already locked the key return lock; } else { lock = locksManager.acquireReadLockForKey(key); transaction.registerLockOnTable(this.table.name, lock); return lock; } } else { return locksManager.acquireReadLockForKey(key); } } private StatementExecutionResult executeInsert(InsertStatement insert, Transaction transaction, StatementEvaluationContext context) throws StatementExecutionException, DataStorageManagerException { /* an insert can succeed only if the row is valid and the "keys" structure does not contain the requested key the insert will add the row in the 'buffer' without assigning a page to it locks: the insert uses global 'insert' lock on the table the insert will update the 'maxKey' for auto_increment primary keys */ Bytes key = new Bytes(insert.getKeyFunction().computeNewValue(null, context, tableContext)); byte[] value = insert.getValuesFunction().computeNewValue(new Record(key, null), context, tableContext); final long size = DataPage.estimateEntrySize(key, value); if (size > maxLogicalPageSize) { throw new RecordTooBigException("New record " + key + " is to big to be inserted: size " + size + ", max size " + maxLogicalPageSize); } LockHandle lock = lockForWrite(key, transaction); try { if (transaction != null) { if (transaction.recordDeleted(table.name, key)) { // OK, INSERT on a DELETED record inside this transaction } else if (transaction.recordInserted(table.name, key) != null) { // ERROR, INSERT on a INSERTED record inside this transaction throw new DuplicatePrimaryKeyException(key, "key " + key + ", decoded as " + RecordSerializer.deserializePrimaryKey(key.data, table) + ", already exists in table " + table.name + " inside transaction " + transaction.transactionId); } else if (keyToPage.containsKey(key)) { throw new DuplicatePrimaryKeyException(key, "key " + key + ", decoded as " + RecordSerializer.deserializePrimaryKey(key.data, table) + ", already exists in table " + table.name + " during transaction " + transaction.transactionId); } } else if (keyToPage.containsKey(key)) { throw new DuplicatePrimaryKeyException(key, "key " + key + ", decoded as " + RecordSerializer.deserializePrimaryKey(key.data, table) + ", already exists in table " + table.name); } LogEntry entry = LogEntryFactory.insert(table, key.data, value, transaction); CommitLogResult pos = log.log(entry, entry.transactionId <= 0); apply(pos, entry, false); return new DMLStatementExecutionResult(entry.transactionId, 1, key, insert.isReturnValues() ? Bytes.from_array(value) : null); } catch (LogNotAvailableException err) { throw new StatementExecutionException(err); } finally { if (transaction == null) { locksManager.releaseWriteLockForKey(key, lock); } } } @SuppressWarnings("serial") private static class ExitLoop extends RuntimeException { private final boolean continueWithTransactionData; public ExitLoop(boolean continueWithTransactionData) { this.continueWithTransactionData = continueWithTransactionData; } } private static class ScanResultOperation { public void accept(Record record) throws StatementExecutionException, DataStorageManagerException, LogNotAvailableException { } public void beginNewRecordsInTransactionBlock() { } } private StatementExecutionResult executeUpdate(UpdateStatement update, Transaction transaction, StatementEvaluationContext context) throws StatementExecutionException, DataStorageManagerException { AtomicInteger updateCount = new AtomicInteger(); Holder<Bytes> lastKey = new Holder<>(); Holder<byte[]> lastValue = new Holder<>(); /* an update can succeed only if the row is valid, the key is contains in the "keys" structure the update will simply override the value of the row, assigning a null page to the row the update can have a 'where' predicate which is to be evaluated against the decoded row, the update will be executed only if the predicate returns boolean 'true' value (CAS operation) locks: the update uses a lock on the the key */ RecordFunction function = update.getFunction(); long transactionId = transaction != null ? transaction.transactionId : 0; Predicate predicate = update.getPredicate(); ScanStatement scan = new ScanStatement(table.tablespace, table, predicate); accessTableData(scan, context, new ScanResultOperation() { @Override public void accept(Record actual) throws StatementExecutionException, LogNotAvailableException, DataStorageManagerException { byte[] newValue = function.computeNewValue(actual, context, tableContext); final long size = DataPage.estimateEntrySize(actual.key, newValue); if (size > maxLogicalPageSize) { throw new RecordTooBigException("New version of record " + actual.key + " is to big to be update: new size " + size + ", actual size " + DataPage.estimateEntrySize(actual) + ", max size " + maxLogicalPageSize); } LogEntry entry = LogEntryFactory.update(table, actual.key.data, newValue, transaction); CommitLogResult pos = log.log(entry, entry.transactionId <= 0); apply(pos, entry, false); lastKey.value = actual.key; lastValue.value = newValue; updateCount.incrementAndGet(); } }, transaction, true, true); return new DMLStatementExecutionResult(transactionId, updateCount.get(), lastKey.value, update.isReturnValues() ? (lastValue.value != null ? Bytes.from_array(lastValue.value) : null) : null); } private StatementExecutionResult executeDelete(DeleteStatement delete, Transaction transaction, StatementEvaluationContext context) throws StatementExecutionException, DataStorageManagerException { AtomicInteger updateCount = new AtomicInteger(); Holder<Bytes> lastKey = new Holder<>(); Holder<byte[]> lastValue = new Holder<>(); long transactionId = transaction != null ? transaction.transactionId : 0; Predicate predicate = delete.getPredicate(); ScanStatement scan = new ScanStatement(table.tablespace, table, predicate); accessTableData(scan, context, new ScanResultOperation() { @Override public void accept(Record actual) throws StatementExecutionException, LogNotAvailableException, DataStorageManagerException { LogEntry entry = LogEntryFactory.delete(table, actual.key.data, transaction); CommitLogResult pos = log.log(entry, entry.transactionId <= 0); apply(pos, entry, false); lastKey.value = actual.key; lastValue.value = actual.value.data; updateCount.incrementAndGet(); } }, transaction, true, true); return new DMLStatementExecutionResult(transactionId, updateCount.get(), lastKey.value, delete.isReturnValues() ? (lastValue.value != null ? Bytes.from_array(lastValue.value) : null) : null); } private StatementExecutionResult executeTruncate(TruncateTableStatement truncate, Transaction transaction, StatementEvaluationContext context) throws StatementExecutionException, DataStorageManagerException { if (transaction != null) { throw new StatementExecutionException("TRUNCATE TABLE cannot be executed within the context of a Transaction"); } try { long estimatedSize = keyToPage.size(); LogEntry entry = LogEntryFactory.truncate(table, null); CommitLogResult pos = log.log(entry, entry.transactionId <= 0); apply(pos, entry, false); return new DMLStatementExecutionResult(0, estimatedSize > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) estimatedSize, null, null); } catch (LogNotAvailableException error) { throw new StatementExecutionException(error); } } private void applyTruncate() throws DataStorageManagerException { if (createdInTransaction > 0) { throw new DataStorageManagerException("TRUNCATE TABLE cannot be executed on an uncommitted table"); } if (checkPointRunning) { throw new DataStorageManagerException("TRUNCATE TABLE cannot be executed during a checkpoint"); } if (tableSpaceManager.isTransactionRunningOnTable(table.name)) { throw new DataStorageManagerException("TRUNCATE TABLE cannot be executed table " + table.name + ": at least one transaction is pending on it"); } Map<String, AbstractIndexManager> indexes = tableSpaceManager.getIndexesOnTable(table.name); if (indexes != null) { for (AbstractIndexManager index : indexes.values()) { if (!index.isAvailable()) { throw new DataStorageManagerException("index " + index.getIndexName() + " in not full available. Cannot TRUNCATE table " + table.name); } } } /* Do not unload the current working page not known to replacement policy */ final long currentDirtyPageId = currentDirtyRecordsPage.get(); final List<DataPage> unload = pages.values().stream() .filter(page -> page.pageId != currentDirtyPageId) .collect(Collectors.toList()); pageReplacementPolicy.remove(unload); pageSet.truncate(); pages.clear(); newPages.clear(); initNewPage(); locksManager.clear(); keyToPage.truncate(); if (indexes != null) { for (AbstractIndexManager index : indexes.values()) { index.truncate(); } } } @Override public void onTransactionCommit(Transaction transaction, boolean recovery) throws DataStorageManagerException { if (transaction == null) { throw new DataStorageManagerException("transaction cannot be null"); } boolean forceFlushTableData = false; if (createdInTransaction > 0) { if (transaction.transactionId != createdInTransaction) { throw new DataStorageManagerException("this tableManager is available only on transaction " + createdInTransaction); } createdInTransaction = 0; forceFlushTableData = true; } checkpointLock.readLock().lock(); try { Map<Bytes, Record> changedRecords = transaction.changedRecords.get(table.name); // transaction is still holding locks on each record, so we can change records Map<Bytes, Record> newRecords = transaction.newRecords.get(table.name); if (newRecords != null) { for (Record record : newRecords.values()) { applyInsert(record.key, record.value, true); } } if (changedRecords != null) { for (Record r : changedRecords.values()) { applyUpdate(r.key, r.value); } } Set<Bytes> deletedRecords = transaction.deletedRecords.get(table.name); if (deletedRecords != null) { for (Bytes key : deletedRecords) { applyDelete(key); } } } finally { checkpointLock.readLock().unlock(); } transaction.releaseLocksOnTable(table.name, locksManager); if (forceFlushTableData) { LOGGER.log(Level.SEVERE, "forcing local checkpoint, table " + table.name + " will be visible to all transactions now"); checkpoint(false); } } @Override public void onTransactionRollback(Transaction transaction) { transaction.releaseLocksOnTable(table.name, locksManager); } @Override public void apply(CommitLogResult writeResult, LogEntry entry, boolean recovery) throws DataStorageManagerException, LogNotAvailableException { if (recovery) { if (writeResult.deferred) { throw new DataStorageManagerException("impossibile to have a deferred CommitLogResult during recovery"); } LogSequenceNumber position = writeResult.getLogSequenceNumber(); if (dumpLogSequenceNumber != null && !position.after(dumpLogSequenceNumber)) { // in "restore mode" the 'position" parameter is from the 'old' transaction log Transaction transaction = null; if (entry.transactionId > 0) { transaction = tableSpaceManager.getTransaction(entry.transactionId); } if (transaction != null) { LOGGER.log(Level.FINER, "{0}.{1} keep {2} at {3}, table restored from position {4}, it belongs to transaction {5} which was in progress during the dump of the table", new Object[]{table.tablespace, table.name, entry, position, dumpLogSequenceNumber, entry.transactionId}); } else { LOGGER.log(Level.FINER, "{0}.{1} skip {2} at {3}, table restored from position {4}", new Object[]{table.tablespace, table.name, entry, position, dumpLogSequenceNumber}); return; } } else if (!position.after(bootSequenceNumber)) { // recovery mode Transaction transaction = null; if (entry.transactionId > 0) { transaction = tableSpaceManager.getTransaction(entry.transactionId); } if (transaction != null) { LOGGER.log(Level.FINER, "{0}.{1} keep {2} at {3}, table booted at {4}, it belongs to transaction {5} which was in progress during the flush of the table", new Object[]{table.tablespace, table.name, entry, position, bootSequenceNumber, entry.transactionId}); } else { LOGGER.log(Level.FINER, "{0}.{1} skip {2} at {3}, table booted at {4}", new Object[]{table.tablespace, table.name, entry, position, bootSequenceNumber}); return; } } } switch (entry.type) { case LogEntryType.DELETE: { // remove the record from the set of existing records Bytes key = new Bytes(entry.key); if (entry.transactionId > 0) { Transaction transaction = tableSpaceManager.getTransaction(entry.transactionId); if (transaction == null) { throw new DataStorageManagerException("no such transaction " + entry.transactionId); } transaction.registerDeleteOnTable(this.table.name, key, writeResult); } else { applyDelete(key); } break; } case LogEntryType.UPDATE: { Bytes key = new Bytes(entry.key); Bytes value = new Bytes(entry.value); if (entry.transactionId > 0) { Transaction transaction = tableSpaceManager.getTransaction(entry.transactionId); if (transaction == null) { throw new DataStorageManagerException("no such transaction " + entry.transactionId); } transaction.registerRecordUpdate(this.table.name, key, value, writeResult); } else { applyUpdate(key, value); } break; } case LogEntryType.INSERT: { Bytes key = new Bytes(entry.key); Bytes value = new Bytes(entry.value); if (entry.transactionId > 0) { Transaction transaction = tableSpaceManager.getTransaction(entry.transactionId); if (transaction == null) { throw new DataStorageManagerException("no such transaction " + entry.transactionId); } transaction.registerInsertOnTable(table.name, key, value, writeResult); } else { applyInsert(key, value, false); } break; } case LogEntryType.TRUNCATE_TABLE: { applyTruncate(); } ; break; default: throw new IllegalArgumentException("unhandled entry type " + entry.type); } } private void applyDelete(Bytes key) throws DataStorageManagerException { /* This could be a normal or a temporary modifiable page */ final Long pageId = keyToPage.remove(key); if (pageId == null) { throw new IllegalStateException("corrupted transaction log: key " + key + " is not present in table " + table.name); } if (LOGGER.isLoggable(Level.FINEST)) LOGGER.log(Level.FINEST, "Deleted key " + key + " from page " + pageId); /* * We'll try to remove the record if in a writable page, otherwise we'll simply set the old page * as dirty. */ final Map<String, AbstractIndexManager> indexes = tableSpaceManager.getIndexesOnTable(table.name); /* * When index is enabled we need the old value to update them, we'll force the page load only if that * record is really needed. */ final DataPage page; final Record previous; if (indexes == null) { /* We don't need the page if isn't loaded or isn't a mutable new page */ page = newPages.get(pageId); previous = null; if (page != null) { pageReplacementPolicy.pageHit(page); } } else { /* We really need the page for update index old values */ page = loadPageToMemory(pageId, false); previous = page.get(key); if (previous == null) { throw new RuntimeException("deleted record at " + key + " was not found?"); } } if (page == null || page.readonly) { /* Unloaded or immutable, set it as dirty */ pageSet.setPageDirty(pageId, previous); } else { /* Mutable page, need to check if still modifiable or already unloaded */ final Lock lock = page.pageLock.readLock(); lock.lock(); try { if (page.unloaded) { /* Unfortunately unloaded, set it as dirty */ pageSet.setPageDirty(pageId, previous); } else { /* We can modify the page directly */ page.remove(key); } } finally { lock.unlock(); } } if (indexes != null) { /* If there are indexes e have already forced a page load and previous record has been loaded */ DataAccessor values = previous.getDataAccessor(table); for (AbstractIndexManager index : indexes.values()) { index.recordDeleted(key, values); } } } private void applyUpdate(Bytes key, Bytes value) throws DataStorageManagerException { /* * New record to be updated, it will always updated if there aren't errors thus is simpler to create * the record now */ final Record record = new Record(key, value); /* This could be a normal or a temporary modifiable page */ final Long prevPageId = keyToPage.get(key); if (prevPageId == null) { throw new IllegalStateException("corrupted transaction log: key " + key + " is not present in table " + table.name); } /* * We'll try to replace the record if in a writable page, otherwise we'll simply set the old page * as dirty and continue like a normal insertion */ final Map<String, AbstractIndexManager> indexes = tableSpaceManager.getIndexesOnTable(table.name); /* * When index is enabled we need the old value to update them, we'll force the page load only if that * record is really needed. */ final DataPage prevPage; final Record previous; boolean insertedInSamePage = false; if (indexes == null) { /* We don't need the page if isn't loaded or isn't a mutable new page*/ prevPage = newPages.get(prevPageId); previous = null; if (prevPage != null) { pageReplacementPolicy.pageHit(prevPage); } } else { /* We really need the page for update index old values */ prevPage = loadPageToMemory(prevPageId, false); previous = prevPage.get(key); if (previous == null) { throw new RuntimeException("updated record at " + key + " was not found?"); } } if (prevPage == null || prevPage.readonly) { /* Unloaded or immutable, set it as dirty */ pageSet.setPageDirty(prevPageId, previous); } else { /* Mutable page, need to check if still modifiable or already unloaded */ final Lock lock = prevPage.pageLock.readLock(); lock.lock(); try { if (prevPage.unloaded) { /* Unfortunately unloaded, set it as dirty */ pageSet.setPageDirty(prevPageId, previous); } else { /* We can try to modify the page directly */ insertedInSamePage = prevPage.put(record); } } finally { lock.unlock(); } } /* Insertion page */ Long insertionPageId; if (insertedInSamePage) { /* Inserted in temporary mutable previous page, no need to alter keyToPage too: no record page change */ insertionPageId = prevPageId; } else { /* Do real insertion */ insertionPageId = currentDirtyRecordsPage.get(); while (true) { final DataPage newPage = newPages.get(insertionPageId); if (newPage != null) { pageReplacementPolicy.pageHit(newPage); /* The temporary memory page could have been unloaded and loaded again in meantime */ if (!newPage.readonly) { /* Mutable page, need to check if still modifiable or already unloaded */ final Lock lock = newPage.pageLock.readLock(); lock.lock(); try { if (!newPage.unloaded) { /* We can try to modify the page directly */ insertedInSamePage = newPage.put(record); if (insertedInSamePage) { break; } } } finally { lock.unlock(); } } } /* Try allocate a new page if no already done */ insertionPageId = allocateLivePage(insertionPageId); } /* Update the value on keyToPage */ keyToPage.put(key, insertionPageId); } if (LOGGER.isLoggable(Level.FINEST)) LOGGER.log(Level.FINEST, "Updated key " + key + " from page " + prevPageId + " to page " + insertionPageId); if (indexes != null) { /* If there are indexes e have already forced a page load and previous record has been loaded */ DataAccessor prevValues = previous.getDataAccessor(table); DataAccessor newValues = record.getDataAccessor(table); for (AbstractIndexManager index : indexes.values()) { index.recordUpdated(key, prevValues, newValues); } } } @Override public void dropTableData() throws DataStorageManagerException { dataStorageManager.dropTable(tableSpaceUUID, table.uuid); } @Override public void scanForIndexRebuild(Consumer<Record> records) throws DataStorageManagerException { LocalScanPageCache localPageCache = new LocalScanPageCache(); Consumer<Map.Entry<Bytes, Long>> scanExecutor = (Map.Entry<Bytes, Long> entry) -> { Bytes key = entry.getKey(); LockHandle lock = lockForRead(key, null); try { Long pageId = entry.getValue(); if (pageId != null) { Record record = fetchRecord(key, pageId, localPageCache); if (record != null) { records.accept(record); } } } catch (DataStorageManagerException | StatementExecutionException error) { throw new RuntimeException(error); } finally { locksManager.releaseReadLockForKey(key, lock); } }; Stream<Map.Entry<Bytes, Long>> scanner = keyToPage.scanner(null, StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), tableContext, null); scanner.forEach(scanExecutor); } @Override public void dump(LogSequenceNumber sequenceNumber, FullTableScanConsumer receiver) throws DataStorageManagerException { dataStorageManager.fullTableScan(tableSpaceUUID, table.uuid, sequenceNumber, receiver); } public void writeFromDump(List<Record> record) throws DataStorageManagerException { LOGGER.log(Level.SEVERE, table.name + " received " + record.size() + " records"); checkpointLock.readLock().lock(); try { for (Record r : record) { applyInsert(r.key, r.value, false); } } finally { checkpointLock.readLock().unlock(); } } private void rebuildNextPrimaryKeyValue() throws DataStorageManagerException { LOGGER.log(Level.SEVERE, "rebuildNextPrimaryKeyValue"); Stream<Entry<Bytes, Long>> scanner = keyToPage.scanner(null, StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), tableContext, null); scanner.forEach((Entry<Bytes, Long> t) -> { Bytes key = t.getKey(); long pk_logical_value; if (table.getColumn(table.primaryKey[0]).type == ColumnTypes.INTEGER) { pk_logical_value = key.to_int(); } else { pk_logical_value = key.to_long(); } nextPrimaryKeyValue.accumulateAndGet(pk_logical_value + 1, EnsureLongIncrementAccumulator.INSTANCE); }); LOGGER.log(Level.SEVERE, "rebuildNextPrimaryKeyValue, newPkValue : " + nextPrimaryKeyValue.get()); } private void applyInsert(Bytes key, Bytes value, boolean onTransaction) throws DataStorageManagerException { if (table.auto_increment) { // the next auto_increment value MUST be greater than every other explict value long pk_logical_value; if (table.getColumn(table.primaryKey[0]).type == ColumnTypes.INTEGER) { pk_logical_value = key.to_int(); } else { pk_logical_value = key.to_long(); } nextPrimaryKeyValue.accumulateAndGet(pk_logical_value + 1, EnsureLongIncrementAccumulator.INSTANCE); } /* * New record to be added, it will always added if there aren't DataStorageManagerException thus is * simpler to create the record now */ final Record record = new Record(key, value); /* Normally we expect this value null or pointing to a temporary modifiable page */ final Long prevPageId = keyToPage.get(key); final Map<String, AbstractIndexManager> indexes = tableSpaceManager.getIndexesOnTable(table.name); /* * When index is enabled we need the old value to update them, we'll force the page load only if that * record is really needed. */ final DataPage prevPage; final Record previous; boolean insertedInSamePage = false; if (prevPageId != null) { /* Very strage but possible inside a transaction which executes DELETE THEN INSERT */ if (!onTransaction) { throw new DataStorageManagerException("new record " + key + " already present in keyToPage?"); } if (indexes == null) { /* We don't need the page if isn't loaded or isn't a mutable new page*/ prevPage = newPages.get(prevPageId); previous = null; if (prevPage != null) { pageReplacementPolicy.pageHit(prevPage); } } else { /* We really need the page for update index old values */ prevPage = loadPageToMemory(prevPageId, false); previous = prevPage.get(key); if (previous == null) { throw new RuntimeException("insert upon delete record at " + key + " was not found?"); } } if (prevPage == null || prevPage.readonly) { /* Unloaded or immutable, set it as dirty */ pageSet.setPageDirty(prevPageId, previous); } else { /* Mutable page, need to check if still modifiable or already unloaded */ final Lock lock = prevPage.pageLock.readLock(); lock.lock(); try { if (prevPage.unloaded) { /* Unfortunately unloaded, set it as dirty */ pageSet.setPageDirty(prevPageId, previous); } else { /* We can try to modify the page directly */ insertedInSamePage = prevPage.put(record); } } finally { lock.unlock(); } } } else { /* * Initialize previous record to null... Non really needed but otherwise compiler cannot compile * indexing instructions below. */ previous = null; } /* Insertion page */ Long insertionPageId; if (insertedInSamePage) { /* Inserted in temporary mutable previous page, no need to alter keyToPage too: no record page change */ insertionPageId = prevPageId; } else { /* Do real insertion */ insertionPageId = currentDirtyRecordsPage.get(); while (true) { final DataPage newPage = newPages.get(insertionPageId); if (newPage != null) { pageReplacementPolicy.pageHit(newPage); /* The temporary memory page could have been unloaded and loaded again in meantime */ if (!newPage.readonly) { /* Mutable page, need to check if still modifiable or already unloaded */ final Lock lock = newPage.pageLock.readLock(); lock.lock(); try { if (!newPage.unloaded) { /* We can try to modify the page directly */ insertedInSamePage = newPage.put(record); if (insertedInSamePage) { break; } } } finally { lock.unlock(); } } } /* Try allocate a new page if no already done */ insertionPageId = allocateLivePage(insertionPageId); } /* Insert/update the value on keyToPage */ keyToPage.put(key, insertionPageId); } if (LOGGER.isLoggable(Level.FINEST)) { if (prevPageId == null) LOGGER.log(Level.FINEST, "Inserted key " + key + " into page " + insertionPageId); else LOGGER.log(Level.FINEST, "Inserted key " + key + " into page " + insertionPageId + " previously was in page " + prevPageId); } if (indexes != null) { if (previous == null) { /* Standard insert */ DataAccessor values = record.getDataAccessor(table); for (AbstractIndexManager index : indexes.values()) { index.recordInserted(key, values); } } else { /* If there is a previous page this is a delete and insert, we really need to update indexes * from old "deleted" values to the new ones. Previus record has already been loaded */ DataAccessor prevValues = previous.getDataAccessor(table); DataAccessor newValues = record.getDataAccessor(table); for (AbstractIndexManager index : indexes.values()) { index.recordUpdated(key, prevValues, newValues); } } } } @Override public void flush() throws DataStorageManagerException { TableCheckpoint checkpoint = checkpoint(false); if (checkpoint != null) { for (PostCheckpointAction action : checkpoint.actions) { action.run(); } } } @Override public void close() { dataStorageManager.releaseKeyToPageMap(tableSpaceUUID, table.uuid, keyToPage); } private StatementExecutionResult executeGet(GetStatement get, Transaction transaction, StatementEvaluationContext context) throws StatementExecutionException, DataStorageManagerException { Bytes key = new Bytes(get.getKey().computeNewValue(null, context, tableContext)); Predicate predicate = get.getPredicate(); boolean requireLock = get.isRequireLock(); long transactionId = transaction != null ? transaction.transactionId : 0; LockHandle lock = (transaction != null || requireLock) ? lockForRead(key, transaction) : null; try { if (transaction != null) { if (transaction.recordDeleted(table.name, key)) { return GetResult.NOT_FOUND(transactionId); } Record loadedInTransaction = transaction.recordUpdated(table.name, key); if (loadedInTransaction != null) { if (predicate != null && !predicate.evaluate(loadedInTransaction, context)) { return GetResult.NOT_FOUND(transactionId); } return new GetResult(transactionId, loadedInTransaction, table); } loadedInTransaction = transaction.recordInserted(table.name, key); if (loadedInTransaction != null) { if (predicate != null && !predicate.evaluate(loadedInTransaction, context)) { return GetResult.NOT_FOUND(transactionId); } return new GetResult(transactionId, loadedInTransaction, table); } } Long pageId = keyToPage.get(key); if (pageId == null) { return GetResult.NOT_FOUND(transactionId); } Record loaded = fetchRecord(key, pageId, null); if (loaded == null || (predicate != null && !predicate.evaluate(loaded, context))) { return GetResult.NOT_FOUND(transactionId); } return new GetResult(transactionId, loaded, table); } finally { if (transaction == null && lock != null) { locksManager.releaseReadLockForKey(key, lock); } } } private DataPage temporaryLoadPageToMemory(Long pageId) throws DataStorageManagerException { long _start = System.currentTimeMillis(); List<Record> page; maxCurrentPagesLoads.acquireUninterruptibly(); try { page = dataStorageManager.readPage(tableSpaceUUID, table.uuid, pageId); } catch (DataPageDoesNotExistException ex) { return null; } finally { maxCurrentPagesLoads.release(); } long _io = System.currentTimeMillis(); DataPage result = buildImmutableDataPage(pageId, page); if (LOGGER.isLoggable(Level.FINEST)) { long _stop = System.currentTimeMillis(); LOGGER.log(Level.FINEST, "tmp table " + table.name + "," + "loaded " + result.size() + " records from page " + pageId + " in " + (_stop - _start) + " ms" + ", (" + (_io - _start) + " ms read)"); } return result; } private DataPage loadPageToMemory(Long pageId, boolean recovery) throws DataStorageManagerException { DataPage result = pages.get(pageId); if (result != null) { pageReplacementPolicy.pageHit(result); return result; } long _start = System.currentTimeMillis(); long _ioAndLock = 0; AtomicBoolean computed = new AtomicBoolean(); try { result = pages.computeIfAbsent(pageId, (id) -> { try { computed.set(true); List<Record> page; maxCurrentPagesLoads.acquireUninterruptibly(); try { page = dataStorageManager.readPage(tableSpaceUUID, table.uuid, pageId); } finally { maxCurrentPagesLoads.release(); } loadedPagesCount.increment(); return buildImmutableDataPage(pageId, page); } catch (DataStorageManagerException err) { throw new RuntimeException(err); } }); if (computed.get()) { _ioAndLock = System.currentTimeMillis(); final Page.Metadata unload = pageReplacementPolicy.add(result); if (unload != null) { unload.owner.unload(unload.pageId); } } } catch (RuntimeException error) { if (error.getCause() != null) { Throwable cause = error.getCause(); if (cause instanceof DataStorageManagerException) { if (cause instanceof DataPageDoesNotExistException) { return null; } throw (DataStorageManagerException) cause; } } throw new DataStorageManagerException(error); } if (computed.get()) { long _stop = System.currentTimeMillis(); LOGGER.log(Level.FINE, "table " + table.name + "," + "loaded " + result.size() + " records from page " + pageId + " in " + (_stop - _start) + " ms" + ", (" + (_ioAndLock - _start) + " ms read + plock" + ", " + (_stop - _ioAndLock) + " ms unlock)"); } return result; } private DataPage buildImmutableDataPage(long pageId, List<Record> page) { Map<Bytes, Record> newPageMap = new HashMap<>(); long estimatedPageSize = 0; for (Record r : page) { newPageMap.put(r.key, r); estimatedPageSize += DataPage.estimateEntrySize(r); } return buildImmutableDataPage(pageId, newPageMap, estimatedPageSize); } private DataPage buildImmutableDataPage(long pageId, Map<Bytes, Record> page, long estimatedPageSize) { DataPage res = new DataPage(this, pageId, maxLogicalPageSize, estimatedPageSize, page, true); return res; } @Override public TableCheckpoint fullCheckpoint(boolean pin) throws DataStorageManagerException { return checkpoint(Double.NEGATIVE_INFINITY, fillThreshold, Long.MAX_VALUE, Long.MAX_VALUE, pin); } @Override public TableCheckpoint checkpoint(boolean pin) throws DataStorageManagerException { return checkpoint(dirtyThreshold, fillThreshold, checkpointTargetTime, compactionTargetTime, pin); } @Override public void unpinCheckpoint(LogSequenceNumber sequenceNumber) throws DataStorageManagerException { /* Unpin secondary indexes too */ final Map<String, AbstractIndexManager> indexes = tableSpaceManager.getIndexesOnTable(table.name); if (indexes != null) { for (AbstractIndexManager indexManager : indexes.values()) { // Checkpointed at the same position of current TableManager indexManager.unpinCheckpoint(sequenceNumber); } } keyToPage.unpinCheckpoint(sequenceNumber); dataStorageManager.unPinTableCheckpoint(tableSpaceUUID, table.uuid, sequenceNumber); } private static final class WeightedPage { public static final Comparator<WeightedPage> ASCENDING_ORDER = (a, b) -> Long.compare(a.weight, b.weight); public static final Comparator<WeightedPage> DESCENDING_ORDER = (a, b) -> Long.compare(b.weight, a.weight); private final Long pageId; private final long weight; public WeightedPage(Long pageId, long weight) { super(); this.pageId = pageId; this.weight = weight; } @Override public String toString() { return pageId + ":" + weight; } } /** * Sums two long values caring of overflows. Assumes that both values are positive! */ private static final long sumOverflowWise(long a, long b) { long total = a + b; return total < 0 ? Long.MAX_VALUE : total; } /** * * @param sequenceNumber * @param dirtyThreshold * @param fillThreshold * @param checkpointTargetTime checkpoint target max milliseconds * @param compactionTargetTime compaction target max milliseconds * @return * @throws DataStorageManagerException */ private TableCheckpoint checkpoint(double dirtyThreshold, double fillThreshold, long checkpointTargetTime, long compactionTargetTime, boolean pin) throws DataStorageManagerException { if (createdInTransaction > 0) { LOGGER.log(Level.SEVERE, "checkpoint for table " + table.name + " skipped," + "this table is created on transaction " + createdInTransaction + " which is not committed"); return null; } final long fillPageThreshold = (long) (fillThreshold * maxLogicalPageSize); final long dirtyPageThreshold = (long) (dirtyThreshold * maxLogicalPageSize); long start = System.currentTimeMillis(); long end; long getlock; long pageAnalysis; long dirtyPagesFlush; long smallPagesFlush; long newPagesFlush; long keytopagecheckpoint; long indexcheckpoint; long tablecheckpoint; final List<PostCheckpointAction> actions = new ArrayList<>(); TableCheckpoint result; checkpointLock.writeLock().lock(); try { LogSequenceNumber sequenceNumber = log.getLastSequenceNumber(); getlock = System.currentTimeMillis(); checkPointRunning = true; final long checkpointLimitInstant = sumOverflowWise(getlock, checkpointTargetTime); final Map<Long, DataPageMetaData> activePages = pageSet.getActivePages(); Map<Bytes, Record> buffer = new HashMap<>(); long bufferPageSize = 0; long flushedRecords = 0; final List<WeightedPage> flushingDirtyPages = new ArrayList<>(); final List<WeightedPage> flushingSmallPages = new ArrayList<>(); final List<Long> flushedPages = new ArrayList<>(); int flushedDirtyPages = 0; int flushedSmallPages = 0; for (Entry<Long, DataPageMetaData> ref : activePages.entrySet()) { final Long pageId = ref.getKey(); final DataPageMetaData metadata = ref.getValue(); final long dirt = metadata.dirt.sum(); /* * Check dirtiness (flush here even small pages if dirty. Small pages flush IGNORES dirty data * handling). */ if (dirt > 0 && (dirt >= dirtyPageThreshold || metadata.size <= fillPageThreshold)) { flushingDirtyPages.add(new WeightedPage(pageId, dirt)); continue; } /* Check emptiness (with a really dirty check to avoid to rewrite an unfillable page) */ if (metadata.size <= fillPageThreshold && maxLogicalPageSize - metadata.avgRecordSize >= fillPageThreshold) { flushingSmallPages.add(new WeightedPage(pageId, metadata.size)); continue; } } /* Clean dirtier first */ flushingDirtyPages.sort(WeightedPage.DESCENDING_ORDER); /* Clean smaller first */ flushingSmallPages.sort(WeightedPage.ASCENDING_ORDER); pageAnalysis = System.currentTimeMillis(); /* Rebuild dirty pages with only records to be kept */ for (WeightedPage weighted : flushingDirtyPages) { /* Page flushed */ flushedPages.add(weighted.pageId); ++flushedDirtyPages; final DataPage dataPage = pages.get(weighted.pageId); final Collection<Record> records; if (dataPage == null) { records = dataStorageManager.readPage(tableSpaceUUID, table.uuid, weighted.pageId); LOGGER.log(Level.FINEST, "loaded dirty page {0} on tmp buffer: {1} records", new Object[]{weighted.pageId, records.size()}); } else { records = dataPage.data.values(); } for (Record record : records) { /* Avoid the record if has been modified or deleted */ final Long currentPageId = keyToPage.get(record.key); if (currentPageId == null || !weighted.pageId.equals(currentPageId)) { continue; } /* Flush the page if it would exceed max page size */ if (bufferPageSize + DataPage.estimateEntrySize(record) > maxLogicalPageSize) { createImmutablePage(buffer, bufferPageSize); flushedRecords += buffer.size(); bufferPageSize = 0; /* Do not clean old buffer! It will used in generated pages to avoid too many copies! */ buffer = new HashMap<>(buffer.size()); } buffer.put(record.key, record); bufferPageSize += DataPage.estimateEntrySize(record); } /* Do not continue if we have used up all configured checkpoint time */ if (checkpointLimitInstant <= System.currentTimeMillis()) { break; } } dirtyPagesFlush = System.currentTimeMillis(); /* * If there is only one without additional data to add * rebuilding the page make no sense: is too probable to rebuild an identical page! */ if (flushingSmallPages.size() == 1 && buffer.isEmpty()) { boolean hasNewPagesData = newPages.values().stream().filter(p -> !p.isEmpty()).findAny().isPresent(); if (!hasNewPagesData) { flushingSmallPages.clear(); } } final long compactionLimitInstant = sumOverflowWise(dirtyPagesFlush, compactionTargetTime); /* Rebuild too small pages */ for (WeightedPage weighted : flushingSmallPages) { /* Page flushed */ flushedPages.add(weighted.pageId); ++flushedSmallPages; final DataPage dataPage = pages.get(weighted.pageId); final Collection<Record> records; if (dataPage == null) { records = dataStorageManager.readPage(tableSpaceUUID, table.uuid, weighted.pageId); LOGGER.log(Level.FINEST, "loaded small page {0} on tmp buffer: {1} records", new Object[]{weighted.pageId, records.size()}); } else { records = dataPage.data.values(); } for (Record record : records) { /* Flush the page if it would exceed max page size */ if (bufferPageSize + DataPage.estimateEntrySize(record) > maxLogicalPageSize) { createImmutablePage(buffer, bufferPageSize); flushedRecords += buffer.size(); bufferPageSize = 0; /* Do not clean old buffer! It will used in generated pages to avoid too many copies! */ buffer = new HashMap<>(buffer.size()); } buffer.put(record.key, record); bufferPageSize += DataPage.estimateEntrySize(record); } final long now = System.currentTimeMillis(); /* * Do not continue if we have used up all configured compaction or checkpoint time (but still compact at * least the smaller page (normally the leftover from last checkpoint) */ if (compactionLimitInstant <= now || checkpointLimitInstant <= now) { break; } } flushingSmallPages.clear(); smallPagesFlush = System.currentTimeMillis(); /* * Flush dirty records (and remaining records from previous step). * * Any newpage remaining here is unflushed and is not set as dirty (if "dirty" were unloaded!). * Just write the pages as they are. * * New empty pages won't be written */ long flushedNewPages = 0; for (DataPage dataPage : newPages.values()) { if (!dataPage.isEmpty()) { bufferPageSize -= flushNewPage(dataPage, buffer); ++flushedNewPages; flushedRecords += dataPage.size(); } } /* Flush remaining records */ if (!buffer.isEmpty()) { createImmutablePage(buffer, bufferPageSize); flushedRecords += buffer.size(); bufferPageSize = 0; /* Do not clean old buffer! It will used in generated pages to avoid too many copies! */ } newPagesFlush = System.currentTimeMillis(); LOGGER.log(Level.INFO, "checkpoint {0}, logpos {1}, flushed: {2} dirty pages, {3} small pages, {4} new pages, {5} records", new Object[]{table.name, sequenceNumber, flushedDirtyPages, flushedSmallPages, flushedNewPages, flushedRecords}); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "checkpoint {0}, logpos {1}, flushed pages: {2}", new Object[]{table.name, sequenceNumber, flushedPages.toString()}); } /* Checkpoint the key to page too */ actions.addAll(keyToPage.checkpoint(sequenceNumber, pin)); keytopagecheckpoint = System.currentTimeMillis(); /* Checkpoint secondary indexes too */ final Map<String, AbstractIndexManager> indexes = tableSpaceManager.getIndexesOnTable(table.name); if (indexes != null) { for (AbstractIndexManager indexManager : indexes.values()) { // Checkpoint at the same position of current TableManager actions.addAll(indexManager.checkpoint(sequenceNumber, pin)); } } indexcheckpoint = System.currentTimeMillis(); pageSet.checkpointDone(flushedPages); TableStatus tableStatus = new TableStatus(table.name, sequenceNumber, Bytes.from_long(nextPrimaryKeyValue.get()).data, nextPageId, pageSet.getActivePages()); actions.addAll(dataStorageManager.tableCheckpoint(tableSpaceUUID, table.uuid, tableStatus, pin)); tablecheckpoint = System.currentTimeMillis(); /* Writes done! Unloading and removing not needed pages and keys */ /* Remove flushed pages handled */ for (Long pageId : flushedPages) { final DataPage page = pages.remove(pageId); /* Current dirty record page isn't known to page replacement policy */ if (page != null && currentDirtyRecordsPage.get() != page.pageId) { pageReplacementPolicy.remove(page); } } /* * Can happen when at checkpoint start all pages are set as dirty or immutable (readonly or * unloaded) due do a deletion: all pages will be removed and no page will remain alive. */ if (newPages.isEmpty()) { /* Allocate live handles the correct policy load/unload of last dirty page */ allocateLivePage(currentDirtyRecordsPage.get()); } checkPointRunning = false; result = new TableCheckpoint(table.name, sequenceNumber, actions); end = System.currentTimeMillis(); LOGGER.log(Level.INFO, "checkpoint {0} finished, logpos {1}, {2} active pages, {3} dirty pages, " + "flushed {4} records, total time {5} ms", new Object[] {table.name, sequenceNumber, pageSet.getActivePagesCount(), pageSet.getDirtyPagesCount(), flushedRecords, Long.toString(end - start)}); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "checkpoint {0} finished, logpos {1}, pageSet: {2}", new Object[]{table.name, sequenceNumber, pageSet.toString()}); } } finally { checkpointLock.writeLock().unlock(); } long delta = end - start; if (delta > 1000) { long delta_lock = getlock - start; long delta_pageAnalysis = pageAnalysis - getlock; long delta_dirtyPagesFlush = dirtyPagesFlush - pageAnalysis; long delta_smallPagesFlush = smallPagesFlush - dirtyPagesFlush; long delta_newPagesFlush = newPagesFlush - smallPagesFlush; long delta_keytopagecheckpoint = keytopagecheckpoint - newPagesFlush; long delta_indexcheckpoint = indexcheckpoint - keytopagecheckpoint; long delta_tablecheckpoint = tablecheckpoint - indexcheckpoint; long delta_unload = end - keytopagecheckpoint; LOGGER.log(Level.INFO, "long checkpoint for {0}, time {1}", new Object[]{table.name, delta + " ms (" + delta_lock + "+" + delta_pageAnalysis + "+" + delta_dirtyPagesFlush + "+" + delta_smallPagesFlush + "+" + delta_newPagesFlush + "+" + delta_keytopagecheckpoint + "+" + delta_indexcheckpoint + "+" + delta_tablecheckpoint + "+" + delta_unload + ")"}); } return result; } @Override public DataScanner scan(ScanStatement statement, StatementEvaluationContext context, Transaction transaction) throws StatementExecutionException { boolean sorted = statement.getComparator() != null; boolean sortedByClusteredIndex = statement.getComparator() != null && statement.getComparator().isOnlyPrimaryKeyAndAscending() && keyToPage.isSortedAscending(); final Projection projection = statement.getProjection(); boolean applyProjectionDuringScan = !sorted && projection != null; MaterializedRecordSet recordSet; if (applyProjectionDuringScan) { recordSet = tableSpaceManager.getDbmanager().getRecordSetFactory() .createRecordSet(projection.getFieldNames(), projection.getColumns()); } else { recordSet = tableSpaceManager.getDbmanager().getRecordSetFactory() .createRecordSet(table.columnNames, table.columns); } ScanLimits limits = statement.getLimits(); int maxRows = limits == null ? 0 : limits.computeMaxRows(context); int offset = limits == null ? 0 : limits.getOffset(); boolean sortDone = false; if (maxRows > 0) { if (sortedByClusteredIndex) { // leverage the sorted nature of the clustered primary key index AtomicInteger remaining = new AtomicInteger(maxRows); if (offset > 0) { remaining.getAndAdd(offset); } accessTableData(statement, context, new ScanResultOperation() { private boolean inTransactionData; @Override public void beginNewRecordsInTransactionBlock() { inTransactionData = true; } @Override public void accept(Record record) throws StatementExecutionException { if (applyProjectionDuringScan) { DataAccessor tuple = projection.map(record.getDataAccessor(table), context); recordSet.add(tuple); } else { recordSet.add(record.getDataAccessor(table)); } if (!inTransactionData) { // we have scanned the table and kept top K record already sorted by the PK // we can exit now from the loop on the primary key // we have to keep all data from the transaction buffer, because it is not sorted // in the same order as the clustered index if (remaining.decrementAndGet() == 0) { // we want to receive transaction data uncommitted records too throw new ExitLoop(true); } } } }, transaction, false, false); // we have to sort data any way, because accessTableData will return partially sorted data sortDone = false; } else if (sorted) { InStreamTupleSorter sorter = new InStreamTupleSorter(offset + maxRows, statement.getComparator()); accessTableData(statement, context, new ScanResultOperation() { @Override public void accept(Record record) throws StatementExecutionException { if (applyProjectionDuringScan) { DataAccessor tuple = projection.map(record.getDataAccessor(table), context); sorter.collect(tuple); } else { sorter.collect(record.getDataAccessor(table)); } } }, transaction, false, false); sorter.flushToRecordSet(recordSet); sortDone = true; } else { // if no sort is present the limits can be applying during the scan and perform an early exit AtomicInteger remaining = new AtomicInteger(maxRows); if (offset > 0) { remaining.getAndAdd(offset); } accessTableData(statement, context, new ScanResultOperation() { @Override public void accept(Record record) throws StatementExecutionException { if (applyProjectionDuringScan) { DataAccessor tuple = projection.map(record.getDataAccessor(table), context); recordSet.add(tuple); } else { recordSet.add(record.getDataAccessor(table)); } if (remaining.decrementAndGet() == 0) { throw new ExitLoop(false); } } }, transaction, false, false); } } else { accessTableData(statement, context, new ScanResultOperation() { @Override public void accept(Record record) throws StatementExecutionException { if (applyProjectionDuringScan) { DataAccessor tuple = projection.map(record.getDataAccessor(table), context); recordSet.add(tuple); } else { recordSet.add(record.getDataAccessor(table)); } } }, transaction, false, false); } recordSet.writeFinished(); if (!sortDone) { recordSet.sort(statement.getComparator()); } recordSet.applyLimits(statement.getLimits(), context); if (!applyProjectionDuringScan) { recordSet.applyProjection(statement.getProjection(), context); } return new SimpleDataScanner(transaction != null ? transaction.transactionId : 0, recordSet); } private void accessTableData(ScanStatement statement, StatementEvaluationContext context, ScanResultOperation consumer, Transaction transaction, boolean lockRequired, boolean forWrite) throws StatementExecutionException { Predicate predicate = statement.getPredicate(); long _start = System.currentTimeMillis(); boolean acquireLock = transaction != null || forWrite || lockRequired; LocalScanPageCache lastPageRead = acquireLock ? null : new LocalScanPageCache(); try { IndexOperation indexOperation = predicate != null ? predicate.getIndexOperation() : null; boolean primaryIndexSeek = indexOperation instanceof PrimaryIndexSeek; AbstractIndexManager useIndex = getIndexForTbleAccess(indexOperation); BatchOrderedExecutor.Executor<Map.Entry<Bytes, Long>> scanExecutor = (List<Map.Entry<Bytes, Long>> batch) -> { for (Map.Entry<Bytes, Long> entry : batch) { Bytes key = entry.getKey(); boolean keep_lock = false; boolean already_locked = transaction != null && transaction.lookupLock(table.name, key) != null; LockHandle lock = acquireLock ? (forWrite ? lockForWrite(key, transaction) : lockForRead(key, transaction)) : null; try { if (transaction != null) { if (transaction.recordDeleted(table.name, key)) { // skip this record. inside current transaction it has been deleted continue; } Record record = transaction.recordUpdated(table.name, key); if (record != null) { // use current transaction version of the record if (predicate == null || predicate.evaluate(record, context)) { consumer.accept(record); keep_lock = true; } continue; } } Long pageId = entry.getValue(); if (pageId != null) { boolean pkFilterCompleteMatch = false; if (!primaryIndexSeek && predicate != null) { Predicate.PrimaryKeyMatchOutcome outcome = predicate.matchesRawPrimaryKey(key, context); if (outcome == Predicate.PrimaryKeyMatchOutcome.FAILED) { continue; } else if (outcome == Predicate.PrimaryKeyMatchOutcome.FULL_CONDITION_VERIFIED) { pkFilterCompleteMatch = true; } } Record record = fetchRecord(key, pageId, lastPageRead); if (record != null && (pkFilterCompleteMatch || predicate == null || predicate.evaluate(record, context))) { consumer.accept(record); keep_lock = true; } } } finally { // release the lock on the key if it did not match scan criteria if (transaction == null) { if (lock != null) { if (forWrite) { locksManager.releaseWriteLockForKey(key, lock); } else { locksManager.releaseReadLockForKey(key, lock); } } } else if (!keep_lock && !already_locked) { transaction.releaseLockOnKey(table.name, key, locksManager); } } } }; BatchOrderedExecutor<Map.Entry<Bytes, Long>> executor = new BatchOrderedExecutor<>(SORTED_PAGE_ACCESS_WINDOW_SIZE, scanExecutor, SORTED_PAGE_ACCESS_COMPARATOR); Stream<Map.Entry<Bytes, Long>> scanner = keyToPage.scanner(indexOperation, context, tableContext, useIndex); boolean exit = false; try { scanner.forEach(executor); executor.finish(); } catch (ExitLoop exitLoop) { exit = !exitLoop.continueWithTransactionData; if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "exit loop during scan {0}, started at {1}: {2}", new Object[]{statement, new java.sql.Timestamp(_start), exitLoop.toString()}); } } catch (final HerdDBInternalException error) { LOGGER.log(Level.SEVERE, "error during scan", error); if (error.getCause() instanceof StatementExecutionException) { throw (StatementExecutionException) error.getCause(); } else if (error.getCause() instanceof DataStorageManagerException) { throw (DataStorageManagerException) error.getCause(); } else if (error instanceof StatementExecutionException) { throw (StatementExecutionException) error; } else if (error instanceof DataStorageManagerException) { throw (DataStorageManagerException) error; } else { throw new StatementExecutionException(error); } } if (!exit && transaction != null) { consumer.beginNewRecordsInTransactionBlock(); Collection<Record> newRecordsForTable = transaction.getNewRecordsForTable(table.name); for (Record record : newRecordsForTable) { if (!transaction.recordDeleted(table.name, record.key) && (predicate == null || predicate.evaluate(record, context))) { consumer.accept(record); } } } } catch (ExitLoop exitLoop) { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "exit loop during scan {0}, started at {1}: {2}", new Object[]{statement, new java.sql.Timestamp(_start), exitLoop.toString()}); } } catch (StatementExecutionException err) { LOGGER.log(Level.SEVERE, "error during scan {0}, started at {1}: {2}", new Object[]{statement, new java.sql.Timestamp(_start), err.toString()}); throw err; } catch (HerdDBInternalException err) { LOGGER.log(Level.SEVERE, "error during scan {0}, started at {1}: {2}", new Object[]{statement, new java.sql.Timestamp(_start), err.toString()}); throw new StatementExecutionException(err); } } private AbstractIndexManager getIndexForTbleAccess(IndexOperation indexOperation) { AbstractIndexManager useIndex = null; if (indexOperation != null) { Map<String, AbstractIndexManager> indexes = tableSpaceManager.getIndexesOnTable(table.name); if (indexes != null) { useIndex = indexes.get(indexOperation.getIndexName()); if (useIndex != null && !useIndex.isAvailable()) { useIndex = null; } } } return useIndex; } @Override public List<Index> getAvailableIndexes() { Map<String, AbstractIndexManager> indexes = tableSpaceManager.getIndexesOnTable(table.name); if (indexes == null) { return Collections.emptyList(); } return indexes.values().stream().filter(AbstractIndexManager::isAvailable).map(AbstractIndexManager::getIndex) .collect(Collectors.toList()); } @Override public KeyToPageIndex getKeyToPageIndex() { return keyToPage; } private Record fetchRecord(Bytes key, Long pageId, LocalScanPageCache localScanPageCache) throws StatementExecutionException, DataStorageManagerException { int maxTrials = 2; while (true) { DataPage dataPage = fetchDataPage(pageId, localScanPageCache); if (dataPage != null) { Record record = dataPage.get(key); if (record != null) { return record; } } Long relocatedPageId = keyToPage.get(key); LOGGER.log(Level.SEVERE, table.name + " fetchRecord " + key + " failed," + "checkPointRunning:" + checkPointRunning + " pageId:" + pageId + " relocatedPageId:" + relocatedPageId); if (relocatedPageId == null) { // deleted LOGGER.log(Level.SEVERE, "table " + table.name + ", activePages " + pageSet.getActivePages() + ", record " + key + " deleted during data access"); return null; } pageId = relocatedPageId; if (maxTrials-- == 0) { throw new DataStorageManagerException("inconsistency! table " + table.name + " no record in memory for " + key + " page " + pageId + ", activePages " + pageSet.getActivePages() + " after many trials"); } } } private DataPage fetchDataPage(Long pageId, LocalScanPageCache localScanPageCache) throws DataStorageManagerException { DataPage dataPage; if (localScanPageCache == null || !ENABLE_LOCAL_SCAN_PAGE_CACHE || pages.containsKey(pageId)) { dataPage = loadPageToMemory(pageId, false); } else { if (pageId.equals(localScanPageCache.pageId)) { // same page needed twice dataPage = localScanPageCache.value; } else { // TODO: add good heuristics and choose whether to load // the page in the main buffer dataPage = pages.get(pageId); if (dataPage == null) { if (ThreadLocalRandom.current().nextInt(10) < 4) { // 25% of pages will be loaded to main buffer dataPage = loadPageToMemory(pageId, false); } else { // 75% of pages will be loaded only to current scan buffer dataPage = temporaryLoadPageToMemory(pageId); localScanPageCache.value = dataPage; localScanPageCache.pageId = pageId; } } else { pageReplacementPolicy.pageHit(dataPage); } } } return dataPage; } @Override public TableManagerStats getStats() { return stats; } @Override public long getNextPrimaryKeyValue() { return nextPrimaryKeyValue.get(); } @Override public boolean isSystemTable() { return false; } @Override public boolean isStarted() { return started; } @Override public void tableAltered(Table table, Transaction transaction) throws DDLException { // compute diff, if some column as been dropped we need to remove the value from each record List<String> droppedColumns = new ArrayList<>(); for (Column c : this.table.columns) { if (table.getColumn(c.name) == null) { droppedColumns.add(c.name); } } this.table = table; if (!droppedColumns.isEmpty()) { // no lock is necessary pages.values().forEach(p -> { p.data.values().forEach(r -> r.clearCache()); }); } if (this.table.auto_increment) { rebuildNextPrimaryKeyValue(); } } @Override public long getCreatedInTransaction() { return createdInTransaction; } private static final Comparator<Map.Entry<Bytes, Long>> SORTED_PAGE_ACCESS_COMPARATOR = (a, b) -> { return a.getValue().compareTo(b.getValue()); }; }
Avoid inutile keyToPage updates: cleanups
herddb-core/src/main/java/herddb/core/TableManager.java
Avoid inutile keyToPage updates: cleanups
<ide><path>erddb-core/src/main/java/herddb/core/TableManager.java <ide> try { <ide> if (!newPage.unloaded) { <ide> /* We can try to modify the page directly */ <del> insertedInSamePage = newPage.put(record); <del> <del> if (insertedInSamePage) { <add> if (newPage.put(record)) { <ide> break; <ide> } <ide> } <ide> try { <ide> if (!newPage.unloaded) { <ide> /* We can try to modify the page directly */ <del> insertedInSamePage = newPage.put(record); <del> <del> if (insertedInSamePage) { <add> if (newPage.put(record)) { <ide> break; <ide> } <ide> }
Java
apache-2.0
4b489e3aaa32ed6e98f782bb87832063161d7562
0
IHTSDO/snow-owl,IHTSDO/snow-owl,b2ihealthcare/snow-owl,IHTSDO/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl,IHTSDO/snow-owl,b2ihealthcare/snow-owl
/* * Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.core.propertytester; import org.eclipse.core.expressions.PropertyTester; import com.b2international.commons.platform.PlatformUtil; import com.b2international.snowowl.core.CoreActivator; /** * Property tester for development version test. Returns <code>true</code> if the running SnowOwl is a dev version, * return <code>false</code> in production environments or in server environments. * * @since 3.0 */ public class DevelopmentVersionPropertyTester extends PropertyTester { @Override public boolean test(final Object receiver, final String property, final Object[] args, final Object expectedValue) { String bundle = args.length > 0 ? (String) args[0] : CoreActivator.PLUGIN_ID; return PlatformUtil.isDevVersion(bundle); } }
core/com.b2international.snowowl.core/src/com/b2international/snowowl/core/propertytester/DevelopmentVersionPropertyTester.java
/* * Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.core.propertytester; import org.eclipse.core.expressions.PropertyTester; import com.b2international.commons.platform.PlatformUtil; import com.b2international.snowowl.core.CoreActivator; /** * Property tester for development version test. Returns <code>true</code> if the running SnowOwl is a dev version, * return <code>false</code> in production environments or in server environments. * * @since 3.0 */ public class DevelopmentVersionPropertyTester extends PropertyTester { @Override public boolean test(final Object receiver, final String property, final Object[] args, final Object expectedValue) { return PlatformUtil.isDevVersion(CoreActivator.PLUGIN_ID); } }
[dev] Parameterize development version property tester
core/com.b2international.snowowl.core/src/com/b2international/snowowl/core/propertytester/DevelopmentVersionPropertyTester.java
[dev] Parameterize development version property tester
<ide><path>ore/com.b2international.snowowl.core/src/com/b2international/snowowl/core/propertytester/DevelopmentVersionPropertyTester.java <ide> <ide> @Override <ide> public boolean test(final Object receiver, final String property, final Object[] args, final Object expectedValue) { <del> return PlatformUtil.isDevVersion(CoreActivator.PLUGIN_ID); <add> String bundle = args.length > 0 ? (String) args[0] : CoreActivator.PLUGIN_ID; <add> return PlatformUtil.isDevVersion(bundle); <ide> } <ide> <ide> }
Java
mit
3fe00277ad027e1828971ee29432b3cd23d63b55
0
Ichicoro/privacylayer
package net.privacylayer.app; import android.app.PendingIntent; import android.app.TaskStackBuilder; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity { public static final String TAG = "PrivacyLayer/MainAct"; public int mode = 0; // 0 = encrypt - 1 = decrypt public Button encryptionButton; public Button decryptionButton; public Spinner spinner; public SharedPreferences sharedPrefs; private String key; private HashMap<String, String> keysMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Declare all interface items here to prevent null pointer exs. encryptionButton = (Button) findViewById(R.id.encryptButton); decryptionButton = (Button) findViewById(R.id.decryptButton); spinner = (Spinner) findViewById(R.id.keychainSpinner); final EditText editText = (EditText) findViewById(R.id.editText); final EditText inputBox = (EditText) findViewById(R.id.inputBox); Button shareButton = (Button) findViewById(R.id.shareButton); sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); /* keystore */ final SharedPreferences keyValues = getApplicationContext() .getSharedPreferences("KeyStore", Context.MODE_PRIVATE); // TODO: fix unchecked thingie warning keysMap = new HashMap<>((Map<String, String>) keyValues.getAll()); keysMap.put("Default key", "defkey"); updateSpinner(); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String thisKeyName = parent.getItemAtPosition(position).toString(); key = keysMap.get(thisKeyName); setCurrentKey(key); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); Intent intent = getIntent(); Boolean fromNotification = intent.getBooleanExtra("fromNotification", false); Log.i(TAG, "Did the user come from a notification? " + fromNotification.toString()); if (fromNotification) { /* If the user came here clicking a notification, attempt to load the clipboard contents * in the input box. */ ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); ClipData clipData = clipboard.getPrimaryClip(); if (clipData != null) { ClipData.Item item = clipData.getItemAt(0); CharSequence text = item.getText(); if (text != null) { inputBox.setText(text); String type = intent.getStringExtra("type"); // TODO: use constants from MainActivity Log.i(TAG, "Notification type is: " + type); if (type.equals("encryption")) setEncryptionMode(); else if (type.equals("decryption")) setDecryptionMode(); /* else if (the text is a valid AES message) setDecryptionMode(); else setEncryptionMode(); */ } } } boolean showPermanentNotification = sharedPrefs.getBoolean("enable_persistent_notification", false); if (showPermanentNotification) { Intent selfIntent = new Intent(this, MainActivity.class); selfIntent.putExtra("fromNotification", true); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(MainActivity.class); stackBuilder.addNextIntent(selfIntent); PendingIntent selfPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); Intent encryptionIntent = new Intent(this, MainActivity.class); encryptionIntent.putExtra("fromNotification", true); encryptionIntent.putExtra("type", "encryption"); Intent decryptionIntent = new Intent(this, MainActivity.class); decryptionIntent.putExtra("fromNotification", true); decryptionIntent.putExtra("type", "decryption"); PermanentNotification.notify(getApplicationContext(), selfPendingIntent, encryptionIntent, decryptionIntent); } // Encrypt/decrypt button encryptionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { editText.setText(encryptBoxText(inputBox.getText().toString())); } catch (IllegalArgumentException e) { Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show(); } } }); decryptionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { editText.setText(decryptBoxText(inputBox.getText().toString())); } catch (IllegalArgumentException e) { Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show(); } } }); // Share button shareButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, editText.getText()); sendIntent.setType("text/plain"); startActivity(Intent.createChooser(sendIntent, "Share with...")); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: Intent settingsIntent = new Intent(MainActivity.this, SettingsActivity.class); startActivity(settingsIntent); return true; case R.id.action_keys: Intent keysIntent = new Intent(MainActivity.this, KeyExchange.class); startActivity(keysIntent); return true; default: // If we got here, the user's action was not recognized. // Invoke the superclass to handle it. return super.onOptionsItemSelected(item); } } public String encryptBoxText(String text) throws Exception { return AESPlatform.encrypt(text, key).toString(); } public String decryptBoxText(String text) throws Exception { return AESPlatform.decrypt(new AESMessage(text), key); } public void setEncryptionMode() { mode = 0; } public void setDecryptionMode() { mode = 1; } public void updateSpinner() { String[] keyNamesArray = keysMap.keySet().toArray(new String[keysMap.size()]); final ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_dropdown_item, keyNamesArray); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); } public void setCurrentKey(String key) { final SharedPreferences appData = getApplicationContext() .getSharedPreferences("appData", Context.MODE_PRIVATE); appData .edit() .putString("encryption_key", key) .apply(); // Log.i(TAG, "Current key is now " + key); } }
app/src/main/java/net/privacylayer/app/MainActivity.java
package net.privacylayer.app; import android.app.PendingIntent; import android.app.TaskStackBuilder; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity { public static final String TAG = "PrivacyLayer/MainAct"; public int mode = 0; // 0 = encrypt - 1 = decrypt public Button encryptionButton; public Button decryptionButton; public Spinner spinner; public SharedPreferences sharedPrefs; private String key; private HashMap<String, String> keysMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Declare all interface items here to prevent null pointer exs. encryptionButton = (Button) findViewById(R.id.encryptButton); decryptionButton = (Button) findViewById(R.id.decryptButton); spinner = (Spinner) findViewById(R.id.keychainSpinner); final EditText editText = (EditText) findViewById(R.id.editText); final EditText inputBox = (EditText) findViewById(R.id.inputBox); Button shareButton = (Button) findViewById(R.id.shareButton); sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); /* keystore */ final SharedPreferences keyValues = getApplicationContext() .getSharedPreferences("KeyStore", Context.MODE_PRIVATE); keysMap = new HashMap<>(1 + keyValues.getAll().size()); keysMap.put("Default key", "defkey"); keysMap.putAll((Map<String, String>) keyValues.getAll()); updateSpinner(); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String thisKeyName = parent.getItemAtPosition(position).toString(); key = keysMap.get(thisKeyName); setCurrentKey(key); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); Intent intent = getIntent(); Boolean fromNotification = intent.getBooleanExtra("fromNotification", false); Log.i(TAG, "Did the user come from a notification? " + fromNotification.toString()); if (fromNotification) { /* If the user came here clicking a notification, attempt to load the clipboard contents * in the input box. */ ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); ClipData clipData = clipboard.getPrimaryClip(); if (clipData != null) { ClipData.Item item = clipData.getItemAt(0); CharSequence text = item.getText(); if (text != null) { inputBox.setText(text); String type = intent.getStringExtra("type"); // TODO: use constants from MainActivity Log.i(TAG, "Notification type is: " + type); if (type.equals("encryption")) setEncryptionMode(); else if (type.equals("decryption")) setDecryptionMode(); /* else if (the text is a valid AES message) setDecryptionMode(); else setEncryptionMode(); */ } } } boolean showPermanentNotification = sharedPrefs.getBoolean("enable_persistent_notification", false); if (showPermanentNotification) { Intent selfIntent = new Intent(this, MainActivity.class); selfIntent.putExtra("fromNotification", true); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(MainActivity.class); stackBuilder.addNextIntent(selfIntent); PendingIntent selfPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); Intent encryptionIntent = new Intent(this, MainActivity.class); encryptionIntent.putExtra("fromNotification", true); encryptionIntent.putExtra("type", "encryption"); Intent decryptionIntent = new Intent(this, MainActivity.class); decryptionIntent.putExtra("fromNotification", true); decryptionIntent.putExtra("type", "decryption"); PermanentNotification.notify(getApplicationContext(), selfPendingIntent, encryptionIntent, decryptionIntent); } // Encrypt/decrypt button encryptionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { editText.setText(encryptBoxText(inputBox.getText().toString())); } catch (IllegalArgumentException e) { Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show(); } } }); decryptionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { editText.setText(decryptBoxText(inputBox.getText().toString())); } catch (IllegalArgumentException e) { Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show(); } } }); // Share button shareButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, editText.getText()); sendIntent.setType("text/plain"); startActivity(Intent.createChooser(sendIntent, "Share with...")); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: Intent settingsIntent = new Intent(MainActivity.this, SettingsActivity.class); startActivity(settingsIntent); return true; case R.id.action_keys: Intent keysIntent = new Intent(MainActivity.this, KeyExchange.class); startActivity(keysIntent); return true; default: // If we got here, the user's action was not recognized. // Invoke the superclass to handle it. return super.onOptionsItemSelected(item); } } public String encryptBoxText(String text) throws Exception { return AESPlatform.encrypt(text, key).toString(); } public String decryptBoxText(String text) throws Exception { return AESPlatform.decrypt(new AESMessage(text), key); } public void setEncryptionMode() { mode = 0; } public void setDecryptionMode() { mode = 1; } public void updateSpinner() { String[] keyNamesArray = keysMap.keySet().toArray(new String[keysMap.size()]); final ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_dropdown_item, keyNamesArray); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); } public void setCurrentKey(String key) { final SharedPreferences appData = getApplicationContext() .getSharedPreferences("appData", Context.MODE_PRIVATE); appData .edit() .putString("encryption_key", key) .apply(); // Log.i(TAG, "Current key is now " + key); } }
Improve key map management
app/src/main/java/net/privacylayer/app/MainActivity.java
Improve key map management
<ide><path>pp/src/main/java/net/privacylayer/app/MainActivity.java <ide> final SharedPreferences keyValues = getApplicationContext() <ide> .getSharedPreferences("KeyStore", Context.MODE_PRIVATE); <ide> <del> <del> keysMap = new HashMap<>(1 + keyValues.getAll().size()); <add> // TODO: fix unchecked thingie warning <add> keysMap = new HashMap<>((Map<String, String>) keyValues.getAll()); <ide> keysMap.put("Default key", "defkey"); <del> keysMap.putAll((Map<String, String>) keyValues.getAll()); <ide> <ide> updateSpinner(); <ide> spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
Java
mit
4a266aeffb6f653af576eb364e36aeb45b95f037
0
JCThePants/NucleusFramework,JCThePants/NucleusFramework
/* * This file is part of NucleusFramework for Bukkit, licensed under the MIT License (MIT). * * Copyright (c) JCThePants (www.jcwhatever.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.jcwhatever.nucleus.views.menu; import com.jcwhatever.nucleus.utils.items.ItemStackUtils; import com.jcwhatever.nucleus.utils.items.serializer.InvalidItemStackStringException; import com.jcwhatever.nucleus.utils.materials.NamedMaterialData; import com.jcwhatever.nucleus.utils.MetaKey; import com.jcwhatever.nucleus.utils.PreCon; import com.jcwhatever.nucleus.utils.text.TextUtils; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.material.MaterialData; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nullable; /** * A utility class to build {@link MenuItem}'s. */ public class MenuItemBuilder { private ItemStack _itemStack; private MaterialData _materialData; private Integer _amount; private String _title; private String _description; private Map<Object, Object> _meta; private List<Runnable> _onClick; /** * Constructor. * * @param itemStack The {@link org.bukkit.inventory.ItemStack} that represents the menu item. */ public MenuItemBuilder(ItemStack itemStack) { PreCon.notNull(itemStack); _itemStack = itemStack; } /** * Constructor. * * @param material The item {@link org.bukkit.Material}. */ public MenuItemBuilder(Material material) { PreCon.notNull(material); _materialData = new MaterialData(material); } /** * Constructor. * * @param materialData The item {@link org.bukkit.material.MaterialData}. */ public MenuItemBuilder(MaterialData materialData) { PreCon.notNull(materialData); _materialData = materialData.clone(); } /** * Constructor. * * @param materialName The name of the material or serialized item stack string. */ public MenuItemBuilder(String materialName) { PreCon.notNullOrEmpty(materialName); _materialData = NamedMaterialData.get(materialName); if (_materialData == null) { try { // try parsing serialized item stack ItemStack[] itemStacks = ItemStackUtils.parse(materialName); if (itemStacks != null && itemStacks.length == 1) { _itemStack = itemStacks[0]; return; } } catch (InvalidItemStackStringException ignore) {} throw new RuntimeException(materialName + " is not a recognized material."); } } /** * Set the menu item title. * * @param title The title text. * @param args Optional title format arguments. * * @return Self for chaining. */ public MenuItemBuilder title(String title, Object... args) { PreCon.notNull(title); _title = TextUtils.format(title, args); return this; } /** * Set the menu item description. * * @param description The description text. * @param args Optional description format arguments. * * @return Self for chaining. */ public MenuItemBuilder description(String description, Object... args) { PreCon.notNull(description); _description = TextUtils.format(description, args); return this; } /** * Set the amount. * * @param amount The amount. * * @return Self for chaining. */ public MenuItemBuilder amount(int amount) { _amount = amount; return this; } /** * Add meta data to the menu item. * * @param key The meta key. * @param value The meta value. * * @param <T> The meta value type. * * @return Self for chaining. */ public <T> MenuItemBuilder meta(MetaKey<T> key, T value) { PreCon.notNull(key); if (_meta == null) { _meta = new HashMap<>(7); } _meta.put(key, value); return this; } public MenuItemBuilder onClick(Runnable onClick) { PreCon.notNull(onClick); if (_onClick == null) _onClick = new ArrayList<>(3); _onClick.add(onClick); return this; } /** * Build and return a new {@Code MenuItem}. * * @param slot The inventory slot the menu item will be placed in. */ public MenuItem build(int slot) { if (_itemStack == null) { _itemStack = new ItemStack(_materialData.getItemType()); _itemStack.setData(_materialData); } MenuItem item = createMenuItem(slot, _itemStack.clone(), _meta, _onClick); if (_amount != null) item.setAmount(_amount); if (_title != null) item.setTitle(_title); if (_description != null) item.setDescription(_description); return item; } protected MenuItem createMenuItem(int slot, ItemStack itemStack, @Nullable Map<Object, Object> meta, @Nullable List<Runnable> onClick) { return new MenuItem(slot, itemStack, meta, onClick); } }
src/com/jcwhatever/nucleus/views/menu/MenuItemBuilder.java
/* * This file is part of NucleusFramework for Bukkit, licensed under the MIT License (MIT). * * Copyright (c) JCThePants (www.jcwhatever.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.jcwhatever.nucleus.views.menu; import com.jcwhatever.nucleus.utils.materials.NamedMaterialData; import com.jcwhatever.nucleus.utils.MetaKey; import com.jcwhatever.nucleus.utils.PreCon; import com.jcwhatever.nucleus.utils.text.TextUtils; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.material.MaterialData; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nullable; /** * A utility class to build {@link MenuItem}'s. */ public class MenuItemBuilder { private ItemStack _itemStack; private MaterialData _materialData; private Integer _amount; private String _title; private String _description; private Map<Object, Object> _meta; private List<Runnable> _onClick; /** * Constructor. * * @param itemStack The {@link org.bukkit.inventory.ItemStack} that represents the menu item. */ public MenuItemBuilder(ItemStack itemStack) { PreCon.notNull(itemStack); _itemStack = itemStack; } /** * Constructor. * * @param material The item {@link org.bukkit.Material}. */ public MenuItemBuilder(Material material) { PreCon.notNull(material); _materialData = new MaterialData(material); } /** * Constructor. * * @param materialData The item {@link org.bukkit.material.MaterialData}. */ public MenuItemBuilder(MaterialData materialData) { PreCon.notNull(materialData); _materialData = materialData.clone(); } /** * Constructor. * * @param materialName The name of the material. */ public MenuItemBuilder(String materialName) { PreCon.notNullOrEmpty(materialName); _materialData = NamedMaterialData.get(materialName); if (_materialData == null) throw new RuntimeException(materialName + " is not a recognized material."); } /** * Set the menu item title. * * @param title The title text. * @param args Optional title format arguments. * * @return Self for chaining. */ public MenuItemBuilder title(String title, Object... args) { PreCon.notNull(title); _title = TextUtils.format(title, args); return this; } /** * Set the menu item description. * * @param description The description text. * @param args Optional description format arguments. * * @return Self for chaining. */ public MenuItemBuilder description(String description, Object... args) { PreCon.notNull(description); _description = TextUtils.format(description, args); return this; } /** * Set the amount. * * @param amount The amount. * * @return Self for chaining. */ public MenuItemBuilder amount(int amount) { _amount = amount; return this; } /** * Add meta data to the menu item. * * @param key The meta key. * @param value The meta value. * * @param <T> The meta value type. * * @return Self for chaining. */ public <T> MenuItemBuilder meta(MetaKey<T> key, T value) { PreCon.notNull(key); if (_meta == null) { _meta = new HashMap<>(7); } _meta.put(key, value); return this; } public MenuItemBuilder onClick(Runnable onClick) { PreCon.notNull(onClick); if (_onClick == null) _onClick = new ArrayList<>(3); _onClick.add(onClick); return this; } /** * Build and return a new {@Code MenuItem}. * * @param slot The inventory slot the menu item will be placed in. */ public MenuItem build(int slot) { if (_itemStack == null) { _itemStack = new ItemStack(_materialData.getItemType()); _itemStack.setData(_materialData); } MenuItem item = createMenuItem(slot, _itemStack.clone(), _meta, _onClick); if (_amount != null) item.setAmount(_amount); if (_title != null) item.setTitle(_title); if (_description != null) item.setDescription(_description); return item; } protected MenuItem createMenuItem(int slot, ItemStack itemStack, @Nullable Map<Object, Object> meta, @Nullable List<Runnable> onClick) { return new MenuItem(slot, itemStack, meta, onClick); } }
add MenuItemBuilder parses serialized item stack strings
src/com/jcwhatever/nucleus/views/menu/MenuItemBuilder.java
add MenuItemBuilder parses serialized item stack strings
<ide><path>rc/com/jcwhatever/nucleus/views/menu/MenuItemBuilder.java <ide> <ide> package com.jcwhatever.nucleus.views.menu; <ide> <add>import com.jcwhatever.nucleus.utils.items.ItemStackUtils; <add>import com.jcwhatever.nucleus.utils.items.serializer.InvalidItemStackStringException; <ide> import com.jcwhatever.nucleus.utils.materials.NamedMaterialData; <ide> import com.jcwhatever.nucleus.utils.MetaKey; <ide> import com.jcwhatever.nucleus.utils.PreCon; <ide> /** <ide> * Constructor. <ide> * <del> * @param materialName The name of the material. <add> * @param materialName The name of the material or serialized item stack string. <ide> */ <ide> public MenuItemBuilder(String materialName) { <ide> PreCon.notNullOrEmpty(materialName); <ide> <ide> _materialData = NamedMaterialData.get(materialName); <del> if (_materialData == null) <add> if (_materialData == null) { <add> try { <add> // try parsing serialized item stack <add> ItemStack[] itemStacks = ItemStackUtils.parse(materialName); <add> if (itemStacks != null && itemStacks.length == 1) { <add> _itemStack = itemStacks[0]; <add> return; <add> } <add> <add> } catch (InvalidItemStackStringException ignore) {} <add> <ide> throw new RuntimeException(materialName + " is not a recognized material."); <add> } <ide> } <ide> <ide> /**
Java
mit
b013c34ee80ea9e3150f52145162b52e4448d511
0
aterai/java-swing-tips,aterai/java-swing-tips,aterai/java-swing-tips,aterai/java-swing-tips
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.concurrent.ExecutionException; import javax.swing.*; public class MainPanel extends JPanel { private static final Color DRAW_COLOR = Color.BLACK; private static final Color BACK_COLOR = Color.WHITE; private static final int MINX = 5; private static final int MAXX = 315; private static final int MINY = 5; private static final int MAXY = 175; private static final int MINN = 50; private static final int MAXN = 500; private final List<Double> array = new ArrayList<>(MAXN); private int number = 150; private double factorx; private double factory; private transient SwingWorker<String, Rectangle> worker; private final JComboBox<GenerateInputs> distributionsChoices = new JComboBox<>(GenerateInputs.values()); private final JComboBox<SortAlgorithms> algorithmsChoices = new JComboBox<>(SortAlgorithms.values()); private final SpinnerNumberModel model = new SpinnerNumberModel(number, MINN, MAXN, 10); private final JSpinner spinner = new JSpinner(model); private final JButton startButton = new JButton("Start"); private final JButton cancelButton = new JButton("Cancel"); protected final JPanel panel = new JPanel() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); drawAllOval(g); } }; public MainPanel() { super(new BorderLayout()); genArray(number); startButton.addActionListener(e -> { setComponentEnabled(false); workerExecute(); }); cancelButton.addActionListener(e -> { if (Objects.nonNull(worker) && !worker.isDone()) { worker.cancel(true); } }); ItemListener il = e -> { if (e.getStateChange() == ItemEvent.SELECTED) { genArray(number); panel.repaint(); } }; distributionsChoices.addItemListener(il); algorithmsChoices.addItemListener(il); panel.setBackground(BACK_COLOR); Box box1 = Box.createHorizontalBox(); box1.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); box1.add(new JLabel(" Number:")); box1.add(spinner); box1.add(new JLabel(" Input:")); box1.add(distributionsChoices); Box box2 = Box.createHorizontalBox(); box2.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); box2.add(new JLabel(" Algorithm:")); box2.add(algorithmsChoices); box2.add(startButton); box2.add(cancelButton); JPanel p = new JPanel(new GridLayout(2, 1)); p.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); p.add(box1); p.add(box2); add(p, BorderLayout.NORTH); add(panel); setPreferredSize(new Dimension(320, 240)); } protected final void drawAllOval(Graphics g) { // g.setColor(DRAW_COLOR); for (int i = 0; i < number; i++) { int px = (int) (MINX + factorx * i); int py = MAXY - (int) (factory * array.get(i)); g.setColor(i % 5 == 0 ? Color.RED : DRAW_COLOR); g.drawOval(px, py, 4, 4); } } protected final void setComponentEnabled(boolean flag) { cancelButton.setEnabled(!flag); startButton.setEnabled(flag); spinner.setEnabled(flag); distributionsChoices.setEnabled(flag); algorithmsChoices.setEnabled(flag); } protected final void genArray(int n) { array.clear(); factorx = (MAXX - MINX) / (double) n; factory = MAXY - MINY; distributionsChoices.getItemAt(distributionsChoices.getSelectedIndex()).generate(array, n); } protected final void workerExecute() { int tmp = model.getNumber().intValue(); if (tmp != number) { number = tmp; genArray(number); } SortAlgorithms sa = algorithmsChoices.getItemAt(algorithmsChoices.getSelectedIndex()); Rectangle paintArea = new Rectangle(MINX, MINY, MAXX - MINX, MAXY - MINY); worker = new SortingTask(sa, number, array, paintArea, factorx, factory) { @Override protected void process(List<Rectangle> chunks) { if (isCancelled()) { return; } if (!isDisplayable()) { System.out.println("process: DISPOSE_ON_CLOSE"); cancel(true); return; } for (Rectangle r: chunks) { panel.repaint(r); } } @Override public void done() { if (!isDisplayable()) { System.out.println("done: DISPOSE_ON_CLOSE"); cancel(true); return; } setComponentEnabled(true); String text; try { text = isCancelled() ? "Cancelled" : get(); } catch (InterruptedException ex) { text = "Interrupted"; Thread.currentThread().interrupt(); } catch (ExecutionException ex) { ex.printStackTrace(); text = "Error: " + ex.getMessage(); } System.out.println(text); repaint(); } }; worker.execute(); } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); // frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.setResizable(false); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } enum SortAlgorithms { ISORT("Insertion Sort"), SELSORT("Selection Sort"), SHELLSORT("Shell Sort"), HSORT("Heap Sort"), QSORT("Quicksort"), QSORT2("2-way Quicksort"); private final String description; SortAlgorithms(String description) { this.description = description; } @Override public String toString() { return description; } } enum GenerateInputs { RANDOM() { @Override public void generate(List<Double> array, int n) { for (int i = 0; i < n; i++) { array.add(Math.random()); } } }, ASCENDING() { @Override public void generate(List<Double> array, int n) { for (int i = 0; i < n; i++) { array.add(i / (double) n); } } }, DESCENDING() { @Override public void generate(List<Double> array, int n) { for (int i = 0; i < n; i++) { array.add(1d - i / (double) n); } } }; abstract void generate(List<Double> array, int n); }
SortingAnimations/src/java/example/MainPanel.java
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.concurrent.ExecutionException; import javax.swing.*; public class MainPanel extends JPanel { private static final Color DRAW_COLOR = Color.BLACK; private static final Color BACK_COLOR = Color.WHITE; private static final int MINX = 5; private static final int MAXX = 315; private static final int MINY = 5; private static final int MAXY = 175; private static final int MINN = 50; private static final int MAXN = 500; private final List<Double> array = new ArrayList<>(MAXN); private int number = 150; private double factorx; private double factory; private transient SwingWorker<String, Rectangle> worker; private final JComboBox<GenerateInputs> distributionsChoices = new JComboBox<>(GenerateInputs.values()); private final JComboBox<SortAlgorithms> algorithmsChoices = new JComboBox<>(SortAlgorithms.values()); private final SpinnerNumberModel model = new SpinnerNumberModel(number, MINN, MAXN, 10); private final JSpinner spinner = new JSpinner(model); private final JButton startButton = new JButton("Start"); private final JButton cancelButton = new JButton("Cancel"); protected final JPanel panel = new JPanel() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); drawAllOval(g); } }; public MainPanel() { super(new BorderLayout()); genArray(number); startButton.addActionListener(e -> { setComponentEnabled(false); workerExecute(); }); cancelButton.addActionListener(e -> { if (Objects.nonNull(worker) && !worker.isDone()) { worker.cancel(true); } }); ItemListener il = e -> { if (e.getStateChange() == ItemEvent.SELECTED) { genArray(number); panel.repaint(); } }; distributionsChoices.addItemListener(il); algorithmsChoices.addItemListener(il); panel.setBackground(BACK_COLOR); Box box1 = Box.createHorizontalBox(); box1.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); box1.add(new JLabel(" Number:")); box1.add(spinner); box1.add(new JLabel(" Input:")); box1.add(distributionsChoices); Box box2 = Box.createHorizontalBox(); box2.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); box2.add(new JLabel(" Algorithm:")); box2.add(algorithmsChoices); box2.add(startButton); box2.add(cancelButton); JPanel p = new JPanel(new GridLayout(2, 1)); p.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); p.add(box1); p.add(box2); add(p, BorderLayout.NORTH); add(panel); setPreferredSize(new Dimension(320, 240)); } protected final void drawAllOval(Graphics g) { // g.setColor(DRAW_COLOR); for (int i = 0; i < number; i++) { int px = (int) (MINX + factorx * i); int py = MAXY - (int) (factory * array.get(i)); g.setColor(i % 5 == 0 ? Color.RED : DRAW_COLOR); g.drawOval(px, py, 4, 4); } } protected final void setComponentEnabled(boolean flag) { cancelButton.setEnabled(!flag); startButton.setEnabled(flag); spinner.setEnabled(flag); distributionsChoices.setEnabled(flag); algorithmsChoices.setEnabled(flag); } protected final void genArray(int n) { array.clear(); factorx = (MAXX - MINX) / (double) n; factory = MAXY - MINY; distributionsChoices.getItemAt(distributionsChoices.getSelectedIndex()).generate(array, n); } protected final void workerExecute() { int tmp = model.getNumber().intValue(); if (tmp != number) { number = tmp; genArray(number); } SortAlgorithms sa = algorithmsChoices.getItemAt(algorithmsChoices.getSelectedIndex()); Rectangle paintArea = new Rectangle(MINX, MINY, MAXX - MINX, MAXY - MINY); worker = new SortingTask(sa, number, array, paintArea, factorx, factory) { @Override protected void process(List<Rectangle> chunks) { if (isCancelled()) { return; } if (!isDisplayable()) { System.out.println("process: DISPOSE_ON_CLOSE"); cancel(true); return; } for (Rectangle r: chunks) { panel.repaint(r); } } @Override public void done() { if (!isDisplayable()) { System.out.println("done: DISPOSE_ON_CLOSE"); cancel(true); return; } setComponentEnabled(true); String text; try { text = isCancelled() ? "Cancelled" : get(); } catch (InterruptedException ex) { text = "Interrupted"; } catch (ExecutionException ex) { ex.printStackTrace(); text = "Error: " + ex.getMessage(); } System.out.println(text); repaint(); } }; worker.execute(); } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); // frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.setResizable(false); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } enum SortAlgorithms { ISORT("Insertion Sort"), SELSORT("Selection Sort"), SHELLSORT("Shell Sort"), HSORT("Heap Sort"), QSORT("Quicksort"), QSORT2("2-way Quicksort"); private final String description; SortAlgorithms(String description) { this.description = description; } @Override public String toString() { return description; } } enum GenerateInputs { RANDOM() { @Override public void generate(List<Double> array, int n) { for (int i = 0; i < n; i++) { array.add(Math.random()); } } }, ASCENDING() { @Override public void generate(List<Double> array, int n) { for (int i = 0; i < n; i++) { array.add(i / (double) n); } } }, DESCENDING() { @Override public void generate(List<Double> array, int n) { for (int i = 0; i < n; i++) { array.add(1d - i / (double) n); } } }; abstract void generate(List<Double> array, int n); }
SonarLint: either re-interrupt this method or rethrow the 'InterruptedException'
SortingAnimations/src/java/example/MainPanel.java
SonarLint: either re-interrupt this method or rethrow the 'InterruptedException'
<ide><path>ortingAnimations/src/java/example/MainPanel.java <ide> text = isCancelled() ? "Cancelled" : get(); <ide> } catch (InterruptedException ex) { <ide> text = "Interrupted"; <add> Thread.currentThread().interrupt(); <ide> } catch (ExecutionException ex) { <ide> ex.printStackTrace(); <ide> text = "Error: " + ex.getMessage();
Java
apache-2.0
dca96d3988b8ff10950febb33542cc50339147dc
0
alter-ego/androidbound,alter-ego/androidbound
package solutions.alterego.androidbound.android; import android.app.Activity; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.view.View; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.List; import java.util.Map; import lombok.Getter; import lombok.experimental.Accessors; import solutions.alterego.androidbound.NullLogger; import solutions.alterego.androidbound.ViewModel; import solutions.alterego.androidbound.android.interfaces.IActivityLifecycle; import solutions.alterego.androidbound.android.interfaces.IBindableView; import solutions.alterego.androidbound.android.interfaces.IBoundActivity; import solutions.alterego.androidbound.android.interfaces.INeedsConfigurationChange; import solutions.alterego.androidbound.android.interfaces.INeedsNewIntent; import solutions.alterego.androidbound.android.interfaces.INeedsOnActivityResult; import solutions.alterego.androidbound.interfaces.IHasLogger; import solutions.alterego.androidbound.interfaces.ILogger; import solutions.alterego.androidbound.interfaces.INeedsLogger; import solutions.alterego.androidbound.interfaces.IViewBinder; @Accessors(prefix = "m") public class BoundActivityDelegate implements IActivityLifecycle, IBoundActivity, INeedsOnActivityResult, INeedsNewIntent, INeedsConfigurationChange, INeedsLogger, IHasLogger { public static final String TAG_VIEWMODEL_MAIN = "androidbound_viewmodel_main"; @Getter private Map<String, ViewModel> mViewModels; private ILogger mLogger = null; private transient WeakReference<Activity> mBoundActivity; private boolean mShouldCallCreate = false; private Bundle mCreateBundle; private IViewBinder mViewBinder; public BoundActivityDelegate(Activity activity) { this(activity, null); } public BoundActivityDelegate(Activity activity, IViewBinder viewBinder) { mBoundActivity = new WeakReference<>(activity); mViewBinder = viewBinder; } private IViewBinder getViewBinder() { if (mViewBinder != null) { return mViewBinder; } else if (getBoundActivity() instanceof IBindableView) { return ((IBindableView) getBoundActivity()).getViewBinder(); } else { throw new RuntimeException("There's no IViewBinder available!"); } } private Activity getBoundActivity() { return mBoundActivity != null ? mBoundActivity.get() : null; } @Override public void setContentView(int layoutResID, ViewModel viewModel) { if (mBoundActivity == null || getBoundActivity() == null) { throw new RuntimeException("Bound Activity is null!"); } getBoundActivity().setContentView(addViewModel(layoutResID, viewModel, TAG_VIEWMODEL_MAIN)); } @Override public View addViewModel(int layoutResID, ViewModel viewModel, String id) { if (mBoundActivity == null) { throw new RuntimeException("Bound Activity is null!"); } if (viewModel == null) { throw new RuntimeException("viewModel is null!"); } if (mViewModels == null) { mViewModels = new HashMap<>(); } if (mViewModels.values().contains(viewModel)) { throw new RuntimeException("cannot add same instance of viewModel twice!"); } viewModel.setParentActivity(getBoundActivity()); viewModel.setLogger(getLogger()); mViewModels.put(id, viewModel); View view = getViewBinder().inflate(getBoundActivity(), viewModel, layoutResID, null); if (mShouldCallCreate) { onCreate(mCreateBundle); } return view; } @Override public ViewModel getViewModel(String id) { if (mViewModels != null) { return mViewModels.get(id); } else { return null; } } @Override public ViewModel getContentViewModel() { return getViewModel(TAG_VIEWMODEL_MAIN); } @Override public void onCreate(Bundle savedInstanceState) { if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { if (!viewModel.isCreated()) { viewModel.onCreate(savedInstanceState); } } mShouldCallCreate = false; } else { mShouldCallCreate = true; mCreateBundle = savedInstanceState; } } @Override public void onStart() { if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { viewModel.onStart(); } } } @Override public void onRestart() { if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { viewModel.onRestart(); } } } @Override public void onResume() { if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { viewModel.onResume(); } } } @Override public void onPause() { if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { viewModel.onPause(); } } } @Override public void onStop() { if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { viewModel.onStop(); } } } @Override public void onSaveInstanceState(Bundle outState) { mShouldCallCreate = false; mCreateBundle = null; if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { viewModel.onSaveInstanceState(outState); } } } @Override public void onDestroy() { Activity boundActivityRef = getBoundActivity(); if (mBoundActivity != null && boundActivityRef != null && boundActivityRef instanceof IBindableView && boundActivityRef.getWindow() != null && boundActivityRef.getWindow().getDecorView() != null) { getViewBinder().clearBindingForViewAndChildren(getBoundActivity().getWindow().getDecorView().getRootView()); } if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { viewModel.onDestroy(); } } mViewModels = null; mBoundActivity.clear(); mBoundActivity = null; mViewBinder = null; mLogger = null; } @Override public void onConfigurationChanged(Configuration newConfig) { if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { if (viewModel instanceof INeedsConfigurationChange) { ((INeedsConfigurationChange) viewModel).onConfigurationChanged(newConfig); } } } } @Override public void onNewIntent(Intent newIntent) { if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { if (viewModel instanceof INeedsNewIntent) { ((INeedsNewIntent) viewModel).onNewIntent(newIntent); } } } if (getBoundActivity() instanceof AppCompatActivity) { List<Fragment> fragments = ((AppCompatActivity) getBoundActivity()).getSupportFragmentManager().getFragments(); if (fragments != null) { for (Fragment fragment : fragments) { if (fragment instanceof INeedsNewIntent) { ((INeedsNewIntent) fragment).onNewIntent(newIntent); } } } } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { if (viewModel instanceof INeedsOnActivityResult) { ((INeedsOnActivityResult) viewModel).onActivityResult(requestCode, resultCode, data); } } } } @Override public ILogger getLogger() { return mLogger != null ? mLogger : NullLogger.instance; } @Override public void setLogger(ILogger logger) { mLogger = logger; if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { viewModel.setLogger(getLogger()); } } if (getBoundActivity() instanceof AppCompatActivity) { List<Fragment> fragments = ((AppCompatActivity) getBoundActivity()).getSupportFragmentManager().getFragments(); if (fragments != null) { for (Fragment fragment : fragments) { if (fragment instanceof INeedsLogger) { ((INeedsLogger) fragment).setLogger(logger); } } } } } }
AndroidBound/src/main/java/solutions/alterego/androidbound/android/BoundActivityDelegate.java
package solutions.alterego.androidbound.android; import android.app.Activity; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.view.View; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.List; import java.util.Map; import lombok.Getter; import lombok.experimental.Accessors; import solutions.alterego.androidbound.NullLogger; import solutions.alterego.androidbound.ViewModel; import solutions.alterego.androidbound.android.interfaces.IActivityLifecycle; import solutions.alterego.androidbound.android.interfaces.IBindableView; import solutions.alterego.androidbound.android.interfaces.IBoundActivity; import solutions.alterego.androidbound.android.interfaces.INeedsConfigurationChange; import solutions.alterego.androidbound.android.interfaces.INeedsNewIntent; import solutions.alterego.androidbound.android.interfaces.INeedsOnActivityResult; import solutions.alterego.androidbound.interfaces.IHasLogger; import solutions.alterego.androidbound.interfaces.ILogger; import solutions.alterego.androidbound.interfaces.INeedsLogger; @Accessors(prefix = "m") public class BoundActivityDelegate implements IActivityLifecycle, IBoundActivity, INeedsOnActivityResult, INeedsNewIntent, INeedsConfigurationChange, INeedsLogger, IHasLogger { public static final String TAG_VIEWMODEL_MAIN = "androidbound_viewmodel_main"; @Getter private Map<String, ViewModel> mViewModels; private ILogger mLogger = null; private transient WeakReference<Activity> mBoundActivity; private boolean mShouldCallCreate = false; private Bundle mCreateBundle; public BoundActivityDelegate(Activity activity) { mBoundActivity = new WeakReference<>(activity); } private Activity getBoundActivity() { return mBoundActivity != null ? mBoundActivity.get() : null; } @Override public void setContentView(int layoutResID, ViewModel viewModel) { if (mBoundActivity == null || getBoundActivity() == null) { throw new RuntimeException("Bound Activity is null!"); } getBoundActivity().setContentView(addViewModel(layoutResID, viewModel, TAG_VIEWMODEL_MAIN)); } @Override public View addViewModel(int layoutResID, ViewModel viewModel, String id) { if (mBoundActivity == null) { throw new RuntimeException("Bound Activity is null!"); } if (!(getBoundActivity() instanceof IBindableView)) { throw new RuntimeException("Activity must implement IBindableView!"); } if (viewModel == null) { throw new RuntimeException("viewModel is null!"); } if (((IBindableView) getBoundActivity()).getViewBinder() == null) { throw new RuntimeException("getViewBinder must not be null!"); } if (mViewModels == null) { mViewModels = new HashMap<>(); } if (mViewModels.values().contains(viewModel)) { throw new RuntimeException("cannot add same instance of viewModel twice!"); } viewModel.setParentActivity(getBoundActivity()); viewModel.setLogger(getLogger()); mViewModels.put(id, viewModel); View view = ((IBindableView) getBoundActivity()).getViewBinder().inflate(getBoundActivity(), viewModel, layoutResID, null); if (mShouldCallCreate) { onCreate(mCreateBundle); } return view; } @Override public ViewModel getViewModel(String id) { if (mViewModels != null) { return mViewModels.get(id); } else { return null; } } @Override public ViewModel getContentViewModel() { return getViewModel(TAG_VIEWMODEL_MAIN); } @Override public void onCreate(Bundle savedInstanceState) { if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { if (!viewModel.isCreated()) { viewModel.onCreate(savedInstanceState); } } } else { mShouldCallCreate = true; mCreateBundle = savedInstanceState; } } @Override public void onStart() { if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { viewModel.onStart(); } } } @Override public void onRestart() { if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { viewModel.onRestart(); } } } @Override public void onResume() { if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { viewModel.onResume(); } } } @Override public void onPause() { if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { viewModel.onPause(); } } } @Override public void onStop() { if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { viewModel.onStop(); } } } @Override public void onSaveInstanceState(Bundle outState) { mShouldCallCreate = false; mCreateBundle = null; if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { viewModel.onSaveInstanceState(outState); } } } @Override public void onDestroy() { Activity boundActivityRef = getBoundActivity(); if (mBoundActivity != null && boundActivityRef != null && boundActivityRef instanceof IBindableView && ((IBindableView) boundActivityRef).getViewBinder() != null && boundActivityRef.getWindow() != null && boundActivityRef.getWindow().getDecorView() != null) { ((IBindableView) boundActivityRef).getViewBinder() .clearBindingForViewAndChildren(getBoundActivity().getWindow().getDecorView().getRootView()); } if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { viewModel.onDestroy(); } } mViewModels = null; mBoundActivity.clear(); mBoundActivity = null; mLogger = null; } @Override public void onConfigurationChanged(Configuration newConfig) { if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { if (viewModel instanceof INeedsConfigurationChange) { ((INeedsConfigurationChange) viewModel).onConfigurationChanged(newConfig); } } } } @Override public void onNewIntent(Intent newIntent) { if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { if (viewModel instanceof INeedsNewIntent) { ((INeedsNewIntent) viewModel).onNewIntent(newIntent); } } } if (getBoundActivity() instanceof AppCompatActivity) { List<Fragment> fragments = ((AppCompatActivity) getBoundActivity()).getSupportFragmentManager().getFragments(); if (fragments != null) { for (Fragment fragment : fragments) { if (fragment instanceof INeedsNewIntent) { ((INeedsNewIntent) fragment).onNewIntent(newIntent); } } } } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { if (viewModel instanceof INeedsOnActivityResult) { ((INeedsOnActivityResult) viewModel).onActivityResult(requestCode, resultCode, data); } } } } @Override public ILogger getLogger() { return mLogger != null ? mLogger : NullLogger.instance; } @Override public void setLogger(ILogger logger) { mLogger = logger; if (getViewModels() != null) { for (ViewModel viewModel : getViewModels().values()) { viewModel.setLogger(getLogger()); } } if (getBoundActivity() instanceof AppCompatActivity) { List<Fragment> fragments = ((AppCompatActivity) getBoundActivity()).getSupportFragmentManager().getFragments(); if (fragments != null) { for (Fragment fragment : fragments) { if (fragment instanceof INeedsLogger) { ((INeedsLogger) fragment).setLogger(logger); } } } } } }
updated BoundActivityDelegate to changes in BoundFragmentDelegate
AndroidBound/src/main/java/solutions/alterego/androidbound/android/BoundActivityDelegate.java
updated BoundActivityDelegate to changes in BoundFragmentDelegate
<ide><path>ndroidBound/src/main/java/solutions/alterego/androidbound/android/BoundActivityDelegate.java <ide> import solutions.alterego.androidbound.interfaces.IHasLogger; <ide> import solutions.alterego.androidbound.interfaces.ILogger; <ide> import solutions.alterego.androidbound.interfaces.INeedsLogger; <add>import solutions.alterego.androidbound.interfaces.IViewBinder; <ide> <ide> @Accessors(prefix = "m") <ide> public class BoundActivityDelegate implements IActivityLifecycle, IBoundActivity, INeedsOnActivityResult, INeedsNewIntent, INeedsConfigurationChange, <ide> <ide> private Bundle mCreateBundle; <ide> <add> private IViewBinder mViewBinder; <add> <ide> public BoundActivityDelegate(Activity activity) { <add> this(activity, null); <add> } <add> <add> public BoundActivityDelegate(Activity activity, IViewBinder viewBinder) { <ide> mBoundActivity = new WeakReference<>(activity); <add> mViewBinder = viewBinder; <add> } <add> <add> private IViewBinder getViewBinder() { <add> if (mViewBinder != null) { <add> return mViewBinder; <add> } else if (getBoundActivity() instanceof IBindableView) { <add> return ((IBindableView) getBoundActivity()).getViewBinder(); <add> } else { <add> throw new RuntimeException("There's no IViewBinder available!"); <add> } <ide> } <ide> <ide> private Activity getBoundActivity() { <ide> throw new RuntimeException("Bound Activity is null!"); <ide> } <ide> <del> if (!(getBoundActivity() instanceof IBindableView)) { <del> throw new RuntimeException("Activity must implement IBindableView!"); <del> } <del> <ide> if (viewModel == null) { <ide> throw new RuntimeException("viewModel is null!"); <del> } <del> <del> if (((IBindableView) getBoundActivity()).getViewBinder() == null) { <del> throw new RuntimeException("getViewBinder must not be null!"); <ide> } <ide> <ide> if (mViewModels == null) { <ide> viewModel.setLogger(getLogger()); <ide> mViewModels.put(id, viewModel); <ide> <del> View view = ((IBindableView) getBoundActivity()).getViewBinder().inflate(getBoundActivity(), viewModel, layoutResID, null); <add> View view = getViewBinder().inflate(getBoundActivity(), viewModel, layoutResID, null); <ide> <ide> if (mShouldCallCreate) { <ide> onCreate(mCreateBundle); <ide> viewModel.onCreate(savedInstanceState); <ide> } <ide> } <add> <add> mShouldCallCreate = false; <ide> } else { <ide> mShouldCallCreate = true; <ide> mCreateBundle = savedInstanceState; <ide> if (mBoundActivity != null <ide> && boundActivityRef != null <ide> && boundActivityRef instanceof IBindableView <del> && ((IBindableView) boundActivityRef).getViewBinder() != null <ide> && boundActivityRef.getWindow() != null <ide> && boundActivityRef.getWindow().getDecorView() != null) { <del> ((IBindableView) boundActivityRef).getViewBinder() <del> .clearBindingForViewAndChildren(getBoundActivity().getWindow().getDecorView().getRootView()); <add> getViewBinder().clearBindingForViewAndChildren(getBoundActivity().getWindow().getDecorView().getRootView()); <ide> } <ide> <ide> if (getViewModels() != null) { <ide> mViewModels = null; <ide> mBoundActivity.clear(); <ide> mBoundActivity = null; <add> mViewBinder = null; <ide> mLogger = null; <ide> } <ide>
Java
lgpl-2.1
52850a3f9b63156e991ad191799d9dad9a1d136b
0
vhhieu/vosao,Jeff-Lewis/vosao,ivanfong01/vosao,ivanfong01/vosao,ivanfong01/vosao,Git-Host/vosao,tectronics/vosao,Dobrojelatel/vosao,psevestre/vosao,Git-Host/vosao,Jeff-Lewis/vosao,Git-Host/vosao,Jeff-Lewis/vosao,vhhieu/vosao,ytrstu/vosao,tectronics/vosao,Jeff-Lewis/vosao,psevestre/vosao,vhhieu/vosao,Dobrojelatel/vosao,ytrstu/vosao,Dobrojelatel/vosao,Dobrojelatel/vosao,Git-Host/vosao,vosaocms/vosao,vosaocms/vosao,tectronics/vosao,vosaocms/vosao,vosaocms/vosao,psevestre/vosao,psevestre/vosao,tectronics/vosao,vhhieu/vosao,ytrstu/vosao,ytrstu/vosao,ivanfong01/vosao
/** * Vosao CMS. Simple CMS for Google App Engine. * * Copyright (C) 2009-2010 Vosao development team. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * email: [email protected] */ package org.vosao.search; import java.io.IOException; import java.util.List; import org.vosao.entity.PageEntity; /** * Search index of all site pages for one language. * * @author Alexander Oleynik * */ public interface SearchIndex { void updateIndex(Long pageId) throws IOException; void removeFromIndex(Long pageId) ; List<Hit> search(SearchResultFilter filter, String query, int textSize); public List<PageEntity> search(SearchResultFilter filter, String query); void saveIndex() throws IOException; String getLanguage(); void clear(); }
api/src/main/java/org/vosao/search/SearchIndex.java
/** * Vosao CMS. Simple CMS for Google App Engine. * * Copyright (C) 2009-2010 Vosao development team. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * email: [email protected] */ package org.vosao.search; import java.io.IOException; import java.util.List; /** * Search index of all site pages for one language. * * @author Alexander Oleynik * */ public interface SearchIndex { void updateIndex(Long pageId) throws IOException; void removeFromIndex(Long pageId) ; List<Hit> search(SearchResultFilter filter, String query, int textSize); void saveIndex() throws IOException; String getLanguage(); void clear(); }
new search method
api/src/main/java/org/vosao/search/SearchIndex.java
new search method
<ide><path>pi/src/main/java/org/vosao/search/SearchIndex.java <ide> import java.io.IOException; <ide> import java.util.List; <ide> <add>import org.vosao.entity.PageEntity; <add> <ide> /** <ide> * Search index of all site pages for one language. <ide> * <ide> <ide> List<Hit> search(SearchResultFilter filter, String query, int textSize); <ide> <add> public List<PageEntity> search(SearchResultFilter filter, String query); <add> <ide> void saveIndex() throws IOException; <ide> <ide> String getLanguage();
Java
epl-1.0
error: pathspec 'src/main/java/org/jtrfp/trcl/game/cht/HoverCheatFactory.java' did not match any file(s) known to git
bf6dca86b58cabc564fa25cd897ab8b905d7d481
1
jtrfp/terminal-recall,jtrfp/terminal-recall,jtrfp/terminal-recall
/******************************************************************************* * This file is part of TERMINAL RECALL * Copyright (c) 2021 Chuck Ritola * Part of the jTRFP.org project * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * chuck - initial API and implementation ******************************************************************************/ package org.jtrfp.trcl.game.cht; import org.jtrfp.trcl.UpfrontDisplay; import org.jtrfp.trcl.core.Feature; import org.jtrfp.trcl.core.Features; import org.jtrfp.trcl.core.TRFactory.TR; import org.jtrfp.trcl.ext.tr.SoundSystemFactory.SoundSystemFeature; import org.jtrfp.trcl.game.TVF3Game; import org.jtrfp.trcl.obj.Propelled; import org.jtrfp.trcl.snd.SoundSystem; import org.springframework.stereotype.Component; @Component public class HoverCheatFactory extends AbstractCheatFactory { private static final String CHEAT_NAME = "Hover! (toggle)"; protected HoverCheatFactory() { super(CHEAT_NAME); } @Override public Class<? extends Feature<?>> getFeatureClass() { return HoverCheat.class; } public class HoverCheat extends AbstractCheatItem { private double defaultMinPropulsion = Double.NaN; public HoverCheat() {super();} @Override protected void invokeCheat() { toggleCheat(); }//end invokeCheat() public void toggleCheat() { if(isCheatEnabled()) disableCheat(); else enableCheat(); }//end toggleCheat() public void enableCheat() { final TVF3Game game = this.getTarget(); final Propelled prop = game.getPlayer().probeForBehavior(Propelled.class); if(!isCheatEnabled()) defaultMinPropulsion = prop.getMinPropulsion(); prop.setMinPropulsion(0); conveyStateToUser(); }//end enableCheat() public void disableCheat() { final TVF3Game game = this.getTarget(); final Propelled prop = game.getPlayer().probeForBehavior(Propelled.class); prop.setMinPropulsion(defaultMinPropulsion); conveyStateToUser(); }//end disableCheat() public boolean isCheatEnabled() { final TVF3Game game = this.getTarget(); final Propelled prop = game.getPlayer().probeForBehavior(Propelled.class); return prop.getMinPropulsion() == 0; }//end isCheatEnabled() private void conveyStateToUser() { final TR tr = getTarget().getTr(); final SoundSystemFeature ssf = Features.get(tr, SoundSystemFeature.class); ssf.enqueuePlaybackEvent(ssf.getPlaybackFactory().create(tr.getResourceManager().soundTextures.get("POWER-1.WAV"), SoundSystem.DEFAULT_SFX_VOLUME_STEREO)); final UpfrontDisplay disp = getTarget().getUpfrontDisplay(); disp.submitMomentaryUpfrontMessage(isCheatEnabled()?"Hover!":"No hover"); }//end conveyStateToUser() }//end HoverCheat }//end HoverCheatFactory
src/main/java/org/jtrfp/trcl/game/cht/HoverCheatFactory.java
⟴HoverCheatFactory. Affects #253.
src/main/java/org/jtrfp/trcl/game/cht/HoverCheatFactory.java
⟴HoverCheatFactory. Affects #253.
<ide><path>rc/main/java/org/jtrfp/trcl/game/cht/HoverCheatFactory.java <add>/******************************************************************************* <add> * This file is part of TERMINAL RECALL <add> * Copyright (c) 2021 Chuck Ritola <add> * Part of the jTRFP.org project <add> * All rights reserved. This program and the accompanying materials <add> * are made available under the terms of the GNU Public License v3.0 <add> * which accompanies this distribution, and is available at <add> * http://www.gnu.org/licenses/gpl.html <add> * <add> * Contributors: <add> * chuck - initial API and implementation <add> ******************************************************************************/ <add> <add>package org.jtrfp.trcl.game.cht; <add> <add>import org.jtrfp.trcl.UpfrontDisplay; <add>import org.jtrfp.trcl.core.Feature; <add>import org.jtrfp.trcl.core.Features; <add>import org.jtrfp.trcl.core.TRFactory.TR; <add>import org.jtrfp.trcl.ext.tr.SoundSystemFactory.SoundSystemFeature; <add>import org.jtrfp.trcl.game.TVF3Game; <add>import org.jtrfp.trcl.obj.Propelled; <add>import org.jtrfp.trcl.snd.SoundSystem; <add>import org.springframework.stereotype.Component; <add> <add>@Component <add>public class HoverCheatFactory extends AbstractCheatFactory { <add> private static final String CHEAT_NAME = "Hover! (toggle)"; <add> <add> protected HoverCheatFactory() { <add> super(CHEAT_NAME); <add> } <add> <add> @Override <add> public Class<? extends Feature<?>> getFeatureClass() { <add> return HoverCheat.class; <add> } <add> <add> public class HoverCheat extends AbstractCheatItem { <add> private double defaultMinPropulsion = Double.NaN; <add> <add> public HoverCheat() {super();} <add> <add> @Override <add> protected void invokeCheat() { <add> toggleCheat(); <add> }//end invokeCheat() <add> <add> public void toggleCheat() { <add> if(isCheatEnabled()) <add> disableCheat(); <add> else <add> enableCheat(); <add> }//end toggleCheat() <add> <add> public void enableCheat() { <add> final TVF3Game game = this.getTarget(); <add> final Propelled prop = game.getPlayer().probeForBehavior(Propelled.class); <add> if(!isCheatEnabled()) <add> defaultMinPropulsion = prop.getMinPropulsion(); <add> prop.setMinPropulsion(0); <add> conveyStateToUser(); <add> }//end enableCheat() <add> <add> public void disableCheat() { <add> final TVF3Game game = this.getTarget(); <add> final Propelled prop = game.getPlayer().probeForBehavior(Propelled.class); <add> prop.setMinPropulsion(defaultMinPropulsion); <add> conveyStateToUser(); <add> }//end disableCheat() <add> <add> public boolean isCheatEnabled() { <add> final TVF3Game game = this.getTarget(); <add> final Propelled prop = game.getPlayer().probeForBehavior(Propelled.class); <add> return prop.getMinPropulsion() == 0; <add> }//end isCheatEnabled() <add> <add> private void conveyStateToUser() { <add> final TR tr = getTarget().getTr(); <add> final SoundSystemFeature ssf = Features.get(tr, SoundSystemFeature.class); <add> ssf.enqueuePlaybackEvent(ssf.getPlaybackFactory().create(tr.getResourceManager().soundTextures.get("POWER-1.WAV"), SoundSystem.DEFAULT_SFX_VOLUME_STEREO)); <add> final UpfrontDisplay disp = getTarget().getUpfrontDisplay(); <add> disp.submitMomentaryUpfrontMessage(isCheatEnabled()?"Hover!":"No hover"); <add> }//end conveyStateToUser() <add> <add> }//end HoverCheat <add> <add>}//end HoverCheatFactory
Java
apache-2.0
a0d22bafdfcd2eecfcc0ce39879e6808ef952035
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 java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.UncheckedIOException; import java.math.BigInteger; import java.net.URL; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.charset.UnsupportedCharsetException; import java.nio.file.CopyOption; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.NotDirectoryException; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.FileTime; import java.time.Duration; import java.time.Instant; import java.time.LocalTime; import java.time.OffsetDateTime; import java.time.OffsetTime; import java.time.ZoneId; import java.time.chrono.ChronoLocalDate; import java.time.chrono.ChronoLocalDateTime; import java.time.chrono.ChronoZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.zip.CRC32; import java.util.zip.CheckedInputStream; import java.util.zip.Checksum; import org.apache.commons.io.file.AccumulatorPathVisitor; import org.apache.commons.io.file.Counters; import org.apache.commons.io.file.PathFilter; import org.apache.commons.io.file.PathUtils; import org.apache.commons.io.file.StandardDeleteOption; import org.apache.commons.io.filefilter.FileEqualsFileFilter; import org.apache.commons.io.filefilter.FileFileFilter; import org.apache.commons.io.filefilter.IOFileFilter; import org.apache.commons.io.filefilter.SuffixFileFilter; import org.apache.commons.io.filefilter.TrueFileFilter; import org.apache.commons.io.function.IOConsumer; import org.apache.commons.io.function.Uncheck; /** * General file manipulation utilities. * <p> * Facilities are provided in the following areas: * </p> * <ul> * <li>writing to a file * <li>reading from a file * <li>make a directory including parent directories * <li>copying files and directories * <li>deleting files and directories * <li>converting to and from a URL * <li>listing files and directories by filter and extension * <li>comparing file content * <li>file last changed date * <li>calculating a checksum * </ul> * <p> * Note that a specific charset should be specified whenever possible. Relying on the platform default means that the * code is Locale-dependent. Only use the default if the files are known to always use the platform default. * </p> * <p> * {@link SecurityException} are not documented in the Javadoc. * </p> * <p> * Origin of code: Excalibur, Alexandria, Commons-Utils * </p> */ public class FileUtils { /** * The number of bytes in a kilobyte. */ public static final long ONE_KB = 1024; /** * The number of bytes in a kilobyte. * * @since 2.4 */ public static final BigInteger ONE_KB_BI = BigInteger.valueOf(ONE_KB); /** * The number of bytes in a megabyte. */ public static final long ONE_MB = ONE_KB * ONE_KB; /** * The number of bytes in a megabyte. * * @since 2.4 */ public static final BigInteger ONE_MB_BI = ONE_KB_BI.multiply(ONE_KB_BI); /** * The number of bytes in a gigabyte. */ public static final long ONE_GB = ONE_KB * ONE_MB; /** * The number of bytes in a gigabyte. * * @since 2.4 */ public static final BigInteger ONE_GB_BI = ONE_KB_BI.multiply(ONE_MB_BI); /** * The number of bytes in a terabyte. */ public static final long ONE_TB = ONE_KB * ONE_GB; /** * The number of bytes in a terabyte. * * @since 2.4 */ public static final BigInteger ONE_TB_BI = ONE_KB_BI.multiply(ONE_GB_BI); /** * The number of bytes in a petabyte. */ public static final long ONE_PB = ONE_KB * ONE_TB; /** * The number of bytes in a petabyte. * * @since 2.4 */ public static final BigInteger ONE_PB_BI = ONE_KB_BI.multiply(ONE_TB_BI); /** * The number of bytes in an exabyte. */ public static final long ONE_EB = ONE_KB * ONE_PB; /** * The number of bytes in an exabyte. * * @since 2.4 */ public static final BigInteger ONE_EB_BI = ONE_KB_BI.multiply(ONE_PB_BI); /** * The number of bytes in a zettabyte. */ public static final BigInteger ONE_ZB = BigInteger.valueOf(ONE_KB).multiply(BigInteger.valueOf(ONE_EB)); /** * The number of bytes in a yottabyte. */ public static final BigInteger ONE_YB = ONE_KB_BI.multiply(ONE_ZB); /** * An empty array of type {@link File}. */ public static final File[] EMPTY_FILE_ARRAY = {}; /** * Copies the given array and adds StandardCopyOption.COPY_ATTRIBUTES. * * @param copyOptions sorted copy options. * @return a new array. */ private static CopyOption[] addCopyAttributes(final CopyOption... copyOptions) { // Make a copy first since we don't want to sort the call site's version. final CopyOption[] actual = Arrays.copyOf(copyOptions, copyOptions.length + 1); Arrays.sort(actual, 0, copyOptions.length); if (Arrays.binarySearch(copyOptions, 0, copyOptions.length, StandardCopyOption.COPY_ATTRIBUTES) >= 0) { return copyOptions; } actual[actual.length - 1] = StandardCopyOption.COPY_ATTRIBUTES; return actual; } /** * Returns a human-readable version of the file size, where the input represents a specific number of bytes. * <p> * If the size is over 1GB, the size is returned as the number of whole GB, i.e. the size is rounded down to the * nearest GB boundary. * </p> * <p> * Similarly for the 1MB and 1KB boundaries. * </p> * * @param size the number of bytes * @return a human-readable display value (includes units - EB, PB, TB, GB, MB, KB or bytes) * @throws NullPointerException if the given {@link BigInteger} is {@code null}. * @see <a href="https://issues.apache.org/jira/browse/IO-226">IO-226 - should the rounding be changed?</a> * @since 2.4 */ // See https://issues.apache.org/jira/browse/IO-226 - should the rounding be changed? public static String byteCountToDisplaySize(final BigInteger size) { Objects.requireNonNull(size, "size"); final String displaySize; if (size.divide(ONE_EB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize = size.divide(ONE_EB_BI) + " EB"; } else if (size.divide(ONE_PB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize = size.divide(ONE_PB_BI) + " PB"; } else if (size.divide(ONE_TB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize = size.divide(ONE_TB_BI) + " TB"; } else if (size.divide(ONE_GB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize = size.divide(ONE_GB_BI) + " GB"; } else if (size.divide(ONE_MB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize = size.divide(ONE_MB_BI) + " MB"; } else if (size.divide(ONE_KB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize = size.divide(ONE_KB_BI) + " KB"; } else { displaySize = size + " bytes"; } return displaySize; } /** * Returns a human-readable version of the file size, where the input represents a specific number of bytes. * <p> * If the size is over 1GB, the size is returned as the number of whole GB, i.e. the size is rounded down to the * nearest GB boundary. * </p> * <p> * Similarly for the 1MB and 1KB boundaries. * </p> * * @param size the number of bytes * @return a human-readable display value (includes units - EB, PB, TB, GB, MB, KB or bytes) * @see <a href="https://issues.apache.org/jira/browse/IO-226">IO-226 - should the rounding be changed?</a> */ // See https://issues.apache.org/jira/browse/IO-226 - should the rounding be changed? public static String byteCountToDisplaySize(final long size) { return byteCountToDisplaySize(BigInteger.valueOf(size)); } /** * Returns a human-readable version of the file size, where the input represents a specific number of bytes. * <p> * If the size is over 1GB, the size is returned as the number of whole GB, i.e. the size is rounded down to the * nearest GB boundary. * </p> * <p> * Similarly for the 1MB and 1KB boundaries. * </p> * * @param size the number of bytes * @return a human-readable display value (includes units - EB, PB, TB, GB, MB, KB or bytes) * @see <a href="https://issues.apache.org/jira/browse/IO-226">IO-226 - should the rounding be changed?</a> * @since 2.12.0 */ // See https://issues.apache.org/jira/browse/IO-226 - should the rounding be changed? public static String byteCountToDisplaySize(final Number size) { return byteCountToDisplaySize(size.longValue()); } /** * Computes the checksum of a file using the specified checksum object. Multiple files may be checked using one * {@link Checksum} instance if desired simply by reusing the same checksum object. For example: * * <pre> * long checksum = FileUtils.checksum(file, new CRC32()).getValue(); * </pre> * * @param file the file to checksum, must not be {@code null} * @param checksum the checksum object to be used, must not be {@code null} * @return the checksum specified, updated with the content of the file * @throws NullPointerException if the given {@link File} is {@code null}. * @throws NullPointerException if the given {@link Checksum} is {@code null}. * @throws IllegalArgumentException if the given {@link File} does not exist or is not a file. * @throws IOException if an IO error occurs reading the file. * @since 1.3 */ public static Checksum checksum(final File file, final Checksum checksum) throws IOException { requireExistsChecked(file, "file"); requireFile(file, "file"); Objects.requireNonNull(checksum, "checksum"); try (InputStream inputStream = new CheckedInputStream(Files.newInputStream(file.toPath()), checksum)) { IOUtils.consume(inputStream); } return checksum; } /** * Computes the checksum of a file using the CRC32 checksum routine. * The value of the checksum is returned. * * @param file the file to checksum, must not be {@code null} * @return the checksum value * @throws NullPointerException if the given {@link File} is {@code null}. * @throws IllegalArgumentException if the given {@link File} does not exist or is not a file. * @throws IOException if an IO error occurs reading the file. * @since 1.3 */ public static long checksumCRC32(final File file) throws IOException { return checksum(file, new CRC32()).getValue(); } /** * Cleans a directory without deleting it. * * @param directory directory to clean * @throws NullPointerException if the given {@link File} is {@code null}. * @throws IllegalArgumentException if directory does not exist or is not a directory. * @throws IOException if an I/O error occurs. * @see #forceDelete(File) */ public static void cleanDirectory(final File directory) throws IOException { IOConsumer.forAll(FileUtils::forceDelete, listFiles(directory, null)); } /** * Cleans a directory without deleting it. * * @param directory directory to clean, must not be {@code null} * @throws NullPointerException if the given {@link File} is {@code null}. * @throws IllegalArgumentException if directory does not exist or is not a directory. * @throws IOException if an I/O error occurs. * @see #forceDeleteOnExit(File) */ private static void cleanDirectoryOnExit(final File directory) throws IOException { IOConsumer.forAll(FileUtils::forceDeleteOnExit, listFiles(directory, null)); } /** * Tests whether the contents of two files are equal. * <p> * This method checks to see if the two files are different lengths or if they point to the same file, before * resorting to byte-by-byte comparison of the contents. * </p> * <p> * Code origin: Avalon * </p> * * @param file1 the first file * @param file2 the second file * @return true if the content of the files are equal or they both don't exist, false otherwise * @throws IllegalArgumentException when an input is not a file. * @throws IOException If an I/O error occurs. * @see org.apache.commons.io.file.PathUtils#fileContentEquals(Path,Path,java.nio.file.LinkOption[],java.nio.file.OpenOption...) */ public static boolean contentEquals(final File file1, final File file2) throws IOException { if (file1 == null && file2 == null) { return true; } if (file1 == null || file2 == null) { return false; } final boolean file1Exists = file1.exists(); if (file1Exists != file2.exists()) { return false; } if (!file1Exists) { // two not existing files are equal return true; } requireFile(file1, "file1"); requireFile(file2, "file2"); if (file1.length() != file2.length()) { // lengths differ, cannot be equal return false; } if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) { // same file return true; } try (InputStream input1 = Files.newInputStream(file1.toPath()); InputStream input2 = Files.newInputStream(file2.toPath())) { return IOUtils.contentEquals(input1, input2); } } /** * Compares the contents of two files to determine if they are equal or not. * <p> * This method checks to see if the two files point to the same file, * before resorting to line-by-line comparison of the contents. * </p> * * @param file1 the first file * @param file2 the second file * @param charsetName the name of the requested charset. * May be null, in which case the platform default is used * @return true if the content of the files are equal or neither exists, * false otherwise * @throws IllegalArgumentException when an input is not a file. * @throws IOException in case of an I/O error. * @throws UnsupportedCharsetException If the named charset is unavailable (unchecked exception). * @see IOUtils#contentEqualsIgnoreEOL(Reader, Reader) * @since 2.2 */ public static boolean contentEqualsIgnoreEOL(final File file1, final File file2, final String charsetName) throws IOException { if (file1 == null && file2 == null) { return true; } if (file1 == null || file2 == null) { return false; } final boolean file1Exists = file1.exists(); if (file1Exists != file2.exists()) { return false; } if (!file1Exists) { // two not existing files are equal return true; } requireFile(file1, "file1"); requireFile(file2, "file2"); if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) { // same file return true; } final Charset charset = Charsets.toCharset(charsetName); try (Reader input1 = new InputStreamReader(Files.newInputStream(file1.toPath()), charset); Reader input2 = new InputStreamReader(Files.newInputStream(file2.toPath()), charset)) { return IOUtils.contentEqualsIgnoreEOL(input1, input2); } } /** * Converts a Collection containing java.io.File instances into array * representation. This is to account for the difference between * File.listFiles() and FileUtils.listFiles(). * * @param files a Collection containing java.io.File instances * @return an array of java.io.File */ public static File[] convertFileCollectionToFileArray(final Collection<File> files) { return files.toArray(EMPTY_FILE_ARRAY); } /** * Copies a whole directory to a new location preserving the file dates. * <p> * This method copies the specified directory and all its child directories and files to the specified destination. * The destination is the new location and name of the directory. * </p> * <p> * The destination directory is created if it does not exist. If the destination directory did exist, then this * method merges the source with the destination, with the source taking precedence. * </p> * <p> * <strong>Note:</strong> This method tries to preserve the files' last modified date/times using * {@link File#setLastModified(long)}, however it is not guaranteed that those operations will succeed. If the * modification operation fails, the methods throws IOException. * </p> * * @param srcDir an existing directory to copy, must not be {@code null}. * @param destDir the new directory, must not be {@code null}. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IllegalArgumentException if the source or destination is invalid. * @throws FileNotFoundException if the source does not exist. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @since 1.1 */ public static void copyDirectory(final File srcDir, final File destDir) throws IOException { copyDirectory(srcDir, destDir, true); } /** * Copies a whole directory to a new location. * <p> * This method copies the contents of the specified source directory to within the specified destination directory. * </p> * <p> * The destination directory is created if it does not exist. If the destination directory did exist, then this * method merges the source with the destination, with the source taking precedence. * </p> * <p> * <strong>Note:</strong> Setting {@code preserveFileDate} to {@code true} tries to preserve the files' last * modified date/times using {@link File#setLastModified(long)}, however it is not guaranteed that those operations * will succeed. If the modification operation fails, the methods throws IOException. * </p> * * @param srcDir an existing directory to copy, must not be {@code null}. * @param destDir the new directory, must not be {@code null}. * @param preserveFileDate true if the file date of the copy should be the same as the original. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IllegalArgumentException if the source or destination is invalid. * @throws FileNotFoundException if the source does not exist. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @since 1.1 */ public static void copyDirectory(final File srcDir, final File destDir, final boolean preserveFileDate) throws IOException { copyDirectory(srcDir, destDir, null, preserveFileDate); } /** * Copies a filtered directory to a new location preserving the file dates. * <p> * This method copies the contents of the specified source directory to within the specified destination directory. * </p> * <p> * The destination directory is created if it does not exist. If the destination directory did exist, then this * method merges the source with the destination, with the source taking precedence. * </p> * <p> * <strong>Note:</strong> This method tries to preserve the files' last modified date/times using * {@link File#setLastModified(long)}, however it is not guaranteed that those operations will succeed. If the * modification operation fails, the methods throws IOException. * </p> * <b>Example: Copy directories only</b> * * <pre> * // only copy the directory structure * FileUtils.copyDirectory(srcDir, destDir, DirectoryFileFilter.DIRECTORY); * </pre> * * <b>Example: Copy directories and txt files</b> * * <pre> * // Create a filter for ".txt" files * IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt"); * IOFileFilter txtFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE, txtSuffixFilter); * * // Create a filter for either directories or ".txt" files * FileFilter filter = FileFilterUtils.orFileFilter(DirectoryFileFilter.DIRECTORY, txtFiles); * * // Copy using the filter * FileUtils.copyDirectory(srcDir, destDir, filter); * </pre> * * @param srcDir an existing directory to copy, must not be {@code null}. * @param destDir the new directory, must not be {@code null}. * @param filter the filter to apply, null means copy all directories and files should be the same as the original. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IllegalArgumentException if the source or destination is invalid. * @throws FileNotFoundException if the source does not exist. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @since 1.4 */ public static void copyDirectory(final File srcDir, final File destDir, final FileFilter filter) throws IOException { copyDirectory(srcDir, destDir, filter, true); } /** * Copies a filtered directory to a new location. * <p> * This method copies the contents of the specified source directory to within the specified destination directory. * </p> * <p> * The destination directory is created if it does not exist. If the destination directory did exist, then this * method merges the source with the destination, with the source taking precedence. * </p> * <p> * <strong>Note:</strong> Setting {@code preserveFileDate} to {@code true} tries to preserve the files' last * modified date/times using {@link File#setLastModified(long)}, however it is not guaranteed that those operations * will succeed. If the modification operation fails, the methods throws IOException. * </p> * <b>Example: Copy directories only</b> * * <pre> * // only copy the directory structure * FileUtils.copyDirectory(srcDir, destDir, DirectoryFileFilter.DIRECTORY, false); * </pre> * * <b>Example: Copy directories and txt files</b> * * <pre> * // Create a filter for ".txt" files * IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt"); * IOFileFilter txtFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE, txtSuffixFilter); * * // Create a filter for either directories or ".txt" files * FileFilter filter = FileFilterUtils.orFileFilter(DirectoryFileFilter.DIRECTORY, txtFiles); * * // Copy using the filter * FileUtils.copyDirectory(srcDir, destDir, filter, false); * </pre> * * @param srcDir an existing directory to copy, must not be {@code null}. * @param destDir the new directory, must not be {@code null}. * @param filter the filter to apply, null means copy all directories and files. * @param preserveFileDate true if the file date of the copy should be the same as the original. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IllegalArgumentException if the source or destination is invalid. * @throws FileNotFoundException if the source does not exist. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @since 1.4 */ public static void copyDirectory(final File srcDir, final File destDir, final FileFilter filter, final boolean preserveFileDate) throws IOException { copyDirectory(srcDir, destDir, filter, preserveFileDate, StandardCopyOption.REPLACE_EXISTING); } /** * Copies a filtered directory to a new location. * <p> * This method copies the contents of the specified source directory to within the specified destination directory. * </p> * <p> * The destination directory is created if it does not exist. If the destination directory did exist, then this * method merges the source with the destination, with the source taking precedence. * </p> * <p> * <strong>Note:</strong> Setting {@code preserveFileDate} to {@code true} tries to preserve the files' last * modified date/times using {@link File#setLastModified(long)}, however it is not guaranteed that those operations * will succeed. If the modification operation fails, the methods throws IOException. * </p> * <b>Example: Copy directories only</b> * * <pre> * // only copy the directory structure * FileUtils.copyDirectory(srcDir, destDir, DirectoryFileFilter.DIRECTORY, false); * </pre> * * <b>Example: Copy directories and txt files</b> * * <pre> * // Create a filter for ".txt" files * IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt"); * IOFileFilter txtFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE, txtSuffixFilter); * * // Create a filter for either directories or ".txt" files * FileFilter filter = FileFilterUtils.orFileFilter(DirectoryFileFilter.DIRECTORY, txtFiles); * * // Copy using the filter * FileUtils.copyDirectory(srcDir, destDir, filter, false); * </pre> * * @param srcDir an existing directory to copy, must not be {@code null} * @param destDir the new directory, must not be {@code null} * @param fileFilter the filter to apply, null means copy all directories and files * @param preserveFileDate true if the file date of the copy should be the same as the original * @param copyOptions options specifying how the copy should be done, for example {@link StandardCopyOption}. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IllegalArgumentException if the source or destination is invalid. * @throws FileNotFoundException if the source does not exist. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @since 2.8.0 */ public static void copyDirectory(final File srcDir, final File destDir, final FileFilter fileFilter, final boolean preserveFileDate, final CopyOption... copyOptions) throws IOException { requireFileCopy(srcDir, destDir); requireDirectory(srcDir, "srcDir"); requireCanonicalPathsNotEquals(srcDir, destDir); // Cater for destination being directory within the source directory (see IO-141) List<String> exclusionList = null; final String srcDirCanonicalPath = srcDir.getCanonicalPath(); final String destDirCanonicalPath = destDir.getCanonicalPath(); if (destDirCanonicalPath.startsWith(srcDirCanonicalPath)) { final File[] srcFiles = listFiles(srcDir, fileFilter); if (srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { exclusionList.add(new File(destDir, srcFile.getName()).getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, fileFilter, exclusionList, preserveFileDate, preserveFileDate ? addCopyAttributes(copyOptions) : copyOptions); } /** * Copies a directory to within another directory preserving the file dates. * <p> * This method copies the source directory and all its contents to a directory of the same name in the specified * destination directory. * </p> * <p> * The destination directory is created if it does not exist. If the destination directory did exist, then this * method merges the source with the destination, with the source taking precedence. * </p> * <p> * <strong>Note:</strong> This method tries to preserve the files' last modified date/times using * {@link File#setLastModified(long)}, however it is not guaranteed that those operations will succeed. If the * modification operation fails, the methods throws IOException. * </p> * * @param sourceDir an existing directory to copy, must not be {@code null}. * @param destinationDir the directory to place the copy in, must not be {@code null}. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IllegalArgumentException if the source or destination is invalid. * @throws FileNotFoundException if the source does not exist. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @since 1.2 */ public static void copyDirectoryToDirectory(final File sourceDir, final File destinationDir) throws IOException { requireDirectoryIfExists(sourceDir, "sourceDir"); requireDirectoryIfExists(destinationDir, "destinationDir"); copyDirectory(sourceDir, new File(destinationDir, sourceDir.getName()), true); } /** * Copies a file to a new location preserving the file date. * <p> * This method copies the contents of the specified source file to the specified destination file. The directory * holding the destination file is created if it does not exist. If the destination file exists, then this method * will overwrite it. * </p> * <p> * <strong>Note:</strong> This method tries to preserve the file's last modified date/times using * {@link StandardCopyOption#COPY_ATTRIBUTES}, however it is not guaranteed that the operation will succeed. If the * modification operation fails, the methods throws IOException. * </p> * * @param srcFile an existing file to copy, must not be {@code null}. * @param destFile the new file, must not be {@code null}. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IOException if source or destination is invalid. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @throws IOException if the output file length is not the same as the input file length after the copy completes. * @see #copyFileToDirectory(File, File) * @see #copyFile(File, File, boolean) */ public static void copyFile(final File srcFile, final File destFile) throws IOException { copyFile(srcFile, destFile, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); } /** * Copies an existing file to a new file location. * <p> * This method copies the contents of the specified source file to the specified destination file. The directory * holding the destination file is created if it does not exist. If the destination file exists, then this method * will overwrite it. * </p> * <p> * <strong>Note:</strong> Setting {@code preserveFileDate} to {@code true} tries to preserve the file's last * modified date/times using {@link StandardCopyOption#COPY_ATTRIBUTES}, however it is not guaranteed that the operation * will succeed. If the modification operation fails, the methods throws IOException. * </p> * * @param srcFile an existing file to copy, must not be {@code null}. * @param destFile the new file, must not be {@code null}. * @param preserveFileDate true if the file date of the copy should be the same as the original. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IOException if source or destination is invalid. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @throws IOException if the output file length is not the same as the input file length after the copy completes * @see #copyFile(File, File, boolean, CopyOption...) */ public static void copyFile(final File srcFile, final File destFile, final boolean preserveFileDate) throws IOException { // @formatter:off copyFile(srcFile, destFile, preserveFileDate ? new CopyOption[] {StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING} : new CopyOption[] {StandardCopyOption.REPLACE_EXISTING}); // @formatter:on } /** * Copies a file to a new location. * <p> * This method copies the contents of the specified source file to the specified destination file. The directory * holding the destination file is created if it does not exist. If the destination file exists, you can overwrite * it with {@link StandardCopyOption#REPLACE_EXISTING}. * </p> * <p> * <strong>Note:</strong> Setting {@code preserveFileDate} to {@code true} tries to preserve the file's last * modified date/times using {@link StandardCopyOption#COPY_ATTRIBUTES}, however it is not guaranteed that the operation * will succeed. If the modification operation fails, the methods throws IOException. * </p> * * @param srcFile an existing file to copy, must not be {@code null}. * @param destFile the new file, must not be {@code null}. * @param preserveFileDate true if the file date of the copy should be the same as the original. * @param copyOptions options specifying how the copy should be done, for example {@link StandardCopyOption}.. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws FileNotFoundException if the source does not exist. * @throws IllegalArgumentException if source is not a file. * @throws IOException if the output file length is not the same as the input file length after the copy completes. * @throws IOException if an I/O error occurs, or setting the last-modified time didn't succeed. * @see #copyFileToDirectory(File, File, boolean) * @since 2.8.0 */ public static void copyFile(final File srcFile, final File destFile, final boolean preserveFileDate, final CopyOption... copyOptions) throws IOException { copyFile(srcFile, destFile, preserveFileDate ? addCopyAttributes(copyOptions) : copyOptions); } /** * Copies a file to a new location. * <p> * This method copies the contents of the specified source file to the specified destination file. The directory * holding the destination file is created if it does not exist. If the destination file exists, you can overwrite * it if you use {@link StandardCopyOption#REPLACE_EXISTING}. * </p> * * @param srcFile an existing file to copy, must not be {@code null}. * @param destFile the new file, must not be {@code null}. * @param copyOptions options specifying how the copy should be done, for example {@link StandardCopyOption}.. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws FileNotFoundException if the source does not exist. * @throws IllegalArgumentException if source is not a file. * @throws IOException if an I/O error occurs. * @see StandardCopyOption * @since 2.9.0 */ public static void copyFile(final File srcFile, final File destFile, final CopyOption... copyOptions) throws IOException { requireFileCopy(srcFile, destFile); requireFile(srcFile, "srcFile"); requireCanonicalPathsNotEquals(srcFile, destFile); createParentDirectories(destFile); requireFileIfExists(destFile, "destFile"); if (destFile.exists()) { requireCanWrite(destFile, "destFile"); } // On Windows, the last modified time is copied by default. Files.copy(srcFile.toPath(), destFile.toPath(), copyOptions); } /** * Copies bytes from a {@link File} to an {@link OutputStream}. * <p> * This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}. * </p> * * @param input the {@link File} to read. * @param output the {@link OutputStream} to write. * @return the number of bytes copied * @throws NullPointerException if the File is {@code null}. * @throws NullPointerException if the OutputStream is {@code null}. * @throws IOException if an I/O error occurs. * @since 2.1 */ public static long copyFile(final File input, final OutputStream output) throws IOException { try (InputStream fis = Files.newInputStream(input.toPath())) { return IOUtils.copyLarge(fis, output); } } /** * Copies a file to a directory preserving the file date. * <p> * This method copies the contents of the specified source file to a file of the same name in the specified * destination directory. The destination directory is created if it does not exist. If the destination file exists, * then this method will overwrite it. * </p> * <p> * <strong>Note:</strong> This method tries to preserve the file's last modified date/times using * {@link StandardCopyOption#COPY_ATTRIBUTES}, however it is not guaranteed that the operation will succeed. If the * modification operation fails, the methods throws IOException. * </p> * * @param srcFile an existing file to copy, must not be {@code null}. * @param destDir the directory to place the copy in, must not be {@code null}. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IllegalArgumentException if source or destination is invalid. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @see #copyFile(File, File, boolean) */ public static void copyFileToDirectory(final File srcFile, final File destDir) throws IOException { copyFileToDirectory(srcFile, destDir, true); } /** * Copies a file to a directory optionally preserving the file date. * <p> * This method copies the contents of the specified source file to a file of the same name in the specified * destination directory. The destination directory is created if it does not exist. If the destination file exists, * then this method will overwrite it. * </p> * <p> * <strong>Note:</strong> Setting {@code preserveFileDate} to {@code true} tries to preserve the file's last * modified date/times using {@link StandardCopyOption#COPY_ATTRIBUTES}, however it is not guaranteed that the operation * will succeed. If the modification operation fails, the methods throws IOException. * </p> * * @param sourceFile an existing file to copy, must not be {@code null}. * @param destinationDir the directory to place the copy in, must not be {@code null}. * @param preserveFileDate true if the file date of the copy should be the same as the original. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @throws IOException if the output file length is not the same as the input file length after the copy completes. * @see #copyFile(File, File, CopyOption...) * @since 1.3 */ public static void copyFileToDirectory(final File sourceFile, final File destinationDir, final boolean preserveFileDate) throws IOException { Objects.requireNonNull(sourceFile, "sourceFile"); requireDirectoryIfExists(destinationDir, "destinationDir"); copyFile(sourceFile, new File(destinationDir, sourceFile.getName()), preserveFileDate); } /** * Copies bytes from an {@link InputStream} {@code source} to a file * {@code destination}. The directories up to {@code destination} * will be created if they don't already exist. {@code destination} * will be overwritten if it already exists. * <p> * <em>The {@code source} stream is closed.</em> * </p> * <p> * See {@link #copyToFile(InputStream, File)} for a method that does not close the input stream. * </p> * * @param source the {@link InputStream} to copy bytes from, must not be {@code null}, will be closed * @param destination the non-directory {@link File} to write bytes to * (possibly overwriting), must not be {@code null} * @throws IOException if {@code destination} is a directory * @throws IOException if {@code destination} cannot be written * @throws IOException if {@code destination} needs creating but can't be * @throws IOException if an IO error occurs during copying * @since 2.0 */ public static void copyInputStreamToFile(final InputStream source, final File destination) throws IOException { try (InputStream inputStream = source) { copyToFile(inputStream, destination); } } /** * Copies a file or directory to within another directory preserving the file dates. * <p> * This method copies the source file or directory, along all its contents, to a directory of the same name in the * specified destination directory. * </p> * <p> * The destination directory is created if it does not exist. If the destination directory did exist, then this method * merges the source with the destination, with the source taking precedence. * </p> * <p> * <strong>Note:</strong> This method tries to preserve the files' last modified date/times using * {@link StandardCopyOption#COPY_ATTRIBUTES} or {@link File#setLastModified(long)} depending on the input, however it * is not guaranteed that those operations will succeed. If the modification operation fails, the methods throws * IOException. * </p> * * @param sourceFile an existing file or directory to copy, must not be {@code null}. * @param destinationDir the directory to place the copy in, must not be {@code null}. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IllegalArgumentException if the source or destination is invalid. * @throws FileNotFoundException if the source does not exist. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @see #copyDirectoryToDirectory(File, File) * @see #copyFileToDirectory(File, File) * @since 2.6 */ public static void copyToDirectory(final File sourceFile, final File destinationDir) throws IOException { Objects.requireNonNull(sourceFile, "sourceFile"); if (sourceFile.isFile()) { copyFileToDirectory(sourceFile, destinationDir); } else if (sourceFile.isDirectory()) { copyDirectoryToDirectory(sourceFile, destinationDir); } else { throw new FileNotFoundException("The source " + sourceFile + " does not exist"); } } /** * Copies a files to a directory preserving each file's date. * <p> * This method copies the contents of the specified source files * to a file of the same name in the specified destination directory. * The destination directory is created if it does not exist. * If the destination file exists, then this method will overwrite it. * </p> * <p> * <strong>Note:</strong> This method tries to preserve the file's last * modified date/times using {@link File#setLastModified(long)}, however * it is not guaranteed that the operation will succeed. * If the modification operation fails, the methods throws IOException. * </p> * * @param sourceIterable existing files to copy, must not be {@code null}. * @param destinationDir the directory to place the copies in, must not be {@code null}. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IOException if source or destination is invalid. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @see #copyFileToDirectory(File, File) * @since 2.6 */ public static void copyToDirectory(final Iterable<File> sourceIterable, final File destinationDir) throws IOException { Objects.requireNonNull(sourceIterable, "sourceIterable"); for (final File src : sourceIterable) { copyFileToDirectory(src, destinationDir); } } /** * Copies bytes from an {@link InputStream} source to a {@link File} destination. The directories * up to {@code destination} will be created if they don't already exist. {@code destination} will be * overwritten if it already exists. The {@code source} stream is left open, e.g. for use with * {@link java.util.zip.ZipInputStream ZipInputStream}. See {@link #copyInputStreamToFile(InputStream, File)} for a * method that closes the input stream. * * @param inputStream the {@link InputStream} to copy bytes from, must not be {@code null} * @param file the non-directory {@link File} to write bytes to (possibly overwriting), must not be * {@code null} * @throws NullPointerException if the InputStream is {@code null}. * @throws NullPointerException if the File is {@code null}. * @throws IllegalArgumentException if the file object is a directory. * @throws IllegalArgumentException if the file is not writable. * @throws IOException if the directories could not be created. * @throws IOException if an IO error occurs during copying. * @since 2.5 */ public static void copyToFile(final InputStream inputStream, final File file) throws IOException { try (OutputStream out = newOutputStream(file, false)) { IOUtils.copy(inputStream, out); } } /** * Copies bytes from the URL {@code source} to a file * {@code destination}. The directories up to {@code destination} * will be created if they don't already exist. {@code destination} * will be overwritten if it already exists. * <p> * Warning: this method does not set a connection or read timeout and thus * might block forever. Use {@link #copyURLToFile(URL, File, int, int)} * with reasonable timeouts to prevent this. * </p> * * @param source the {@link URL} to copy bytes from, must not be {@code null} * @param destination the non-directory {@link File} to write bytes to * (possibly overwriting), must not be {@code null} * @throws IOException if {@code source} URL cannot be opened * @throws IOException if {@code destination} is a directory * @throws IOException if {@code destination} cannot be written * @throws IOException if {@code destination} needs creating but can't be * @throws IOException if an IO error occurs during copying */ public static void copyURLToFile(final URL source, final File destination) throws IOException { try (InputStream stream = source.openStream()) { final Path path = destination.toPath(); PathUtils.createParentDirectories(path); Files.copy(stream, path, StandardCopyOption.REPLACE_EXISTING); } } /** * Copies bytes from the URL {@code source} to a file {@code destination}. The directories up to * {@code destination} will be created if they don't already exist. {@code destination} will be * overwritten if it already exists. * * @param source the {@link URL} to copy bytes from, must not be {@code null} * @param destination the non-directory {@link File} to write bytes to (possibly overwriting), must not be * {@code null} * @param connectionTimeoutMillis the number of milliseconds until this method will time out if no connection could * be established to the {@code source} * @param readTimeoutMillis the number of milliseconds until this method will time out if no data could be read from * the {@code source} * @throws IOException if {@code source} URL cannot be opened * @throws IOException if {@code destination} is a directory * @throws IOException if {@code destination} cannot be written * @throws IOException if {@code destination} needs creating but can't be * @throws IOException if an IO error occurs during copying * @since 2.0 */ public static void copyURLToFile(final URL source, final File destination, final int connectionTimeoutMillis, final int readTimeoutMillis) throws IOException { try (CloseableURLConnection urlConnection = CloseableURLConnection.open(source)) { urlConnection.setConnectTimeout(connectionTimeoutMillis); urlConnection.setReadTimeout(readTimeoutMillis); try (InputStream stream = urlConnection.getInputStream()) { copyInputStreamToFile(stream, destination); } } } /** * Creates all parent directories for a File object. * * @param file the File that may need parents, may be null. * @return The parent directory, or {@code null} if the given file does not name a parent * @throws IOException if the directory was not created along with all its parent directories. * @throws IOException if the given file object is not null and not a directory. * @since 2.9.0 */ public static File createParentDirectories(final File file) throws IOException { return mkdirs(getParentFile(file)); } /** * Gets the current directory. * * @return the current directory. * @since 2.12.0 */ public static File current() { return PathUtils.current().toFile(); } /** * Decodes the specified URL as per RFC 3986, i.e. transforms * percent-encoded octets to characters by decoding with the UTF-8 character * set. This function is primarily intended for usage with * {@link java.net.URL} which unfortunately does not enforce proper URLs. As * such, this method will leniently accept invalid characters or malformed * percent-encoded octets and simply pass them literally through to the * result string. Except for rare edge cases, this will make unencoded URLs * pass through unaltered. * * @param url The URL to decode, may be {@code null}. * @return The decoded URL or {@code null} if the input was * {@code null}. */ static String decodeUrl(final String url) { String decoded = url; if (url != null && url.indexOf('%') >= 0) { final int n = url.length(); final StringBuilder builder = new StringBuilder(); final ByteBuffer byteBuffer = ByteBuffer.allocate(n); for (int i = 0; i < n; ) { if (url.charAt(i) == '%') { try { do { final byte octet = (byte) Integer.parseInt(url.substring(i + 1, i + 3), 16); byteBuffer.put(octet); i += 3; } while (i < n && url.charAt(i) == '%'); continue; } catch (final RuntimeException ignored) { // malformed percent-encoded octet, fall through and // append characters literally } finally { if (byteBuffer.position() > 0) { byteBuffer.flip(); builder.append(StandardCharsets.UTF_8.decode(byteBuffer).toString()); byteBuffer.clear(); } } } builder.append(url.charAt(i++)); } decoded = builder.toString(); } return decoded; } /** * Deletes the given File but throws an IOException if it cannot, unlike {@link File#delete()} which returns a * boolean. * * @param file The file to delete. * @return the given file. * @throws NullPointerException if the parameter is {@code null} * @throws IOException if the file cannot be deleted. * @see File#delete() * @since 2.9.0 */ public static File delete(final File file) throws IOException { Objects.requireNonNull(file, "file"); Files.delete(file.toPath()); return file; } /** * Deletes a directory recursively. * * @param directory directory to delete * @throws IOException in case deletion is unsuccessful * @throws NullPointerException if the parameter is {@code null} * @throws IllegalArgumentException if {@code directory} is not a directory */ public static void deleteDirectory(final File directory) throws IOException { Objects.requireNonNull(directory, "directory"); if (!directory.exists()) { return; } if (!isSymlink(directory)) { cleanDirectory(directory); } delete(directory); } /** * Schedules a directory recursively for deletion on JVM exit. * * @param directory directory to delete, must not be {@code null} * @throws NullPointerException if the directory is {@code null} * @throws IOException in case deletion is unsuccessful */ private static void deleteDirectoryOnExit(final File directory) throws IOException { if (!directory.exists()) { return; } directory.deleteOnExit(); if (!isSymlink(directory)) { cleanDirectoryOnExit(directory); } } /** * Deletes a file, never throwing an exception. If file is a directory, delete it and all subdirectories. * <p> * The difference between File.delete() and this method are: * </p> * <ul> * <li>A directory to be deleted does not have to be empty.</li> * <li>No exceptions are thrown when a file or directory cannot be deleted.</li> * </ul> * * @param file file or directory to delete, can be {@code null} * @return {@code true} if the file or directory was deleted, otherwise * {@code false} * * @since 1.4 */ public static boolean deleteQuietly(final File file) { if (file == null) { return false; } try { if (file.isDirectory()) { cleanDirectory(file); } } catch (final Exception ignored) { // ignore } try { return file.delete(); } catch (final Exception ignored) { return false; } } /** * Determines whether the {@code parent} directory contains the {@code child} element (a file or directory). * <p> * Files are normalized before comparison. * </p> * * Edge cases: * <ul> * <li>A {@code directory} must not be null: if null, throw IllegalArgumentException</li> * <li>A {@code directory} must be a directory: if not a directory, throw IllegalArgumentException</li> * <li>A directory does not contain itself: return false</li> * <li>A null child file is not contained in any parent: return false</li> * </ul> * * @param directory the file to consider as the parent. * @param child the file to consider as the child. * @return true is the candidate leaf is under by the specified composite. False otherwise. * @throws IOException if an IO error occurs while checking the files. * @throws NullPointerException if the given {@link File} is {@code null}. * @throws IllegalArgumentException if the given {@link File} does not exist or is not a directory. * @see FilenameUtils#directoryContains(String, String) * @since 2.2 */ public static boolean directoryContains(final File directory, final File child) throws IOException { requireDirectoryExists(directory, "directory"); if (child == null || !directory.exists() || !child.exists()) { return false; } // Canonicalize paths (normalizes relative paths) return FilenameUtils.directoryContains(directory.getCanonicalPath(), child.getCanonicalPath()); } /** * Internal copy directory method. * * @param srcDir the validated source directory, must not be {@code null}. * @param destDir the validated destination directory, must not be {@code null}. * @param fileFilter the filter to apply, null means copy all directories and files. * @param exclusionList List of files and directories to exclude from the copy, may be null. * @param preserveDirDate preserve the directories last modified dates. * @param copyOptions options specifying how the copy should be done, see {@link StandardCopyOption}. * @throws IOException if the directory was not created along with all its parent directories. * @throws IOException if the given file object is not a directory. */ private static void doCopyDirectory(final File srcDir, final File destDir, final FileFilter fileFilter, final List<String> exclusionList, final boolean preserveDirDate, final CopyOption... copyOptions) throws IOException { // recurse dirs, copy files. final File[] srcFiles = listFiles(srcDir, fileFilter); requireDirectoryIfExists(destDir, "destDir"); mkdirs(destDir); requireCanWrite(destDir, "destDir"); for (final File srcFile : srcFiles) { final File dstFile = new File(destDir, srcFile.getName()); if (exclusionList == null || !exclusionList.contains(srcFile.getCanonicalPath())) { if (srcFile.isDirectory()) { doCopyDirectory(srcFile, dstFile, fileFilter, exclusionList, preserveDirDate, copyOptions); } else { copyFile(srcFile, dstFile, copyOptions); } } } // Do this last, as the above has probably affected directory metadata if (preserveDirDate) { setLastModified(srcDir, destDir); } } /** * Deletes a file or directory. For a directory, delete it and all subdirectories. * <p> * The difference between File.delete() and this method are: * </p> * <ul> * <li>The directory does not have to be empty.</li> * <li>You get an exception when a file or directory cannot be deleted.</li> * </ul> * * @param file file or directory to delete, must not be {@code null}. * @throws NullPointerException if the file is {@code null}. * @throws FileNotFoundException if the file was not found. * @throws IOException in case deletion is unsuccessful. */ public static void forceDelete(final File file) throws IOException { Objects.requireNonNull(file, "file"); final Counters.PathCounters deleteCounters; try { deleteCounters = PathUtils.delete(file.toPath(), PathUtils.EMPTY_LINK_OPTION_ARRAY, StandardDeleteOption.OVERRIDE_READ_ONLY); } catch (final IOException e) { throw new IOException("Cannot delete file: " + file, e); } if (deleteCounters.getFileCounter().get() < 1 && deleteCounters.getDirectoryCounter().get() < 1) { // didn't find a file to delete. throw new FileNotFoundException("File does not exist: " + file); } } /** * Schedules a file to be deleted when JVM exits. * If file is directory delete it and all subdirectories. * * @param file file or directory to delete, must not be {@code null}. * @throws NullPointerException if the file is {@code null}. * @throws IOException in case deletion is unsuccessful. */ public static void forceDeleteOnExit(final File file) throws IOException { Objects.requireNonNull(file, "file"); if (file.isDirectory()) { deleteDirectoryOnExit(file); } else { file.deleteOnExit(); } } /** * Makes a directory, including any necessary but nonexistent parent * directories. If a file already exists with specified name but it is * not a directory then an IOException is thrown. * If the directory cannot be created (or the file already exists but is not a directory) * then an IOException is thrown. * * @param directory directory to create, may be {@code null}. * @throws IOException if the directory was not created along with all its parent directories. * @throws IOException if the given file object is not a directory. * @throws SecurityException See {@link File#mkdirs()}. */ public static void forceMkdir(final File directory) throws IOException { mkdirs(directory); } /** * Makes any necessary but nonexistent parent directories for a given File. If the parent directory cannot be * created then an IOException is thrown. * * @param file file with parent to create, must not be {@code null}. * @throws NullPointerException if the file is {@code null}. * @throws IOException if the parent directory cannot be created. * @since 2.5 */ public static void forceMkdirParent(final File file) throws IOException { Objects.requireNonNull(file, "file"); forceMkdir(getParentFile(file)); } /** * Constructs a file from the set of name elements. * * @param directory the parent directory. * @param names the name elements. * @return the new file. * @since 2.1 */ public static File getFile(final File directory, final String... names) { Objects.requireNonNull(directory, "directory"); Objects.requireNonNull(names, "names"); File file = directory; for (final String name : names) { file = new File(file, name); } return file; } /** * Constructs a file from the set of name elements. * * @param names the name elements. * @return the file. * @since 2.1 */ public static File getFile(final String... names) { Objects.requireNonNull(names, "names"); File file = null; for (final String name : names) { if (file == null) { file = new File(name); } else { file = new File(file, name); } } return file; } /** * Gets the parent of the given file. The given file may be bull and a file's parent may as well be null. * * @param file The file to query. * @return The parent file or {@code null}. */ private static File getParentFile(final File file) { return file == null ? null : file.getParentFile(); } /** * Returns a {@link File} representing the system temporary directory. * * @return the system temporary directory. * * @since 2.0 */ public static File getTempDirectory() { return new File(getTempDirectoryPath()); } /** * Returns the path to the system temporary directory. * * @return the path to the system temporary directory. * * @since 2.0 */ public static String getTempDirectoryPath() { return System.getProperty("java.io.tmpdir"); } /** * Returns a {@link File} representing the user's home directory. * * @return the user's home directory. * * @since 2.0 */ public static File getUserDirectory() { return new File(getUserDirectoryPath()); } /** * Returns the path to the user's home directory. * * @return the path to the user's home directory. * * @since 2.0 */ public static String getUserDirectoryPath() { return System.getProperty("user.home"); } /** * Tests whether the specified {@link File} is a directory or not. Implemented as a * null-safe delegate to {@link Files#isDirectory(Path path, LinkOption... options)}. * * @param file the path to the file. * @param options options indicating how symbolic links are handled * @return {@code true} if the file is a directory; {@code false} if * the path is null, the file does not exist, is not a directory, or it cannot * be determined if the file is a directory or not. * @throws SecurityException In the case of the default provider, and a security manager is installed, the * {@link SecurityManager#checkRead(String) checkRead} method is invoked to check read * access to the directory. * @since 2.9.0 */ public static boolean isDirectory(final File file, final LinkOption... options) { return file != null && Files.isDirectory(file.toPath(), options); } /** * Tests whether the directory is empty. * * @param directory the directory to query. * @return whether the directory is empty. * @throws IOException if an I/O error occurs. * @throws NotDirectoryException if the file could not otherwise be opened because it is not a directory * <i>(optional specific exception)</i>. * @since 2.9.0 */ public static boolean isEmptyDirectory(final File directory) throws IOException { return PathUtils.isEmptyDirectory(directory.toPath()); } /** * Tests if the specified {@link File} is newer than the specified {@link ChronoLocalDate} * at the current time. * * <p>Note: The input date is assumed to be in the system default time-zone with the time * part set to the current time. To use a non-default time-zone use the method * {@link #isFileNewer(File, ChronoLocalDateTime, ZoneId) * isFileNewer(file, chronoLocalDate.atTime(LocalTime.now(zoneId)), zoneId)} where * {@code zoneId} is a valid {@link ZoneId}. * * @param file the {@link File} of which the modification date must be compared. * @param chronoLocalDate the date reference. * @return true if the {@link File} exists and has been modified after the given * {@link ChronoLocalDate} at the current time. * @throws NullPointerException if the file or local date is {@code null}. * @since 2.8.0 */ public static boolean isFileNewer(final File file, final ChronoLocalDate chronoLocalDate) { return isFileNewer(file, chronoLocalDate, LocalTime.now()); } /** * Tests if the specified {@link File} is newer than the specified {@link ChronoLocalDate} * at the specified time. * * <p>Note: The input date and time are assumed to be in the system default time-zone. To use a * non-default time-zone use the method {@link #isFileNewer(File, ChronoLocalDateTime, ZoneId) * isFileNewer(file, chronoLocalDate.atTime(localTime), zoneId)} where {@code zoneId} is a valid * {@link ZoneId}. * * @param file the {@link File} of which the modification date must be compared. * @param chronoLocalDate the date reference. * @param localTime the time reference. * @return true if the {@link File} exists and has been modified after the given * {@link ChronoLocalDate} at the given time. * @throws NullPointerException if the file, local date or zone ID is {@code null}. * @since 2.8.0 */ public static boolean isFileNewer(final File file, final ChronoLocalDate chronoLocalDate, final LocalTime localTime) { Objects.requireNonNull(chronoLocalDate, "chronoLocalDate"); Objects.requireNonNull(localTime, "localTime"); return isFileNewer(file, chronoLocalDate.atTime(localTime)); } /** * Tests if the specified {@link File} is newer than the specified {@link ChronoLocalDate} at the specified * {@link OffsetTime}. * * @param file the {@link File} of which the modification date must be compared * @param chronoLocalDate the date reference * @param offsetTime the time reference * @return true if the {@link File} exists and has been modified after the given {@link ChronoLocalDate} at the given * {@link OffsetTime}. * @throws NullPointerException if the file, local date or zone ID is {@code null} * @since 2.12.0 */ public static boolean isFileNewer(final File file, final ChronoLocalDate chronoLocalDate, final OffsetTime offsetTime) { Objects.requireNonNull(chronoLocalDate, "chronoLocalDate"); Objects.requireNonNull(offsetTime, "offsetTime"); return isFileNewer(file, chronoLocalDate.atTime(offsetTime.toLocalTime())); } /** * Tests if the specified {@link File} is newer than the specified {@link ChronoLocalDateTime} * at the system-default time zone. * * <p>Note: The input date and time is assumed to be in the system default time-zone. To use a * non-default time-zone use the method {@link #isFileNewer(File, ChronoLocalDateTime, ZoneId) * isFileNewer(file, chronoLocalDateTime, zoneId)} where {@code zoneId} is a valid * {@link ZoneId}. * * @param file the {@link File} of which the modification date must be compared. * @param chronoLocalDateTime the date reference. * @return true if the {@link File} exists and has been modified after the given * {@link ChronoLocalDateTime} at the system-default time zone. * @throws NullPointerException if the file or local date time is {@code null}. * @since 2.8.0 */ public static boolean isFileNewer(final File file, final ChronoLocalDateTime<?> chronoLocalDateTime) { return isFileNewer(file, chronoLocalDateTime, ZoneId.systemDefault()); } /** * Tests if the specified {@link File} is newer than the specified {@link ChronoLocalDateTime} * at the specified {@link ZoneId}. * * @param file the {@link File} of which the modification date must be compared. * @param chronoLocalDateTime the date reference. * @param zoneId the time zone. * @return true if the {@link File} exists and has been modified after the given * {@link ChronoLocalDateTime} at the given {@link ZoneId}. * @throws NullPointerException if the file, local date time or zone ID is {@code null}. * @since 2.8.0 */ public static boolean isFileNewer(final File file, final ChronoLocalDateTime<?> chronoLocalDateTime, final ZoneId zoneId) { Objects.requireNonNull(chronoLocalDateTime, "chronoLocalDateTime"); Objects.requireNonNull(zoneId, "zoneId"); return isFileNewer(file, chronoLocalDateTime.atZone(zoneId)); } /** * Tests if the specified {@link File} is newer than the specified {@link ChronoZonedDateTime}. * * @param file the {@link File} of which the modification date must be compared. * @param chronoZonedDateTime the date reference. * @return true if the {@link File} exists and has been modified after the given * {@link ChronoZonedDateTime}. * @throws NullPointerException if the file or zoned date time is {@code null}. * @since 2.8.0 */ public static boolean isFileNewer(final File file, final ChronoZonedDateTime<?> chronoZonedDateTime) { Objects.requireNonNull(file, "file"); Objects.requireNonNull(chronoZonedDateTime, "chronoZonedDateTime"); return Uncheck.get(() -> PathUtils.isNewer(file.toPath(), chronoZonedDateTime)); } /** * Tests if the specified {@link File} is newer than the specified {@link Date}. * * @param file the {@link File} of which the modification date must be compared. * @param date the date reference. * @return true if the {@link File} exists and has been modified * after the given {@link Date}. * @throws NullPointerException if the file or date is {@code null}. */ public static boolean isFileNewer(final File file, final Date date) { Objects.requireNonNull(date, "date"); return isFileNewer(file, date.getTime()); } /** * Tests if the specified {@link File} is newer than the reference {@link File}. * * @param file the {@link File} of which the modification date must be compared. * @param reference the {@link File} of which the modification date is used. * @return true if the {@link File} exists and has been modified more * recently than the reference {@link File}. * @throws NullPointerException if the file or reference file is {@code null}. * @throws IllegalArgumentException if the reference file doesn't exist. */ public static boolean isFileNewer(final File file, final File reference) { requireExists(reference, "reference"); return Uncheck.get(() -> PathUtils.isNewer(file.toPath(), reference.toPath())); } /** * Tests if the specified {@link File} is newer than the specified {@link FileTime}. * * @param file the {@link File} of which the modification date must be compared. * @param fileTime the file time reference. * @return true if the {@link File} exists and has been modified after the given {@link FileTime}. * @throws IOException if an I/O error occurs. * @throws NullPointerException if the file or local date is {@code null}. * @since 2.12.0 */ public static boolean isFileNewer(final File file, final FileTime fileTime) throws IOException { Objects.requireNonNull(file, "file"); return PathUtils.isNewer(file.toPath(), fileTime); } /** * Tests if the specified {@link File} is newer than the specified {@link Instant}. * * @param file the {@link File} of which the modification date must be compared. * @param instant the date reference. * @return true if the {@link File} exists and has been modified after the given {@link Instant}. * @throws NullPointerException if the file or instant is {@code null}. * @since 2.8.0 */ public static boolean isFileNewer(final File file, final Instant instant) { Objects.requireNonNull(instant, "instant"); return Uncheck.get(() -> PathUtils.isNewer(file.toPath(), instant)); } /** * Tests if the specified {@link File} is newer than the specified time reference. * * @param file the {@link File} of which the modification date must be compared. * @param timeMillis the time reference measured in milliseconds since the * epoch (00:00:00 GMT, January 1, 1970). * @return true if the {@link File} exists and has been modified after the given time reference. * @throws NullPointerException if the file is {@code null}. */ public static boolean isFileNewer(final File file, final long timeMillis) { Objects.requireNonNull(file, "file"); return Uncheck.get(() -> PathUtils.isNewer(file.toPath(), timeMillis)); } /** * Tests if the specified {@link File} is newer than the specified {@link OffsetDateTime}. * * @param file the {@link File} of which the modification date must be compared * @param offsetDateTime the date reference * @return true if the {@link File} exists and has been modified before the given {@link OffsetDateTime}. * @throws NullPointerException if the file or zoned date time is {@code null} * @since 2.12.0 */ public static boolean isFileNewer(final File file, final OffsetDateTime offsetDateTime) { Objects.requireNonNull(offsetDateTime, "offsetDateTime"); return isFileNewer(file, offsetDateTime.toInstant()); } /** * Tests if the specified {@link File} is older than the specified {@link ChronoLocalDate} * at the current time. * * <p>Note: The input date is assumed to be in the system default time-zone with the time * part set to the current time. To use a non-default time-zone use the method * {@link #isFileOlder(File, ChronoLocalDateTime, ZoneId) * isFileOlder(file, chronoLocalDate.atTime(LocalTime.now(zoneId)), zoneId)} where * {@code zoneId} is a valid {@link ZoneId}. * * @param file the {@link File} of which the modification date must be compared. * @param chronoLocalDate the date reference. * @return true if the {@link File} exists and has been modified before the given * {@link ChronoLocalDate} at the current time. * @throws NullPointerException if the file or local date is {@code null}. * @see ZoneId#systemDefault() * @see LocalTime#now() * * @since 2.8.0 */ public static boolean isFileOlder(final File file, final ChronoLocalDate chronoLocalDate) { return isFileOlder(file, chronoLocalDate, LocalTime.now()); } /** * Tests if the specified {@link File} is older than the specified {@link ChronoLocalDate} * at the specified {@link LocalTime}. * * <p>Note: The input date and time are assumed to be in the system default time-zone. To use a * non-default time-zone use the method {@link #isFileOlder(File, ChronoLocalDateTime, ZoneId) * isFileOlder(file, chronoLocalDate.atTime(localTime), zoneId)} where {@code zoneId} is a valid * {@link ZoneId}. * * @param file the {@link File} of which the modification date must be compared. * @param chronoLocalDate the date reference. * @param localTime the time reference. * @return true if the {@link File} exists and has been modified before the * given {@link ChronoLocalDate} at the specified time. * @throws NullPointerException if the file, local date or local time is {@code null}. * @see ZoneId#systemDefault() * @since 2.8.0 */ public static boolean isFileOlder(final File file, final ChronoLocalDate chronoLocalDate, final LocalTime localTime) { Objects.requireNonNull(chronoLocalDate, "chronoLocalDate"); Objects.requireNonNull(localTime, "localTime"); return isFileOlder(file, chronoLocalDate.atTime(localTime)); } /** * Tests if the specified {@link File} is older than the specified {@link ChronoLocalDate} at the specified * {@link OffsetTime}. * * @param file the {@link File} of which the modification date must be compared * @param chronoLocalDate the date reference * @param offsetTime the time reference * @return true if the {@link File} exists and has been modified after the given {@link ChronoLocalDate} at the given * {@link OffsetTime}. * @throws NullPointerException if the file, local date or zone ID is {@code null} * @since 2.12.0 */ public static boolean isFileOlder(final File file, final ChronoLocalDate chronoLocalDate, final OffsetTime offsetTime) { Objects.requireNonNull(chronoLocalDate, "chronoLocalDate"); Objects.requireNonNull(offsetTime, "offsetTime"); return isFileOlder(file, chronoLocalDate.atTime(offsetTime.toLocalTime())); } /** * Tests if the specified {@link File} is older than the specified {@link ChronoLocalDateTime} * at the system-default time zone. * * <p>Note: The input date and time is assumed to be in the system default time-zone. To use a * non-default time-zone use the method {@link #isFileOlder(File, ChronoLocalDateTime, ZoneId) * isFileOlder(file, chronoLocalDateTime, zoneId)} where {@code zoneId} is a valid * {@link ZoneId}. * * @param file the {@link File} of which the modification date must be compared. * @param chronoLocalDateTime the date reference. * @return true if the {@link File} exists and has been modified before the given * {@link ChronoLocalDateTime} at the system-default time zone. * @throws NullPointerException if the file or local date time is {@code null}. * @see ZoneId#systemDefault() * @since 2.8.0 */ public static boolean isFileOlder(final File file, final ChronoLocalDateTime<?> chronoLocalDateTime) { return isFileOlder(file, chronoLocalDateTime, ZoneId.systemDefault()); } /** * Tests if the specified {@link File} is older than the specified {@link ChronoLocalDateTime} * at the specified {@link ZoneId}. * * @param file the {@link File} of which the modification date must be compared. * @param chronoLocalDateTime the date reference. * @param zoneId the time zone. * @return true if the {@link File} exists and has been modified before the given * {@link ChronoLocalDateTime} at the given {@link ZoneId}. * @throws NullPointerException if the file, local date time or zone ID is {@code null}. * @since 2.8.0 */ public static boolean isFileOlder(final File file, final ChronoLocalDateTime<?> chronoLocalDateTime, final ZoneId zoneId) { Objects.requireNonNull(chronoLocalDateTime, "chronoLocalDateTime"); Objects.requireNonNull(zoneId, "zoneId"); return isFileOlder(file, chronoLocalDateTime.atZone(zoneId)); } /** * Tests if the specified {@link File} is older than the specified {@link ChronoZonedDateTime}. * * @param file the {@link File} of which the modification date must be compared. * @param chronoZonedDateTime the date reference. * @return true if the {@link File} exists and has been modified before the given * {@link ChronoZonedDateTime}. * @throws NullPointerException if the file or zoned date time is {@code null}. * @since 2.8.0 */ public static boolean isFileOlder(final File file, final ChronoZonedDateTime<?> chronoZonedDateTime) { Objects.requireNonNull(chronoZonedDateTime, "chronoZonedDateTime"); return isFileOlder(file, chronoZonedDateTime.toInstant()); } /** * Tests if the specified {@link File} is older than the specified {@link Date}. * * @param file the {@link File} of which the modification date must be compared. * @param date the date reference. * @return true if the {@link File} exists and has been modified before the given {@link Date}. * @throws NullPointerException if the file or date is {@code null}. */ public static boolean isFileOlder(final File file, final Date date) { Objects.requireNonNull(date, "date"); return isFileOlder(file, date.getTime()); } /** * Tests if the specified {@link File} is older than the reference {@link File}. * * @param file the {@link File} of which the modification date must be compared. * @param reference the {@link File} of which the modification date is used. * @return true if the {@link File} exists and has been modified before the reference {@link File}. * @throws NullPointerException if the file or reference file is {@code null}. * @throws IllegalArgumentException if the reference file doesn't exist. */ public static boolean isFileOlder(final File file, final File reference) { requireExists(reference, "reference"); return Uncheck.get(() -> PathUtils.isOlder(file.toPath(), reference.toPath())); } /** * Tests if the specified {@link File} is older than the specified {@link FileTime}. * * @param file the {@link File} of which the modification date must be compared. * @param fileTime the file time reference. * @return true if the {@link File} exists and has been modified before the given {@link FileTime}. * @throws IOException if an I/O error occurs. * @throws NullPointerException if the file or local date is {@code null}. * @since 2.12.0 */ public static boolean isFileOlder(final File file, final FileTime fileTime) throws IOException { Objects.requireNonNull(file, "file"); return PathUtils.isOlder(file.toPath(), fileTime); } /** * Tests if the specified {@link File} is older than the specified {@link Instant}. * * @param file the {@link File} of which the modification date must be compared. * @param instant the date reference. * @return true if the {@link File} exists and has been modified before the given {@link Instant}. * @throws NullPointerException if the file or instant is {@code null}. * @since 2.8.0 */ public static boolean isFileOlder(final File file, final Instant instant) { Objects.requireNonNull(instant, "instant"); return Uncheck.get(() -> PathUtils.isOlder(file.toPath(), instant)); } /** * Tests if the specified {@link File} is older than the specified time reference. * * @param file the {@link File} of which the modification date must be compared. * @param timeMillis the time reference measured in milliseconds since the * epoch (00:00:00 GMT, January 1, 1970). * @return true if the {@link File} exists and has been modified before the given time reference. * @throws NullPointerException if the file is {@code null}. */ public static boolean isFileOlder(final File file, final long timeMillis) { Objects.requireNonNull(file, "file"); return Uncheck.get(() -> PathUtils.isOlder(file.toPath(), timeMillis)); } /** * Tests if the specified {@link File} is older than the specified {@link OffsetDateTime}. * * @param file the {@link File} of which the modification date must be compared * @param offsetDateTime the date reference * @return true if the {@link File} exists and has been modified before the given {@link OffsetDateTime}. * @throws NullPointerException if the file or zoned date time is {@code null} * @since 2.12.0 */ public static boolean isFileOlder(final File file, final OffsetDateTime offsetDateTime) { Objects.requireNonNull(offsetDateTime, "offsetDateTime"); return isFileOlder(file, offsetDateTime.toInstant()); } /** * Tests whether the specified {@link File} is a regular file or not. Implemented as a * null-safe delegate to {@link Files#isRegularFile(Path path, LinkOption... options)}. * * @param file the path to the file. * @param options options indicating how symbolic links are handled * @return {@code true} if the file is a regular file; {@code false} if * the path is null, the file does not exist, is not a regular file, or it cannot * be determined if the file is a regular file or not. * @throws SecurityException In the case of the default provider, and a security manager is installed, the * {@link SecurityManager#checkRead(String) checkRead} method is invoked to check read * access to the directory. * @since 2.9.0 */ public static boolean isRegularFile(final File file, final LinkOption... options) { return file != null && Files.isRegularFile(file.toPath(), options); } /** * Tests whether the specified file is a symbolic link rather than an actual file. * <p> * This method delegates to {@link Files#isSymbolicLink(Path path)} * </p> * * @param file the file to test. * @return true if the file is a symbolic link, see {@link Files#isSymbolicLink(Path path)}. * @since 2.0 * @see Files#isSymbolicLink(Path) */ public static boolean isSymlink(final File file) { return file != null && Files.isSymbolicLink(file.toPath()); } /** * Iterates over the files in given directory (and optionally * its subdirectories). * <p> * The resulting iterator MUST be consumed in its entirety in order to close its underlying stream. * </p> * <p> * All files found are filtered by an IOFileFilter. * </p> * * @param directory the directory to search in * @param fileFilter filter to apply when finding files. * @param dirFilter optional filter to apply when finding subdirectories. * If this parameter is {@code null}, subdirectories will not be included in the * search. Use TrueFileFilter.INSTANCE to match all directories. * @return an iterator of java.io.File for the matching files * @see org.apache.commons.io.filefilter.FileFilterUtils * @see org.apache.commons.io.filefilter.NameFileFilter * @since 1.2 */ public static Iterator<File> iterateFiles(final File directory, final IOFileFilter fileFilter, final IOFileFilter dirFilter) { return listFiles(directory, fileFilter, dirFilter).iterator(); } /** * Iterates over the files in a given directory (and optionally * its subdirectories) which match an array of extensions. * <p> * The resulting iterator MUST be consumed in its entirety in order to close its underlying stream. * </p> * * @param directory the directory to search in * @param extensions an array of extensions, ex. {"java","xml"}. If this * parameter is {@code null}, all files are returned. * @param recursive if true all subdirectories are searched as well * @return an iterator of java.io.File with the matching files * @since 1.2 */ public static Iterator<File> iterateFiles(final File directory, final String[] extensions, final boolean recursive) { return Uncheck.apply(d -> streamFiles(d, recursive, extensions).iterator(), directory); } /** * Iterates over the files in given directory (and optionally * its subdirectories). * <p> * The resulting iterator MUST be consumed in its entirety in order to close its underlying stream. * </p> * <p> * All files found are filtered by an IOFileFilter. * </p> * <p> * The resulting iterator includes the subdirectories themselves. * </p> * * @param directory the directory to search in * @param fileFilter filter to apply when finding files. * @param dirFilter optional filter to apply when finding subdirectories. * If this parameter is {@code null}, subdirectories will not be included in the * search. Use TrueFileFilter.INSTANCE to match all directories. * @return an iterator of java.io.File for the matching files * @see org.apache.commons.io.filefilter.FileFilterUtils * @see org.apache.commons.io.filefilter.NameFileFilter * @since 2.2 */ public static Iterator<File> iterateFilesAndDirs(final File directory, final IOFileFilter fileFilter, final IOFileFilter dirFilter) { return listFilesAndDirs(directory, fileFilter, dirFilter).iterator(); } /** * Returns the last modification time in milliseconds via * {@link java.nio.file.Files#getLastModifiedTime(Path, LinkOption...)}. * <p> * For the best precision, use {@link #lastModifiedFileTime(File)}. * </p> * <p> * Use this method to avoid issues with {@link File#lastModified()} like * <a href="https://bugs.openjdk.java.net/browse/JDK-8177809">JDK-8177809</a> where {@link File#lastModified()} is * losing milliseconds (always ends in 000). This bug exists in OpenJDK 8 and 9, and is fixed in 10. * </p> * * @param file The File to query. * @return See {@link java.nio.file.attribute.FileTime#toMillis()}. * @throws IOException if an I/O error occurs. * @since 2.9.0 */ public static long lastModified(final File file) throws IOException { // https://bugs.openjdk.java.net/browse/JDK-8177809 // File.lastModified() is losing milliseconds (always ends in 000) // This bug is in OpenJDK 8 and 9, and fixed in 10. return lastModifiedFileTime(file).toMillis(); } /** * Returns the last modification {@link FileTime} via * {@link java.nio.file.Files#getLastModifiedTime(Path, LinkOption...)}. * <p> * Use this method to avoid issues with {@link File#lastModified()} like * <a href="https://bugs.openjdk.java.net/browse/JDK-8177809">JDK-8177809</a> where {@link File#lastModified()} is * losing milliseconds (always ends in 000). This bug exists in OpenJDK 8 and 9, and is fixed in 10. * </p> * * @param file The File to query. * @return See {@link java.nio.file.Files#getLastModifiedTime(Path, LinkOption...)}. * @throws IOException if an I/O error occurs. * @since 2.12.0 */ public static FileTime lastModifiedFileTime(final File file) throws IOException { // https://bugs.openjdk.java.net/browse/JDK-8177809 // File.lastModified() is losing milliseconds (always ends in 000) // This bug is in OpenJDK 8 and 9, and fixed in 10. return Files.getLastModifiedTime(Objects.requireNonNull(file.toPath(), "file")); } /** * Returns the last modification time in milliseconds via * {@link java.nio.file.Files#getLastModifiedTime(Path, LinkOption...)}. * <p> * For the best precision, use {@link #lastModifiedFileTime(File)}. * </p> * <p> * Use this method to avoid issues with {@link File#lastModified()} like * <a href="https://bugs.openjdk.java.net/browse/JDK-8177809">JDK-8177809</a> where {@link File#lastModified()} is * losing milliseconds (always ends in 000). This bug exists in OpenJDK 8 and 9, and is fixed in 10. * </p> * * @param file The File to query. * @return See {@link java.nio.file.attribute.FileTime#toMillis()}. * @throws UncheckedIOException if an I/O error occurs. * @since 2.9.0 */ public static long lastModifiedUnchecked(final File file) { // https://bugs.openjdk.java.net/browse/JDK-8177809 // File.lastModified() is losing milliseconds (always ends in 000) // This bug is in OpenJDK 8 and 9, and fixed in 10. return Uncheck.apply(FileUtils::lastModified, file); } /** * Returns an Iterator for the lines in a {@link File} using the default encoding for the VM. * * @param file the file to open for input, must not be {@code null} * @return an Iterator of the lines in the file, never {@code null} * @throws NullPointerException if file is {@code null}. * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some * other reason cannot be opened for reading. * @throws IOException if an I/O error occurs. * @see #lineIterator(File, String) * @since 1.3 */ public static LineIterator lineIterator(final File file) throws IOException { return lineIterator(file, null); } /** * Returns an Iterator for the lines in a {@link File}. * <p> * This method opens an {@link InputStream} for the file. * When you have finished with the iterator you should close the stream * to free internal resources. This can be done by using a try-with-resources block or calling the * {@link LineIterator#close()} method. * </p> * <p> * The recommended usage pattern is: * </p> * <pre> * LineIterator it = FileUtils.lineIterator(file, StandardCharsets.UTF_8.name()); * try { * while (it.hasNext()) { * String line = it.nextLine(); * /// do something with line * } * } finally { * LineIterator.closeQuietly(iterator); * } * </pre> * <p> * If an exception occurs during the creation of the iterator, the * underlying stream is closed. * </p> * * @param file the file to open for input, must not be {@code null} * @param charsetName the name of the requested charset, {@code null} means platform default * @return a LineIterator for lines in the file, never {@code null}; MUST be closed by the caller. * @throws NullPointerException if file is {@code null}. * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some * other reason cannot be opened for reading. * @throws IOException if an I/O error occurs. * @since 1.2 */ @SuppressWarnings("resource") // Caller closes the result LineIterator. public static LineIterator lineIterator(final File file, final String charsetName) throws IOException { InputStream inputStream = null; try { inputStream = Files.newInputStream(file.toPath()); return IOUtils.lineIterator(inputStream, charsetName); } catch (final IOException | RuntimeException ex) { IOUtils.closeQuietly(inputStream, ex::addSuppressed); throw ex; } } private static AccumulatorPathVisitor listAccumulate(final File directory, final IOFileFilter fileFilter, final IOFileFilter dirFilter, final FileVisitOption... options) throws IOException { final boolean isDirFilterSet = dirFilter != null; final FileEqualsFileFilter rootDirFilter = new FileEqualsFileFilter(directory); final PathFilter dirPathFilter = isDirFilterSet ? rootDirFilter.or(dirFilter) : rootDirFilter; final AccumulatorPathVisitor visitor = new AccumulatorPathVisitor(Counters.noopPathCounters(), fileFilter, dirPathFilter, (p, e) -> FileVisitResult.CONTINUE); final Set<FileVisitOption> optionSet = new HashSet<>(); Collections.addAll(optionSet, options); Files.walkFileTree(directory.toPath(), optionSet, toMaxDepth(isDirFilterSet), visitor); return visitor; } /** * Lists files in a directory, asserting that the supplied directory exists and is a directory. * * @param directory The directory to list * @param fileFilter Optional file filter, may be null. * @return The files in the directory, never {@code null}. * @throws NullPointerException if directory is {@code null}. * @throws IllegalArgumentException if directory does not exist or is not a directory. * @throws IOException if an I/O error occurs. */ private static File[] listFiles(final File directory, final FileFilter fileFilter) throws IOException { requireDirectoryExists(directory, "directory"); final File[] files = fileFilter == null ? directory.listFiles() : directory.listFiles(fileFilter); if (files == null) { // null if the directory does not denote a directory, or if an I/O error occurs. throw new IOException("Unknown I/O error listing contents of directory: " + directory); } return files; } /** * Finds files within a given directory (and optionally its * subdirectories). All files found are filtered by an IOFileFilter. * <p> * If your search should recurse into subdirectories you can pass in * an IOFileFilter for directories. You don't need to bind a * DirectoryFileFilter (via logical AND) to this filter. This method does * that for you. * </p> * <p> * An example: If you want to search through all directories called * "temp" you pass in {@code FileFilterUtils.NameFileFilter("temp")} * </p> * <p> * Another common usage of this method is find files in a directory * tree but ignoring the directories generated CVS. You can simply pass * in {@code FileFilterUtils.makeCVSAware(null)}. * </p> * * @param directory the directory to search in * @param fileFilter filter to apply when finding files. Must not be {@code null}, * use {@link TrueFileFilter#INSTANCE} to match all files in selected directories. * @param dirFilter optional filter to apply when finding subdirectories. * If this parameter is {@code null}, subdirectories will not be included in the * search. Use {@link TrueFileFilter#INSTANCE} to match all directories. * @return a collection of java.io.File with the matching files * @see org.apache.commons.io.filefilter.FileFilterUtils * @see org.apache.commons.io.filefilter.NameFileFilter */ public static Collection<File> listFiles(final File directory, final IOFileFilter fileFilter, final IOFileFilter dirFilter) { final AccumulatorPathVisitor visitor = Uncheck .apply(d -> listAccumulate(d, FileFileFilter.INSTANCE.and(fileFilter), dirFilter, FileVisitOption.FOLLOW_LINKS), directory); return visitor.getFileList().stream().map(Path::toFile).collect(Collectors.toList()); } /** * Finds files within a given directory (and optionally its subdirectories) * which match an array of extensions. * * @param directory the directory to search in * @param extensions an array of extensions, ex. {"java","xml"}. If this * parameter is {@code null}, all files are returned. * @param recursive if true all subdirectories are searched as well * @return a collection of java.io.File with the matching files */ public static Collection<File> listFiles(final File directory, final String[] extensions, final boolean recursive) { return Uncheck.apply(d -> toList(streamFiles(d, recursive, extensions)), directory); } /** * Finds files within a given directory (and optionally its * subdirectories). All files found are filtered by an IOFileFilter. * <p> * The resulting collection includes the starting directory and * any subdirectories that match the directory filter. * </p> * * @param directory the directory to search in * @param fileFilter filter to apply when finding files. * @param dirFilter optional filter to apply when finding subdirectories. * If this parameter is {@code null}, subdirectories will not be included in the * search. Use TrueFileFilter.INSTANCE to match all directories. * @return a collection of java.io.File with the matching files * @see org.apache.commons.io.FileUtils#listFiles * @see org.apache.commons.io.filefilter.FileFilterUtils * @see org.apache.commons.io.filefilter.NameFileFilter * @since 2.2 */ public static Collection<File> listFilesAndDirs(final File directory, final IOFileFilter fileFilter, final IOFileFilter dirFilter) { final AccumulatorPathVisitor visitor = Uncheck.apply(d -> listAccumulate(d, fileFilter, dirFilter, FileVisitOption.FOLLOW_LINKS), directory); final List<Path> list = visitor.getFileList(); list.addAll(visitor.getDirList()); return list.stream().map(Path::toFile).collect(Collectors.toList()); } /** * Calls {@link File#mkdirs()} and throws an exception on failure. * * @param directory the receiver for {@code mkdirs()}, may be null. * @return the given file, may be null. * @throws IOException if the directory was not created along with all its parent directories. * @throws IOException if the given file object is not a directory. * @throws SecurityException See {@link File#mkdirs()}. * @see File#mkdirs() */ private static File mkdirs(final File directory) throws IOException { if (directory != null && !directory.mkdirs() && !directory.isDirectory()) { throw new IOException("Cannot create directory '" + directory + "'."); } return directory; } /** * Moves a directory. * <p> * When the destination directory is on another file system, do a "copy and delete". * </p> * * @param srcDir the directory to be moved. * @param destDir the destination directory. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IllegalArgumentException if the source or destination is invalid. * @throws FileNotFoundException if the source does not exist. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @since 1.4 */ public static void moveDirectory(final File srcDir, final File destDir) throws IOException { validateMoveParameters(srcDir, destDir); requireDirectory(srcDir, "srcDir"); requireAbsent(destDir, "destDir"); if (!srcDir.renameTo(destDir)) { if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath() + File.separator)) { throw new IOException("Cannot move directory: " + srcDir + " to a subdirectory of itself: " + destDir); } copyDirectory(srcDir, destDir); deleteDirectory(srcDir); if (srcDir.exists()) { throw new IOException("Failed to delete original directory '" + srcDir + "' after copy to '" + destDir + "'"); } } } /** * Moves a directory to another directory. * * @param source the file to be moved. * @param destDir the destination file. * @param createDestDir If {@code true} create the destination directory, otherwise if {@code false} throw an * IOException. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IllegalArgumentException if the source or destination is invalid. * @throws FileNotFoundException if the source does not exist. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @since 1.4 */ public static void moveDirectoryToDirectory(final File source, final File destDir, final boolean createDestDir) throws IOException { validateMoveParameters(source, destDir); if (!destDir.isDirectory()) { if (destDir.exists()) { throw new IOException("Destination '" + destDir + "' is not a directory"); } if (!createDestDir) { throw new FileNotFoundException("Destination directory '" + destDir + "' does not exist [createDestDir=" + false + "]"); } mkdirs(destDir); } moveDirectory(source, new File(destDir, source.getName())); } /** * Moves a file preserving attributes. * <p> * Shorthand for {@code moveFile(srcFile, destFile, StandardCopyOption.COPY_ATTRIBUTES)}. * </p> * <p> * When the destination file is on another file system, do a "copy and delete". * </p> * * @param srcFile the file to be moved. * @param destFile the destination file. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws FileExistsException if the destination file exists. * @throws FileNotFoundException if the source file does not exist. * @throws IOException if source or destination is invalid. * @throws IOException if an error occurs. * @since 1.4 */ public static void moveFile(final File srcFile, final File destFile) throws IOException { moveFile(srcFile, destFile, StandardCopyOption.COPY_ATTRIBUTES); } /** * Moves a file. * <p> * When the destination file is on another file system, do a "copy and delete". * </p> * * @param srcFile the file to be moved. * @param destFile the destination file. * @param copyOptions Copy options. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws FileExistsException if the destination file exists. * @throws FileNotFoundException if the source file does not exist. * @throws IOException if source or destination is invalid. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @since 2.9.0 */ public static void moveFile(final File srcFile, final File destFile, final CopyOption... copyOptions) throws IOException { validateMoveParameters(srcFile, destFile); requireFile(srcFile, "srcFile"); requireAbsent(destFile, "destFile"); final boolean rename = srcFile.renameTo(destFile); if (!rename) { copyFile(srcFile, destFile, copyOptions); if (!srcFile.delete()) { FileUtils.deleteQuietly(destFile); throw new IOException("Failed to delete original file '" + srcFile + "' after copy to '" + destFile + "'"); } } } /** * Moves a file to a directory. * * @param srcFile the file to be moved. * @param destDir the destination file. * @param createDestDir If {@code true} create the destination directory, otherwise if {@code false} throw an * IOException. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws FileExistsException if the destination file exists. * @throws FileNotFoundException if the source file does not exist. * @throws IOException if source or destination is invalid. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @since 1.4 */ public static void moveFileToDirectory(final File srcFile, final File destDir, final boolean createDestDir) throws IOException { validateMoveParameters(srcFile, destDir); if (!destDir.exists() && createDestDir) { mkdirs(destDir); } requireExistsChecked(destDir, "destDir"); requireDirectory(destDir, "destDir"); moveFile(srcFile, new File(destDir, srcFile.getName())); } /** * Moves a file or directory to the destination directory. * <p> * When the destination is on another file system, do a "copy and delete". * </p> * * @param src the file or directory to be moved. * @param destDir the destination directory. * @param createDestDir If {@code true} create the destination directory, otherwise if {@code false} throw an * IOException. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws FileExistsException if the directory or file exists in the destination directory. * @throws FileNotFoundException if the source file does not exist. * @throws IOException if source or destination is invalid. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @since 1.4 */ public static void moveToDirectory(final File src, final File destDir, final boolean createDestDir) throws IOException { validateMoveParameters(src, destDir); if (src.isDirectory()) { moveDirectoryToDirectory(src, destDir, createDestDir); } else { moveFileToDirectory(src, destDir, createDestDir); } } /** * Creates a new OutputStream by opening or creating a file, returning an output stream that may be used to write bytes * to the file. * * @param append Whether or not to append. * @param file the File. * @return a new OutputStream. * @throws IOException if an I/O error occurs. * @see PathUtils#newOutputStream(Path, boolean) * @since 2.12.0 */ public static OutputStream newOutputStream(final File file, final boolean append) throws IOException { return PathUtils.newOutputStream(Objects.requireNonNull(file, "file").toPath(), append); } /** * Opens a {@link FileInputStream} for the specified file, providing better error messages than simply calling * {@code new FileInputStream(file)}. * <p> * At the end of the method either the stream will be successfully opened, or an exception will have been thrown. * </p> * <p> * An exception is thrown if the file does not exist. An exception is thrown if the file object exists but is a * directory. An exception is thrown if the file exists but cannot be read. * </p> * * @param file the file to open for input, must not be {@code null} * @return a new {@link FileInputStream} for the specified file * @throws NullPointerException if file is {@code null}. * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some * other reason cannot be opened for reading. * @throws IOException See FileNotFoundException above, FileNotFoundException is a subclass of IOException. * @since 1.3 */ public static FileInputStream openInputStream(final File file) throws IOException { Objects.requireNonNull(file, "file"); return new FileInputStream(file); } /** * Opens a {@link FileOutputStream} for the specified file, checking and * creating the parent directory if it does not exist. * <p> * At the end of the method either the stream will be successfully opened, * or an exception will have been thrown. * </p> * <p> * The parent directory will be created if it does not exist. * The file will be created if it does not exist. * An exception is thrown if the file object exists but is a directory. * An exception is thrown if the file exists but cannot be written to. * An exception is thrown if the parent directory cannot be created. * </p> * * @param file the file to open for output, must not be {@code null} * @return a new {@link FileOutputStream} for the specified file * @throws NullPointerException if the file object is {@code null}. * @throws IllegalArgumentException if the file object is a directory * @throws IllegalArgumentException if the file is not writable. * @throws IOException if the directories could not be created. * @since 1.3 */ public static FileOutputStream openOutputStream(final File file) throws IOException { return openOutputStream(file, false); } /** * Opens a {@link FileOutputStream} for the specified file, checking and * creating the parent directory if it does not exist. * <p> * At the end of the method either the stream will be successfully opened, * or an exception will have been thrown. * </p> * <p> * The parent directory will be created if it does not exist. * The file will be created if it does not exist. * An exception is thrown if the file object exists but is a directory. * An exception is thrown if the file exists but cannot be written to. * An exception is thrown if the parent directory cannot be created. * </p> * * @param file the file to open for output, must not be {@code null} * @param append if {@code true}, then bytes will be added to the * end of the file rather than overwriting * @return a new {@link FileOutputStream} for the specified file * @throws NullPointerException if the file object is {@code null}. * @throws IllegalArgumentException if the file object is a directory * @throws IllegalArgumentException if the file is not writable. * @throws IOException if the directories could not be created. * @since 2.1 */ public static FileOutputStream openOutputStream(final File file, final boolean append) throws IOException { Objects.requireNonNull(file, "file"); if (file.exists()) { requireFile(file, "file"); requireCanWrite(file, "file"); } else { createParentDirectories(file); } return new FileOutputStream(file, append); } /** * Reads the contents of a file into a byte array. * The file is always closed. * * @param file the file to read, must not be {@code null} * @return the file contents, never {@code null} * @throws NullPointerException if file is {@code null}. * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some * other reason cannot be opened for reading. * @throws IOException if an I/O error occurs. * @since 1.1 */ public static byte[] readFileToByteArray(final File file) throws IOException { Objects.requireNonNull(file, "file"); return Files.readAllBytes(file.toPath()); } /** * Reads the contents of a file into a String using the default encoding for the VM. * The file is always closed. * * @param file the file to read, must not be {@code null} * @return the file contents, never {@code null} * @throws NullPointerException if file is {@code null}. * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some * other reason cannot be opened for reading. * @throws IOException if an I/O error occurs. * @since 1.3.1 * @deprecated 2.5 use {@link #readFileToString(File, Charset)} instead (and specify the appropriate encoding) */ @Deprecated public static String readFileToString(final File file) throws IOException { return readFileToString(file, Charset.defaultCharset()); } /** * Reads the contents of a file into a String. * The file is always closed. * * @param file the file to read, must not be {@code null} * @param charsetName the name of the requested charset, {@code null} means platform default * @return the file contents, never {@code null} * @throws NullPointerException if file is {@code null}. * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some * other reason cannot be opened for reading. * @throws IOException if an I/O error occurs. * @since 2.3 */ public static String readFileToString(final File file, final Charset charsetName) throws IOException { try (InputStream inputStream = Files.newInputStream(file.toPath())) { return IOUtils.toString(inputStream, Charsets.toCharset(charsetName)); } } /** * Reads the contents of a file into a String. The file is always closed. * * @param file the file to read, must not be {@code null} * @param charsetName the name of the requested charset, {@code null} means platform default * @return the file contents, never {@code null} * @throws NullPointerException if file is {@code null}. * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some * other reason cannot be opened for reading. * @throws IOException if an I/O error occurs. * @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io * .UnsupportedEncodingException} in version 2.2 if the named charset is unavailable. * @since 2.3 */ public static String readFileToString(final File file, final String charsetName) throws IOException { return readFileToString(file, Charsets.toCharset(charsetName)); } /** * Reads the contents of a file line by line to a List of Strings using the default encoding for the VM. * The file is always closed. * * @param file the file to read, must not be {@code null} * @return the list of Strings representing each line in the file, never {@code null} * @throws NullPointerException if file is {@code null}. * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some * other reason cannot be opened for reading. * @throws IOException if an I/O error occurs. * @since 1.3 * @deprecated 2.5 use {@link #readLines(File, Charset)} instead (and specify the appropriate encoding) */ @Deprecated public static List<String> readLines(final File file) throws IOException { return readLines(file, Charset.defaultCharset()); } /** * Reads the contents of a file line by line to a List of Strings. * The file is always closed. * * @param file the file to read, must not be {@code null} * @param charset the charset to use, {@code null} means platform default * @return the list of Strings representing each line in the file, never {@code null} * @throws NullPointerException if file is {@code null}. * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some * other reason cannot be opened for reading. * @throws IOException if an I/O error occurs. * @since 2.3 */ public static List<String> readLines(final File file, final Charset charset) throws IOException { return Files.readAllLines(file.toPath(), charset); } /** * Reads the contents of a file line by line to a List of Strings. The file is always closed. * * @param file the file to read, must not be {@code null} * @param charsetName the name of the requested charset, {@code null} means platform default * @return the list of Strings representing each line in the file, never {@code null} * @throws NullPointerException if file is {@code null}. * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some * other reason cannot be opened for reading. * @throws IOException if an I/O error occurs. * @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io * .UnsupportedEncodingException} in version 2.2 if the named charset is unavailable. * @since 1.1 */ public static List<String> readLines(final File file, final String charsetName) throws IOException { return readLines(file, Charsets.toCharset(charsetName)); } private static void requireAbsent(final File file, final String name) throws FileExistsException { if (file.exists()) { throw new FileExistsException(String.format("File element in parameter '%s' already exists: '%s'", name, file)); } } /** * Throws IllegalArgumentException if the given files' canonical representations are equal. * * @param file1 The first file to compare. * @param file2 The second file to compare. * @throws IOException if an I/O error occurs. * @throws IllegalArgumentException if the given files' canonical representations are equal. */ private static void requireCanonicalPathsNotEquals(final File file1, final File file2) throws IOException { final String canonicalPath = file1.getCanonicalPath(); if (canonicalPath.equals(file2.getCanonicalPath())) { throw new IllegalArgumentException(String .format("File canonical paths are equal: '%s' (file1='%s', file2='%s')", canonicalPath, file1, file2)); } } /** * Throws an {@link IllegalArgumentException} if the file is not writable. This provides a more precise exception * message than a plain access denied. * * @param file The file to test. * @param name The parameter name to use in the exception message. * @throws NullPointerException if the given {@link File} is {@code null}. * @throws IllegalArgumentException if the file is not writable. */ private static void requireCanWrite(final File file, final String name) { Objects.requireNonNull(file, "file"); if (!file.canWrite()) { throw new IllegalArgumentException("File parameter '" + name + " is not writable: '" + file + "'"); } } /** * Requires that the given {@link File} is a directory. * * @param directory The {@link File} to check. * @param name The parameter name to use in the exception message in case of null input or if the file is not a directory. * @return the given directory. * @throws NullPointerException if the given {@link File} is {@code null}. * @throws IllegalArgumentException if the given {@link File} does not exist or is not a directory. */ private static File requireDirectory(final File directory, final String name) { Objects.requireNonNull(directory, name); if (!directory.isDirectory()) { throw new IllegalArgumentException("Parameter '" + name + "' is not a directory: '" + directory + "'"); } return directory; } /** * Requires that the given {@link File} exists and is a directory. * * @param directory The {@link File} to check. * @param name The parameter name to use in the exception message in case of null input. * @return the given directory. * @throws NullPointerException if the given {@link File} is {@code null}. * @throws IllegalArgumentException if the given {@link File} does not exist or is not a directory. */ private static File requireDirectoryExists(final File directory, final String name) { requireExists(directory, name); requireDirectory(directory, name); return directory; } /** * Requires that the given {@link File} is a directory if it exists. * * @param directory The {@link File} to check. * @param name The parameter name to use in the exception message in case of null input. * @return the given directory. * @throws NullPointerException if the given {@link File} is {@code null}. * @throws IllegalArgumentException if the given {@link File} exists but is not a directory. */ private static File requireDirectoryIfExists(final File directory, final String name) { Objects.requireNonNull(directory, name); if (directory.exists()) { requireDirectory(directory, name); } return directory; } /** * Requires that the given {@link File} exists and throws an {@link IllegalArgumentException} if it doesn't. * * @param file The {@link File} to check. * @param fileParamName The parameter name to use in the exception message in case of {@code null} input. * @return the given file. * @throws NullPointerException if the given {@link File} is {@code null}. * @throws IllegalArgumentException if the given {@link File} does not exist. */ private static File requireExists(final File file, final String fileParamName) { Objects.requireNonNull(file, fileParamName); if (!file.exists()) { throw new IllegalArgumentException("File system element for parameter '" + fileParamName + "' does not exist: '" + file + "'"); } return file; } /** * Requires that the given {@link File} exists and throws an {@link FileNotFoundException} if it doesn't. * * @param file The {@link File} to check. * @param fileParamName The parameter name to use in the exception message in case of {@code null} input. * @return the given file. * @throws NullPointerException if the given {@link File} is {@code null}. * @throws FileNotFoundException if the given {@link File} does not exist. */ private static File requireExistsChecked(final File file, final String fileParamName) throws FileNotFoundException { Objects.requireNonNull(file, fileParamName); if (!file.exists()) { throw new FileNotFoundException("File system element for parameter '" + fileParamName + "' does not exist: '" + file + "'"); } return file; } /** * Requires that the given {@link File} is a file. * * @param file The {@link File} to check. * @param name The parameter name to use in the exception message. * @return the given file. * @throws NullPointerException if the given {@link File} is {@code null}. * @throws IllegalArgumentException if the given {@link File} does not exist or is not a file. */ private static File requireFile(final File file, final String name) { Objects.requireNonNull(file, name); if (!file.isFile()) { throw new IllegalArgumentException("Parameter '" + name + "' is not a file: " + file); } return file; } /** * Requires parameter attributes for a file copy operation. * * @param source the source file * @param destination the destination * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws FileNotFoundException if the source does not exist. */ private static void requireFileCopy(final File source, final File destination) throws FileNotFoundException { requireExistsChecked(source, "source"); Objects.requireNonNull(destination, "destination"); } /** * Requires that the given {@link File} is a file if it exists. * * @param file The {@link File} to check. * @param name The parameter name to use in the exception message in case of null input. * @return the given directory. * @throws NullPointerException if the given {@link File} is {@code null}. * @throws IllegalArgumentException if the given {@link File} exists but is not a directory. */ private static File requireFileIfExists(final File file, final String name) { Objects.requireNonNull(file, name); return file.exists() ? requireFile(file, name) : file; } /** * Sets the given {@code targetFile}'s last modified date to the value from {@code sourceFile}. * * @param sourceFile The source file to query. * @param targetFile The target file or directory to set. * @throws NullPointerException if sourceFile is {@code null}. * @throws NullPointerException if targetFile is {@code null}. * @throws IOException if setting the last-modified time failed. */ private static void setLastModified(final File sourceFile, final File targetFile) throws IOException { Objects.requireNonNull(sourceFile, "sourceFile"); Objects.requireNonNull(targetFile, "targetFile"); if (targetFile.isFile()) { PathUtils.setLastModifiedTime(targetFile.toPath(), sourceFile.toPath()); } else { setLastModified(targetFile, lastModified(sourceFile)); } } /** * Sets the given {@code targetFile}'s last modified date to the given value. * * @param file The source file to query. * @param timeMillis The new last-modified time, measured in milliseconds since the epoch 01-01-1970 GMT. * @throws NullPointerException if file is {@code null}. * @throws IOException if setting the last-modified time failed. */ private static void setLastModified(final File file, final long timeMillis) throws IOException { Objects.requireNonNull(file, "file"); if (!file.setLastModified(timeMillis)) { throw new IOException(String.format("Failed setLastModified(%s) on '%s'", timeMillis, file)); } } /** * Returns the size of the specified file or directory. If the provided * {@link File} is a regular file, then the file's length is returned. * If the argument is a directory, then the size of the directory is * calculated recursively. If a directory or subdirectory is security * restricted, its size will not be included. * <p> * Note that overflow is not detected, and the return value may be negative if * overflow occurs. See {@link #sizeOfAsBigInteger(File)} for an alternative * method that does not overflow. * </p> * * @param file the regular file or directory to return the size * of (must not be {@code null}). * * @return the length of the file, or recursive size of the directory, * provided (in bytes). * * @throws NullPointerException if the file is {@code null}. * @throws IllegalArgumentException if the file does not exist. * @throws UncheckedIOException if an IO error occurs. * @since 2.0 */ public static long sizeOf(final File file) { requireExists(file, "file"); return Uncheck.get(() -> PathUtils.sizeOf(file.toPath())); } /** * Returns the size of the specified file or directory. If the provided * {@link File} is a regular file, then the file's length is returned. * If the argument is a directory, then the size of the directory is * calculated recursively. If a directory or subdirectory is security * restricted, its size will not be included. * * @param file the regular file or directory to return the size * of (must not be {@code null}). * * @return the length of the file, or recursive size of the directory, * provided (in bytes). * * @throws NullPointerException if the file is {@code null}. * @throws IllegalArgumentException if the file does not exist. * @throws UncheckedIOException if an IO error occurs. * @since 2.4 */ public static BigInteger sizeOfAsBigInteger(final File file) { requireExists(file, "file"); return Uncheck.get(() -> PathUtils.sizeOfAsBigInteger(file.toPath())); } /** * Counts the size of a directory recursively (sum of the length of all files). * <p> * Note that overflow is not detected, and the return value may be negative if * overflow occurs. See {@link #sizeOfDirectoryAsBigInteger(File)} for an alternative * method that does not overflow. * </p> * * @param directory directory to inspect, must not be {@code null}. * @return size of directory in bytes, 0 if directory is security restricted, a negative number when the real total * is greater than {@link Long#MAX_VALUE}. * @throws NullPointerException if the directory is {@code null}. * @throws UncheckedIOException if an IO error occurs. */ public static long sizeOfDirectory(final File directory) { requireDirectoryExists(directory, "directory"); return Uncheck.get(() -> PathUtils.sizeOfDirectory(directory.toPath())); } /** * Counts the size of a directory recursively (sum of the length of all files). * * @param directory directory to inspect, must not be {@code null}. * @return size of directory in bytes, 0 if directory is security restricted. * @throws NullPointerException if the directory is {@code null}. * @throws UncheckedIOException if an IO error occurs. * @since 2.4 */ public static BigInteger sizeOfDirectoryAsBigInteger(final File directory) { requireDirectoryExists(directory, "directory"); return Uncheck.get(() -> PathUtils.sizeOfDirectoryAsBigInteger(directory.toPath())); } /** * Streams over the files in a given directory (and optionally * its subdirectories) which match an array of extensions. * * @param directory the directory to search in * @param recursive if true all subdirectories are searched as well * @param extensions an array of extensions, ex. {"java","xml"}. If this * parameter is {@code null}, all files are returned. * @return an iterator of java.io.File with the matching files * @throws IOException if an I/O error is thrown when accessing the starting file. * @since 2.9.0 */ public static Stream<File> streamFiles(final File directory, final boolean recursive, final String... extensions) throws IOException { // @formatter:off final IOFileFilter filter = extensions == null ? FileFileFilter.INSTANCE : FileFileFilter.INSTANCE.and(new SuffixFileFilter(toSuffixes(extensions))); // @formatter:on return PathUtils.walk(directory.toPath(), filter, toMaxDepth(recursive), false, FileVisitOption.FOLLOW_LINKS).map(Path::toFile); } /** * Converts from a {@link URL} to a {@link File}. * <p> * From version 1.1 this method will decode the URL. * Syntax such as {@code file:///my%20docs/file.txt} will be * correctly decoded to {@code /my docs/file.txt}. Starting with version * 1.5, this method uses UTF-8 to decode percent-encoded octets to characters. * Additionally, malformed percent-encoded octets are handled leniently by * passing them through literally. * </p> * * @param url the file URL to convert, {@code null} returns {@code null} * @return the equivalent {@link File} object, or {@code null} * if the URL's protocol is not {@code file} */ public static File toFile(final URL url) { if (url == null || !"file".equalsIgnoreCase(url.getProtocol())) { return null; } final String filename = url.getFile().replace('/', File.separatorChar); return new File(decodeUrl(filename)); } /** * Converts each of an array of {@link URL} to a {@link File}. * <p> * Returns an array of the same size as the input. * If the input is {@code null}, an empty array is returned. * If the input contains {@code null}, the output array contains {@code null} at the same * index. * </p> * <p> * This method will decode the URL. * Syntax such as {@code file:///my%20docs/file.txt} will be * correctly decoded to {@code /my docs/file.txt}. * </p> * * @param urls the file URLs to convert, {@code null} returns empty array * @return a non-{@code null} array of Files matching the input, with a {@code null} item * if there was a {@code null} at that index in the input array * @throws IllegalArgumentException if any file is not a URL file * @throws IllegalArgumentException if any file is incorrectly encoded * @since 1.1 */ public static File[] toFiles(final URL... urls) { if (IOUtils.length(urls) == 0) { return EMPTY_FILE_ARRAY; } final File[] files = new File[urls.length]; for (int i = 0; i < urls.length; i++) { final URL url = urls[i]; if (url != null) { if (!"file".equalsIgnoreCase(url.getProtocol())) { throw new IllegalArgumentException("Can only convert file URL to a File: " + url); } files[i] = toFile(url); } } return files; } private static List<File> toList(final Stream<File> stream) { return stream.collect(Collectors.toList()); } /** * Converts whether or not to recurse into a recursion max depth. * * @param recursive whether or not to recurse * @return the recursion depth */ private static int toMaxDepth(final boolean recursive) { return recursive ? Integer.MAX_VALUE : 1; } /** * Converts an array of file extensions to suffixes. * * @param extensions an array of extensions. Format: {"java", "xml"} * @return an array of suffixes. Format: {".java", ".xml"} * @throws NullPointerException if the parameter is null */ private static String[] toSuffixes(final String... extensions) { return Stream.of(Objects.requireNonNull(extensions, "extensions")).map(e -> "." + e).toArray(String[]::new); } /** * Implements behavior similar to the Unix "touch" utility. Creates a new file with size 0, or, if the file exists, just * updates the file's modified time. * <p> * NOTE: As from v1.3, this method throws an IOException if the last modified date of the file cannot be set. Also, as * from v1.3 this method creates parent directories if they do not exist. * </p> * * @param file the File to touch. * @throws NullPointerException if the parameter is {@code null}. * @throws IOException if setting the last-modified time failed or an I/O problem occurs. */ public static void touch(final File file) throws IOException { PathUtils.touch(Objects.requireNonNull(file, "file").toPath()); } /** * Converts each of an array of {@link File} to a {@link URL}. * <p> * Returns an array of the same size as the input. * </p> * * @param files the files to convert, must not be {@code null} * @return an array of URLs matching the input * @throws IOException if a file cannot be converted * @throws NullPointerException if the parameter is null */ public static URL[] toURLs(final File... files) throws IOException { Objects.requireNonNull(files, "files"); final URL[] urls = new URL[files.length]; for (int i = 0; i < urls.length; i++) { urls[i] = files[i].toURI().toURL(); } return urls; } /** * Validates the given arguments. * <ul> * <li>Throws {@link NullPointerException} if {@code source} is null</li> * <li>Throws {@link NullPointerException} if {@code destination} is null</li> * <li>Throws {@link FileNotFoundException} if {@code source} does not exist</li> * </ul> * * @param source the file or directory to be moved. * @param destination the destination file or directory. * @throws FileNotFoundException if the source file does not exist. */ private static void validateMoveParameters(final File source, final File destination) throws FileNotFoundException { Objects.requireNonNull(source, "source"); Objects.requireNonNull(destination, "destination"); if (!source.exists()) { throw new FileNotFoundException("Source '" + source + "' does not exist"); } } /** * Waits for the file system to propagate a file creation, with a timeout. * <p> * This method repeatedly tests {@link Files#exists(Path, LinkOption...)} until it returns * true up to the maximum time specified in seconds. * </p> * * @param file the file to check, must not be {@code null} * @param seconds the maximum time in seconds to wait * @return true if file exists * @throws NullPointerException if the file is {@code null} */ public static boolean waitFor(final File file, final int seconds) { Objects.requireNonNull(file, "file"); return PathUtils.waitFor(file.toPath(), Duration.ofSeconds(seconds), PathUtils.EMPTY_LINK_OPTION_ARRAY); } /** * Writes a CharSequence to a file creating the file if it does not exist using the default encoding for the VM. * * @param file the file to write * @param data the content to write to the file * @throws IOException in case of an I/O error * @since 2.0 * @deprecated 2.5 use {@link #write(File, CharSequence, Charset)} instead (and specify the appropriate encoding) */ @Deprecated public static void write(final File file, final CharSequence data) throws IOException { write(file, data, Charset.defaultCharset(), false); } /** * Writes a CharSequence to a file creating the file if it does not exist using the default encoding for the VM. * * @param file the file to write * @param data the content to write to the file * @param append if {@code true}, then the data will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.1 * @deprecated 2.5 use {@link #write(File, CharSequence, Charset, boolean)} instead (and specify the appropriate encoding) */ @Deprecated public static void write(final File file, final CharSequence data, final boolean append) throws IOException { write(file, data, Charset.defaultCharset(), append); } /** * Writes a CharSequence to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param charset the name of the requested charset, {@code null} means platform default * @throws IOException in case of an I/O error * @since 2.3 */ public static void write(final File file, final CharSequence data, final Charset charset) throws IOException { write(file, data, charset, false); } /** * Writes a CharSequence to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param charset the charset to use, {@code null} means platform default * @param append if {@code true}, then the data will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.3 */ public static void write(final File file, final CharSequence data, final Charset charset, final boolean append) throws IOException { writeStringToFile(file, Objects.toString(data, null), charset, append); } /** * Writes a CharSequence to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param charsetName the name of the requested charset, {@code null} means platform default * @throws IOException in case of an I/O error * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM * @since 2.0 */ public static void write(final File file, final CharSequence data, final String charsetName) throws IOException { write(file, data, charsetName, false); } /** * Writes a CharSequence to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param charsetName the name of the requested charset, {@code null} means platform default * @param append if {@code true}, then the data will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io * .UnsupportedEncodingException} in version 2.2 if the encoding is not supported by the VM * @since 2.1 */ public static void write(final File file, final CharSequence data, final String charsetName, final boolean append) throws IOException { write(file, data, Charsets.toCharset(charsetName), append); } // Must be called with a directory /** * Writes a byte array to a file creating the file if it does not exist. * <p> * NOTE: As from v1.3, the parent directories of the file will be created * if they do not exist. * </p> * * @param file the file to write to * @param data the content to write to the file * @throws IOException in case of an I/O error * @since 1.1 */ public static void writeByteArrayToFile(final File file, final byte[] data) throws IOException { writeByteArrayToFile(file, data, false); } /** * Writes a byte array to a file creating the file if it does not exist. * * @param file the file to write to * @param data the content to write to the file * @param append if {@code true}, then bytes will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.1 */ public static void writeByteArrayToFile(final File file, final byte[] data, final boolean append) throws IOException { writeByteArrayToFile(file, data, 0, data.length, append); } /** * Writes {@code len} bytes from the specified byte array starting * at offset {@code off} to a file, creating the file if it does * not exist. * * @param file the file to write to * @param data the content to write to the file * @param off the start offset in the data * @param len the number of bytes to write * @throws IOException in case of an I/O error * @since 2.5 */ public static void writeByteArrayToFile(final File file, final byte[] data, final int off, final int len) throws IOException { writeByteArrayToFile(file, data, off, len, false); } /** * Writes {@code len} bytes from the specified byte array starting * at offset {@code off} to a file, creating the file if it does * not exist. * * @param file the file to write to * @param data the content to write to the file * @param off the start offset in the data * @param len the number of bytes to write * @param append if {@code true}, then bytes will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.5 */ public static void writeByteArrayToFile(final File file, final byte[] data, final int off, final int len, final boolean append) throws IOException { try (OutputStream out = newOutputStream(file, append)) { out.write(data, off, len); } } /** * Writes the {@code toString()} value of each item in a collection to * the specified {@link File} line by line. * The default VM encoding and the default line ending will be used. * * @param file the file to write to * @param lines the lines to write, {@code null} entries produce blank lines * @throws IOException in case of an I/O error * @since 1.3 */ public static void writeLines(final File file, final Collection<?> lines) throws IOException { writeLines(file, null, lines, null, false); } /** * Writes the {@code toString()} value of each item in a collection to * the specified {@link File} line by line. * The default VM encoding and the default line ending will be used. * * @param file the file to write to * @param lines the lines to write, {@code null} entries produce blank lines * @param append if {@code true}, then the lines will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.1 */ public static void writeLines(final File file, final Collection<?> lines, final boolean append) throws IOException { writeLines(file, null, lines, null, append); } /** * Writes the {@code toString()} value of each item in a collection to * the specified {@link File} line by line. * The default VM encoding and the specified line ending will be used. * * @param file the file to write to * @param lines the lines to write, {@code null} entries produce blank lines * @param lineEnding the line separator to use, {@code null} is system default * @throws IOException in case of an I/O error * @since 1.3 */ public static void writeLines(final File file, final Collection<?> lines, final String lineEnding) throws IOException { writeLines(file, null, lines, lineEnding, false); } /** * Writes the {@code toString()} value of each item in a collection to * the specified {@link File} line by line. * The default VM encoding and the specified line ending will be used. * * @param file the file to write to * @param lines the lines to write, {@code null} entries produce blank lines * @param lineEnding the line separator to use, {@code null} is system default * @param append if {@code true}, then the lines will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.1 */ public static void writeLines(final File file, final Collection<?> lines, final String lineEnding, final boolean append) throws IOException { writeLines(file, null, lines, lineEnding, append); } /** * Writes the {@code toString()} value of each item in a collection to * the specified {@link File} line by line. * The specified character encoding and the default line ending will be used. * <p> * NOTE: As from v1.3, the parent directories of the file will be created * if they do not exist. * </p> * * @param file the file to write to * @param charsetName the name of the requested charset, {@code null} means platform default * @param lines the lines to write, {@code null} entries produce blank lines * @throws IOException in case of an I/O error * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM * @since 1.1 */ public static void writeLines(final File file, final String charsetName, final Collection<?> lines) throws IOException { writeLines(file, charsetName, lines, null, false); } /** * Writes the {@code toString()} value of each item in a collection to * the specified {@link File} line by line, optionally appending. * The specified character encoding and the default line ending will be used. * * @param file the file to write to * @param charsetName the name of the requested charset, {@code null} means platform default * @param lines the lines to write, {@code null} entries produce blank lines * @param append if {@code true}, then the lines will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM * @since 2.1 */ public static void writeLines(final File file, final String charsetName, final Collection<?> lines, final boolean append) throws IOException { writeLines(file, charsetName, lines, null, append); } /** * Writes the {@code toString()} value of each item in a collection to * the specified {@link File} line by line. * The specified character encoding and the line ending will be used. * <p> * NOTE: As from v1.3, the parent directories of the file will be created * if they do not exist. * </p> * * @param file the file to write to * @param charsetName the name of the requested charset, {@code null} means platform default * @param lines the lines to write, {@code null} entries produce blank lines * @param lineEnding the line separator to use, {@code null} is system default * @throws IOException in case of an I/O error * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM * @since 1.1 */ public static void writeLines(final File file, final String charsetName, final Collection<?> lines, final String lineEnding) throws IOException { writeLines(file, charsetName, lines, lineEnding, false); } /** * Writes the {@code toString()} value of each item in a collection to * the specified {@link File} line by line. * The specified character encoding and the line ending will be used. * * @param file the file to write to * @param charsetName the name of the requested charset, {@code null} means platform default * @param lines the lines to write, {@code null} entries produce blank lines * @param lineEnding the line separator to use, {@code null} is system default * @param append if {@code true}, then the lines will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM * @since 2.1 */ public static void writeLines(final File file, final String charsetName, final Collection<?> lines, final String lineEnding, final boolean append) throws IOException { try (OutputStream out = new BufferedOutputStream(newOutputStream(file, append))) { IOUtils.writeLines(lines, lineEnding, out, charsetName); } } /** * Writes a String to a file creating the file if it does not exist using the default encoding for the VM. * * @param file the file to write * @param data the content to write to the file * @throws IOException in case of an I/O error * @deprecated 2.5 use {@link #writeStringToFile(File, String, Charset)} instead (and specify the appropriate encoding) */ @Deprecated public static void writeStringToFile(final File file, final String data) throws IOException { writeStringToFile(file, data, Charset.defaultCharset(), false); } /** * Writes a String to a file creating the file if it does not exist using the default encoding for the VM. * * @param file the file to write * @param data the content to write to the file * @param append if {@code true}, then the String will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.1 * @deprecated 2.5 use {@link #writeStringToFile(File, String, Charset, boolean)} instead (and specify the appropriate encoding) */ @Deprecated public static void writeStringToFile(final File file, final String data, final boolean append) throws IOException { writeStringToFile(file, data, Charset.defaultCharset(), append); } /** * Writes a String to a file creating the file if it does not exist. * <p> * NOTE: As from v1.3, the parent directories of the file will be created * if they do not exist. * </p> * * @param file the file to write * @param data the content to write to the file * @param charset the charset to use, {@code null} means platform default * @throws IOException in case of an I/O error * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM * @since 2.4 */ public static void writeStringToFile(final File file, final String data, final Charset charset) throws IOException { writeStringToFile(file, data, charset, false); } /** * Writes a String to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param charset the charset to use, {@code null} means platform default * @param append if {@code true}, then the String will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.3 */ public static void writeStringToFile(final File file, final String data, final Charset charset, final boolean append) throws IOException { try (OutputStream out = newOutputStream(file, append)) { IOUtils.write(data, out, charset); } } /** * Writes a String to a file creating the file if it does not exist. * <p> * NOTE: As from v1.3, the parent directories of the file will be created * if they do not exist. * </p> * * @param file the file to write * @param data the content to write to the file * @param charsetName the name of the requested charset, {@code null} means platform default * @throws IOException in case of an I/O error * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM */ public static void writeStringToFile(final File file, final String data, final String charsetName) throws IOException { writeStringToFile(file, data, charsetName, false); } /** * Writes a String to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param charsetName the name of the requested charset, {@code null} means platform default * @param append if {@code true}, then the String will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io * .UnsupportedEncodingException} in version 2.2 if the encoding is not supported by the VM * @since 2.1 */ public static void writeStringToFile(final File file, final String data, final String charsetName, final boolean append) throws IOException { writeStringToFile(file, data, Charsets.toCharset(charsetName), append); } /** * Instances should NOT be constructed in standard programming. * @deprecated Will be private in 3.0. */ @Deprecated public FileUtils() { //NOSONAR } }
src/main/java/org/apache/commons/io/FileUtils.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 java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.UncheckedIOException; import java.math.BigInteger; import java.net.URL; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.charset.UnsupportedCharsetException; import java.nio.file.CopyOption; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.NotDirectoryException; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.FileTime; import java.time.Duration; import java.time.Instant; import java.time.LocalTime; import java.time.OffsetDateTime; import java.time.OffsetTime; import java.time.ZoneId; import java.time.chrono.ChronoLocalDate; import java.time.chrono.ChronoLocalDateTime; import java.time.chrono.ChronoZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.zip.CRC32; import java.util.zip.CheckedInputStream; import java.util.zip.Checksum; import org.apache.commons.io.file.AccumulatorPathVisitor; import org.apache.commons.io.file.Counters; import org.apache.commons.io.file.PathFilter; import org.apache.commons.io.file.PathUtils; import org.apache.commons.io.file.StandardDeleteOption; import org.apache.commons.io.filefilter.FileEqualsFileFilter; import org.apache.commons.io.filefilter.FileFileFilter; import org.apache.commons.io.filefilter.IOFileFilter; import org.apache.commons.io.filefilter.SuffixFileFilter; import org.apache.commons.io.filefilter.TrueFileFilter; import org.apache.commons.io.function.IOConsumer; import org.apache.commons.io.function.Uncheck; /** * General file manipulation utilities. * <p> * Facilities are provided in the following areas: * </p> * <ul> * <li>writing to a file * <li>reading from a file * <li>make a directory including parent directories * <li>copying files and directories * <li>deleting files and directories * <li>converting to and from a URL * <li>listing files and directories by filter and extension * <li>comparing file content * <li>file last changed date * <li>calculating a checksum * </ul> * <p> * Note that a specific charset should be specified whenever possible. Relying on the platform default means that the * code is Locale-dependent. Only use the default if the files are known to always use the platform default. * </p> * <p> * {@link SecurityException} are not documented in the Javadoc. * </p> * <p> * Origin of code: Excalibur, Alexandria, Commons-Utils * </p> */ public class FileUtils { /** * The number of bytes in a kilobyte. */ public static final long ONE_KB = 1024; /** * The number of bytes in a kilobyte. * * @since 2.4 */ public static final BigInteger ONE_KB_BI = BigInteger.valueOf(ONE_KB); /** * The number of bytes in a megabyte. */ public static final long ONE_MB = ONE_KB * ONE_KB; /** * The number of bytes in a megabyte. * * @since 2.4 */ public static final BigInteger ONE_MB_BI = ONE_KB_BI.multiply(ONE_KB_BI); /** * The number of bytes in a gigabyte. */ public static final long ONE_GB = ONE_KB * ONE_MB; /** * The number of bytes in a gigabyte. * * @since 2.4 */ public static final BigInteger ONE_GB_BI = ONE_KB_BI.multiply(ONE_MB_BI); /** * The number of bytes in a terabyte. */ public static final long ONE_TB = ONE_KB * ONE_GB; /** * The number of bytes in a terabyte. * * @since 2.4 */ public static final BigInteger ONE_TB_BI = ONE_KB_BI.multiply(ONE_GB_BI); /** * The number of bytes in a petabyte. */ public static final long ONE_PB = ONE_KB * ONE_TB; /** * The number of bytes in a petabyte. * * @since 2.4 */ public static final BigInteger ONE_PB_BI = ONE_KB_BI.multiply(ONE_TB_BI); /** * The number of bytes in an exabyte. */ public static final long ONE_EB = ONE_KB * ONE_PB; /** * The number of bytes in an exabyte. * * @since 2.4 */ public static final BigInteger ONE_EB_BI = ONE_KB_BI.multiply(ONE_PB_BI); /** * The number of bytes in a zettabyte. */ public static final BigInteger ONE_ZB = BigInteger.valueOf(ONE_KB).multiply(BigInteger.valueOf(ONE_EB)); /** * The number of bytes in a yottabyte. */ public static final BigInteger ONE_YB = ONE_KB_BI.multiply(ONE_ZB); /** * An empty array of type {@link File}. */ public static final File[] EMPTY_FILE_ARRAY = {}; /** * Copies the given array and adds StandardCopyOption.COPY_ATTRIBUTES. * * @param copyOptions sorted copy options. * @return a new array. */ private static CopyOption[] addCopyAttributes(final CopyOption... copyOptions) { // Make a copy first since we don't want to sort the call site's version. final CopyOption[] actual = Arrays.copyOf(copyOptions, copyOptions.length + 1); Arrays.sort(actual, 0, copyOptions.length); if (Arrays.binarySearch(copyOptions, 0, copyOptions.length, StandardCopyOption.COPY_ATTRIBUTES) >= 0) { return copyOptions; } actual[actual.length - 1] = StandardCopyOption.COPY_ATTRIBUTES; return actual; } /** * Returns a human-readable version of the file size, where the input represents a specific number of bytes. * <p> * If the size is over 1GB, the size is returned as the number of whole GB, i.e. the size is rounded down to the * nearest GB boundary. * </p> * <p> * Similarly for the 1MB and 1KB boundaries. * </p> * * @param size the number of bytes * @return a human-readable display value (includes units - EB, PB, TB, GB, MB, KB or bytes) * @throws NullPointerException if the given {@link BigInteger} is {@code null}. * @see <a href="https://issues.apache.org/jira/browse/IO-226">IO-226 - should the rounding be changed?</a> * @since 2.4 */ // See https://issues.apache.org/jira/browse/IO-226 - should the rounding be changed? public static String byteCountToDisplaySize(final BigInteger size) { Objects.requireNonNull(size, "size"); final String displaySize; if (size.divide(ONE_EB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize = size.divide(ONE_EB_BI) + " EB"; } else if (size.divide(ONE_PB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize = size.divide(ONE_PB_BI) + " PB"; } else if (size.divide(ONE_TB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize = size.divide(ONE_TB_BI) + " TB"; } else if (size.divide(ONE_GB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize = size.divide(ONE_GB_BI) + " GB"; } else if (size.divide(ONE_MB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize = size.divide(ONE_MB_BI) + " MB"; } else if (size.divide(ONE_KB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize = size.divide(ONE_KB_BI) + " KB"; } else { displaySize = size + " bytes"; } return displaySize; } /** * Returns a human-readable version of the file size, where the input represents a specific number of bytes. * <p> * If the size is over 1GB, the size is returned as the number of whole GB, i.e. the size is rounded down to the * nearest GB boundary. * </p> * <p> * Similarly for the 1MB and 1KB boundaries. * </p> * * @param size the number of bytes * @return a human-readable display value (includes units - EB, PB, TB, GB, MB, KB or bytes) * @see <a href="https://issues.apache.org/jira/browse/IO-226">IO-226 - should the rounding be changed?</a> */ // See https://issues.apache.org/jira/browse/IO-226 - should the rounding be changed? public static String byteCountToDisplaySize(final long size) { return byteCountToDisplaySize(BigInteger.valueOf(size)); } /** * Returns a human-readable version of the file size, where the input represents a specific number of bytes. * <p> * If the size is over 1GB, the size is returned as the number of whole GB, i.e. the size is rounded down to the * nearest GB boundary. * </p> * <p> * Similarly for the 1MB and 1KB boundaries. * </p> * * @param size the number of bytes * @return a human-readable display value (includes units - EB, PB, TB, GB, MB, KB or bytes) * @see <a href="https://issues.apache.org/jira/browse/IO-226">IO-226 - should the rounding be changed?</a> * @since 2.12.0 */ // See https://issues.apache.org/jira/browse/IO-226 - should the rounding be changed? public static String byteCountToDisplaySize(final Number size) { return byteCountToDisplaySize(size.longValue()); } /** * Computes the checksum of a file using the specified checksum object. Multiple files may be checked using one * {@link Checksum} instance if desired simply by reusing the same checksum object. For example: * * <pre> * long checksum = FileUtils.checksum(file, new CRC32()).getValue(); * </pre> * * @param file the file to checksum, must not be {@code null} * @param checksum the checksum object to be used, must not be {@code null} * @return the checksum specified, updated with the content of the file * @throws NullPointerException if the given {@link File} is {@code null}. * @throws NullPointerException if the given {@link Checksum} is {@code null}. * @throws IllegalArgumentException if the given {@link File} does not exist or is not a file. * @throws IOException if an IO error occurs reading the file. * @since 1.3 */ public static Checksum checksum(final File file, final Checksum checksum) throws IOException { requireExistsChecked(file, "file"); requireFile(file, "file"); Objects.requireNonNull(checksum, "checksum"); try (InputStream inputStream = new CheckedInputStream(Files.newInputStream(file.toPath()), checksum)) { IOUtils.consume(inputStream); } return checksum; } /** * Computes the checksum of a file using the CRC32 checksum routine. * The value of the checksum is returned. * * @param file the file to checksum, must not be {@code null} * @return the checksum value * @throws NullPointerException if the given {@link File} is {@code null}. * @throws IllegalArgumentException if the given {@link File} does not exist or is not a file. * @throws IOException if an IO error occurs reading the file. * @since 1.3 */ public static long checksumCRC32(final File file) throws IOException { return checksum(file, new CRC32()).getValue(); } /** * Cleans a directory without deleting it. * * @param directory directory to clean * @throws NullPointerException if the given {@link File} is {@code null}. * @throws IllegalArgumentException if directory does not exist or is not a directory. * @throws IOException if an I/O error occurs. * @see #forceDelete(File) */ public static void cleanDirectory(final File directory) throws IOException { IOConsumer.forAll(FileUtils::forceDelete, listFiles(directory, null)); } /** * Cleans a directory without deleting it. * * @param directory directory to clean, must not be {@code null} * @throws NullPointerException if the given {@link File} is {@code null}. * @throws IllegalArgumentException if directory does not exist or is not a directory. * @throws IOException if an I/O error occurs. * @see #forceDeleteOnExit(File) */ private static void cleanDirectoryOnExit(final File directory) throws IOException { IOConsumer.forAll(FileUtils::forceDeleteOnExit, listFiles(directory, null)); } /** * Tests whether the contents of two files are equal. * <p> * This method checks to see if the two files are different lengths or if they point to the same file, before * resorting to byte-by-byte comparison of the contents. * </p> * <p> * Code origin: Avalon * </p> * * @param file1 the first file * @param file2 the second file * @return true if the content of the files are equal or they both don't exist, false otherwise * @throws IllegalArgumentException when an input is not a file. * @throws IOException If an I/O error occurs. * @see org.apache.commons.io.file.PathUtils#fileContentEquals(Path,Path,java.nio.file.LinkOption[],java.nio.file.OpenOption...) */ public static boolean contentEquals(final File file1, final File file2) throws IOException { if (file1 == null && file2 == null) { return true; } if (file1 == null || file2 == null) { return false; } final boolean file1Exists = file1.exists(); if (file1Exists != file2.exists()) { return false; } if (!file1Exists) { // two not existing files are equal return true; } requireFile(file1, "file1"); requireFile(file2, "file2"); if (file1.length() != file2.length()) { // lengths differ, cannot be equal return false; } if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) { // same file return true; } try (InputStream input1 = Files.newInputStream(file1.toPath()); InputStream input2 = Files.newInputStream(file2.toPath())) { return IOUtils.contentEquals(input1, input2); } } /** * Compares the contents of two files to determine if they are equal or not. * <p> * This method checks to see if the two files point to the same file, * before resorting to line-by-line comparison of the contents. * </p> * * @param file1 the first file * @param file2 the second file * @param charsetName the name of the requested charset. * May be null, in which case the platform default is used * @return true if the content of the files are equal or neither exists, * false otherwise * @throws IllegalArgumentException when an input is not a file. * @throws IOException in case of an I/O error. * @throws UnsupportedCharsetException If the named charset is unavailable (unchecked exception). * @see IOUtils#contentEqualsIgnoreEOL(Reader, Reader) * @since 2.2 */ public static boolean contentEqualsIgnoreEOL(final File file1, final File file2, final String charsetName) throws IOException { if (file1 == null && file2 == null) { return true; } if (file1 == null || file2 == null) { return false; } final boolean file1Exists = file1.exists(); if (file1Exists != file2.exists()) { return false; } if (!file1Exists) { // two not existing files are equal return true; } requireFile(file1, "file1"); requireFile(file2, "file2"); if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) { // same file return true; } final Charset charset = Charsets.toCharset(charsetName); try (Reader input1 = new InputStreamReader(Files.newInputStream(file1.toPath()), charset); Reader input2 = new InputStreamReader(Files.newInputStream(file2.toPath()), charset)) { return IOUtils.contentEqualsIgnoreEOL(input1, input2); } } /** * Converts a Collection containing java.io.File instances into array * representation. This is to account for the difference between * File.listFiles() and FileUtils.listFiles(). * * @param files a Collection containing java.io.File instances * @return an array of java.io.File */ public static File[] convertFileCollectionToFileArray(final Collection<File> files) { return files.toArray(EMPTY_FILE_ARRAY); } /** * Copies a whole directory to a new location preserving the file dates. * <p> * This method copies the specified directory and all its child directories and files to the specified destination. * The destination is the new location and name of the directory. * </p> * <p> * The destination directory is created if it does not exist. If the destination directory did exist, then this * method merges the source with the destination, with the source taking precedence. * </p> * <p> * <strong>Note:</strong> This method tries to preserve the files' last modified date/times using * {@link File#setLastModified(long)}, however it is not guaranteed that those operations will succeed. If the * modification operation fails, the methods throws IOException. * </p> * * @param srcDir an existing directory to copy, must not be {@code null}. * @param destDir the new directory, must not be {@code null}. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IllegalArgumentException if the source or destination is invalid. * @throws FileNotFoundException if the source does not exist. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @since 1.1 */ public static void copyDirectory(final File srcDir, final File destDir) throws IOException { copyDirectory(srcDir, destDir, true); } /** * Copies a whole directory to a new location. * <p> * This method copies the contents of the specified source directory to within the specified destination directory. * </p> * <p> * The destination directory is created if it does not exist. If the destination directory did exist, then this * method merges the source with the destination, with the source taking precedence. * </p> * <p> * <strong>Note:</strong> Setting {@code preserveFileDate} to {@code true} tries to preserve the files' last * modified date/times using {@link File#setLastModified(long)}, however it is not guaranteed that those operations * will succeed. If the modification operation fails, the methods throws IOException. * </p> * * @param srcDir an existing directory to copy, must not be {@code null}. * @param destDir the new directory, must not be {@code null}. * @param preserveFileDate true if the file date of the copy should be the same as the original. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IllegalArgumentException if the source or destination is invalid. * @throws FileNotFoundException if the source does not exist. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @since 1.1 */ public static void copyDirectory(final File srcDir, final File destDir, final boolean preserveFileDate) throws IOException { copyDirectory(srcDir, destDir, null, preserveFileDate); } /** * Copies a filtered directory to a new location preserving the file dates. * <p> * This method copies the contents of the specified source directory to within the specified destination directory. * </p> * <p> * The destination directory is created if it does not exist. If the destination directory did exist, then this * method merges the source with the destination, with the source taking precedence. * </p> * <p> * <strong>Note:</strong> This method tries to preserve the files' last modified date/times using * {@link File#setLastModified(long)}, however it is not guaranteed that those operations will succeed. If the * modification operation fails, the methods throws IOException. * </p> * <b>Example: Copy directories only</b> * * <pre> * // only copy the directory structure * FileUtils.copyDirectory(srcDir, destDir, DirectoryFileFilter.DIRECTORY); * </pre> * * <b>Example: Copy directories and txt files</b> * * <pre> * // Create a filter for ".txt" files * IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt"); * IOFileFilter txtFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE, txtSuffixFilter); * * // Create a filter for either directories or ".txt" files * FileFilter filter = FileFilterUtils.orFileFilter(DirectoryFileFilter.DIRECTORY, txtFiles); * * // Copy using the filter * FileUtils.copyDirectory(srcDir, destDir, filter); * </pre> * * @param srcDir an existing directory to copy, must not be {@code null}. * @param destDir the new directory, must not be {@code null}. * @param filter the filter to apply, null means copy all directories and files should be the same as the original. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IllegalArgumentException if the source or destination is invalid. * @throws FileNotFoundException if the source does not exist. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @since 1.4 */ public static void copyDirectory(final File srcDir, final File destDir, final FileFilter filter) throws IOException { copyDirectory(srcDir, destDir, filter, true); } /** * Copies a filtered directory to a new location. * <p> * This method copies the contents of the specified source directory to within the specified destination directory. * </p> * <p> * The destination directory is created if it does not exist. If the destination directory did exist, then this * method merges the source with the destination, with the source taking precedence. * </p> * <p> * <strong>Note:</strong> Setting {@code preserveFileDate} to {@code true} tries to preserve the files' last * modified date/times using {@link File#setLastModified(long)}, however it is not guaranteed that those operations * will succeed. If the modification operation fails, the methods throws IOException. * </p> * <b>Example: Copy directories only</b> * * <pre> * // only copy the directory structure * FileUtils.copyDirectory(srcDir, destDir, DirectoryFileFilter.DIRECTORY, false); * </pre> * * <b>Example: Copy directories and txt files</b> * * <pre> * // Create a filter for ".txt" files * IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt"); * IOFileFilter txtFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE, txtSuffixFilter); * * // Create a filter for either directories or ".txt" files * FileFilter filter = FileFilterUtils.orFileFilter(DirectoryFileFilter.DIRECTORY, txtFiles); * * // Copy using the filter * FileUtils.copyDirectory(srcDir, destDir, filter, false); * </pre> * * @param srcDir an existing directory to copy, must not be {@code null}. * @param destDir the new directory, must not be {@code null}. * @param filter the filter to apply, null means copy all directories and files. * @param preserveFileDate true if the file date of the copy should be the same as the original. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IllegalArgumentException if the source or destination is invalid. * @throws FileNotFoundException if the source does not exist. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @since 1.4 */ public static void copyDirectory(final File srcDir, final File destDir, final FileFilter filter, final boolean preserveFileDate) throws IOException { copyDirectory(srcDir, destDir, filter, preserveFileDate, StandardCopyOption.REPLACE_EXISTING); } /** * Copies a filtered directory to a new location. * <p> * This method copies the contents of the specified source directory to within the specified destination directory. * </p> * <p> * The destination directory is created if it does not exist. If the destination directory did exist, then this * method merges the source with the destination, with the source taking precedence. * </p> * <p> * <strong>Note:</strong> Setting {@code preserveFileDate} to {@code true} tries to preserve the files' last * modified date/times using {@link File#setLastModified(long)}, however it is not guaranteed that those operations * will succeed. If the modification operation fails, the methods throws IOException. * </p> * <b>Example: Copy directories only</b> * * <pre> * // only copy the directory structure * FileUtils.copyDirectory(srcDir, destDir, DirectoryFileFilter.DIRECTORY, false); * </pre> * * <b>Example: Copy directories and txt files</b> * * <pre> * // Create a filter for ".txt" files * IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt"); * IOFileFilter txtFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE, txtSuffixFilter); * * // Create a filter for either directories or ".txt" files * FileFilter filter = FileFilterUtils.orFileFilter(DirectoryFileFilter.DIRECTORY, txtFiles); * * // Copy using the filter * FileUtils.copyDirectory(srcDir, destDir, filter, false); * </pre> * * @param srcDir an existing directory to copy, must not be {@code null} * @param destDir the new directory, must not be {@code null} * @param fileFilter the filter to apply, null means copy all directories and files * @param preserveFileDate true if the file date of the copy should be the same as the original * @param copyOptions options specifying how the copy should be done, for example {@link StandardCopyOption}. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IllegalArgumentException if the source or destination is invalid. * @throws FileNotFoundException if the source does not exist. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @since 2.8.0 */ public static void copyDirectory(final File srcDir, final File destDir, final FileFilter fileFilter, final boolean preserveFileDate, final CopyOption... copyOptions) throws IOException { requireFileCopy(srcDir, destDir); requireDirectory(srcDir, "srcDir"); requireCanonicalPathsNotEquals(srcDir, destDir); // Cater for destination being directory within the source directory (see IO-141) List<String> exclusionList = null; final String srcDirCanonicalPath = srcDir.getCanonicalPath(); final String destDirCanonicalPath = destDir.getCanonicalPath(); if (destDirCanonicalPath.startsWith(srcDirCanonicalPath)) { final File[] srcFiles = listFiles(srcDir, fileFilter); if (srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { exclusionList.add(new File(destDir, srcFile.getName()).getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, fileFilter, exclusionList, preserveFileDate, preserveFileDate ? addCopyAttributes(copyOptions) : copyOptions); } /** * Copies a directory to within another directory preserving the file dates. * <p> * This method copies the source directory and all its contents to a directory of the same name in the specified * destination directory. * </p> * <p> * The destination directory is created if it does not exist. If the destination directory did exist, then this * method merges the source with the destination, with the source taking precedence. * </p> * <p> * <strong>Note:</strong> This method tries to preserve the files' last modified date/times using * {@link File#setLastModified(long)}, however it is not guaranteed that those operations will succeed. If the * modification operation fails, the methods throws IOException. * </p> * * @param sourceDir an existing directory to copy, must not be {@code null}. * @param destinationDir the directory to place the copy in, must not be {@code null}. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IllegalArgumentException if the source or destination is invalid. * @throws FileNotFoundException if the source does not exist. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @since 1.2 */ public static void copyDirectoryToDirectory(final File sourceDir, final File destinationDir) throws IOException { requireDirectoryIfExists(sourceDir, "sourceDir"); requireDirectoryIfExists(destinationDir, "destinationDir"); copyDirectory(sourceDir, new File(destinationDir, sourceDir.getName()), true); } /** * Copies a file to a new location preserving the file date. * <p> * This method copies the contents of the specified source file to the specified destination file. The directory * holding the destination file is created if it does not exist. If the destination file exists, then this method * will overwrite it. * </p> * <p> * <strong>Note:</strong> This method tries to preserve the file's last modified date/times using * {@link StandardCopyOption#COPY_ATTRIBUTES}, however it is not guaranteed that the operation will succeed. If the * modification operation fails, the methods throws IOException. * </p> * * @param srcFile an existing file to copy, must not be {@code null}. * @param destFile the new file, must not be {@code null}. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IOException if source or destination is invalid. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @throws IOException if the output file length is not the same as the input file length after the copy completes. * @see #copyFileToDirectory(File, File) * @see #copyFile(File, File, boolean) */ public static void copyFile(final File srcFile, final File destFile) throws IOException { copyFile(srcFile, destFile, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); } /** * Copies an existing file to a new file location. * <p> * This method copies the contents of the specified source file to the specified destination file. The directory * holding the destination file is created if it does not exist. If the destination file exists, then this method * will overwrite it. * </p> * <p> * <strong>Note:</strong> Setting {@code preserveFileDate} to {@code true} tries to preserve the file's last * modified date/times using {@link StandardCopyOption#COPY_ATTRIBUTES}, however it is not guaranteed that the operation * will succeed. If the modification operation fails, the methods throws IOException. * </p> * * @param srcFile an existing file to copy, must not be {@code null}. * @param destFile the new file, must not be {@code null}. * @param preserveFileDate true if the file date of the copy should be the same as the original. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IOException if source or destination is invalid. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @throws IOException if the output file length is not the same as the input file length after the copy completes * @see #copyFile(File, File, boolean, CopyOption...) */ public static void copyFile(final File srcFile, final File destFile, final boolean preserveFileDate) throws IOException { // @formatter:off copyFile(srcFile, destFile, preserveFileDate ? new CopyOption[] {StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING} : new CopyOption[] {StandardCopyOption.REPLACE_EXISTING}); // @formatter:on } /** * Copies a file to a new location. * <p> * This method copies the contents of the specified source file to the specified destination file. The directory * holding the destination file is created if it does not exist. If the destination file exists, you can overwrite * it with {@link StandardCopyOption#REPLACE_EXISTING}. * </p> * <p> * <strong>Note:</strong> Setting {@code preserveFileDate} to {@code true} tries to preserve the file's last * modified date/times using {@link StandardCopyOption#COPY_ATTRIBUTES}, however it is not guaranteed that the operation * will succeed. If the modification operation fails, the methods throws IOException. * </p> * * @param srcFile an existing file to copy, must not be {@code null}. * @param destFile the new file, must not be {@code null}. * @param preserveFileDate true if the file date of the copy should be the same as the original. * @param copyOptions options specifying how the copy should be done, for example {@link StandardCopyOption}.. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws FileNotFoundException if the source does not exist. * @throws IllegalArgumentException if source is not a file. * @throws IOException if the output file length is not the same as the input file length after the copy completes. * @throws IOException if an I/O error occurs, or setting the last-modified time didn't succeed. * @see #copyFileToDirectory(File, File, boolean) * @since 2.8.0 */ public static void copyFile(final File srcFile, final File destFile, final boolean preserveFileDate, final CopyOption... copyOptions) throws IOException { copyFile(srcFile, destFile, preserveFileDate ? addCopyAttributes(copyOptions) : copyOptions); } /** * Copies a file to a new location. * <p> * This method copies the contents of the specified source file to the specified destination file. The directory * holding the destination file is created if it does not exist. If the destination file exists, you can overwrite * it if you use {@link StandardCopyOption#REPLACE_EXISTING}. * </p> * * @param srcFile an existing file to copy, must not be {@code null}. * @param destFile the new file, must not be {@code null}. * @param copyOptions options specifying how the copy should be done, for example {@link StandardCopyOption}.. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws FileNotFoundException if the source does not exist. * @throws IllegalArgumentException if source is not a file. * @throws IOException if an I/O error occurs. * @see StandardCopyOption * @since 2.9.0 */ public static void copyFile(final File srcFile, final File destFile, final CopyOption... copyOptions) throws IOException { requireFileCopy(srcFile, destFile); requireFile(srcFile, "srcFile"); requireCanonicalPathsNotEquals(srcFile, destFile); createParentDirectories(destFile); requireFileIfExists(destFile, "destFile"); if (destFile.exists()) { requireCanWrite(destFile, "destFile"); } // On Windows, the last modified time is copied by default. Files.copy(srcFile.toPath(), destFile.toPath(), copyOptions); } /** * Copies bytes from a {@link File} to an {@link OutputStream}. * <p> * This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}. * </p> * * @param input the {@link File} to read. * @param output the {@link OutputStream} to write. * @return the number of bytes copied * @throws NullPointerException if the File is {@code null}. * @throws NullPointerException if the OutputStream is {@code null}. * @throws IOException if an I/O error occurs. * @since 2.1 */ public static long copyFile(final File input, final OutputStream output) throws IOException { try (InputStream fis = Files.newInputStream(input.toPath())) { return IOUtils.copyLarge(fis, output); } } /** * Copies a file to a directory preserving the file date. * <p> * This method copies the contents of the specified source file to a file of the same name in the specified * destination directory. The destination directory is created if it does not exist. If the destination file exists, * then this method will overwrite it. * </p> * <p> * <strong>Note:</strong> This method tries to preserve the file's last modified date/times using * {@link StandardCopyOption#COPY_ATTRIBUTES}, however it is not guaranteed that the operation will succeed. If the * modification operation fails, the methods throws IOException. * </p> * * @param srcFile an existing file to copy, must not be {@code null}. * @param destDir the directory to place the copy in, must not be {@code null}. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IllegalArgumentException if source or destination is invalid. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @see #copyFile(File, File, boolean) */ public static void copyFileToDirectory(final File srcFile, final File destDir) throws IOException { copyFileToDirectory(srcFile, destDir, true); } /** * Copies a file to a directory optionally preserving the file date. * <p> * This method copies the contents of the specified source file to a file of the same name in the specified * destination directory. The destination directory is created if it does not exist. If the destination file exists, * then this method will overwrite it. * </p> * <p> * <strong>Note:</strong> Setting {@code preserveFileDate} to {@code true} tries to preserve the file's last * modified date/times using {@link StandardCopyOption#COPY_ATTRIBUTES}, however it is not guaranteed that the operation * will succeed. If the modification operation fails, the methods throws IOException. * </p> * * @param sourceFile an existing file to copy, must not be {@code null}. * @param destinationDir the directory to place the copy in, must not be {@code null}. * @param preserveFileDate true if the file date of the copy should be the same as the original. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @throws IOException if the output file length is not the same as the input file length after the copy completes. * @see #copyFile(File, File, CopyOption...) * @since 1.3 */ public static void copyFileToDirectory(final File sourceFile, final File destinationDir, final boolean preserveFileDate) throws IOException { Objects.requireNonNull(sourceFile, "sourceFile"); requireDirectoryIfExists(destinationDir, "destinationDir"); copyFile(sourceFile, new File(destinationDir, sourceFile.getName()), preserveFileDate); } /** * Copies bytes from an {@link InputStream} {@code source} to a file * {@code destination}. The directories up to {@code destination} * will be created if they don't already exist. {@code destination} * will be overwritten if it already exists. * <p> * <em>The {@code source} stream is closed.</em> * </p> * <p> * See {@link #copyToFile(InputStream, File)} for a method that does not close the input stream. * </p> * * @param source the {@link InputStream} to copy bytes from, must not be {@code null}, will be closed * @param destination the non-directory {@link File} to write bytes to * (possibly overwriting), must not be {@code null} * @throws IOException if {@code destination} is a directory * @throws IOException if {@code destination} cannot be written * @throws IOException if {@code destination} needs creating but can't be * @throws IOException if an IO error occurs during copying * @since 2.0 */ public static void copyInputStreamToFile(final InputStream source, final File destination) throws IOException { try (InputStream inputStream = source) { copyToFile(inputStream, destination); } } /** * Copies a file or directory to within another directory preserving the file dates. * <p> * This method copies the source file or directory, along all its contents, to a directory of the same name in the * specified destination directory. * </p> * <p> * The destination directory is created if it does not exist. If the destination directory did exist, then this method * merges the source with the destination, with the source taking precedence. * </p> * <p> * <strong>Note:</strong> This method tries to preserve the files' last modified date/times using * {@link StandardCopyOption#COPY_ATTRIBUTES} or {@link File#setLastModified(long)} depending on the input, however it * is not guaranteed that those operations will succeed. If the modification operation fails, the methods throws * IOException. * </p> * * @param sourceFile an existing file or directory to copy, must not be {@code null}. * @param destinationDir the directory to place the copy in, must not be {@code null}. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IllegalArgumentException if the source or destination is invalid. * @throws FileNotFoundException if the source does not exist. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @see #copyDirectoryToDirectory(File, File) * @see #copyFileToDirectory(File, File) * @since 2.6 */ public static void copyToDirectory(final File sourceFile, final File destinationDir) throws IOException { Objects.requireNonNull(sourceFile, "sourceFile"); if (sourceFile.isFile()) { copyFileToDirectory(sourceFile, destinationDir); } else if (sourceFile.isDirectory()) { copyDirectoryToDirectory(sourceFile, destinationDir); } else { throw new FileNotFoundException("The source " + sourceFile + " does not exist"); } } /** * Copies a files to a directory preserving each file's date. * <p> * This method copies the contents of the specified source files * to a file of the same name in the specified destination directory. * The destination directory is created if it does not exist. * If the destination file exists, then this method will overwrite it. * </p> * <p> * <strong>Note:</strong> This method tries to preserve the file's last * modified date/times using {@link File#setLastModified(long)}, however * it is not guaranteed that the operation will succeed. * If the modification operation fails, the methods throws IOException. * </p> * * @param sourceIterable existing files to copy, must not be {@code null}. * @param destinationDir the directory to place the copies in, must not be {@code null}. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IOException if source or destination is invalid. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @see #copyFileToDirectory(File, File) * @since 2.6 */ public static void copyToDirectory(final Iterable<File> sourceIterable, final File destinationDir) throws IOException { Objects.requireNonNull(sourceIterable, "sourceIterable"); for (final File src : sourceIterable) { copyFileToDirectory(src, destinationDir); } } /** * Copies bytes from an {@link InputStream} source to a {@link File} destination. The directories * up to {@code destination} will be created if they don't already exist. {@code destination} will be * overwritten if it already exists. The {@code source} stream is left open, e.g. for use with * {@link java.util.zip.ZipInputStream ZipInputStream}. See {@link #copyInputStreamToFile(InputStream, File)} for a * method that closes the input stream. * * @param inputStream the {@link InputStream} to copy bytes from, must not be {@code null} * @param file the non-directory {@link File} to write bytes to (possibly overwriting), must not be * {@code null} * @throws NullPointerException if the InputStream is {@code null}. * @throws NullPointerException if the File is {@code null}. * @throws IllegalArgumentException if the file object is a directory. * @throws IllegalArgumentException if the file is not writable. * @throws IOException if the directories could not be created. * @throws IOException if an IO error occurs during copying. * @since 2.5 */ public static void copyToFile(final InputStream inputStream, final File file) throws IOException { try (OutputStream out = newOutputStream(file, false)) { IOUtils.copy(inputStream, out); } } /** * Copies bytes from the URL {@code source} to a file * {@code destination}. The directories up to {@code destination} * will be created if they don't already exist. {@code destination} * will be overwritten if it already exists. * <p> * Warning: this method does not set a connection or read timeout and thus * might block forever. Use {@link #copyURLToFile(URL, File, int, int)} * with reasonable timeouts to prevent this. * </p> * * @param source the {@link URL} to copy bytes from, must not be {@code null} * @param destination the non-directory {@link File} to write bytes to * (possibly overwriting), must not be {@code null} * @throws IOException if {@code source} URL cannot be opened * @throws IOException if {@code destination} is a directory * @throws IOException if {@code destination} cannot be written * @throws IOException if {@code destination} needs creating but can't be * @throws IOException if an IO error occurs during copying */ public static void copyURLToFile(final URL source, final File destination) throws IOException { try (InputStream stream = source.openStream()) { final Path path = destination.toPath(); PathUtils.createParentDirectories(path); Files.copy(stream, path, StandardCopyOption.REPLACE_EXISTING); } } /** * Copies bytes from the URL {@code source} to a file {@code destination}. The directories up to * {@code destination} will be created if they don't already exist. {@code destination} will be * overwritten if it already exists. * * @param source the {@link URL} to copy bytes from, must not be {@code null} * @param destination the non-directory {@link File} to write bytes to (possibly overwriting), must not be * {@code null} * @param connectionTimeoutMillis the number of milliseconds until this method will time out if no connection could * be established to the {@code source} * @param readTimeoutMillis the number of milliseconds until this method will time out if no data could be read from * the {@code source} * @throws IOException if {@code source} URL cannot be opened * @throws IOException if {@code destination} is a directory * @throws IOException if {@code destination} cannot be written * @throws IOException if {@code destination} needs creating but can't be * @throws IOException if an IO error occurs during copying * @since 2.0 */ public static void copyURLToFile(final URL source, final File destination, final int connectionTimeoutMillis, final int readTimeoutMillis) throws IOException { try (CloseableURLConnection urlConnection = CloseableURLConnection.open(source)) { urlConnection.setConnectTimeout(connectionTimeoutMillis); urlConnection.setReadTimeout(readTimeoutMillis); try (InputStream stream = urlConnection.getInputStream()) { copyInputStreamToFile(stream, destination); } } } /** * Creates all parent directories for a File object. * * @param file the File that may need parents, may be null. * @return The parent directory, or {@code null} if the given file does not name a parent * @throws IOException if the directory was not created along with all its parent directories. * @throws IOException if the given file object is not null and not a directory. * @since 2.9.0 */ public static File createParentDirectories(final File file) throws IOException { return mkdirs(getParentFile(file)); } /** * Gets the current directory. * * @return the current directory. * @since 2.12.0 */ public static File current() { return PathUtils.current().toFile(); } /** * Decodes the specified URL as per RFC 3986, i.e. transforms * percent-encoded octets to characters by decoding with the UTF-8 character * set. This function is primarily intended for usage with * {@link java.net.URL} which unfortunately does not enforce proper URLs. As * such, this method will leniently accept invalid characters or malformed * percent-encoded octets and simply pass them literally through to the * result string. Except for rare edge cases, this will make unencoded URLs * pass through unaltered. * * @param url The URL to decode, may be {@code null}. * @return The decoded URL or {@code null} if the input was * {@code null}. */ static String decodeUrl(final String url) { String decoded = url; if (url != null && url.indexOf('%') >= 0) { final int n = url.length(); final StringBuilder builder = new StringBuilder(); final ByteBuffer byteBuffer = ByteBuffer.allocate(n); for (int i = 0; i < n; ) { if (url.charAt(i) == '%') { try { do { final byte octet = (byte) Integer.parseInt(url.substring(i + 1, i + 3), 16); byteBuffer.put(octet); i += 3; } while (i < n && url.charAt(i) == '%'); continue; } catch (final RuntimeException ignored) { // malformed percent-encoded octet, fall through and // append characters literally } finally { if (byteBuffer.position() > 0) { byteBuffer.flip(); builder.append(StandardCharsets.UTF_8.decode(byteBuffer).toString()); byteBuffer.clear(); } } } builder.append(url.charAt(i++)); } decoded = builder.toString(); } return decoded; } /** * Deletes the given File but throws an IOException if it cannot, unlike {@link File#delete()} which returns a * boolean. * * @param file The file to delete. * @return the given file. * @throws NullPointerException if the parameter is {@code null} * @throws IOException if the file cannot be deleted. * @see File#delete() * @since 2.9.0 */ public static File delete(final File file) throws IOException { Objects.requireNonNull(file, "file"); Files.delete(file.toPath()); return file; } /** * Deletes a directory recursively. * * @param directory directory to delete * @throws IOException in case deletion is unsuccessful * @throws NullPointerException if the parameter is {@code null} * @throws IllegalArgumentException if {@code directory} is not a directory */ public static void deleteDirectory(final File directory) throws IOException { Objects.requireNonNull(directory, "directory"); if (!directory.exists()) { return; } if (!isSymlink(directory)) { cleanDirectory(directory); } delete(directory); } /** * Schedules a directory recursively for deletion on JVM exit. * * @param directory directory to delete, must not be {@code null} * @throws NullPointerException if the directory is {@code null} * @throws IOException in case deletion is unsuccessful */ private static void deleteDirectoryOnExit(final File directory) throws IOException { if (!directory.exists()) { return; } directory.deleteOnExit(); if (!isSymlink(directory)) { cleanDirectoryOnExit(directory); } } /** * Deletes a file, never throwing an exception. If file is a directory, delete it and all subdirectories. * <p> * The difference between File.delete() and this method are: * </p> * <ul> * <li>A directory to be deleted does not have to be empty.</li> * <li>No exceptions are thrown when a file or directory cannot be deleted.</li> * </ul> * * @param file file or directory to delete, can be {@code null} * @return {@code true} if the file or directory was deleted, otherwise * {@code false} * * @since 1.4 */ public static boolean deleteQuietly(final File file) { if (file == null) { return false; } try { if (file.isDirectory()) { cleanDirectory(file); } } catch (final Exception ignored) { // ignore } try { return file.delete(); } catch (final Exception ignored) { return false; } } /** * Determines whether the {@code parent} directory contains the {@code child} element (a file or directory). * <p> * Files are normalized before comparison. * </p> * * Edge cases: * <ul> * <li>A {@code directory} must not be null: if null, throw IllegalArgumentException</li> * <li>A {@code directory} must be a directory: if not a directory, throw IllegalArgumentException</li> * <li>A directory does not contain itself: return false</li> * <li>A null child file is not contained in any parent: return false</li> * </ul> * * @param directory the file to consider as the parent. * @param child the file to consider as the child. * @return true is the candidate leaf is under by the specified composite. False otherwise. * @throws IOException if an IO error occurs while checking the files. * @throws NullPointerException if the given {@link File} is {@code null}. * @throws IllegalArgumentException if the given {@link File} does not exist or is not a directory. * @see FilenameUtils#directoryContains(String, String) * @since 2.2 */ public static boolean directoryContains(final File directory, final File child) throws IOException { requireDirectoryExists(directory, "directory"); if (child == null || !directory.exists() || !child.exists()) { return false; } // Canonicalize paths (normalizes relative paths) return FilenameUtils.directoryContains(directory.getCanonicalPath(), child.getCanonicalPath()); } /** * Internal copy directory method. * * @param srcDir the validated source directory, must not be {@code null}. * @param destDir the validated destination directory, must not be {@code null}. * @param fileFilter the filter to apply, null means copy all directories and files. * @param exclusionList List of files and directories to exclude from the copy, may be null. * @param preserveDirDate preserve the directories last modified dates. * @param copyOptions options specifying how the copy should be done, see {@link StandardCopyOption}. * @throws IOException if the directory was not created along with all its parent directories. * @throws IOException if the given file object is not a directory. */ private static void doCopyDirectory(final File srcDir, final File destDir, final FileFilter fileFilter, final List<String> exclusionList, final boolean preserveDirDate, final CopyOption... copyOptions) throws IOException { // recurse dirs, copy files. final File[] srcFiles = listFiles(srcDir, fileFilter); requireDirectoryIfExists(destDir, "destDir"); mkdirs(destDir); requireCanWrite(destDir, "destDir"); for (final File srcFile : srcFiles) { final File dstFile = new File(destDir, srcFile.getName()); if (exclusionList == null || !exclusionList.contains(srcFile.getCanonicalPath())) { if (srcFile.isDirectory()) { doCopyDirectory(srcFile, dstFile, fileFilter, exclusionList, preserveDirDate, copyOptions); } else { copyFile(srcFile, dstFile, copyOptions); } } } // Do this last, as the above has probably affected directory metadata if (preserveDirDate) { setLastModified(srcDir, destDir); } } /** * Deletes a file or directory. For a directory, delete it and all subdirectories. * <p> * The difference between File.delete() and this method are: * </p> * <ul> * <li>The directory does not have to be empty.</li> * <li>You get an exception when a file or directory cannot be deleted.</li> * </ul> * * @param file file or directory to delete, must not be {@code null}. * @throws NullPointerException if the file is {@code null}. * @throws FileNotFoundException if the file was not found. * @throws IOException in case deletion is unsuccessful. */ public static void forceDelete(final File file) throws IOException { Objects.requireNonNull(file, "file"); final Counters.PathCounters deleteCounters; try { deleteCounters = PathUtils.delete(file.toPath(), PathUtils.EMPTY_LINK_OPTION_ARRAY, StandardDeleteOption.OVERRIDE_READ_ONLY); } catch (final IOException e) { throw new IOException("Cannot delete file: " + file, e); } if (deleteCounters.getFileCounter().get() < 1 && deleteCounters.getDirectoryCounter().get() < 1) { // didn't find a file to delete. throw new FileNotFoundException("File does not exist: " + file); } } /** * Schedules a file to be deleted when JVM exits. * If file is directory delete it and all subdirectories. * * @param file file or directory to delete, must not be {@code null}. * @throws NullPointerException if the file is {@code null}. * @throws IOException in case deletion is unsuccessful. */ public static void forceDeleteOnExit(final File file) throws IOException { Objects.requireNonNull(file, "file"); if (file.isDirectory()) { deleteDirectoryOnExit(file); } else { file.deleteOnExit(); } } /** * Makes a directory, including any necessary but nonexistent parent * directories. If a file already exists with specified name but it is * not a directory then an IOException is thrown. * If the directory cannot be created (or the file already exists but is not a directory) * then an IOException is thrown. * * @param directory directory to create, may be {@code null}. * @throws IOException if the directory was not created along with all its parent directories. * @throws IOException if the given file object is not a directory. * @throws SecurityException See {@link File#mkdirs()}. */ public static void forceMkdir(final File directory) throws IOException { mkdirs(directory); } /** * Makes any necessary but nonexistent parent directories for a given File. If the parent directory cannot be * created then an IOException is thrown. * * @param file file with parent to create, must not be {@code null}. * @throws NullPointerException if the file is {@code null}. * @throws IOException if the parent directory cannot be created. * @since 2.5 */ public static void forceMkdirParent(final File file) throws IOException { Objects.requireNonNull(file, "file"); forceMkdir(getParentFile(file)); } /** * Constructs a file from the set of name elements. * * @param directory the parent directory. * @param names the name elements. * @return the new file. * @since 2.1 */ public static File getFile(final File directory, final String... names) { Objects.requireNonNull(directory, "directory"); Objects.requireNonNull(names, "names"); File file = directory; for (final String name : names) { file = new File(file, name); } return file; } /** * Constructs a file from the set of name elements. * * @param names the name elements. * @return the file. * @since 2.1 */ public static File getFile(final String... names) { Objects.requireNonNull(names, "names"); File file = null; for (final String name : names) { if (file == null) { file = new File(name); } else { file = new File(file, name); } } return file; } /** * Gets the parent of the given file. The given file may be bull and a file's parent may as well be null. * * @param file The file to query. * @return The parent file or {@code null}. */ private static File getParentFile(final File file) { return file == null ? null : file.getParentFile(); } /** * Returns a {@link File} representing the system temporary directory. * * @return the system temporary directory. * * @since 2.0 */ public static File getTempDirectory() { return new File(getTempDirectoryPath()); } /** * Returns the path to the system temporary directory. * * @return the path to the system temporary directory. * * @since 2.0 */ public static String getTempDirectoryPath() { return System.getProperty("java.io.tmpdir"); } /** * Returns a {@link File} representing the user's home directory. * * @return the user's home directory. * * @since 2.0 */ public static File getUserDirectory() { return new File(getUserDirectoryPath()); } /** * Returns the path to the user's home directory. * * @return the path to the user's home directory. * * @since 2.0 */ public static String getUserDirectoryPath() { return System.getProperty("user.home"); } /** * Tests whether the specified {@link File} is a directory or not. Implemented as a * null-safe delegate to {@link Files#isDirectory(Path path, LinkOption... options)}. * * @param file the path to the file. * @param options options indicating how symbolic links are handled * @return {@code true} if the file is a directory; {@code false} if * the path is null, the file does not exist, is not a directory, or it cannot * be determined if the file is a directory or not. * @throws SecurityException In the case of the default provider, and a security manager is installed, the * {@link SecurityManager#checkRead(String) checkRead} method is invoked to check read * access to the directory. * @since 2.9.0 */ public static boolean isDirectory(final File file, final LinkOption... options) { return file != null && Files.isDirectory(file.toPath(), options); } /** * Tests whether the directory is empty. * * @param directory the directory to query. * @return whether the directory is empty. * @throws IOException if an I/O error occurs. * @throws NotDirectoryException if the file could not otherwise be opened because it is not a directory * <i>(optional specific exception)</i>. * @since 2.9.0 */ public static boolean isEmptyDirectory(final File directory) throws IOException { return PathUtils.isEmptyDirectory(directory.toPath()); } /** * Tests if the specified {@link File} is newer than the specified {@link ChronoLocalDate} * at the current time. * * <p>Note: The input date is assumed to be in the system default time-zone with the time * part set to the current time. To use a non-default time-zone use the method * {@link #isFileNewer(File, ChronoLocalDateTime, ZoneId) * isFileNewer(file, chronoLocalDate.atTime(LocalTime.now(zoneId)), zoneId)} where * {@code zoneId} is a valid {@link ZoneId}. * * @param file the {@link File} of which the modification date must be compared. * @param chronoLocalDate the date reference. * @return true if the {@link File} exists and has been modified after the given * {@link ChronoLocalDate} at the current time. * @throws NullPointerException if the file or local date is {@code null}. * @since 2.8.0 */ public static boolean isFileNewer(final File file, final ChronoLocalDate chronoLocalDate) { return isFileNewer(file, chronoLocalDate, LocalTime.now()); } /** * Tests if the specified {@link File} is newer than the specified {@link ChronoLocalDate} * at the specified time. * * <p>Note: The input date and time are assumed to be in the system default time-zone. To use a * non-default time-zone use the method {@link #isFileNewer(File, ChronoLocalDateTime, ZoneId) * isFileNewer(file, chronoLocalDate.atTime(localTime), zoneId)} where {@code zoneId} is a valid * {@link ZoneId}. * * @param file the {@link File} of which the modification date must be compared. * @param chronoLocalDate the date reference. * @param localTime the time reference. * @return true if the {@link File} exists and has been modified after the given * {@link ChronoLocalDate} at the given time. * @throws NullPointerException if the file, local date or zone ID is {@code null}. * @since 2.8.0 */ public static boolean isFileNewer(final File file, final ChronoLocalDate chronoLocalDate, final LocalTime localTime) { Objects.requireNonNull(chronoLocalDate, "chronoLocalDate"); Objects.requireNonNull(localTime, "localTime"); return isFileNewer(file, chronoLocalDate.atTime(localTime)); } /** * Tests if the specified {@link File} is newer than the specified {@link ChronoLocalDate} at the specified * {@link OffsetTime}. * * @param file the {@link File} of which the modification date must be compared * @param chronoLocalDate the date reference * @param offsetTime the time reference * @return true if the {@link File} exists and has been modified after the given {@link ChronoLocalDate} at the given * {@link OffsetTime}. * @throws NullPointerException if the file, local date or zone ID is {@code null} * @since 2.12.0 */ public static boolean isFileNewer(final File file, final ChronoLocalDate chronoLocalDate, final OffsetTime offsetTime) { Objects.requireNonNull(chronoLocalDate, "chronoLocalDate"); Objects.requireNonNull(offsetTime, "offsetTime"); return isFileNewer(file, chronoLocalDate.atTime(offsetTime.toLocalTime())); } /** * Tests if the specified {@link File} is newer than the specified {@link ChronoLocalDateTime} * at the system-default time zone. * * <p>Note: The input date and time is assumed to be in the system default time-zone. To use a * non-default time-zone use the method {@link #isFileNewer(File, ChronoLocalDateTime, ZoneId) * isFileNewer(file, chronoLocalDateTime, zoneId)} where {@code zoneId} is a valid * {@link ZoneId}. * * @param file the {@link File} of which the modification date must be compared. * @param chronoLocalDateTime the date reference. * @return true if the {@link File} exists and has been modified after the given * {@link ChronoLocalDateTime} at the system-default time zone. * @throws NullPointerException if the file or local date time is {@code null}. * @since 2.8.0 */ public static boolean isFileNewer(final File file, final ChronoLocalDateTime<?> chronoLocalDateTime) { return isFileNewer(file, chronoLocalDateTime, ZoneId.systemDefault()); } /** * Tests if the specified {@link File} is newer than the specified {@link ChronoLocalDateTime} * at the specified {@link ZoneId}. * * @param file the {@link File} of which the modification date must be compared. * @param chronoLocalDateTime the date reference. * @param zoneId the time zone. * @return true if the {@link File} exists and has been modified after the given * {@link ChronoLocalDateTime} at the given {@link ZoneId}. * @throws NullPointerException if the file, local date time or zone ID is {@code null}. * @since 2.8.0 */ public static boolean isFileNewer(final File file, final ChronoLocalDateTime<?> chronoLocalDateTime, final ZoneId zoneId) { Objects.requireNonNull(chronoLocalDateTime, "chronoLocalDateTime"); Objects.requireNonNull(zoneId, "zoneId"); return isFileNewer(file, chronoLocalDateTime.atZone(zoneId)); } /** * Tests if the specified {@link File} is newer than the specified {@link ChronoZonedDateTime}. * * @param file the {@link File} of which the modification date must be compared. * @param chronoZonedDateTime the date reference. * @return true if the {@link File} exists and has been modified after the given * {@link ChronoZonedDateTime}. * @throws NullPointerException if the file or zoned date time is {@code null}. * @since 2.8.0 */ public static boolean isFileNewer(final File file, final ChronoZonedDateTime<?> chronoZonedDateTime) { Objects.requireNonNull(file, "file"); Objects.requireNonNull(chronoZonedDateTime, "chronoZonedDateTime"); return Uncheck.get(() -> PathUtils.isNewer(file.toPath(), chronoZonedDateTime)); } /** * Tests if the specified {@link File} is newer than the specified {@link Date}. * * @param file the {@link File} of which the modification date must be compared. * @param date the date reference. * @return true if the {@link File} exists and has been modified * after the given {@link Date}. * @throws NullPointerException if the file or date is {@code null}. */ public static boolean isFileNewer(final File file, final Date date) { Objects.requireNonNull(date, "date"); return isFileNewer(file, date.getTime()); } /** * Tests if the specified {@link File} is newer than the reference {@link File}. * * @param file the {@link File} of which the modification date must be compared. * @param reference the {@link File} of which the modification date is used. * @return true if the {@link File} exists and has been modified more * recently than the reference {@link File}. * @throws NullPointerException if the file or reference file is {@code null}. * @throws IllegalArgumentException if the reference file doesn't exist. */ public static boolean isFileNewer(final File file, final File reference) { requireExists(reference, "reference"); return Uncheck.get(() -> PathUtils.isNewer(file.toPath(), reference.toPath())); } /** * Tests if the specified {@link File} is newer than the specified {@link FileTime}. * * @param file the {@link File} of which the modification date must be compared. * @param fileTime the file time reference. * @return true if the {@link File} exists and has been modified after the given {@link FileTime}. * @throws IOException if an I/O error occurs. * @throws NullPointerException if the file or local date is {@code null}. * @since 2.12.0 */ public static boolean isFileNewer(final File file, final FileTime fileTime) throws IOException { Objects.requireNonNull(file, "file"); return PathUtils.isNewer(file.toPath(), fileTime); } /** * Tests if the specified {@link File} is newer than the specified {@link Instant}. * * @param file the {@link File} of which the modification date must be compared. * @param instant the date reference. * @return true if the {@link File} exists and has been modified after the given {@link Instant}. * @throws NullPointerException if the file or instant is {@code null}. * @since 2.8.0 */ public static boolean isFileNewer(final File file, final Instant instant) { Objects.requireNonNull(instant, "instant"); return Uncheck.get(() -> PathUtils.isNewer(file.toPath(), instant)); } /** * Tests if the specified {@link File} is newer than the specified time reference. * * @param file the {@link File} of which the modification date must be compared. * @param timeMillis the time reference measured in milliseconds since the * epoch (00:00:00 GMT, January 1, 1970). * @return true if the {@link File} exists and has been modified after the given time reference. * @throws NullPointerException if the file is {@code null}. */ public static boolean isFileNewer(final File file, final long timeMillis) { Objects.requireNonNull(file, "file"); return Uncheck.get(() -> PathUtils.isNewer(file.toPath(), timeMillis)); } /** * Tests if the specified {@link File} is newer than the specified {@link OffsetDateTime}. * * @param file the {@link File} of which the modification date must be compared * @param offsetDateTime the date reference * @return true if the {@link File} exists and has been modified before the given {@link OffsetDateTime}. * @throws NullPointerException if the file or zoned date time is {@code null} * @since 2.12.0 */ public static boolean isFileNewer(final File file, final OffsetDateTime offsetDateTime) { Objects.requireNonNull(offsetDateTime, "offsetDateTime"); return isFileNewer(file, offsetDateTime.toInstant()); } /** * Tests if the specified {@link File} is older than the specified {@link ChronoLocalDate} * at the current time. * * <p>Note: The input date is assumed to be in the system default time-zone with the time * part set to the current time. To use a non-default time-zone use the method * {@link #isFileOlder(File, ChronoLocalDateTime, ZoneId) * isFileOlder(file, chronoLocalDate.atTime(LocalTime.now(zoneId)), zoneId)} where * {@code zoneId} is a valid {@link ZoneId}. * * @param file the {@link File} of which the modification date must be compared. * @param chronoLocalDate the date reference. * @return true if the {@link File} exists and has been modified before the given * {@link ChronoLocalDate} at the current time. * @throws NullPointerException if the file or local date is {@code null}. * @see ZoneId#systemDefault() * @see LocalTime#now() * * @since 2.8.0 */ public static boolean isFileOlder(final File file, final ChronoLocalDate chronoLocalDate) { return isFileOlder(file, chronoLocalDate, LocalTime.now()); } /** * Tests if the specified {@link File} is older than the specified {@link ChronoLocalDate} * at the specified {@link LocalTime}. * * <p>Note: The input date and time are assumed to be in the system default time-zone. To use a * non-default time-zone use the method {@link #isFileOlder(File, ChronoLocalDateTime, ZoneId) * isFileOlder(file, chronoLocalDate.atTime(localTime), zoneId)} where {@code zoneId} is a valid * {@link ZoneId}. * * @param file the {@link File} of which the modification date must be compared. * @param chronoLocalDate the date reference. * @param localTime the time reference. * @return true if the {@link File} exists and has been modified before the * given {@link ChronoLocalDate} at the specified time. * @throws NullPointerException if the file, local date or local time is {@code null}. * @see ZoneId#systemDefault() * @since 2.8.0 */ public static boolean isFileOlder(final File file, final ChronoLocalDate chronoLocalDate, final LocalTime localTime) { Objects.requireNonNull(chronoLocalDate, "chronoLocalDate"); Objects.requireNonNull(localTime, "localTime"); return isFileOlder(file, chronoLocalDate.atTime(localTime)); } /** * Tests if the specified {@link File} is older than the specified {@link ChronoLocalDate} at the specified * {@link OffsetTime}. * * @param file the {@link File} of which the modification date must be compared * @param chronoLocalDate the date reference * @param offsetTime the time reference * @return true if the {@link File} exists and has been modified after the given {@link ChronoLocalDate} at the given * {@link OffsetTime}. * @throws NullPointerException if the file, local date or zone ID is {@code null} * @since 2.12.0 */ public static boolean isFileOlder(final File file, final ChronoLocalDate chronoLocalDate, final OffsetTime offsetTime) { Objects.requireNonNull(chronoLocalDate, "chronoLocalDate"); Objects.requireNonNull(offsetTime, "offsetTime"); return isFileOlder(file, chronoLocalDate.atTime(offsetTime.toLocalTime())); } /** * Tests if the specified {@link File} is older than the specified {@link ChronoLocalDateTime} * at the system-default time zone. * * <p>Note: The input date and time is assumed to be in the system default time-zone. To use a * non-default time-zone use the method {@link #isFileOlder(File, ChronoLocalDateTime, ZoneId) * isFileOlder(file, chronoLocalDateTime, zoneId)} where {@code zoneId} is a valid * {@link ZoneId}. * * @param file the {@link File} of which the modification date must be compared. * @param chronoLocalDateTime the date reference. * @return true if the {@link File} exists and has been modified before the given * {@link ChronoLocalDateTime} at the system-default time zone. * @throws NullPointerException if the file or local date time is {@code null}. * @see ZoneId#systemDefault() * @since 2.8.0 */ public static boolean isFileOlder(final File file, final ChronoLocalDateTime<?> chronoLocalDateTime) { return isFileOlder(file, chronoLocalDateTime, ZoneId.systemDefault()); } /** * Tests if the specified {@link File} is older than the specified {@link ChronoLocalDateTime} * at the specified {@link ZoneId}. * * @param file the {@link File} of which the modification date must be compared. * @param chronoLocalDateTime the date reference. * @param zoneId the time zone. * @return true if the {@link File} exists and has been modified before the given * {@link ChronoLocalDateTime} at the given {@link ZoneId}. * @throws NullPointerException if the file, local date time or zone ID is {@code null}. * @since 2.8.0 */ public static boolean isFileOlder(final File file, final ChronoLocalDateTime<?> chronoLocalDateTime, final ZoneId zoneId) { Objects.requireNonNull(chronoLocalDateTime, "chronoLocalDateTime"); Objects.requireNonNull(zoneId, "zoneId"); return isFileOlder(file, chronoLocalDateTime.atZone(zoneId)); } /** * Tests if the specified {@link File} is older than the specified {@link ChronoZonedDateTime}. * * @param file the {@link File} of which the modification date must be compared. * @param chronoZonedDateTime the date reference. * @return true if the {@link File} exists and has been modified before the given * {@link ChronoZonedDateTime}. * @throws NullPointerException if the file or zoned date time is {@code null}. * @since 2.8.0 */ public static boolean isFileOlder(final File file, final ChronoZonedDateTime<?> chronoZonedDateTime) { Objects.requireNonNull(chronoZonedDateTime, "chronoZonedDateTime"); return isFileOlder(file, chronoZonedDateTime.toInstant()); } /** * Tests if the specified {@link File} is older than the specified {@link Date}. * * @param file the {@link File} of which the modification date must be compared. * @param date the date reference. * @return true if the {@link File} exists and has been modified before the given {@link Date}. * @throws NullPointerException if the file or date is {@code null}. */ public static boolean isFileOlder(final File file, final Date date) { Objects.requireNonNull(date, "date"); return isFileOlder(file, date.getTime()); } /** * Tests if the specified {@link File} is older than the reference {@link File}. * * @param file the {@link File} of which the modification date must be compared. * @param reference the {@link File} of which the modification date is used. * @return true if the {@link File} exists and has been modified before the reference {@link File}. * @throws NullPointerException if the file or reference file is {@code null}. * @throws IllegalArgumentException if the reference file doesn't exist. */ public static boolean isFileOlder(final File file, final File reference) { requireExists(reference, "reference"); return Uncheck.get(() -> PathUtils.isOlder(file.toPath(), reference.toPath())); } /** * Tests if the specified {@link File} is older than the specified {@link FileTime}. * * @param file the {@link File} of which the modification date must be compared. * @param fileTime the file time reference. * @return true if the {@link File} exists and has been modified before the given {@link FileTime}. * @throws IOException if an I/O error occurs. * @throws NullPointerException if the file or local date is {@code null}. * @since 2.12.0 */ public static boolean isFileOlder(final File file, final FileTime fileTime) throws IOException { Objects.requireNonNull(file, "file"); return PathUtils.isOlder(file.toPath(), fileTime); } /** * Tests if the specified {@link File} is older than the specified {@link Instant}. * * @param file the {@link File} of which the modification date must be compared. * @param instant the date reference. * @return true if the {@link File} exists and has been modified before the given {@link Instant}. * @throws NullPointerException if the file or instant is {@code null}. * @since 2.8.0 */ public static boolean isFileOlder(final File file, final Instant instant) { Objects.requireNonNull(instant, "instant"); return Uncheck.get(() -> PathUtils.isOlder(file.toPath(), instant)); } /** * Tests if the specified {@link File} is older than the specified time reference. * * @param file the {@link File} of which the modification date must be compared. * @param timeMillis the time reference measured in milliseconds since the * epoch (00:00:00 GMT, January 1, 1970). * @return true if the {@link File} exists and has been modified before the given time reference. * @throws NullPointerException if the file is {@code null}. */ public static boolean isFileOlder(final File file, final long timeMillis) { Objects.requireNonNull(file, "file"); return Uncheck.get(() -> PathUtils.isOlder(file.toPath(), timeMillis)); } /** * Tests if the specified {@link File} is older than the specified {@link OffsetDateTime}. * * @param file the {@link File} of which the modification date must be compared * @param offsetDateTime the date reference * @return true if the {@link File} exists and has been modified before the given {@link OffsetDateTime}. * @throws NullPointerException if the file or zoned date time is {@code null} * @since 2.12.0 */ public static boolean isFileOlder(final File file, final OffsetDateTime offsetDateTime) { Objects.requireNonNull(offsetDateTime, "offsetDateTime"); return isFileOlder(file, offsetDateTime.toInstant()); } /** * Tests whether the specified {@link File} is a regular file or not. Implemented as a * null-safe delegate to {@link Files#isRegularFile(Path path, LinkOption... options)}. * * @param file the path to the file. * @param options options indicating how symbolic links are handled * @return {@code true} if the file is a regular file; {@code false} if * the path is null, the file does not exist, is not a regular file, or it cannot * be determined if the file is a regular file or not. * @throws SecurityException In the case of the default provider, and a security manager is installed, the * {@link SecurityManager#checkRead(String) checkRead} method is invoked to check read * access to the directory. * @since 2.9.0 */ public static boolean isRegularFile(final File file, final LinkOption... options) { return file != null && Files.isRegularFile(file.toPath(), options); } /** * Tests whether the specified file is a symbolic link rather than an actual file. * <p> * This method delegates to {@link Files#isSymbolicLink(Path path)} * </p> * * @param file the file to test. * @return true if the file is a symbolic link, see {@link Files#isSymbolicLink(Path path)}. * @since 2.0 * @see Files#isSymbolicLink(Path) */ public static boolean isSymlink(final File file) { return file != null && Files.isSymbolicLink(file.toPath()); } /** * Iterates over the files in given directory (and optionally * its subdirectories). * <p> * The resulting iterator MUST be consumed in its entirety in order to close its underlying stream. * </p> * <p> * All files found are filtered by an IOFileFilter. * </p> * * @param directory the directory to search in * @param fileFilter filter to apply when finding files. * @param dirFilter optional filter to apply when finding subdirectories. * If this parameter is {@code null}, subdirectories will not be included in the * search. Use TrueFileFilter.INSTANCE to match all directories. * @return an iterator of java.io.File for the matching files * @see org.apache.commons.io.filefilter.FileFilterUtils * @see org.apache.commons.io.filefilter.NameFileFilter * @since 1.2 */ public static Iterator<File> iterateFiles(final File directory, final IOFileFilter fileFilter, final IOFileFilter dirFilter) { return listFiles(directory, fileFilter, dirFilter).iterator(); } /** * Iterates over the files in a given directory (and optionally * its subdirectories) which match an array of extensions. * <p> * The resulting iterator MUST be consumed in its entirety in order to close its underlying stream. * </p> * * @param directory the directory to search in * @param extensions an array of extensions, ex. {"java","xml"}. If this * parameter is {@code null}, all files are returned. * @param recursive if true all subdirectories are searched as well * @return an iterator of java.io.File with the matching files * @since 1.2 */ public static Iterator<File> iterateFiles(final File directory, final String[] extensions, final boolean recursive) { return Uncheck.apply(d -> streamFiles(d, recursive, extensions).iterator(), directory); } /** * Iterates over the files in given directory (and optionally * its subdirectories). * <p> * The resulting iterator MUST be consumed in its entirety in order to close its underlying stream. * </p> * <p> * All files found are filtered by an IOFileFilter. * </p> * <p> * The resulting iterator includes the subdirectories themselves. * </p> * * @param directory the directory to search in * @param fileFilter filter to apply when finding files. * @param dirFilter optional filter to apply when finding subdirectories. * If this parameter is {@code null}, subdirectories will not be included in the * search. Use TrueFileFilter.INSTANCE to match all directories. * @return an iterator of java.io.File for the matching files * @see org.apache.commons.io.filefilter.FileFilterUtils * @see org.apache.commons.io.filefilter.NameFileFilter * @since 2.2 */ public static Iterator<File> iterateFilesAndDirs(final File directory, final IOFileFilter fileFilter, final IOFileFilter dirFilter) { return listFilesAndDirs(directory, fileFilter, dirFilter).iterator(); } /** * Returns the last modification time in milliseconds via * {@link java.nio.file.Files#getLastModifiedTime(Path, LinkOption...)}. * <p> * For the best precision, use {@link #lastModifiedFileTime(File)}. * </p> * <p> * Use this method to avoid issues with {@link File#lastModified()} like * <a href="https://bugs.openjdk.java.net/browse/JDK-8177809">JDK-8177809</a> where {@link File#lastModified()} is * losing milliseconds (always ends in 000). This bug exists in OpenJDK 8 and 9, and is fixed in 10. * </p> * * @param file The File to query. * @return See {@link java.nio.file.attribute.FileTime#toMillis()}. * @throws IOException if an I/O error occurs. * @since 2.9.0 */ public static long lastModified(final File file) throws IOException { // https://bugs.openjdk.java.net/browse/JDK-8177809 // File.lastModified() is losing milliseconds (always ends in 000) // This bug is in OpenJDK 8 and 9, and fixed in 10. return lastModifiedFileTime(file).toMillis(); } /** * Returns the last modification {@link FileTime} via * {@link java.nio.file.Files#getLastModifiedTime(Path, LinkOption...)}. * <p> * Use this method to avoid issues with {@link File#lastModified()} like * <a href="https://bugs.openjdk.java.net/browse/JDK-8177809">JDK-8177809</a> where {@link File#lastModified()} is * losing milliseconds (always ends in 000). This bug exists in OpenJDK 8 and 9, and is fixed in 10. * </p> * * @param file The File to query. * @return See {@link java.nio.file.Files#getLastModifiedTime(Path, LinkOption...)}. * @throws IOException if an I/O error occurs. * @since 2.12.0 */ public static FileTime lastModifiedFileTime(final File file) throws IOException { // https://bugs.openjdk.java.net/browse/JDK-8177809 // File.lastModified() is losing milliseconds (always ends in 000) // This bug is in OpenJDK 8 and 9, and fixed in 10. return Files.getLastModifiedTime(Objects.requireNonNull(file.toPath(), "file")); } /** * Returns the last modification time in milliseconds via * {@link java.nio.file.Files#getLastModifiedTime(Path, LinkOption...)}. * <p> * For the best precision, use {@link #lastModifiedFileTime(File)}. * </p> * <p> * Use this method to avoid issues with {@link File#lastModified()} like * <a href="https://bugs.openjdk.java.net/browse/JDK-8177809">JDK-8177809</a> where {@link File#lastModified()} is * losing milliseconds (always ends in 000). This bug exists in OpenJDK 8 and 9, and is fixed in 10. * </p> * * @param file The File to query. * @return See {@link java.nio.file.attribute.FileTime#toMillis()}. * @throws UncheckedIOException if an I/O error occurs. * @since 2.9.0 */ public static long lastModifiedUnchecked(final File file) { // https://bugs.openjdk.java.net/browse/JDK-8177809 // File.lastModified() is losing milliseconds (always ends in 000) // This bug is in OpenJDK 8 and 9, and fixed in 10. return Uncheck.apply(FileUtils::lastModified, file); } /** * Returns an Iterator for the lines in a {@link File} using the default encoding for the VM. * * @param file the file to open for input, must not be {@code null} * @return an Iterator of the lines in the file, never {@code null} * @throws NullPointerException if file is {@code null}. * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some * other reason cannot be opened for reading. * @throws IOException if an I/O error occurs. * @see #lineIterator(File, String) * @since 1.3 */ public static LineIterator lineIterator(final File file) throws IOException { return lineIterator(file, null); } /** * Returns an Iterator for the lines in a {@link File}. * <p> * This method opens an {@link InputStream} for the file. * When you have finished with the iterator you should close the stream * to free internal resources. This can be done by using a try-with-resources block or calling the * {@link LineIterator#close()} method. * </p> * <p> * The recommended usage pattern is: * </p> * <pre> * LineIterator it = FileUtils.lineIterator(file, StandardCharsets.UTF_8.name()); * try { * while (it.hasNext()) { * String line = it.nextLine(); * /// do something with line * } * } finally { * LineIterator.closeQuietly(iterator); * } * </pre> * <p> * If an exception occurs during the creation of the iterator, the * underlying stream is closed. * </p> * * @param file the file to open for input, must not be {@code null} * @param charsetName the name of the requested charset, {@code null} means platform default * @return a LineIterator for lines in the file, never {@code null}; MUST be closed by the caller. * @throws NullPointerException if file is {@code null}. * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some * other reason cannot be opened for reading. * @throws IOException if an I/O error occurs. * @since 1.2 */ @SuppressWarnings("resource") // Caller closes the result LineIterator. public static LineIterator lineIterator(final File file, final String charsetName) throws IOException { InputStream inputStream = null; try { inputStream = Files.newInputStream(file.toPath()); return IOUtils.lineIterator(inputStream, charsetName); } catch (final IOException | RuntimeException ex) { IOUtils.closeQuietly(inputStream, ex::addSuppressed); throw ex; } } private static AccumulatorPathVisitor listAccumulate(final File directory, final IOFileFilter fileFilter, final IOFileFilter dirFilter, final FileVisitOption... options) throws IOException { final boolean isDirFilterSet = dirFilter != null; final FileEqualsFileFilter rootDirFilter = new FileEqualsFileFilter(directory); final PathFilter dirPathFilter = isDirFilterSet ? rootDirFilter.or(dirFilter) : rootDirFilter; final AccumulatorPathVisitor visitor = new AccumulatorPathVisitor(Counters.noopPathCounters(), fileFilter, dirPathFilter, (p, e) -> FileVisitResult.CONTINUE); final Set<FileVisitOption> optionSet = new HashSet<>(); Collections.addAll(optionSet, options); Files.walkFileTree(directory.toPath(), optionSet, toMaxDepth(isDirFilterSet), visitor); return visitor; } /** * Lists files in a directory, asserting that the supplied directory exists and is a directory. * * @param directory The directory to list * @param fileFilter Optional file filter, may be null. * @return The files in the directory, never {@code null}. * @throws NullPointerException if directory is {@code null}. * @throws IllegalArgumentException if directory does not exist or is not a directory. * @throws IOException if an I/O error occurs. */ private static File[] listFiles(final File directory, final FileFilter fileFilter) throws IOException { requireDirectoryExists(directory, "directory"); final File[] files = fileFilter == null ? directory.listFiles() : directory.listFiles(fileFilter); if (files == null) { // null if the directory does not denote a directory, or if an I/O error occurs. throw new IOException("Unknown I/O error listing contents of directory: " + directory); } return files; } /** * Finds files within a given directory (and optionally its * subdirectories). All files found are filtered by an IOFileFilter. * <p> * If your search should recurse into subdirectories you can pass in * an IOFileFilter for directories. You don't need to bind a * DirectoryFileFilter (via logical AND) to this filter. This method does * that for you. * </p> * <p> * An example: If you want to search through all directories called * "temp" you pass in {@code FileFilterUtils.NameFileFilter("temp")} * </p> * <p> * Another common usage of this method is find files in a directory * tree but ignoring the directories generated CVS. You can simply pass * in {@code FileFilterUtils.makeCVSAware(null)}. * </p> * * @param directory the directory to search in * @param fileFilter filter to apply when finding files. Must not be {@code null}, * use {@link TrueFileFilter#INSTANCE} to match all files in selected directories. * @param dirFilter optional filter to apply when finding subdirectories. * If this parameter is {@code null}, subdirectories will not be included in the * search. Use {@link TrueFileFilter#INSTANCE} to match all directories. * @return a collection of java.io.File with the matching files * @see org.apache.commons.io.filefilter.FileFilterUtils * @see org.apache.commons.io.filefilter.NameFileFilter */ public static Collection<File> listFiles(final File directory, final IOFileFilter fileFilter, final IOFileFilter dirFilter) { final AccumulatorPathVisitor visitor = Uncheck .apply(d -> listAccumulate(d, FileFileFilter.INSTANCE.and(fileFilter), dirFilter, FileVisitOption.FOLLOW_LINKS), directory); return visitor.getFileList().stream().map(Path::toFile).collect(Collectors.toList()); } /** * Finds files within a given directory (and optionally its subdirectories) * which match an array of extensions. * * @param directory the directory to search in * @param extensions an array of extensions, ex. {"java","xml"}. If this * parameter is {@code null}, all files are returned. * @param recursive if true all subdirectories are searched as well * @return a collection of java.io.File with the matching files */ public static Collection<File> listFiles(final File directory, final String[] extensions, final boolean recursive) { return Uncheck.apply(d -> toList(streamFiles(d, recursive, extensions)), directory); } /** * Finds files within a given directory (and optionally its * subdirectories). All files found are filtered by an IOFileFilter. * <p> * The resulting collection includes the starting directory and * any subdirectories that match the directory filter. * </p> * * @param directory the directory to search in * @param fileFilter filter to apply when finding files. * @param dirFilter optional filter to apply when finding subdirectories. * If this parameter is {@code null}, subdirectories will not be included in the * search. Use TrueFileFilter.INSTANCE to match all directories. * @return a collection of java.io.File with the matching files * @see org.apache.commons.io.FileUtils#listFiles * @see org.apache.commons.io.filefilter.FileFilterUtils * @see org.apache.commons.io.filefilter.NameFileFilter * @since 2.2 */ public static Collection<File> listFilesAndDirs(final File directory, final IOFileFilter fileFilter, final IOFileFilter dirFilter) { final AccumulatorPathVisitor visitor = Uncheck.apply(d -> listAccumulate(d, fileFilter, dirFilter, FileVisitOption.FOLLOW_LINKS), directory); final List<Path> list = visitor.getFileList(); list.addAll(visitor.getDirList()); return list.stream().map(Path::toFile).collect(Collectors.toList()); } /** * Calls {@link File#mkdirs()} and throws an exception on failure. * * @param directory the receiver for {@code mkdirs()}, may be null. * @return the given file, may be null. * @throws IOException if the directory was not created along with all its parent directories. * @throws IOException if the given file object is not a directory. * @throws SecurityException See {@link File#mkdirs()}. * @see File#mkdirs() */ private static File mkdirs(final File directory) throws IOException { if (directory != null && !directory.mkdirs() && !directory.isDirectory()) { throw new IOException("Cannot create directory '" + directory + "'."); } return directory; } /** * Moves a directory. * <p> * When the destination directory is on another file system, do a "copy and delete". * </p> * * @param srcDir the directory to be moved. * @param destDir the destination directory. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IllegalArgumentException if the source or destination is invalid. * @throws FileNotFoundException if the source does not exist. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @since 1.4 */ public static void moveDirectory(final File srcDir, final File destDir) throws IOException { validateMoveParameters(srcDir, destDir); requireDirectory(srcDir, "srcDir"); requireAbsent(destDir, "destDir"); if (!srcDir.renameTo(destDir)) { if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath() + File.separator)) { throw new IOException("Cannot move directory: " + srcDir + " to a subdirectory of itself: " + destDir); } copyDirectory(srcDir, destDir); deleteDirectory(srcDir); if (srcDir.exists()) { throw new IOException("Failed to delete original directory '" + srcDir + "' after copy to '" + destDir + "'"); } } } /** * Moves a directory to another directory. * * @param source the file to be moved. * @param destDir the destination file. * @param createDestDir If {@code true} create the destination directory, otherwise if {@code false} throw an * IOException. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws IllegalArgumentException if the source or destination is invalid. * @throws FileNotFoundException if the source does not exist. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @since 1.4 */ public static void moveDirectoryToDirectory(final File source, final File destDir, final boolean createDestDir) throws IOException { validateMoveParameters(source, destDir); if (!destDir.isDirectory()) { if (destDir.exists()) { throw new IOException("Destination '" + destDir + "' is not a directory"); } if (!createDestDir) { throw new FileNotFoundException("Destination directory '" + destDir + "' does not exist [createDestDir=" + false + "]"); } mkdirs(destDir); } moveDirectory(source, new File(destDir, source.getName())); } /** * Moves a file preserving attributes. * <p> * Shorthand for {@code moveFile(srcFile, destFile, StandardCopyOption.COPY_ATTRIBUTES)}. * </p> * <p> * When the destination file is on another file system, do a "copy and delete". * </p> * * @param srcFile the file to be moved. * @param destFile the destination file. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws FileExistsException if the destination file exists. * @throws FileNotFoundException if the source file does not exist. * @throws IOException if source or destination is invalid. * @throws IOException if an error occurs. * @since 1.4 */ public static void moveFile(final File srcFile, final File destFile) throws IOException { moveFile(srcFile, destFile, StandardCopyOption.COPY_ATTRIBUTES); } /** * Moves a file. * <p> * When the destination file is on another file system, do a "copy and delete". * </p> * * @param srcFile the file to be moved. * @param destFile the destination file. * @param copyOptions Copy options. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws FileExistsException if the destination file exists. * @throws FileNotFoundException if the source file does not exist. * @throws IOException if source or destination is invalid. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @since 2.9.0 */ public static void moveFile(final File srcFile, final File destFile, final CopyOption... copyOptions) throws IOException { validateMoveParameters(srcFile, destFile); requireFile(srcFile, "srcFile"); requireAbsent(destFile, "destFile"); final boolean rename = srcFile.renameTo(destFile); if (!rename) { copyFile(srcFile, destFile, copyOptions); if (!srcFile.delete()) { FileUtils.deleteQuietly(destFile); throw new IOException("Failed to delete original file '" + srcFile + "' after copy to '" + destFile + "'"); } } } /** * Moves a file to a directory. * * @param srcFile the file to be moved. * @param destDir the destination file. * @param createDestDir If {@code true} create the destination directory, otherwise if {@code false} throw an * IOException. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws FileExistsException if the destination file exists. * @throws FileNotFoundException if the source file does not exist. * @throws IOException if source or destination is invalid. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @since 1.4 */ public static void moveFileToDirectory(final File srcFile, final File destDir, final boolean createDestDir) throws IOException { validateMoveParameters(srcFile, destDir); if (!destDir.exists() && createDestDir) { mkdirs(destDir); } requireExistsChecked(destDir, "destDir"); requireDirectory(destDir, "destDir"); moveFile(srcFile, new File(destDir, srcFile.getName())); } /** * Moves a file or directory to the destination directory. * <p> * When the destination is on another file system, do a "copy and delete". * </p> * * @param src the file or directory to be moved. * @param destDir the destination directory. * @param createDestDir If {@code true} create the destination directory, otherwise if {@code false} throw an * IOException. * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws FileExistsException if the directory or file exists in the destination directory. * @throws FileNotFoundException if the source file does not exist. * @throws IOException if source or destination is invalid. * @throws IOException if an error occurs or setting the last-modified time didn't succeed. * @since 1.4 */ public static void moveToDirectory(final File src, final File destDir, final boolean createDestDir) throws IOException { validateMoveParameters(src, destDir); if (src.isDirectory()) { moveDirectoryToDirectory(src, destDir, createDestDir); } else { moveFileToDirectory(src, destDir, createDestDir); } } /** * Creates a new OutputStream by opening or creating a file, returning an output stream that may be used to write bytes * to the file. * * @param append Whether or not to append. * @param file the File. * @return a new OutputStream. * @throws IOException if an I/O error occurs. * @see PathUtils#newOutputStream(Path, boolean) * @since 2.12.0 */ public static OutputStream newOutputStream(final File file, final boolean append) throws IOException { return PathUtils.newOutputStream(Objects.requireNonNull(file, "file").toPath(), append); } /** * Opens a {@link FileInputStream} for the specified file, providing better error messages than simply calling * {@code new FileInputStream(file)}. * <p> * At the end of the method either the stream will be successfully opened, or an exception will have been thrown. * </p> * <p> * An exception is thrown if the file does not exist. An exception is thrown if the file object exists but is a * directory. An exception is thrown if the file exists but cannot be read. * </p> * * @param file the file to open for input, must not be {@code null} * @return a new {@link FileInputStream} for the specified file * @throws NullPointerException if file is {@code null}. * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some * other reason cannot be opened for reading. * @throws IOException See FileNotFoundException above, FileNotFoundException is a subclass of IOException. * @since 1.3 */ public static FileInputStream openInputStream(final File file) throws IOException { Objects.requireNonNull(file, "file"); return new FileInputStream(file); } /** * Opens a {@link FileOutputStream} for the specified file, checking and * creating the parent directory if it does not exist. * <p> * At the end of the method either the stream will be successfully opened, * or an exception will have been thrown. * </p> * <p> * The parent directory will be created if it does not exist. * The file will be created if it does not exist. * An exception is thrown if the file object exists but is a directory. * An exception is thrown if the file exists but cannot be written to. * An exception is thrown if the parent directory cannot be created. * </p> * * @param file the file to open for output, must not be {@code null} * @return a new {@link FileOutputStream} for the specified file * @throws NullPointerException if the file object is {@code null}. * @throws IllegalArgumentException if the file object is a directory * @throws IllegalArgumentException if the file is not writable. * @throws IOException if the directories could not be created. * @since 1.3 */ public static FileOutputStream openOutputStream(final File file) throws IOException { return openOutputStream(file, false); } /** * Opens a {@link FileOutputStream} for the specified file, checking and * creating the parent directory if it does not exist. * <p> * At the end of the method either the stream will be successfully opened, * or an exception will have been thrown. * </p> * <p> * The parent directory will be created if it does not exist. * The file will be created if it does not exist. * An exception is thrown if the file object exists but is a directory. * An exception is thrown if the file exists but cannot be written to. * An exception is thrown if the parent directory cannot be created. * </p> * * @param file the file to open for output, must not be {@code null} * @param append if {@code true}, then bytes will be added to the * end of the file rather than overwriting * @return a new {@link FileOutputStream} for the specified file * @throws NullPointerException if the file object is {@code null}. * @throws IllegalArgumentException if the file object is a directory * @throws IllegalArgumentException if the file is not writable. * @throws IOException if the directories could not be created. * @since 2.1 */ public static FileOutputStream openOutputStream(final File file, final boolean append) throws IOException { Objects.requireNonNull(file, "file"); if (file.exists()) { requireFile(file, "file"); requireCanWrite(file, "file"); } else { createParentDirectories(file); } return new FileOutputStream(file, append); } /** * Reads the contents of a file into a byte array. * The file is always closed. * * @param file the file to read, must not be {@code null} * @return the file contents, never {@code null} * @throws NullPointerException if file is {@code null}. * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some * other reason cannot be opened for reading. * @throws IOException if an I/O error occurs. * @since 1.1 */ public static byte[] readFileToByteArray(final File file) throws IOException { Objects.requireNonNull(file, "file"); return Files.readAllBytes(file.toPath()); } /** * Reads the contents of a file into a String using the default encoding for the VM. * The file is always closed. * * @param file the file to read, must not be {@code null} * @return the file contents, never {@code null} * @throws NullPointerException if file is {@code null}. * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some * other reason cannot be opened for reading. * @throws IOException if an I/O error occurs. * @since 1.3.1 * @deprecated 2.5 use {@link #readFileToString(File, Charset)} instead (and specify the appropriate encoding) */ @Deprecated public static String readFileToString(final File file) throws IOException { return readFileToString(file, Charset.defaultCharset()); } /** * Reads the contents of a file into a String. * The file is always closed. * * @param file the file to read, must not be {@code null} * @param charsetName the name of the requested charset, {@code null} means platform default * @return the file contents, never {@code null} * @throws NullPointerException if file is {@code null}. * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some * other reason cannot be opened for reading. * @throws IOException if an I/O error occurs. * @since 2.3 */ public static String readFileToString(final File file, final Charset charsetName) throws IOException { try (InputStream inputStream = Files.newInputStream(file.toPath())) { return IOUtils.toString(inputStream, Charsets.toCharset(charsetName)); } } /** * Reads the contents of a file into a String. The file is always closed. * * @param file the file to read, must not be {@code null} * @param charsetName the name of the requested charset, {@code null} means platform default * @return the file contents, never {@code null} * @throws NullPointerException if file is {@code null}. * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some * other reason cannot be opened for reading. * @throws IOException if an I/O error occurs. * @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io * .UnsupportedEncodingException} in version 2.2 if the named charset is unavailable. * @since 2.3 */ public static String readFileToString(final File file, final String charsetName) throws IOException { return readFileToString(file, Charsets.toCharset(charsetName)); } /** * Reads the contents of a file line by line to a List of Strings using the default encoding for the VM. * The file is always closed. * * @param file the file to read, must not be {@code null} * @return the list of Strings representing each line in the file, never {@code null} * @throws NullPointerException if file is {@code null}. * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some * other reason cannot be opened for reading. * @throws IOException if an I/O error occurs. * @since 1.3 * @deprecated 2.5 use {@link #readLines(File, Charset)} instead (and specify the appropriate encoding) */ @Deprecated public static List<String> readLines(final File file) throws IOException { return readLines(file, Charset.defaultCharset()); } /** * Reads the contents of a file line by line to a List of Strings. * The file is always closed. * * @param file the file to read, must not be {@code null} * @param charset the charset to use, {@code null} means platform default * @return the list of Strings representing each line in the file, never {@code null} * @throws NullPointerException if file is {@code null}. * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some * other reason cannot be opened for reading. * @throws IOException if an I/O error occurs. * @since 2.3 */ public static List<String> readLines(final File file, final Charset charset) throws IOException { return Files.readAllLines(file.toPath(), charset); } /** * Reads the contents of a file line by line to a List of Strings. The file is always closed. * * @param file the file to read, must not be {@code null} * @param charsetName the name of the requested charset, {@code null} means platform default * @return the list of Strings representing each line in the file, never {@code null} * @throws NullPointerException if file is {@code null}. * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some * other reason cannot be opened for reading. * @throws IOException if an I/O error occurs. * @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io * .UnsupportedEncodingException} in version 2.2 if the named charset is unavailable. * @since 1.1 */ public static List<String> readLines(final File file, final String charsetName) throws IOException { return readLines(file, Charsets.toCharset(charsetName)); } private static void requireAbsent(final File file, final String name) throws FileExistsException { if (file.exists()) { throw new FileExistsException(String.format("File element in parameter '%s' already exists: '%s'", name, file)); } } /** * Throws IllegalArgumentException if the given files' canonical representations are equal. * * @param file1 The first file to compare. * @param file2 The second file to compare. * @throws IOException if an I/O error occurs. * @throws IllegalArgumentException if the given files' canonical representations are equal. */ private static void requireCanonicalPathsNotEquals(final File file1, final File file2) throws IOException { final String canonicalPath = file1.getCanonicalPath(); if (canonicalPath.equals(file2.getCanonicalPath())) { throw new IllegalArgumentException(String .format("File canonical paths are equal: '%s' (file1='%s', file2='%s')", canonicalPath, file1, file2)); } } /** * Throws an {@link IllegalArgumentException} if the file is not writable. This provides a more precise exception * message than a plain access denied. * * @param file The file to test. * @param name The parameter name to use in the exception message. * @throws NullPointerException if the given {@link File} is {@code null}. * @throws IllegalArgumentException if the file is not writable. */ private static void requireCanWrite(final File file, final String name) { Objects.requireNonNull(file, "file"); if (!file.canWrite()) { throw new IllegalArgumentException("File parameter '" + name + " is not writable: '" + file + "'"); } } /** * Requires that the given {@link File} is a directory. * * @param directory The {@link File} to check. * @param name The parameter name to use in the exception message in case of null input or if the file is not a directory. * @return the given directory. * @throws NullPointerException if the given {@link File} is {@code null}. * @throws IllegalArgumentException if the given {@link File} does not exist or is not a directory. */ private static File requireDirectory(final File directory, final String name) { Objects.requireNonNull(directory, name); if (!directory.isDirectory()) { throw new IllegalArgumentException("Parameter '" + name + "' is not a directory: '" + directory + "'"); } return directory; } /** * Requires that the given {@link File} exists and is a directory. * * @param directory The {@link File} to check. * @param name The parameter name to use in the exception message in case of null input. * @return the given directory. * @throws NullPointerException if the given {@link File} is {@code null}. * @throws IllegalArgumentException if the given {@link File} does not exist or is not a directory. */ private static File requireDirectoryExists(final File directory, final String name) { requireExists(directory, name); requireDirectory(directory, name); return directory; } /** * Requires that the given {@link File} is a directory if it exists. * * @param directory The {@link File} to check. * @param name The parameter name to use in the exception message in case of null input. * @return the given directory. * @throws NullPointerException if the given {@link File} is {@code null}. * @throws IllegalArgumentException if the given {@link File} exists but is not a directory. */ private static File requireDirectoryIfExists(final File directory, final String name) { Objects.requireNonNull(directory, name); if (directory.exists()) { requireDirectory(directory, name); } return directory; } /** * Requires that the given {@link File} exists and throws an {@link IllegalArgumentException} if it doesn't. * * @param file The {@link File} to check. * @param fileParamName The parameter name to use in the exception message in case of {@code null} input. * @return the given file. * @throws NullPointerException if the given {@link File} is {@code null}. * @throws IllegalArgumentException if the given {@link File} does not exist. */ private static File requireExists(final File file, final String fileParamName) { Objects.requireNonNull(file, fileParamName); if (!file.exists()) { throw new IllegalArgumentException("File system element for parameter '" + fileParamName + "' does not exist: '" + file + "'"); } return file; } /** * Requires that the given {@link File} exists and throws an {@link FileNotFoundException} if it doesn't. * * @param file The {@link File} to check. * @param fileParamName The parameter name to use in the exception message in case of {@code null} input. * @return the given file. * @throws NullPointerException if the given {@link File} is {@code null}. * @throws FileNotFoundException if the given {@link File} does not exist. */ private static File requireExistsChecked(final File file, final String fileParamName) throws FileNotFoundException { Objects.requireNonNull(file, fileParamName); if (!file.exists()) { throw new FileNotFoundException("File system element for parameter '" + fileParamName + "' does not exist: '" + file + "'"); } return file; } /** * Requires that the given {@link File} is a file. * * @param file The {@link File} to check. * @param name The parameter name to use in the exception message. * @return the given file. * @throws NullPointerException if the given {@link File} is {@code null}. * @throws IllegalArgumentException if the given {@link File} does not exist or is not a file. */ private static File requireFile(final File file, final String name) { Objects.requireNonNull(file, name); if (!file.isFile()) { throw new IllegalArgumentException("Parameter '" + name + "' is not a file: " + file); } return file; } /** * Requires parameter attributes for a file copy operation. * * @param source the source file * @param destination the destination * @throws NullPointerException if any of the given {@link File}s are {@code null}. * @throws FileNotFoundException if the source does not exist. */ private static void requireFileCopy(final File source, final File destination) throws FileNotFoundException { requireExistsChecked(source, "source"); Objects.requireNonNull(destination, "destination"); } /** * Requires that the given {@link File} is a file if it exists. * * @param file The {@link File} to check. * @param name The parameter name to use in the exception message in case of null input. * @return the given directory. * @throws NullPointerException if the given {@link File} is {@code null}. * @throws IllegalArgumentException if the given {@link File} exists but is not a directory. */ private static File requireFileIfExists(final File file, final String name) { Objects.requireNonNull(file, name); return file.exists() ? requireFile(file, name) : file; } /** * Sets the given {@code targetFile}'s last modified date to the value from {@code sourceFile}. * * @param sourceFile The source file to query. * @param targetFile The target file or directory to set. * @throws NullPointerException if sourceFile is {@code null}. * @throws NullPointerException if targetFile is {@code null}. * @throws IOException if setting the last-modified time failed. */ private static void setLastModified(final File sourceFile, final File targetFile) throws IOException { Objects.requireNonNull(sourceFile, "sourceFile"); Objects.requireNonNull(targetFile, "targetFile"); if (targetFile.isFile()) { PathUtils.setLastModifiedTime(targetFile.toPath(), sourceFile.toPath()); } else { setLastModified(targetFile, lastModified(sourceFile)); } } /** * Sets the given {@code targetFile}'s last modified date to the given value. * * @param file The source file to query. * @param timeMillis The new last-modified time, measured in milliseconds since the epoch 01-01-1970 GMT. * @throws NullPointerException if file is {@code null}. * @throws IOException if setting the last-modified time failed. */ private static void setLastModified(final File file, final long timeMillis) throws IOException { Objects.requireNonNull(file, "file"); if (!file.setLastModified(timeMillis)) { throw new IOException(String.format("Failed setLastModified(%s) on '%s'", timeMillis, file)); } } /** * Returns the size of the specified file or directory. If the provided * {@link File} is a regular file, then the file's length is returned. * If the argument is a directory, then the size of the directory is * calculated recursively. If a directory or subdirectory is security * restricted, its size will not be included. * <p> * Note that overflow is not detected, and the return value may be negative if * overflow occurs. See {@link #sizeOfAsBigInteger(File)} for an alternative * method that does not overflow. * </p> * * @param file the regular file or directory to return the size * of (must not be {@code null}). * * @return the length of the file, or recursive size of the directory, * provided (in bytes). * * @throws NullPointerException if the file is {@code null}. * @throws IllegalArgumentException if the file does not exist. * @throws UncheckedIOException if an IO error occurs. * @since 2.0 */ public static long sizeOf(final File file) { requireExists(file, "file"); return Uncheck.get(() -> PathUtils.sizeOf(file.toPath())); } /** * Returns the size of the specified file or directory. If the provided * {@link File} is a regular file, then the file's length is returned. * If the argument is a directory, then the size of the directory is * calculated recursively. If a directory or subdirectory is security * restricted, its size will not be included. * * @param file the regular file or directory to return the size * of (must not be {@code null}). * * @return the length of the file, or recursive size of the directory, * provided (in bytes). * * @throws NullPointerException if the file is {@code null}. * @throws IllegalArgumentException if the file does not exist. * @throws UncheckedIOException if an IO error occurs. * @since 2.4 */ public static BigInteger sizeOfAsBigInteger(final File file) { requireExists(file, "file"); return Uncheck.get(() -> PathUtils.sizeOfAsBigInteger(file.toPath())); } /** * Counts the size of a directory recursively (sum of the length of all files). * <p> * Note that overflow is not detected, and the return value may be negative if * overflow occurs. See {@link #sizeOfDirectoryAsBigInteger(File)} for an alternative * method that does not overflow. * </p> * * @param directory directory to inspect, must not be {@code null}. * @return size of directory in bytes, 0 if directory is security restricted, a negative number when the real total * is greater than {@link Long#MAX_VALUE}. * @throws NullPointerException if the directory is {@code null}. * @throws UncheckedIOException if an IO error occurs. */ public static long sizeOfDirectory(final File directory) { requireDirectoryExists(directory, "directory"); return Uncheck.get(() -> PathUtils.sizeOfDirectory(directory.toPath())); } /** * Counts the size of a directory recursively (sum of the length of all files). * * @param directory directory to inspect, must not be {@code null}. * @return size of directory in bytes, 0 if directory is security restricted. * @throws NullPointerException if the directory is {@code null}. * @throws UncheckedIOException if an IO error occurs. * @since 2.4 */ public static BigInteger sizeOfDirectoryAsBigInteger(final File directory) { requireDirectoryExists(directory, "directory"); return Uncheck.get(() -> PathUtils.sizeOfDirectoryAsBigInteger(directory.toPath())); } /** * Streams over the files in a given directory (and optionally * its subdirectories) which match an array of extensions. * * @param directory the directory to search in * @param recursive if true all subdirectories are searched as well * @param extensions an array of extensions, ex. {"java","xml"}. If this * parameter is {@code null}, all files are returned. * @return an iterator of java.io.File with the matching files * @throws IOException if an I/O error is thrown when accessing the starting file. * @since 2.9.0 */ public static Stream<File> streamFiles(final File directory, final boolean recursive, final String... extensions) throws IOException { // @formatter:off final IOFileFilter filter = extensions == null ? FileFileFilter.INSTANCE : FileFileFilter.INSTANCE.and(new SuffixFileFilter(toSuffixes(extensions))); // @formatter:on return PathUtils.walk(directory.toPath(), filter, toMaxDepth(recursive), false, FileVisitOption.FOLLOW_LINKS).map(Path::toFile); } /** * Converts from a {@link URL} to a {@link File}. * <p> * From version 1.1 this method will decode the URL. * Syntax such as {@code file:///my%20docs/file.txt} will be * correctly decoded to {@code /my docs/file.txt}. Starting with version * 1.5, this method uses UTF-8 to decode percent-encoded octets to characters. * Additionally, malformed percent-encoded octets are handled leniently by * passing them through literally. * </p> * * @param url the file URL to convert, {@code null} returns {@code null} * @return the equivalent {@link File} object, or {@code null} * if the URL's protocol is not {@code file} */ public static File toFile(final URL url) { if (url == null || !"file".equalsIgnoreCase(url.getProtocol())) { return null; } final String filename = url.getFile().replace('/', File.separatorChar); return new File(decodeUrl(filename)); } /** * Converts each of an array of {@link URL} to a {@link File}. * <p> * Returns an array of the same size as the input. * If the input is {@code null}, an empty array is returned. * If the input contains {@code null}, the output array contains {@code null} at the same * index. * </p> * <p> * This method will decode the URL. * Syntax such as {@code file:///my%20docs/file.txt} will be * correctly decoded to {@code /my docs/file.txt}. * </p> * * @param urls the file URLs to convert, {@code null} returns empty array * @return a non-{@code null} array of Files matching the input, with a {@code null} item * if there was a {@code null} at that index in the input array * @throws IllegalArgumentException if any file is not a URL file * @throws IllegalArgumentException if any file is incorrectly encoded * @since 1.1 */ public static File[] toFiles(final URL... urls) { if (IOUtils.length(urls) == 0) { return EMPTY_FILE_ARRAY; } final File[] files = new File[urls.length]; for (int i = 0; i < urls.length; i++) { final URL url = urls[i]; if (url != null) { if (!"file".equalsIgnoreCase(url.getProtocol())) { throw new IllegalArgumentException("Can only convert file URL to a File: " + url); } files[i] = toFile(url); } } return files; } private static List<File> toList(final Stream<File> stream) { return stream.collect(Collectors.toList()); } /** * Converts whether or not to recurse into a recursion max depth. * * @param recursive whether or not to recurse * @return the recursion depth */ private static int toMaxDepth(final boolean recursive) { return recursive ? Integer.MAX_VALUE : 1; } /** * Converts an array of file extensions to suffixes. * * @param extensions an array of extensions. Format: {"java", "xml"} * @return an array of suffixes. Format: {".java", ".xml"} * @throws NullPointerException if the parameter is null */ private static String[] toSuffixes(final String... extensions) { Objects.requireNonNull(extensions, "extensions"); final String[] suffixes = new String[extensions.length]; for (int i = 0; i < extensions.length; i++) { suffixes[i] = "." + extensions[i]; } return suffixes; } /** * Implements behavior similar to the Unix "touch" utility. Creates a new file with size 0, or, if the file exists, just * updates the file's modified time. * <p> * NOTE: As from v1.3, this method throws an IOException if the last modified date of the file cannot be set. Also, as * from v1.3 this method creates parent directories if they do not exist. * </p> * * @param file the File to touch. * @throws NullPointerException if the parameter is {@code null}. * @throws IOException if setting the last-modified time failed or an I/O problem occurs. */ public static void touch(final File file) throws IOException { PathUtils.touch(Objects.requireNonNull(file, "file").toPath()); } /** * Converts each of an array of {@link File} to a {@link URL}. * <p> * Returns an array of the same size as the input. * </p> * * @param files the files to convert, must not be {@code null} * @return an array of URLs matching the input * @throws IOException if a file cannot be converted * @throws NullPointerException if the parameter is null */ public static URL[] toURLs(final File... files) throws IOException { Objects.requireNonNull(files, "files"); final URL[] urls = new URL[files.length]; for (int i = 0; i < urls.length; i++) { urls[i] = files[i].toURI().toURL(); } return urls; } /** * Validates the given arguments. * <ul> * <li>Throws {@link NullPointerException} if {@code source} is null</li> * <li>Throws {@link NullPointerException} if {@code destination} is null</li> * <li>Throws {@link FileNotFoundException} if {@code source} does not exist</li> * </ul> * * @param source the file or directory to be moved. * @param destination the destination file or directory. * @throws FileNotFoundException if the source file does not exist. */ private static void validateMoveParameters(final File source, final File destination) throws FileNotFoundException { Objects.requireNonNull(source, "source"); Objects.requireNonNull(destination, "destination"); if (!source.exists()) { throw new FileNotFoundException("Source '" + source + "' does not exist"); } } /** * Waits for the file system to propagate a file creation, with a timeout. * <p> * This method repeatedly tests {@link Files#exists(Path, LinkOption...)} until it returns * true up to the maximum time specified in seconds. * </p> * * @param file the file to check, must not be {@code null} * @param seconds the maximum time in seconds to wait * @return true if file exists * @throws NullPointerException if the file is {@code null} */ public static boolean waitFor(final File file, final int seconds) { Objects.requireNonNull(file, "file"); return PathUtils.waitFor(file.toPath(), Duration.ofSeconds(seconds), PathUtils.EMPTY_LINK_OPTION_ARRAY); } /** * Writes a CharSequence to a file creating the file if it does not exist using the default encoding for the VM. * * @param file the file to write * @param data the content to write to the file * @throws IOException in case of an I/O error * @since 2.0 * @deprecated 2.5 use {@link #write(File, CharSequence, Charset)} instead (and specify the appropriate encoding) */ @Deprecated public static void write(final File file, final CharSequence data) throws IOException { write(file, data, Charset.defaultCharset(), false); } /** * Writes a CharSequence to a file creating the file if it does not exist using the default encoding for the VM. * * @param file the file to write * @param data the content to write to the file * @param append if {@code true}, then the data will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.1 * @deprecated 2.5 use {@link #write(File, CharSequence, Charset, boolean)} instead (and specify the appropriate encoding) */ @Deprecated public static void write(final File file, final CharSequence data, final boolean append) throws IOException { write(file, data, Charset.defaultCharset(), append); } /** * Writes a CharSequence to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param charset the name of the requested charset, {@code null} means platform default * @throws IOException in case of an I/O error * @since 2.3 */ public static void write(final File file, final CharSequence data, final Charset charset) throws IOException { write(file, data, charset, false); } /** * Writes a CharSequence to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param charset the charset to use, {@code null} means platform default * @param append if {@code true}, then the data will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.3 */ public static void write(final File file, final CharSequence data, final Charset charset, final boolean append) throws IOException { writeStringToFile(file, Objects.toString(data, null), charset, append); } /** * Writes a CharSequence to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param charsetName the name of the requested charset, {@code null} means platform default * @throws IOException in case of an I/O error * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM * @since 2.0 */ public static void write(final File file, final CharSequence data, final String charsetName) throws IOException { write(file, data, charsetName, false); } /** * Writes a CharSequence to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param charsetName the name of the requested charset, {@code null} means platform default * @param append if {@code true}, then the data will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io * .UnsupportedEncodingException} in version 2.2 if the encoding is not supported by the VM * @since 2.1 */ public static void write(final File file, final CharSequence data, final String charsetName, final boolean append) throws IOException { write(file, data, Charsets.toCharset(charsetName), append); } // Must be called with a directory /** * Writes a byte array to a file creating the file if it does not exist. * <p> * NOTE: As from v1.3, the parent directories of the file will be created * if they do not exist. * </p> * * @param file the file to write to * @param data the content to write to the file * @throws IOException in case of an I/O error * @since 1.1 */ public static void writeByteArrayToFile(final File file, final byte[] data) throws IOException { writeByteArrayToFile(file, data, false); } /** * Writes a byte array to a file creating the file if it does not exist. * * @param file the file to write to * @param data the content to write to the file * @param append if {@code true}, then bytes will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.1 */ public static void writeByteArrayToFile(final File file, final byte[] data, final boolean append) throws IOException { writeByteArrayToFile(file, data, 0, data.length, append); } /** * Writes {@code len} bytes from the specified byte array starting * at offset {@code off} to a file, creating the file if it does * not exist. * * @param file the file to write to * @param data the content to write to the file * @param off the start offset in the data * @param len the number of bytes to write * @throws IOException in case of an I/O error * @since 2.5 */ public static void writeByteArrayToFile(final File file, final byte[] data, final int off, final int len) throws IOException { writeByteArrayToFile(file, data, off, len, false); } /** * Writes {@code len} bytes from the specified byte array starting * at offset {@code off} to a file, creating the file if it does * not exist. * * @param file the file to write to * @param data the content to write to the file * @param off the start offset in the data * @param len the number of bytes to write * @param append if {@code true}, then bytes will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.5 */ public static void writeByteArrayToFile(final File file, final byte[] data, final int off, final int len, final boolean append) throws IOException { try (OutputStream out = newOutputStream(file, append)) { out.write(data, off, len); } } /** * Writes the {@code toString()} value of each item in a collection to * the specified {@link File} line by line. * The default VM encoding and the default line ending will be used. * * @param file the file to write to * @param lines the lines to write, {@code null} entries produce blank lines * @throws IOException in case of an I/O error * @since 1.3 */ public static void writeLines(final File file, final Collection<?> lines) throws IOException { writeLines(file, null, lines, null, false); } /** * Writes the {@code toString()} value of each item in a collection to * the specified {@link File} line by line. * The default VM encoding and the default line ending will be used. * * @param file the file to write to * @param lines the lines to write, {@code null} entries produce blank lines * @param append if {@code true}, then the lines will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.1 */ public static void writeLines(final File file, final Collection<?> lines, final boolean append) throws IOException { writeLines(file, null, lines, null, append); } /** * Writes the {@code toString()} value of each item in a collection to * the specified {@link File} line by line. * The default VM encoding and the specified line ending will be used. * * @param file the file to write to * @param lines the lines to write, {@code null} entries produce blank lines * @param lineEnding the line separator to use, {@code null} is system default * @throws IOException in case of an I/O error * @since 1.3 */ public static void writeLines(final File file, final Collection<?> lines, final String lineEnding) throws IOException { writeLines(file, null, lines, lineEnding, false); } /** * Writes the {@code toString()} value of each item in a collection to * the specified {@link File} line by line. * The default VM encoding and the specified line ending will be used. * * @param file the file to write to * @param lines the lines to write, {@code null} entries produce blank lines * @param lineEnding the line separator to use, {@code null} is system default * @param append if {@code true}, then the lines will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.1 */ public static void writeLines(final File file, final Collection<?> lines, final String lineEnding, final boolean append) throws IOException { writeLines(file, null, lines, lineEnding, append); } /** * Writes the {@code toString()} value of each item in a collection to * the specified {@link File} line by line. * The specified character encoding and the default line ending will be used. * <p> * NOTE: As from v1.3, the parent directories of the file will be created * if they do not exist. * </p> * * @param file the file to write to * @param charsetName the name of the requested charset, {@code null} means platform default * @param lines the lines to write, {@code null} entries produce blank lines * @throws IOException in case of an I/O error * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM * @since 1.1 */ public static void writeLines(final File file, final String charsetName, final Collection<?> lines) throws IOException { writeLines(file, charsetName, lines, null, false); } /** * Writes the {@code toString()} value of each item in a collection to * the specified {@link File} line by line, optionally appending. * The specified character encoding and the default line ending will be used. * * @param file the file to write to * @param charsetName the name of the requested charset, {@code null} means platform default * @param lines the lines to write, {@code null} entries produce blank lines * @param append if {@code true}, then the lines will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM * @since 2.1 */ public static void writeLines(final File file, final String charsetName, final Collection<?> lines, final boolean append) throws IOException { writeLines(file, charsetName, lines, null, append); } /** * Writes the {@code toString()} value of each item in a collection to * the specified {@link File} line by line. * The specified character encoding and the line ending will be used. * <p> * NOTE: As from v1.3, the parent directories of the file will be created * if they do not exist. * </p> * * @param file the file to write to * @param charsetName the name of the requested charset, {@code null} means platform default * @param lines the lines to write, {@code null} entries produce blank lines * @param lineEnding the line separator to use, {@code null} is system default * @throws IOException in case of an I/O error * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM * @since 1.1 */ public static void writeLines(final File file, final String charsetName, final Collection<?> lines, final String lineEnding) throws IOException { writeLines(file, charsetName, lines, lineEnding, false); } /** * Writes the {@code toString()} value of each item in a collection to * the specified {@link File} line by line. * The specified character encoding and the line ending will be used. * * @param file the file to write to * @param charsetName the name of the requested charset, {@code null} means platform default * @param lines the lines to write, {@code null} entries produce blank lines * @param lineEnding the line separator to use, {@code null} is system default * @param append if {@code true}, then the lines will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM * @since 2.1 */ public static void writeLines(final File file, final String charsetName, final Collection<?> lines, final String lineEnding, final boolean append) throws IOException { try (OutputStream out = new BufferedOutputStream(newOutputStream(file, append))) { IOUtils.writeLines(lines, lineEnding, out, charsetName); } } /** * Writes a String to a file creating the file if it does not exist using the default encoding for the VM. * * @param file the file to write * @param data the content to write to the file * @throws IOException in case of an I/O error * @deprecated 2.5 use {@link #writeStringToFile(File, String, Charset)} instead (and specify the appropriate encoding) */ @Deprecated public static void writeStringToFile(final File file, final String data) throws IOException { writeStringToFile(file, data, Charset.defaultCharset(), false); } /** * Writes a String to a file creating the file if it does not exist using the default encoding for the VM. * * @param file the file to write * @param data the content to write to the file * @param append if {@code true}, then the String will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.1 * @deprecated 2.5 use {@link #writeStringToFile(File, String, Charset, boolean)} instead (and specify the appropriate encoding) */ @Deprecated public static void writeStringToFile(final File file, final String data, final boolean append) throws IOException { writeStringToFile(file, data, Charset.defaultCharset(), append); } /** * Writes a String to a file creating the file if it does not exist. * <p> * NOTE: As from v1.3, the parent directories of the file will be created * if they do not exist. * </p> * * @param file the file to write * @param data the content to write to the file * @param charset the charset to use, {@code null} means platform default * @throws IOException in case of an I/O error * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM * @since 2.4 */ public static void writeStringToFile(final File file, final String data, final Charset charset) throws IOException { writeStringToFile(file, data, charset, false); } /** * Writes a String to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param charset the charset to use, {@code null} means platform default * @param append if {@code true}, then the String will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.3 */ public static void writeStringToFile(final File file, final String data, final Charset charset, final boolean append) throws IOException { try (OutputStream out = newOutputStream(file, append)) { IOUtils.write(data, out, charset); } } /** * Writes a String to a file creating the file if it does not exist. * <p> * NOTE: As from v1.3, the parent directories of the file will be created * if they do not exist. * </p> * * @param file the file to write * @param data the content to write to the file * @param charsetName the name of the requested charset, {@code null} means platform default * @throws IOException in case of an I/O error * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM */ public static void writeStringToFile(final File file, final String data, final String charsetName) throws IOException { writeStringToFile(file, data, charsetName, false); } /** * Writes a String to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param charsetName the name of the requested charset, {@code null} means platform default * @param append if {@code true}, then the String will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io * .UnsupportedEncodingException} in version 2.2 if the encoding is not supported by the VM * @since 2.1 */ public static void writeStringToFile(final File file, final String data, final String charsetName, final boolean append) throws IOException { writeStringToFile(file, data, Charsets.toCharset(charsetName), append); } /** * Instances should NOT be constructed in standard programming. * @deprecated Will be private in 3.0. */ @Deprecated public FileUtils() { //NOSONAR } }
Use streams
src/main/java/org/apache/commons/io/FileUtils.java
Use streams
<ide><path>rc/main/java/org/apache/commons/io/FileUtils.java <ide> * @throws NullPointerException if the parameter is null <ide> */ <ide> private static String[] toSuffixes(final String... extensions) { <del> Objects.requireNonNull(extensions, "extensions"); <del> final String[] suffixes = new String[extensions.length]; <del> for (int i = 0; i < extensions.length; i++) { <del> suffixes[i] = "." + extensions[i]; <del> } <del> return suffixes; <add> return Stream.of(Objects.requireNonNull(extensions, "extensions")).map(e -> "." + e).toArray(String[]::new); <ide> } <ide> <ide> /**
Java
bsd-3-clause
11576ac58077ea323556bf4ba4b987f16e53ba53
0
jnehlmeier/threetenbp,ThreeTen/threetenbp,pepyakin/threetenbp,ThreeTen/threetenbp,naixx/threetenbp,pepyakin/threetenbp,naixx/threetenbp,jnehlmeier/threetenbp
/* * Copyright (c) 2008-2011, Stephen Colebourne & Michael Nascimento Santos * * 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 JSR-310 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 javax.time.calendar.format; import javax.time.CalendricalException; import javax.time.calendar.Calendrical; /** * Strategy for printing a calendrical to an appendable. * <p> * The printer may print any part, or the whole, of the input Calendrical. * Typically, a complete print is constructed from a number of smaller * units, each outputting a single field. * <p> * DateTimePrinter is an interface and must be implemented with care * to ensure other classes in the framework operate correctly. * All instantiable implementations must be final, immutable and thread-safe. * * @author Stephen Colebourne */ public interface DateTimePrinter { /** * Prints the calendrical object to the buffer. * <p> * The buffer must not be mutated beyond the content controlled by the implementation. * * @param calendrical the calendrical to print, not null * @param buf the buffer to append to, not null * @param symbols the formatting symbols to use, not null * @throws CalendricalException if the calendrical cannot be printed successfully */ void print(Calendrical calendrical, StringBuilder buf, DateTimeFormatSymbols symbols); }
src/main/java/javax/time/calendar/format/DateTimePrinter.java
/* * Copyright (c) 2008-2011, Stephen Colebourne & Michael Nascimento Santos * * 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 JSR-310 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 javax.time.calendar.format; import javax.time.CalendricalException; import javax.time.calendar.Calendrical; /** * Strategy for printing a calendrical to an appendable. * <p> * The printer may print any part, or the whole, of the input Calendrical. * Typically, a complete print is constructed from a number of smaller * units, each outputting a single field. * <p> * DateTimePrinter is an interface and must be implemented with care * to ensure other classes in the framework operate correctly. * All instantiable implementations must be final, immutable and thread-safe. * * @author Stephen Colebourne */ public interface DateTimePrinter { /** * Prints the calendrical object to the buffer. * <p> * The buffer must not be mutated other than with an appending method. * * @param calendrical the calendrical to print, not null * @param buf the buffer to append to, not null * @param symbols the formatting symbols to use, not null * @throws CalendricalException if the calendrical cannot be printed successfully */ void print(Calendrical calendrical, StringBuilder buf, DateTimeFormatSymbols symbols); }
Javadoc git-svn-id: d4c00b25eded7fd74432537d461d9a0ef86f0050@1401 291d795c-afe8-5c46-8ee5-bf9dd72e1864
src/main/java/javax/time/calendar/format/DateTimePrinter.java
Javadoc
<ide><path>rc/main/java/javax/time/calendar/format/DateTimePrinter.java <ide> /** <ide> * Prints the calendrical object to the buffer. <ide> * <p> <del> * The buffer must not be mutated other than with an appending method. <add> * The buffer must not be mutated beyond the content controlled by the implementation. <ide> * <ide> * @param calendrical the calendrical to print, not null <ide> * @param buf the buffer to append to, not null
Java
lgpl-2.1
0b0134684e071ff67db1b0ebea0695636bb363b1
0
levants/lightmare
package org.lightmare.utils.reflect; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import org.lightmare.libraries.LibraryLoader; import org.lightmare.utils.ObjectUtils; /** * Class to use reflection {@link Method} calls and {@link Field} information * sets * * @author levan * */ public class MetaUtils { // default values for primitives private static final byte byteDef = 0; private static final boolean booleanDef = Boolean.FALSE; private static final char charDef = '\u0000'; private static final short shortDef = 0; private static final int intDef = 0; private static final long longDef = 0L; private static final float floatDef = 0F; private static double doubleDef = 0D; // default value for modifier private static final int DEFAULT_MODIFIER = 0; /** * Sets object accessible flag as true if it is not * * @param accessibleObject * @param accessible */ private static void setAccessible(AccessibleObject accessibleObject, boolean accessible) { if (ObjectUtils.notTrue(accessible)) { synchronized (accessibleObject) { if (ObjectUtils.notTrue(accessibleObject.isAccessible())) { accessibleObject.setAccessible(Boolean.TRUE); } } } } /** * Sets passed {@link AccessibleObject}'s accessible flag as passed * accessible boolean value if the last one is false * * @param accessibleObject * @param accessible */ private static void resetAccessible(AccessibleObject accessibleObject, boolean accessible) { if (ObjectUtils.notTrue(accessible)) { synchronized (accessibleObject) { if (accessibleObject.isAccessible()) { accessibleObject.setAccessible(accessible); } } } } /** * Makes accessible passed {@link Constructor}'s and invokes * {@link Constructor#newInstance(Object...)} method * * @param constructor * @param parameters * @return <code>T</code> * @throws IOException */ public static <T> T newInstance(Constructor<T> constructor, Object... parameters) throws IOException { T instance; boolean accessible = constructor.isAccessible(); try { setAccessible(constructor, accessible); instance = constructor.newInstance(parameters); } catch (InstantiationException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } finally { resetAccessible(constructor, accessible); } return instance; } /** * Gets declared constructor for given {@link Class} and given parameters * * @param type * @param parameterTypes * @return {@link Constructor} * @throws IOException */ public static <T> Constructor<T> getConstructor(Class<T> type, Class<?>... parameterTypes) throws IOException { Constructor<T> constructor; try { constructor = type.getDeclaredConstructor(parameterTypes); } catch (NoSuchMethodException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return constructor; } /** * Instantiates class by {@link Constructor} (MetaUtils * {@link #newInstance(Constructor, Object...)}) after * {@link MetaUtils#getConstructor(Class, Class...)} method call * * @param type * @param parameterTypes * @param parameters * @return <code>T</code> * @throws IOException */ public static <T> T callConstructor(Class<T> type, Class<?>[] parameterTypes, Object... parameters) throws IOException { T instance; Constructor<T> constructor = getConstructor(type, parameterTypes); instance = newInstance(constructor, parameters); return instance; } /** * Loads class by name * * @param className * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className) throws IOException { Class<?> clazz = classForName(className, null); return clazz; } /** * Loads class by name with specific {@link ClassLoader} if it is not * <code>null</code> * * @param className * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className, ClassLoader loader) throws IOException { Class<?> clazz = classForName(className, Boolean.TRUE, loader); return clazz; } /** * Loads and if initialize parameter is true initializes class by name with * specific {@link ClassLoader} if it is not <code>null</code> * * @param className * @param initialize * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className, boolean initialize, ClassLoader loader) throws IOException { Class<?> clazz; try { if (loader == null) { clazz = Class.forName(className); } else { clazz = Class.forName(className, initialize, loader); } } catch (ClassNotFoundException ex) { throw new IOException(ex); } return clazz; } /** * Loads class by name with current {@link Thread}'s {@link ClassLoader} and * initializes it * * @param className * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> initClassForName(String className) throws IOException { Class<?> clazz; ClassLoader loader = LibraryLoader.getContextClassLoader(); clazz = classForName(className, Boolean.TRUE, loader); return clazz; } /** * Creates {@link Class} instance by {@link Class#newInstance()} method call * * @param clazz * @return */ public static <T> T instantiate(Class<T> clazz) throws IOException { T instance; try { instance = clazz.newInstance(); } catch (InstantiationException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } return instance; } /** * Gets declared method from class * * @param clazz * @param methodName * @param parameterTypes * @return {@link Method} * @throws IOException */ public static Method getDeclaredMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) throws IOException { Method method; try { method = clazz.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return method; } /** * Gets all declared methods from class * * @param clazz * @param methodName * @param parameterTypes * @return {@link Method} * @throws IOException */ public static Method[] getDeclaredMethods(Class<?> clazz) throws IOException { Method[] methods; try { methods = clazz.getDeclaredMethods(); } catch (SecurityException ex) { throw new IOException(ex); } return methods; } /** * Gets one modifier <code>int</code> value for passed collection * * @param modifiers * @return <code>int</code> */ private static int calculateModifier(int[] modifiers) { int modifier = DEFAULT_MODIFIER; if (ObjectUtils.notNull(modifiers)) { int length = modifiers.length; int modifierValue; for (int i = 0; i < length; i++) { modifierValue = modifiers[i]; modifier = modifier | modifierValue; } } return modifier; } /** * Finds if passed {@link Class} has declared public {@link Method} with * appropriated name * * @param clazz * @param modifiers * @param methodName * @return <code>boolean</code> * @throws IOException */ private static boolean classHasMethod(Class<?> clazz, String methodName, int... modifiers) throws IOException { boolean found = Boolean.FALSE; Method[] methods = getDeclaredMethods(clazz); int length = methods.length; int modifier = calculateModifier(modifiers); Method method; for (int i = 0; i < length && ObjectUtils.notTrue(found); i++) { method = methods[i]; found = method.getName().equals(methodName); if (found && ObjectUtils.notEquals(modifier, DEFAULT_MODIFIER)) { found = ((method.getModifiers() & modifier) > DEFAULT_MODIFIER); } } return found; } /** * Finds if passed {@link Class} has {@link Method} with appropriated name * and modifiers * * @param clazz * @param methodName * @param modifiers * @return <code>boolean</code> * @throws IOException */ public static boolean hasMethod(Class<?> clazz, String methodName, int... modifiers) throws IOException { boolean found = Boolean.FALSE; Class<?> superClass = clazz; while (ObjectUtils.notNull(superClass) && ObjectUtils.notTrue(found)) { found = MetaUtils.classHasMethod(superClass, methodName, modifiers); if (ObjectUtils.notTrue(found)) { superClass = superClass.getSuperclass(); } } return found; } /** * Finds if passed {@link Class} has public {@link Method} with appropriated * name * * @param clazz * @param methodName * @return <code>boolean</code> * @throws IOException */ public static boolean hasPublicMethod(Class<?> clazz, String methodName) throws IOException { boolean found = MetaUtils.hasMethod(clazz, methodName, Modifier.PUBLIC); return found; } /** * Gets declared field from passed class with specified name * * @param clazz * @param name * @return {@link Field} * @throws IOException */ public static Field getDeclaredField(Class<?> clazz, String name) throws IOException { Field field; try { field = clazz.getDeclaredField(name); } catch (NoSuchFieldException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return field; } /** * Returns passed {@link Field}'s modifier * * @param field * @return <code>int</code> */ public static int getModifiers(Field field) { return field.getModifiers(); } /** * Returns passed {@link Method}'s modifier * * @param method * @return <code>int</code> */ public static int getModifiers(Method method) { return method.getModifiers(); } /** * Returns type of passed {@link Field} invoking {@link Field#getType()} * method * * @param field * @return {@link Class}<?> */ public static Class<?> getType(Field field) { return field.getType(); } /** * Common method to invoke {@link Method} with reflection * * @param method * @param data * @param arguments * @return {@link Object} * @throws IOException */ public static Object invoke(Method method, Object data, Object... arguments) throws IOException { Object value; try { value = method.invoke(data, arguments); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } return value; } /** * Common method to invoke {@link Method} with reflection * * @param method * @param data * @param arguments * @return {@link Object} * @throws IOException */ public static Object invokePrivate(Method method, Object data, Object... arguments) throws IOException { Object value; boolean accessible = method.isAccessible(); try { setAccessible(method, accessible); value = invoke(method, data, arguments); } finally { resetAccessible(method, accessible); } return value; } /** * Common method to invoke static {@link Method} with reflection * * @param method * @param arguments * @return * @throws IOException */ public static Object invokeStatic(Method method, Object... arguments) throws IOException { Object value; try { value = method.invoke(null, arguments); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } return value; } /** * Common method to invoke private static {@link Method} * * @param method * @param arguments * @return * @throws IOException */ public static Object invokePrivateStatic(Method method, Object... arguments) throws IOException { Object value; boolean accessible = method.isAccessible(); try { setAccessible(method, accessible); value = invokeStatic(method, arguments); } finally { resetAccessible(method, accessible); } return value; } /** * Sets value to {@link Field} sets accessible Boolean.TRUE remporary if * needed * * @param field * @param value * @throws IOException */ public static void setFieldValue(Field field, Object data, Object value) throws IOException { boolean accessible = field.isAccessible(); try { setAccessible(field, accessible); field.set(data, value); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } finally { resetAccessible(field, accessible); } } /** * Gets value of specific field in specific {@link Object} * * @param field * @param data * @return {@link Object} * @throws IOException */ public static Object getFieldValue(Field field, Object data) throws IOException { Object value; boolean accessible = field.isAccessible(); try { setAccessible(field, accessible); value = field.get(data); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } finally { resetAccessible(field, accessible); } return value; } /** * Gets value of specific static field * * @param field * @return {@link Object} * @throws IOException */ public static Object getFieldValue(Field field) throws IOException { Object value = getFieldValue(field, null); return value; } /** * Gets {@link List} of all {@link Method}s from passed class annotated with * specified annotation * * @param clazz * @param annotationClass * @return {@link List}<Method> * @throws IOException */ public static List<Method> getAnnotatedMethods(Class<?> clazz, Class<? extends Annotation> annotationClass) throws IOException { List<Method> methods = new ArrayList<Method>(); Method[] allMethods = getDeclaredMethods(clazz); for (Method method : allMethods) { if (method.isAnnotationPresent(annotationClass)) { methods.add(method); } } return methods; } /** * Gets {@link List} of all {@link Field}s from passed class annotated with * specified annotation * * @param clazz * @param annotationClass * @return {@link List}<Field> * @throws IOException */ public static List<Field> getAnnotatedFields(Class<?> clazz, Class<? extends Annotation> annotationClass) throws IOException { List<Field> fields = new ArrayList<Field>(); Field[] allFields = clazz.getDeclaredFields(); for (Field field : allFields) { if (field.isAnnotationPresent(annotationClass)) { fields.add(field); } } return fields; } /** * Gets wrapper class if passed class is primitive type * * @param type * @return {@link Class}<T> */ public static <T> Class<T> getWrapper(Class<?> type) { Class<T> wrapper; if (type.isPrimitive()) { if (type.equals(byte.class)) { wrapper = ObjectUtils.cast(Byte.class); } else if (type.equals(boolean.class)) { wrapper = ObjectUtils.cast(Boolean.class); } else if (type.equals(char.class)) { wrapper = ObjectUtils.cast(Character.class); } else if (type.equals(short.class)) { wrapper = ObjectUtils.cast(Short.class); } else if (type.equals(int.class)) { wrapper = ObjectUtils.cast(Integer.class); } else if (type.equals(long.class)) { wrapper = ObjectUtils.cast(Long.class); } else if (type.equals(float.class)) { wrapper = ObjectUtils.cast(Float.class); } else if (type.equals(double.class)) { wrapper = ObjectUtils.cast(Double.class); } else { wrapper = ObjectUtils.cast(type); } } else { wrapper = ObjectUtils.cast(type); } return wrapper; } /** * Returns default values if passed class is primitive else returns null * * @param clazz * @return Object */ public static Object getDefault(Class<?> clazz) { Object value; if (clazz.isPrimitive()) { if (clazz.equals(byte.class)) { value = byteDef; } else if (clazz.equals(boolean.class)) { value = booleanDef; } else if (clazz.equals(char.class)) { value = charDef; } else if (clazz.equals(short.class)) { value = shortDef; } else if (clazz.equals(int.class)) { value = intDef; } else if (clazz.equals(long.class)) { value = longDef; } else if (clazz.equals(float.class)) { value = floatDef; } else if (clazz.equals(double.class)) { value = doubleDef; } else { value = null; } } else { value = null; } return value; } }
src/main/java/org/lightmare/utils/reflect/MetaUtils.java
package org.lightmare.utils.reflect; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import org.lightmare.libraries.LibraryLoader; import org.lightmare.utils.ObjectUtils; /** * Class to use reflection {@link Method} calls and {@link Field} information * sets * * @author levan * */ public class MetaUtils { // default values for primitives private static final byte byteDef = 0; private static final boolean booleanDef = Boolean.FALSE; private static final char charDef = '\u0000'; private static final short shortDef = 0; private static final int intDef = 0; private static final long longDef = 0L; private static float floatDef = 0F; private static double doubleDef = 0D; // default value for modifier private static final int DEFAULT_MODIFIER = 0; /** * Sets object accessible flag as true if it is not * * @param accessibleObject * @param accessible */ private static void setAccessible(AccessibleObject accessibleObject, boolean accessible) { if (ObjectUtils.notTrue(accessible)) { synchronized (accessibleObject) { if (ObjectUtils.notTrue(accessibleObject.isAccessible())) { accessibleObject.setAccessible(Boolean.TRUE); } } } } /** * Sets passed {@link AccessibleObject}'s accessible flag as passed * accessible boolean value if the last one is false * * @param accessibleObject * @param accessible */ private static void resetAccessible(AccessibleObject accessibleObject, boolean accessible) { if (ObjectUtils.notTrue(accessible)) { synchronized (accessibleObject) { if (accessibleObject.isAccessible()) { accessibleObject.setAccessible(accessible); } } } } /** * Makes accessible passed {@link Constructor}'s and invokes * {@link Constructor#newInstance(Object...)} method * * @param constructor * @param parameters * @return <code>T</code> * @throws IOException */ public static <T> T newInstance(Constructor<T> constructor, Object... parameters) throws IOException { T instance; boolean accessible = constructor.isAccessible(); try { setAccessible(constructor, accessible); instance = constructor.newInstance(parameters); } catch (InstantiationException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } finally { resetAccessible(constructor, accessible); } return instance; } /** * Gets declared constructor for given {@link Class} and given parameters * * @param type * @param parameterTypes * @return {@link Constructor} * @throws IOException */ public static <T> Constructor<T> getConstructor(Class<T> type, Class<?>... parameterTypes) throws IOException { Constructor<T> constructor; try { constructor = type.getDeclaredConstructor(parameterTypes); } catch (NoSuchMethodException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return constructor; } /** * Instantiates class by {@link Constructor} (MetaUtils * {@link #newInstance(Constructor, Object...)}) after * {@link MetaUtils#getConstructor(Class, Class...)} method call * * @param type * @param parameterTypes * @param parameters * @return <code>T</code> * @throws IOException */ public static <T> T callConstructor(Class<T> type, Class<?>[] parameterTypes, Object... parameters) throws IOException { T instance; Constructor<T> constructor = getConstructor(type, parameterTypes); instance = newInstance(constructor, parameters); return instance; } /** * Loads class by name * * @param className * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className) throws IOException { Class<?> clazz = classForName(className, null); return clazz; } /** * Loads class by name with specific {@link ClassLoader} if it is not * <code>null</code> * * @param className * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className, ClassLoader loader) throws IOException { Class<?> clazz = classForName(className, Boolean.TRUE, loader); return clazz; } /** * Loads and if initialize parameter is true initializes class by name with * specific {@link ClassLoader} if it is not <code>null</code> * * @param className * @param initialize * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className, boolean initialize, ClassLoader loader) throws IOException { Class<?> clazz; try { if (loader == null) { clazz = Class.forName(className); } else { clazz = Class.forName(className, initialize, loader); } } catch (ClassNotFoundException ex) { throw new IOException(ex); } return clazz; } /** * Loads class by name with current {@link Thread}'s {@link ClassLoader} and * initializes it * * @param className * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> initClassForName(String className) throws IOException { Class<?> clazz; ClassLoader loader = LibraryLoader.getContextClassLoader(); clazz = classForName(className, Boolean.TRUE, loader); return clazz; } /** * Creates {@link Class} instance by {@link Class#newInstance()} method call * * @param clazz * @return */ public static <T> T instantiate(Class<T> clazz) throws IOException { T instance; try { instance = clazz.newInstance(); } catch (InstantiationException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } return instance; } /** * Gets declared method from class * * @param clazz * @param methodName * @param parameterTypes * @return {@link Method} * @throws IOException */ public static Method getDeclaredMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) throws IOException { Method method; try { method = clazz.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return method; } /** * Gets all declared methods from class * * @param clazz * @param methodName * @param parameterTypes * @return {@link Method} * @throws IOException */ public static Method[] getDeclaredMethods(Class<?> clazz) throws IOException { Method[] methods; try { methods = clazz.getDeclaredMethods(); } catch (SecurityException ex) { throw new IOException(ex); } return methods; } /** * Gets one modifier <code>int</code> value for passed collection * * @param modifiers * @return <code>int</code> */ private static int calculateModifier(int[] modifiers) { int modifier = DEFAULT_MODIFIER; if (ObjectUtils.notNull(modifiers)) { int length = modifiers.length; int modifierValue; for (int i = 0; i < length; i++) { modifierValue = modifiers[i]; modifier = modifier | modifierValue; } } return modifier; } /** * Finds if passed {@link Class} has declared public {@link Method} with * appropriated name * * @param clazz * @param modifiers * @param methodName * @return <code>boolean</code> * @throws IOException */ private static boolean classHasMethod(Class<?> clazz, String methodName, int... modifiers) throws IOException { boolean found = Boolean.FALSE; Method[] methods = getDeclaredMethods(clazz); int length = methods.length; int modifier = calculateModifier(modifiers); Method method; for (int i = 0; i < length && ObjectUtils.notTrue(found); i++) { method = methods[i]; found = method.getName().equals(methodName); if (found && ObjectUtils.notEquals(modifier, DEFAULT_MODIFIER)) { found = ((method.getModifiers() & modifier) > DEFAULT_MODIFIER); } } return found; } /** * Finds if passed {@link Class} has {@link Method} with appropriated name * and modifiers * * @param clazz * @param methodName * @param modifiers * @return <code>boolean</code> * @throws IOException */ public static boolean hasMethod(Class<?> clazz, String methodName, int... modifiers) throws IOException { boolean found = Boolean.FALSE; Class<?> superClass = clazz; while (ObjectUtils.notNull(superClass) && ObjectUtils.notTrue(found)) { found = MetaUtils.classHasMethod(superClass, methodName, modifiers); if (ObjectUtils.notTrue(found)) { superClass = superClass.getSuperclass(); } } return found; } /** * Finds if passed {@link Class} has public {@link Method} with appropriated * name * * @param clazz * @param methodName * @return <code>boolean</code> * @throws IOException */ public static boolean hasPublicMethod(Class<?> clazz, String methodName) throws IOException { boolean found = MetaUtils.hasMethod(clazz, methodName, Modifier.PUBLIC); return found; } /** * Gets declared field from passed class with specified name * * @param clazz * @param name * @return {@link Field} * @throws IOException */ public static Field getDeclaredField(Class<?> clazz, String name) throws IOException { Field field; try { field = clazz.getDeclaredField(name); } catch (NoSuchFieldException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return field; } /** * Returns passed {@link Field}'s modifier * * @param field * @return <code>int</code> */ public static int getModifiers(Field field) { return field.getModifiers(); } /** * Returns passed {@link Method}'s modifier * * @param method * @return <code>int</code> */ public static int getModifiers(Method method) { return method.getModifiers(); } /** * Returns type of passed {@link Field} invoking {@link Field#getType()} * method * * @param field * @return {@link Class}<?> */ public static Class<?> getType(Field field) { return field.getType(); } /** * Common method to invoke {@link Method} with reflection * * @param method * @param data * @param arguments * @return {@link Object} * @throws IOException */ public static Object invoke(Method method, Object data, Object... arguments) throws IOException { Object value; try { value = method.invoke(data, arguments); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } return value; } /** * Common method to invoke {@link Method} with reflection * * @param method * @param data * @param arguments * @return {@link Object} * @throws IOException */ public static Object invokePrivate(Method method, Object data, Object... arguments) throws IOException { Object value; boolean accessible = method.isAccessible(); try { setAccessible(method, accessible); value = invoke(method, data, arguments); } finally { resetAccessible(method, accessible); } return value; } /** * Common method to invoke static {@link Method} with reflection * * @param method * @param arguments * @return * @throws IOException */ public static Object invokeStatic(Method method, Object... arguments) throws IOException { Object value; try { value = method.invoke(null, arguments); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } return value; } /** * Common method to invoke private static {@link Method} * * @param method * @param arguments * @return * @throws IOException */ public static Object invokePrivateStatic(Method method, Object... arguments) throws IOException { Object value; boolean accessible = method.isAccessible(); try { setAccessible(method, accessible); value = invokeStatic(method, arguments); } finally { resetAccessible(method, accessible); } return value; } /** * Sets value to {@link Field} sets accessible Boolean.TRUE remporary if * needed * * @param field * @param value * @throws IOException */ public static void setFieldValue(Field field, Object data, Object value) throws IOException { boolean accessible = field.isAccessible(); try { setAccessible(field, accessible); field.set(data, value); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } finally { resetAccessible(field, accessible); } } /** * Gets value of specific field in specific {@link Object} * * @param field * @param data * @return {@link Object} * @throws IOException */ public static Object getFieldValue(Field field, Object data) throws IOException { Object value; boolean accessible = field.isAccessible(); try { setAccessible(field, accessible); value = field.get(data); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } finally { resetAccessible(field, accessible); } return value; } /** * Gets value of specific static field * * @param field * @return {@link Object} * @throws IOException */ public static Object getFieldValue(Field field) throws IOException { Object value = getFieldValue(field, null); return value; } /** * Gets {@link List} of all {@link Method}s from passed class annotated with * specified annotation * * @param clazz * @param annotationClass * @return {@link List}<Method> * @throws IOException */ public static List<Method> getAnnotatedMethods(Class<?> clazz, Class<? extends Annotation> annotationClass) throws IOException { List<Method> methods = new ArrayList<Method>(); Method[] allMethods = getDeclaredMethods(clazz); for (Method method : allMethods) { if (method.isAnnotationPresent(annotationClass)) { methods.add(method); } } return methods; } /** * Gets {@link List} of all {@link Field}s from passed class annotated with * specified annotation * * @param clazz * @param annotationClass * @return {@link List}<Field> * @throws IOException */ public static List<Field> getAnnotatedFields(Class<?> clazz, Class<? extends Annotation> annotationClass) throws IOException { List<Field> fields = new ArrayList<Field>(); Field[] allFields = clazz.getDeclaredFields(); for (Field field : allFields) { if (field.isAnnotationPresent(annotationClass)) { fields.add(field); } } return fields; } /** * Gets wrapper class if passed class is primitive type * * @param type * @return {@link Class}<T> */ public static <T> Class<T> getWrapper(Class<?> type) { Class<T> wrapper; if (type.isPrimitive()) { if (type.equals(byte.class)) { wrapper = ObjectUtils.cast(Byte.class); } else if (type.equals(boolean.class)) { wrapper = ObjectUtils.cast(Boolean.class); } else if (type.equals(char.class)) { wrapper = ObjectUtils.cast(Character.class); } else if (type.equals(short.class)) { wrapper = ObjectUtils.cast(Short.class); } else if (type.equals(int.class)) { wrapper = ObjectUtils.cast(Integer.class); } else if (type.equals(long.class)) { wrapper = ObjectUtils.cast(Long.class); } else if (type.equals(float.class)) { wrapper = ObjectUtils.cast(Float.class); } else if (type.equals(double.class)) { wrapper = ObjectUtils.cast(Double.class); } else { wrapper = ObjectUtils.cast(type); } } else { wrapper = ObjectUtils.cast(type); } return wrapper; } /** * Returns default values if passed class is primitive else returns null * * @param clazz * @return Object */ public static Object getDefault(Class<?> clazz) { Object value; if (clazz.isPrimitive()) { if (clazz.equals(byte.class)) { value = byteDef; } else if (clazz.equals(boolean.class)) { value = booleanDef; } else if (clazz.equals(char.class)) { value = charDef; } else if (clazz.equals(short.class)) { value = shortDef; } else if (clazz.equals(int.class)) { value = intDef; } else if (clazz.equals(long.class)) { value = longDef; } else if (clazz.equals(float.class)) { value = floatDef; } else if (clazz.equals(double.class)) { value = doubleDef; } else { value = null; } } else { value = null; } return value; } }
improved reflection utilities
src/main/java/org/lightmare/utils/reflect/MetaUtils.java
improved reflection utilities
<ide><path>rc/main/java/org/lightmare/utils/reflect/MetaUtils.java <ide> <ide> private static final long longDef = 0L; <ide> <del> private static float floatDef = 0F; <add> private static final float floatDef = 0F; <ide> <ide> private static double doubleDef = 0D; <ide>
Java
apache-2.0
d62fcb3e065e26ecd7ac5523dd8b17eb279b5c5e
0
boalang/compiler,boalang/compiler,boalang/compiler,boalang/compiler,boalang/compiler
/* * Copyright 2016, Hridesh Rajan, Robert Dyer, Hoan Nguyen * Iowa State University of Science and Technology * and Bowling Green State University * * 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 boa.datagen.scm; import java.io.*; import java.util.*; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.SequenceFile.Writer; import org.dom4j.dom.DOMDocument; import org.dom4j.io.SAXReader; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.dom.*; import org.eclipse.php.internal.core.PHPVersion; import org.eclipse.php.internal.core.ast.nodes.Program; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.mozilla.javascript.CompilerEnvirons; import org.mozilla.javascript.Context; import org.mozilla.javascript.ast.AstRoot; import org.w3c.css.sac.InputSource; import com.steadystate.css.dom.CSSStyleSheetImpl; import boa.types.Ast.ASTRoot; import boa.types.Code.Revision; import boa.types.Diff.ChangedFile; import boa.types.Diff.ChangedFile.Builder; import boa.types.Diff.ChangedFile.FileKind; import boa.types.Shared.ChangeKind; import boa.types.Shared.Person; import boa.datagen.DefaultProperties; import boa.datagen.dependencies.PomFile; import boa.datagen.treed.TreedConstants; import boa.datagen.treed.TreedMapper; import boa.datagen.util.CssVisitor; import boa.datagen.util.FileIO; import boa.datagen.util.HtmlVisitor; import boa.datagen.util.JavaScriptErrorCheckVisitor; import boa.datagen.util.JavaScriptVisitor; import boa.datagen.util.PHPErrorCheckVisitor; import boa.datagen.util.PHPVisitor; import boa.datagen.util.Properties; import boa.datagen.util.XMLVisitor; import boa.datagen.util.Java7Visitor; import boa.datagen.util.Java8Visitor; import boa.datagen.util.JavaASTUtil; import boa.datagen.util.JavaErrorCheckVisitor; /** * @author rdyer */ public abstract class AbstractCommit { protected static final boolean debug = Properties.getBoolean("debug", DefaultProperties.DEBUG); protected static final boolean debugparse = Properties.getBoolean("debugparse", DefaultProperties.DEBUGPARSE); protected static final boolean STORE_ASCII_PRINTABLE_CONTENTS = Properties.getBoolean("ascii", DefaultProperties.STORE_ASCII_PRINTABLE_CONTENTS); protected AbstractConnector connector; protected AbstractCommit(AbstractConnector cnn) { this.connector = cnn; } protected Map<String, Integer> fileNameIndices = new HashMap<String, Integer>(); protected List<ChangedFile.Builder> changedFiles = new ArrayList<ChangedFile.Builder>(); protected ChangedFile.Builder getChangeFile(String path) { ChangedFile.Builder cfb = null; Integer index = fileNameIndices.get(path); if (index == null) { cfb = ChangedFile.newBuilder(); cfb.setKind(FileKind.OTHER); cfb.setKey(-1); cfb.setAst(false); fileNameIndices.put(path, changedFiles.size()); changedFiles.add(cfb); } else cfb = changedFiles.get(index); return cfb; } protected String id = null; public String getId() { return id; } public void setId(final String id) { this.id = id; } protected Person author; public void setAuthor(final String username, final String realname, final String email) { final Person.Builder person = Person.newBuilder(); person.setUsername(username); if (realname != null) person.setRealName(realname); person.setEmail(email); author = person.build(); } protected Person committer; public void setCommitter(final String username, final String realname, final String email) { final Person.Builder person = Person.newBuilder(); person.setUsername(username); if (realname != null) person.setRealName(realname); person.setEmail(email); committer = person.build(); } protected String message; public void setMessage(final String message) { this.message = message; } protected Date date; public void setDate(final Date date) { this.date = date; } protected int[] parentIndices; protected List<Integer> childrenIndices = new LinkedList<Integer>(); protected static final ByteArrayOutputStream buffer = new ByteArrayOutputStream(4096); protected abstract String getFileContents(final String path); public abstract String writeFile(final String classpathRoot, final String path); public abstract Set<String> getGradleDependencies(final String classpathRoot, final String path); public abstract Set<String> getPomDependencies(String classpathroot, String name, HashSet<String> globalRepoLinks, HashMap<String, String> globalProperties, HashMap<String, String> globalManagedDependencies, Stack<PomFile> parentPomFiles); public Revision asProtobuf(final boolean parse, final Writer astWriter, final Writer contentWriter) { final Revision.Builder revision = Revision.newBuilder(); revision.setId(id); if (this.author != null) { final Person author = Person.newBuilder(this.author).build(); revision.setAuthor(author); } final Person committer = Person.newBuilder(this.committer).build(); revision.setCommitter(committer); long time = -1; if (date != null) time = date.getTime() * 1000; revision.setCommitDate(time); if (message != null) revision.setLog(message); else revision.setLog(""); if (this.parentIndices != null) for (int parentIndex : this.parentIndices) revision.addParents(parentIndex); for (ChangedFile.Builder cfb : changedFiles) { if (cfb.getChange() == ChangeKind.DELETED || cfb.getChange() == ChangeKind.UNKNOWN) { cfb.setKey(-1); cfb.setKind(connector.revisions.get(cfb.getPreviousVersions(0)).changedFiles .get(cfb.getPreviousIndices(0)).getKind()); } else processChangeFile(cfb, parse, astWriter, contentWriter); revision.addFiles(cfb.build()); } return revision.build(); } @SuppressWarnings("deprecation") private Builder processChangeFile(final ChangedFile.Builder fb, boolean parse, final Writer astWriter, final Writer contentWriter) { long len = -1; try { len = astWriter.getLength(); } catch (IOException e1) { if (debug) System.err.println("Error getting length of sequence file writer!!!"); } String path = fb.getName(); fb.setKind(FileKind.OTHER); final String lowerPath = path.toLowerCase(); if (lowerPath.endsWith(".txt")) fb.setKind(FileKind.TEXT); else if (lowerPath.endsWith(".xml")) fb.setKind(FileKind.XML); else if (lowerPath.endsWith(".jar") || lowerPath.endsWith(".class")) fb.setKind(FileKind.BINARY); else if (lowerPath.endsWith(".java") && parse) { final String content = getFileContents(path); fb.setKind(FileKind.SOURCE_JAVA_JLS2); if (!parseJavaFile(path, fb, content, JavaCore.VERSION_1_4, AST.JLS2, false, astWriter)) { if (debugparse) System.err.println("Found JLS2 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_JAVA_JLS3); if (!parseJavaFile(path, fb, content, JavaCore.VERSION_1_5, AST.JLS3, false, astWriter)) { if (debugparse) System.err.println("Found JLS3 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_JAVA_JLS4); if (!parseJavaFile(path, fb, content, JavaCore.VERSION_1_7, AST.JLS4, false, astWriter)) { if (debugparse) System.err.println("Found JLS4 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_JAVA_JLS8); if (!parseJavaFile(path, fb, content, JavaCore.VERSION_1_8, AST.JLS8, false, astWriter)) { if (debugparse) System.err.println("Found JLS8 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_JAVA_ERROR); // try { // astWriter.append(new LongWritable(len), new // BytesWritable(ASTRoot.newBuilder().build().toByteArray())); // } catch (IOException e) { // e.printStackTrace(); // } } else if (debugparse) System.err.println("Accepted JLS8: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted JLS4: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted JLS3: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted JLS2: revision " + id + ": file " + path); } else if (lowerPath.endsWith(".js") && parse) { final String content = getFileContents(path); fb.setKind(FileKind.SOURCE_JS_ES1); if (!parseJavaScriptFile(path, fb, content, Context.VERSION_1_1, false, astWriter)) { if (debugparse) System.err.println("Found ES3 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_JS_ES2); if (!parseJavaScriptFile(path, fb, content, Context.VERSION_1_2, false, astWriter)) { if (debugparse) System.err.println("Found ES3 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_JS_ES3); if (!parseJavaScriptFile(path, fb, content, Context.VERSION_1_3, false, astWriter)) { if (debugparse) System.err.println("Found ES3 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_JS_ES5); if (!parseJavaScriptFile(path, fb, content, Context.VERSION_1_5, false, astWriter)) { if (debugparse) System.err.println("Found ES4 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_JS_ES6); if (!parseJavaScriptFile(path, fb, content, Context.VERSION_1_6, false, astWriter)) { if (debugparse) System.err.println("Found ES4 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_JS_ES7); if (!parseJavaScriptFile(path, fb, content, Context.VERSION_1_7, false, astWriter)) { if (debugparse) System.err .println("Found ES3 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_JS_ES8); if (!parseJavaScriptFile(path, fb, content, Context.VERSION_1_8, false, astWriter)) { if (debugparse) System.err.println( "Found ES4 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_JS_ERROR); // try { // astWriter.append(new // LongWritable(len), new // BytesWritable(ASTRoot.newBuilder().build().toByteArray())); // } catch (IOException e) { // e.printStackTrace(); // } } else if (debugparse) System.err.println("Accepted ES8: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted ES7: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted ES6: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted ES5: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted ES3: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted ES2: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted ES1: revision " + id + ": file " + path); } else if (lowerPath.endsWith(".php") && parse) { final String content = getFileContents(path); fb.setKind(FileKind.SOURCE_PHP5); if (!parsePHPFile(path, fb, content, PHPVersion.PHP5, false, astWriter)) { if (debugparse) System.err.println("Found ES3 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_PHP5_3); if (!parsePHPFile(path, fb, content, PHPVersion.PHP5_3, false, astWriter)) { if (debugparse) System.err.println("Found ES3 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_PHP5_4); if (!parsePHPFile(path, fb, content, PHPVersion.PHP5_4, false, astWriter)) { if (debugparse) System.err.println("Found ES3 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_PHP5_5); if (!parsePHPFile(path, fb, content, PHPVersion.PHP5_5, false, astWriter)) { if (debugparse) System.err.println("Found ES4 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_PHP5_6); if (!parsePHPFile(path, fb, content, PHPVersion.PHP5_6, false, astWriter)) { if (debugparse) System.err.println("Found ES4 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_PHP7_0); if (!parsePHPFile(path, fb, content, PHPVersion.PHP7_0, false, astWriter)) { if (debugparse) System.err .println("Found ES3 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_PHP7_1); if (!parsePHPFile(path, fb, content, PHPVersion.PHP7_1, false, astWriter)) { if (debugparse) System.err.println( "Found ES4 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_PHP_ERROR); // try { // astWriter.append(new // LongWritable(len), new // BytesWritable(ASTRoot.newBuilder().build().toByteArray())); // } catch (IOException e) { // e.printStackTrace(); // } } else if (debugparse) System.err.println("Accepted PHP7_1: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted PHP7_0: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted PHP5_6: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted PHP5_5: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted PHP5_4: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted PHP5_3: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted PHP5: revision " + id + ": file " + path); } else if (lowerPath.endsWith(".html") && parse) { final String content = getFileContents(path); fb.setKind(FileKind.Source_HTML); if (!HTMLParse(path, fb, content, false, astWriter)) { if (debugparse) System.err.println("Found an HTML parse error in : revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_HTML_ERROR); } else if (debugparse) System.err.println("Accepted HTML: revisison " + id + ": file " + path); } else if (lowerPath.endsWith(".xml") && parse) { final String content = getFileContents(path); fb.setKind(FileKind.Source_XML); if (!XMLParse(path, fb, content, false, astWriter)) { if (debugparse) System.err.println("Found an XML parse error in : revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_XML_ERROR); }else if (debugparse) System.err.println("Accepted XML: revisison " + id + ": file " + path); } else if (lowerPath.endsWith(".css") && parse) { final String content = getFileContents(path); fb.setKind(FileKind.Source_CSS); if (!CSSParse(path, fb, content, false, astWriter)) { if (debugparse) System.err.println("Found an CSS parse error in : revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_CSS_ERROR); }else if (debugparse) System.err.println("Accepted CSS: revisison " + id + ": file " + path); } /* * else { final String content = getFileContents(path); if * (STORE_ASCII_PRINTABLE_CONTENTS && * StringUtils.isAsciiPrintable(content)) { try { * fb.setKey(contentWriter.getLength()); contentWriter.append(new * LongWritable(contentWriter.getLength()), new * BytesWritable(content.getBytes())); } catch (IOException e) { * e.printStackTrace(); } } } */ try { if (astWriter.getLength() > len) { fb.setKey(len); fb.setAst(true); } } catch (IOException e) { if (debug) System.err.println("Error getting length of sequence file writer!!!"); } return fb; } private boolean HTMLParse(String path, Builder fb, String content, boolean b, Writer astWriter) { Document doc; HtmlVisitor visitor = new HtmlVisitor(); final ASTRoot.Builder ast = ASTRoot.newBuilder(); try { doc = Jsoup.parse(content); } catch (Exception e) { if (debug) { System.err.println("Error parsing HTML file: " + path); e.printStackTrace(); } return false; } try { ast.setDocument(visitor.getDocument(doc)); } catch (final UnsupportedOperationException e) { return false; } catch (final Throwable e) { if (debug) System.err.println("Error visiting HTML file: " + path); e.printStackTrace(); System.exit(-1); return false; } try { // System.out.println("writing=" + count + "\t" + path); astWriter.append(new LongWritable(astWriter.getLength()), new BytesWritable(ast.build().toByteArray())); } catch (IOException e) { e.printStackTrace(); } return true; } private boolean XMLParse(String path, Builder fb, String content, boolean b, Writer astWriter) { org.dom4j.Document doc; XMLVisitor visitor = new XMLVisitor(); final ASTRoot.Builder ast = ASTRoot.newBuilder(); try { org.dom4j.dom.DOMDocumentFactory di = new org.dom4j.dom.DOMDocumentFactory(); SAXReader reader = new SAXReader(di); doc = reader.read(content); } catch (Exception e) { if (debug) { System.err.println("Error parsing HTML file: " + path); e.printStackTrace(); } return false; } try { ast.setDocument(visitor.getDocument((DOMDocument) doc)); } catch (final UnsupportedOperationException e) { return false; } catch (final Throwable e) { if (debug) System.err.println("Error visiting HTML file: " + path); e.printStackTrace(); System.exit(-1); return false; } try { // System.out.println("writing=" + count + "\t" + path); astWriter.append(new LongWritable(astWriter.getLength()), new BytesWritable(ast.build().toByteArray())); } catch (IOException e) { e.printStackTrace(); } return true; } private boolean CSSParse(String path, Builder fb, String content, boolean b, Writer astWriter) { com.steadystate.css.dom.CSSStyleSheetImpl sSheet = null; CssVisitor visitor = new CssVisitor(); final ASTRoot.Builder ast = ASTRoot.newBuilder(); try { com.steadystate.css.parser.CSSOMParser parser = new com.steadystate.css.parser.CSSOMParser(); InputSource source = new InputSource(new StringReader(content)); sSheet = (CSSStyleSheetImpl) parser.parseStyleSheet(source, null, null); } catch (Exception e) { if (debug) { System.err.println("Error parsing HTML file: " + path); e.printStackTrace(); } return false; } try { ast.setDocument(visitor.getDocument(sSheet)); } catch (final UnsupportedOperationException e) { return false; } catch (final Throwable e) { if (debug) System.err.println("Error visiting HTML file: " + path); e.printStackTrace(); System.exit(-1); return false; } try { // System.out.println("writing=" + count + "\t" + path); astWriter.append(new LongWritable(astWriter.getLength()), new BytesWritable(ast.build().toByteArray())); } catch (IOException e) { e.printStackTrace(); } return true; } private boolean parsePHPFile(final String path, final ChangedFile.Builder fb, final String content, final PHPVersion astLevel, final boolean storeOnError, Writer astWriter) { org.eclipse.php.internal.core.ast.nodes.ASTParser parser = org.eclipse.php.internal.core.ast.nodes.ASTParser .newParser(astLevel); Program cu = null; try { parser.setSource(content.toCharArray()); cu = parser.createAST(null); if (cu == null) return false; } catch (Exception e) { if (debug) System.err.println("Error parsing PHP file: " + path); // e.printStackTrace(); return false; } PHPErrorCheckVisitor errorCheck = new PHPErrorCheckVisitor(); if (!errorCheck.hasError || storeOnError) { final ASTRoot.Builder ast = ASTRoot.newBuilder(); PHPVisitor visitor = new PHPVisitor(content); try { ast.addNamespaces(visitor.getNamespace(cu)); } catch (final UnsupportedOperationException e) { return false; } catch (final Throwable e) { if (debug) System.err.println("Error visiting PHP file: " + path); e.printStackTrace(); System.exit(-1); return false; } try { // System.out.println("writing=" + count + "\t" + path); astWriter.append(new LongWritable(astWriter.getLength()), new BytesWritable(ast.build().toByteArray())); } catch (IOException e) { e.printStackTrace(); } } return !errorCheck.hasError; } private boolean parseJavaScriptFile(final String path, final ChangedFile.Builder fb, final String content, final int astLevel, final boolean storeOnError, Writer astWriter) { try { // System.out.println("parsing=" + (++count) + "\t" + path); CompilerEnvirons cp = new CompilerEnvirons(); cp.setLanguageVersion(astLevel); final org.mozilla.javascript.Parser parser = new org.mozilla.javascript.Parser(cp); AstRoot cu; try { cu = parser.parse(content, null, 0); } catch (java.lang.IllegalArgumentException ex) { return false; } catch (org.mozilla.javascript.EvaluatorException ex) { return false; } final JavaScriptErrorCheckVisitor errorCheck = new JavaScriptErrorCheckVisitor(); cu.visit(errorCheck); if (!errorCheck.hasError || storeOnError) { final ASTRoot.Builder ast = ASTRoot.newBuilder(); // final CommentsRoot.Builder comments = // CommentsRoot.newBuilder(); final JavaScriptVisitor visitor = new JavaScriptVisitor(content); try { ast.addNamespaces(visitor.getNamespaces(cu)); // for (final String s : visitor.getImports()) // ast.addImports(s); /* * for (final Comment c : visitor.getComments()) * comments.addComments(c); */ } catch (final UnsupportedOperationException e) { return false; } catch (final Throwable e) { if (debug) System.err.println("Error visiting JS file: " + path); e.printStackTrace(); System.exit(-1); return false; } try { // System.out.println("writing=" + count + "\t" + path); astWriter.append(new LongWritable(astWriter.getLength()), new BytesWritable(ast.build().toByteArray())); } catch (IOException e) { e.printStackTrace(); } // fb.setComments(comments); } return !errorCheck.hasError; } catch (final Exception e) { e.printStackTrace(); return false; } } public Map<String, String> getLOC() { final Map<String, String> l = new HashMap<String, String>(); for (final ChangedFile.Builder cf : changedFiles) if (cf.getChange() != ChangeKind.DELETED) l.put(cf.getName(), processLOC(cf.getName())); return l; } private boolean parseJavaFile(final String path, final ChangedFile.Builder fb, final String content, final String compliance, final int astLevel, final boolean storeOnError, Writer astWriter) { try { final org.eclipse.jdt.core.dom.ASTParser parser = org.eclipse.jdt.core.dom.ASTParser.newParser(astLevel); parser.setKind(org.eclipse.jdt.core.dom.ASTParser.K_COMPILATION_UNIT); // parser.setResolveBindings(true); parser.setSource(content.toCharArray()); final Map<?, ?> options = JavaCore.getOptions(); JavaCore.setComplianceOptions(compliance, options); parser.setCompilerOptions(options); final CompilationUnit cu = (CompilationUnit) parser.createAST(null); final JavaErrorCheckVisitor errorCheck = new JavaErrorCheckVisitor(); cu.accept(errorCheck); if (!errorCheck.hasError || storeOnError) { final ASTRoot.Builder ast = ASTRoot.newBuilder(); // final CommentsRoot.Builder comments = // CommentsRoot.newBuilder(); final Java7Visitor visitor; if (astLevel == AST.JLS8) visitor = new Java8Visitor(content); else visitor = new Java7Visitor(content); try { ast.addNamespaces(visitor.getNamespaces(cu)); /* * for (final Comment c : visitor.getComments()) * comments.addComments(c); */ } catch (final UnsupportedOperationException e) { if (debugparse) { System.err.println("Error visiting Java file: " + path); e.printStackTrace(); } return false; } catch (final Throwable e) { if (debug) System.err.println("Error visiting Java file: " + path); e.printStackTrace(); System.exit(-1); return false; } ASTRoot.Builder preAst = null; CompilationUnit preCu = null; if (fb.getChange() == ChangeKind.MODIFIED && this.parentIndices.length == 1 && fb.getPreviousIndicesCount() == 1) { AbstractCommit previousCommit = this.connector.revisions.get(fb.getPreviousVersions(0)); ChangedFile.Builder pcf = previousCommit.changedFiles.get(fb.getPreviousIndices(0)); String previousFilePath = pcf.getName(); String previousContent = previousCommit.getFileContents(previousFilePath); FileKind fileKind = pcf.getKind(); org.eclipse.jdt.core.dom.ASTParser previuousParser = JavaASTUtil.buildParser(fileKind); if (previuousParser != null) { try { previuousParser.setSource(previousContent.toCharArray()); preCu = (CompilationUnit) previuousParser.createAST(null); TreedMapper tm = new TreedMapper(preCu, cu); tm.map(); preAst = ASTRoot.newBuilder(); Integer index = (Integer) preCu.getProperty(Java7Visitor.PROPERTY_INDEX); if (index != null) preAst.setKey(index); ChangeKind status = (ChangeKind) preCu.getProperty(TreedConstants.PROPERTY_STATUS); if (status != null) preAst.setChangeKind(status); preAst.setMappedNode((Integer) cu.getProperty(TreedConstants.PROPERTY_INDEX)); final Java7Visitor preVisitor; if (preCu.getAST().apiLevel() == AST.JLS8) preVisitor = new Java8Visitor(previousContent); else preVisitor = new Java7Visitor(previousContent); preAst.addNamespaces(preVisitor.getNamespaces(preCu)); } catch (Throwable e) { preAst = null; preCu = null; } } } Integer index = (Integer) cu.getProperty(Java7Visitor.PROPERTY_INDEX); if (index != null) { ast.setKey(index); if (preCu != null) { ChangeKind status = (ChangeKind) cu.getProperty(TreedConstants.PROPERTY_STATUS); if (status != null) ast.setChangeKind(status); ast.setMappedNode((Integer) preCu.getProperty(TreedConstants.PROPERTY_INDEX)); } } long len = astWriter.getLength(); try { astWriter.append(new LongWritable(len), new BytesWritable(ast.build().toByteArray())); } catch (IOException e) { if (debug) e.printStackTrace(); len = Long.MAX_VALUE; } long plen = astWriter.getLength(); if (preAst != null && plen > len) { try { astWriter.append(new LongWritable(plen), new BytesWritable(preAst.build().toByteArray())); } catch (IOException e) { if (debug) e.printStackTrace(); plen = Long.MAX_VALUE; } } if (preAst != null && astWriter.getLength() > plen) fb.setMappedKey(plen); else fb.setMappedKey(-1); // fb.setComments(comments); } return !errorCheck.hasError; } catch (final Exception e) { if (debug) e.printStackTrace(); return false; } } protected String processLOC(final String path) { String loc = ""; final String lowerPath = path.toLowerCase(); if (!(lowerPath.endsWith(".txt") || lowerPath.endsWith(".xml") || lowerPath.endsWith(".java"))) return loc; final String content = getFileContents(path); final File dir = new File(new File(System.getProperty("java.io.tmpdir")), UUID.randomUUID().toString()); final File tmpPath = new File(dir, path.substring(0, path.lastIndexOf("/"))); tmpPath.mkdirs(); final File tmpFile = new File(tmpPath, path.substring(path.lastIndexOf("/") + 1)); FileIO.writeFileContents(tmpFile, content); try { final Process proc = Runtime.getRuntime() .exec(new String[] { "/home/boa/ohcount/bin/ohcount", "-i", tmpFile.getPath() }); final BufferedReader outStream = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line = null; while ((line = outStream.readLine()) != null) loc += line; outStream.close(); proc.waitFor(); } catch (final IOException e) { e.printStackTrace(); } catch (final InterruptedException e) { e.printStackTrace(); } try { FileIO.delete(dir); } catch (final IOException e) { e.printStackTrace(); } return loc; } protected List<int[]> getPreviousFiles(String parentName, String path) { int commitId = connector.revisionMap.get(parentName); Set<Integer> queuedCommitIds = new HashSet<Integer>(); List<int[]> l = new ArrayList<int[]>(); PriorityQueue<Integer> pq = new PriorityQueue<Integer>(100, new Comparator<Integer>() { @Override public int compare(Integer i1, Integer i2) { return i2 - i1; } }); pq.offer(commitId); queuedCommitIds.add(commitId); while (!pq.isEmpty()) { commitId = pq.poll(); AbstractCommit commit = connector.revisions.get(commitId); Integer i = commit.fileNameIndices.get(path); if (i != null) { ChangedFile.Builder cfb = commit.changedFiles.get(i); if (cfb.getChange() != ChangeKind.DELETED) { l.add(new int[] { i, commitId }); } } else if (commit.parentIndices != null) { for (int parentId : commit.parentIndices) { if (!queuedCommitIds.contains(parentId)) { pq.offer(parentId); queuedCommitIds.add(parentId); } } } } if (l.isEmpty()) { System.err.println("Cannot find previous version!"); System.exit(-1); } return l; } }
src/java/boa/datagen/scm/AbstractCommit.java
/* * Copyright 2016, Hridesh Rajan, Robert Dyer, Hoan Nguyen * Iowa State University of Science and Technology * and Bowling Green State University * * 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 boa.datagen.scm; import java.io.*; import java.util.*; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.SequenceFile.Writer; import org.dom4j.dom.DOMDocument; import org.dom4j.io.SAXReader; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.dom.*; import org.eclipse.php.internal.core.PHPVersion; import org.eclipse.php.internal.core.ast.nodes.Program; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.mozilla.javascript.CompilerEnvirons; import org.mozilla.javascript.Context; import org.mozilla.javascript.ast.AstRoot; import org.w3c.css.sac.InputSource; import com.steadystate.css.dom.CSSStyleSheetImpl; import boa.types.Ast.ASTRoot; import boa.types.Code.Revision; import boa.types.Diff.ChangedFile; import boa.types.Diff.ChangedFile.Builder; import boa.types.Diff.ChangedFile.FileKind; import boa.types.Shared.ChangeKind; import boa.types.Shared.Person; import boa.datagen.DefaultProperties; import boa.datagen.dependencies.PomFile; import boa.datagen.treed.TreedConstants; import boa.datagen.treed.TreedMapper; import boa.datagen.util.CssVisitor; import boa.datagen.util.FileIO; import boa.datagen.util.HtmlVisitor; import boa.datagen.util.JavaScriptErrorCheckVisitor; import boa.datagen.util.JavaScriptVisitor; import boa.datagen.util.PHPErrorCheckVisitor; import boa.datagen.util.PHPVisitor; import boa.datagen.util.Properties; import boa.datagen.util.XMLVisitor; import boa.datagen.util.Java7Visitor; import boa.datagen.util.Java8Visitor; import boa.datagen.util.JavaASTUtil; import boa.datagen.util.JavaErrorCheckVisitor; /** * @author rdyer */ public abstract class AbstractCommit { protected static final boolean debug = Properties.getBoolean("debug", DefaultProperties.DEBUG); protected static final boolean debugparse = Properties.getBoolean("debugparse", DefaultProperties.DEBUGPARSE); protected static final boolean STORE_ASCII_PRINTABLE_CONTENTS = Properties.getBoolean("ascii", DefaultProperties.STORE_ASCII_PRINTABLE_CONTENTS); protected AbstractConnector connector; protected AbstractCommit(AbstractConnector cnn) { this.connector = cnn; } protected Map<String, Integer> fileNameIndices = new HashMap<String, Integer>(); protected List<ChangedFile.Builder> changedFiles = new ArrayList<ChangedFile.Builder>(); protected ChangedFile.Builder getChangeFile(String path) { ChangedFile.Builder cfb = null; Integer index = fileNameIndices.get(path); if (index == null) { cfb = ChangedFile.newBuilder(); cfb.setKind(FileKind.OTHER); cfb.setKey(-1); cfb.setAst(false); fileNameIndices.put(path, changedFiles.size()); changedFiles.add(cfb); } else cfb = changedFiles.get(index); return cfb; } protected String id = null; public String getId() { return id; } public void setId(final String id) { this.id = id; } protected Person author; public void setAuthor(final String username, final String realname, final String email) { final Person.Builder person = Person.newBuilder(); person.setUsername(username); if (realname != null) person.setRealName(realname); person.setEmail(email); author = person.build(); } protected Person committer; public void setCommitter(final String username, final String realname, final String email) { final Person.Builder person = Person.newBuilder(); person.setUsername(username); if (realname != null) person.setRealName(realname); person.setEmail(email); committer = person.build(); } protected String message; public void setMessage(final String message) { this.message = message; } protected Date date; public void setDate(final Date date) { this.date = date; } protected int[] parentIndices; protected List<Integer> childrenIndices = new LinkedList<Integer>(); protected static final ByteArrayOutputStream buffer = new ByteArrayOutputStream(4096); protected abstract String getFileContents(final String path); public abstract String writeFile(final String classpathRoot, final String path); public abstract Set<String> getGradleDependencies(final String classpathRoot, final String path); public abstract Set<String> getPomDependencies(String classpathroot, String name, HashSet<String> globalRepoLinks, HashMap<String, String> globalProperties, HashMap<String, String> globalManagedDependencies, Stack<PomFile> parentPomFiles); public Revision asProtobuf(final boolean parse, final Writer astWriter, final Writer contentWriter) { final Revision.Builder revision = Revision.newBuilder(); revision.setId(id); if (this.author != null) { final Person author = Person.newBuilder(this.author).build(); revision.setAuthor(author); } final Person committer = Person.newBuilder(this.committer).build(); revision.setCommitter(committer); long time = -1; if (date != null) time = date.getTime() * 1000; revision.setCommitDate(time); if (message != null) revision.setLog(message); else revision.setLog(""); if (this.parentIndices != null) for (int parentIndex : this.parentIndices) revision.addParents(parentIndex); for (ChangedFile.Builder cfb : changedFiles) { if (cfb.getChange() == ChangeKind.DELETED || cfb.getChange() == ChangeKind.UNKNOWN) { cfb.setKey(-1); cfb.setKind(connector.revisions.get(cfb.getPreviousVersions(0)).changedFiles .get(cfb.getPreviousIndices(0)).getKind()); } else processChangeFile(cfb, parse, astWriter, contentWriter); revision.addFiles(cfb.build()); } return revision.build(); } @SuppressWarnings("deprecation") private Builder processChangeFile(final ChangedFile.Builder fb, boolean parse, final Writer astWriter, final Writer contentWriter) { long len = -1; try { len = astWriter.getLength(); } catch (IOException e1) { if (debug) System.err.println("Error getting length of sequence file writer!!!"); } String path = fb.getName(); fb.setKind(FileKind.OTHER); final String lowerPath = path.toLowerCase(); if (lowerPath.endsWith(".txt")) fb.setKind(FileKind.TEXT); else if (lowerPath.endsWith(".xml")) fb.setKind(FileKind.XML); else if (lowerPath.endsWith(".jar") || lowerPath.endsWith(".class")) fb.setKind(FileKind.BINARY); else if (lowerPath.endsWith(".java") && parse) { final String content = getFileContents(path); fb.setKind(FileKind.SOURCE_JAVA_JLS2); if (!parseJavaFile(path, fb, content, JavaCore.VERSION_1_4, AST.JLS2, false, astWriter)) { if (debugparse) System.err.println("Found JLS2 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_JAVA_JLS3); if (!parseJavaFile(path, fb, content, JavaCore.VERSION_1_5, AST.JLS3, false, astWriter)) { if (debugparse) System.err.println("Found JLS3 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_JAVA_JLS4); if (!parseJavaFile(path, fb, content, JavaCore.VERSION_1_7, AST.JLS4, false, astWriter)) { if (debugparse) System.err.println("Found JLS4 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_JAVA_JLS8); if (!parseJavaFile(path, fb, content, JavaCore.VERSION_1_8, AST.JLS8, false, astWriter)) { if (debugparse) System.err.println("Found JLS8 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_JAVA_ERROR); // try { // astWriter.append(new LongWritable(len), new // BytesWritable(ASTRoot.newBuilder().build().toByteArray())); // } catch (IOException e) { // e.printStackTrace(); // } } else if (debugparse) System.err.println("Accepted JLS8: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted JLS4: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted JLS3: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted JLS2: revision " + id + ": file " + path); } else if (lowerPath.endsWith(".js") && parse) { final String content = getFileContents(path); fb.setKind(FileKind.SOURCE_JS_ES1); if (!parseJavaScriptFile(path, fb, content, Context.VERSION_1_1, false, astWriter)) { if (debugparse) System.err.println("Found ES3 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_JS_ES2); if (!parseJavaScriptFile(path, fb, content, Context.VERSION_1_2, false, astWriter)) { if (debugparse) System.err.println("Found ES3 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_JS_ES3); if (!parseJavaScriptFile(path, fb, content, Context.VERSION_1_3, false, astWriter)) { if (debugparse) System.err.println("Found ES3 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_JS_ES5); if (!parseJavaScriptFile(path, fb, content, Context.VERSION_1_5, false, astWriter)) { if (debugparse) System.err.println("Found ES4 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_JS_ES6); if (!parseJavaScriptFile(path, fb, content, Context.VERSION_1_6, false, astWriter)) { if (debugparse) System.err.println("Found ES4 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_JS_ES7); if (!parseJavaScriptFile(path, fb, content, Context.VERSION_1_7, false, astWriter)) { if (debugparse) System.err .println("Found ES3 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_JS_ES8); if (!parseJavaScriptFile(path, fb, content, Context.VERSION_1_8, false, astWriter)) { if (debugparse) System.err.println( "Found ES4 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_JS_ERROR); // try { // astWriter.append(new // LongWritable(len), new // BytesWritable(ASTRoot.newBuilder().build().toByteArray())); // } catch (IOException e) { // e.printStackTrace(); // } } else if (debugparse) System.err.println("Accepted ES8: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted ES7: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted ES6: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted ES5: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted ES3: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted ES2: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted ES1: revision " + id + ": file " + path); } else if (lowerPath.endsWith(".php") && parse) { final String content = getFileContents(path); fb.setKind(FileKind.SOURCE_PHP5); if (!parsePHPFile(path, fb, content, PHPVersion.PHP5, false, astWriter)) { if (debugparse) System.err.println("Found ES3 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_PHP5_3); if (!parsePHPFile(path, fb, content, PHPVersion.PHP5_3, false, astWriter)) { if (debugparse) System.err.println("Found ES3 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_PHP5_4); if (!parsePHPFile(path, fb, content, PHPVersion.PHP5_4, false, astWriter)) { if (debugparse) System.err.println("Found ES3 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_PHP5_5); if (!parsePHPFile(path, fb, content, PHPVersion.PHP5_5, false, astWriter)) { if (debugparse) System.err.println("Found ES4 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_PHP5_6); if (!parsePHPFile(path, fb, content, PHPVersion.PHP5_6, false, astWriter)) { if (debugparse) System.err.println("Found ES4 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_PHP7_0); if (!parsePHPFile(path, fb, content, PHPVersion.PHP7_0, false, astWriter)) { if (debugparse) System.err .println("Found ES3 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_PHP7_1); if (!parsePHPFile(path, fb, content, PHPVersion.PHP7_1, false, astWriter)) { if (debugparse) System.err.println( "Found ES4 parse error in: revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_PHP_ERROR); // try { // astWriter.append(new // LongWritable(len), new // BytesWritable(ASTRoot.newBuilder().build().toByteArray())); // } catch (IOException e) { // e.printStackTrace(); // } } else if (debugparse) System.err.println("Accepted PHP7_1: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted PHP7_0: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted PHP5_6: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted PHP5_5: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted PHP5_4: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted PHP5_3: revision " + id + ": file " + path); } else if (debugparse) System.err.println("Accepted PHP5: revision " + id + ": file " + path); } else if (lowerPath.endsWith(".html") && parse) { final String content = getFileContents(path); fb.setKind(FileKind.Source_HTML); if (!HTMLParse(path, fb, content, false, astWriter)) { if (debugparse) System.err.println("Found an HTML parse error in : revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_HTML_ERROR); } else if (debugparse) System.err.println("Accepted HTML: revisison " + id + ": file " + path); } else if (lowerPath.endsWith(".xml") && parse) { final String content = getFileContents(path); fb.setKind(FileKind.Source_XML); if (!XMLParse(path, fb, content, false, astWriter)) { if (debugparse) System.err.println("Found an XML parse error in : revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_XML_ERROR); }else if (debugparse) System.err.println("Accepted XML: revisison " + id + ": file " + path); } else if (lowerPath.endsWith(".css") && parse) { final String content = getFileContents(path); fb.setKind(FileKind.Source_CSS); if (!CSSParse(path, fb, content, false, astWriter)) { if (debugparse) System.err.println("Found an CSS parse error in : revision " + id + ": file " + path); fb.setKind(FileKind.SOURCE_CSS_ERROR); }else if (debugparse) System.err.println("Accepted CSS: revisison " + id + ": file " + path); } /* * else { final String content = getFileContents(path); if * (STORE_ASCII_PRINTABLE_CONTENTS && * StringUtils.isAsciiPrintable(content)) { try { * fb.setKey(contentWriter.getLength()); contentWriter.append(new * LongWritable(contentWriter.getLength()), new * BytesWritable(content.getBytes())); } catch (IOException e) { * e.printStackTrace(); } } } */ try { if (astWriter.getLength() > len) { fb.setKey(len); fb.setAst(true); } } catch (IOException e) { if (debug) System.err.println("Error getting length of sequence file writer!!!"); } return fb; } private boolean HTMLParse(String path, Builder fb, String content, boolean b, Writer astWriter) { Document doc; HtmlVisitor visitor = new HtmlVisitor(); final ASTRoot.Builder ast = ASTRoot.newBuilder(); try { doc = Jsoup.parse(content); } catch (Exception e) { if (debug) { System.err.println("Error parsing HTML file: " + path); e.printStackTrace(); } return false; } try { ast.setDocument(visitor.getDocument(doc)); } catch (final UnsupportedOperationException e) { return false; } catch (final Throwable e) { if (debug) System.err.println("Error visiting HTML file: " + path); e.printStackTrace(); // System.exit(-1); return false; } try { // System.out.println("writing=" + count + "\t" + path); astWriter.append(new LongWritable(astWriter.getLength()), new BytesWritable(ast.build().toByteArray())); } catch (IOException e) { e.printStackTrace(); } return true; } private boolean XMLParse(String path, Builder fb, String content, boolean b, Writer astWriter) { org.dom4j.Document doc; XMLVisitor visitor = new XMLVisitor(); final ASTRoot.Builder ast = ASTRoot.newBuilder(); try { org.dom4j.dom.DOMDocumentFactory di = new org.dom4j.dom.DOMDocumentFactory(); SAXReader reader = new SAXReader(di); doc = reader.read(content); } catch (Exception e) { if (debug) { System.err.println("Error parsing HTML file: " + path); e.printStackTrace(); } return false; } try { ast.setDocument(visitor.getDocument((DOMDocument) doc)); } catch (final UnsupportedOperationException e) { return false; } catch (final Throwable e) { if (debug) System.err.println("Error visiting HTML file: " + path); e.printStackTrace(); // System.exit(-1); return false; } try { // System.out.println("writing=" + count + "\t" + path); astWriter.append(new LongWritable(astWriter.getLength()), new BytesWritable(ast.build().toByteArray())); } catch (IOException e) { e.printStackTrace(); } return true; } private boolean CSSParse(String path, Builder fb, String content, boolean b, Writer astWriter) { com.steadystate.css.dom.CSSStyleSheetImpl sSheet = null; CssVisitor visitor = new CssVisitor(); final ASTRoot.Builder ast = ASTRoot.newBuilder(); try { com.steadystate.css.parser.CSSOMParser parser = new com.steadystate.css.parser.CSSOMParser(); InputSource source = new InputSource(new StringReader(content)); sSheet = (CSSStyleSheetImpl) parser.parseStyleSheet(source, null, null); } catch (Exception e) { if (debug) { System.err.println("Error parsing HTML file: " + path); e.printStackTrace(); } return false; } try { ast.setDocument(visitor.getDocument(sSheet)); } catch (final UnsupportedOperationException e) { return false; } catch (final Throwable e) { if (debug) System.err.println("Error visiting HTML file: " + path); e.printStackTrace(); // System.exit(-1); return false; } try { // System.out.println("writing=" + count + "\t" + path); astWriter.append(new LongWritable(astWriter.getLength()), new BytesWritable(ast.build().toByteArray())); } catch (IOException e) { e.printStackTrace(); } return true; } private boolean parsePHPFile(final String path, final ChangedFile.Builder fb, final String content, final PHPVersion astLevel, final boolean storeOnError, Writer astWriter) { org.eclipse.php.internal.core.ast.nodes.ASTParser parser = org.eclipse.php.internal.core.ast.nodes.ASTParser .newParser(astLevel); Program cu = null; try { parser.setSource(content.toCharArray()); cu = parser.createAST(null); if (cu == null) return false; } catch (Exception e) { if (debug) System.err.println("Error parsing PHP file: " + path); // e.printStackTrace(); return false; } PHPErrorCheckVisitor errorCheck = new PHPErrorCheckVisitor(); if (!errorCheck.hasError || storeOnError) { final ASTRoot.Builder ast = ASTRoot.newBuilder(); PHPVisitor visitor = new PHPVisitor(content); try { ast.addNamespaces(visitor.getNamespace(cu)); } catch (final UnsupportedOperationException e) { return false; } catch (final Throwable e) { if (debug) System.err.println("Error visiting PHP file: " + path); e.printStackTrace(); System.exit(-1); return false; } try { // System.out.println("writing=" + count + "\t" + path); astWriter.append(new LongWritable(astWriter.getLength()), new BytesWritable(ast.build().toByteArray())); } catch (IOException e) { e.printStackTrace(); } } return !errorCheck.hasError; } private boolean parseJavaScriptFile(final String path, final ChangedFile.Builder fb, final String content, final int astLevel, final boolean storeOnError, Writer astWriter) { try { // System.out.println("parsing=" + (++count) + "\t" + path); CompilerEnvirons cp = new CompilerEnvirons(); cp.setLanguageVersion(astLevel); final org.mozilla.javascript.Parser parser = new org.mozilla.javascript.Parser(cp); AstRoot cu; try { cu = parser.parse(content, null, 0); } catch (java.lang.IllegalArgumentException ex) { return false; } catch (org.mozilla.javascript.EvaluatorException ex) { return false; } final JavaScriptErrorCheckVisitor errorCheck = new JavaScriptErrorCheckVisitor(); cu.visit(errorCheck); if (!errorCheck.hasError || storeOnError) { final ASTRoot.Builder ast = ASTRoot.newBuilder(); // final CommentsRoot.Builder comments = // CommentsRoot.newBuilder(); final JavaScriptVisitor visitor = new JavaScriptVisitor(content); try { ast.addNamespaces(visitor.getNamespaces(cu)); // for (final String s : visitor.getImports()) // ast.addImports(s); /* * for (final Comment c : visitor.getComments()) * comments.addComments(c); */ } catch (final UnsupportedOperationException e) { return false; } catch (final Throwable e) { if (debug) System.err.println("Error visiting JS file: " + path); e.printStackTrace(); System.exit(-1); return false; } try { // System.out.println("writing=" + count + "\t" + path); astWriter.append(new LongWritable(astWriter.getLength()), new BytesWritable(ast.build().toByteArray())); } catch (IOException e) { e.printStackTrace(); } // fb.setComments(comments); } return !errorCheck.hasError; } catch (final Exception e) { e.printStackTrace(); return false; } } public Map<String, String> getLOC() { final Map<String, String> l = new HashMap<String, String>(); for (final ChangedFile.Builder cf : changedFiles) if (cf.getChange() != ChangeKind.DELETED) l.put(cf.getName(), processLOC(cf.getName())); return l; } private boolean parseJavaFile(final String path, final ChangedFile.Builder fb, final String content, final String compliance, final int astLevel, final boolean storeOnError, Writer astWriter) { try { final org.eclipse.jdt.core.dom.ASTParser parser = org.eclipse.jdt.core.dom.ASTParser.newParser(astLevel); parser.setKind(org.eclipse.jdt.core.dom.ASTParser.K_COMPILATION_UNIT); // parser.setResolveBindings(true); parser.setSource(content.toCharArray()); final Map<?, ?> options = JavaCore.getOptions(); JavaCore.setComplianceOptions(compliance, options); parser.setCompilerOptions(options); final CompilationUnit cu = (CompilationUnit) parser.createAST(null); final JavaErrorCheckVisitor errorCheck = new JavaErrorCheckVisitor(); cu.accept(errorCheck); if (!errorCheck.hasError || storeOnError) { final ASTRoot.Builder ast = ASTRoot.newBuilder(); // final CommentsRoot.Builder comments = // CommentsRoot.newBuilder(); final Java7Visitor visitor; if (astLevel == AST.JLS8) visitor = new Java8Visitor(content); else visitor = new Java7Visitor(content); try { ast.addNamespaces(visitor.getNamespaces(cu)); /* * for (final Comment c : visitor.getComments()) * comments.addComments(c); */ } catch (final UnsupportedOperationException e) { if (debugparse) { System.err.println("Error visiting Java file: " + path); e.printStackTrace(); } return false; } catch (final Throwable e) { if (debug) System.err.println("Error visiting Java file: " + path); e.printStackTrace(); System.exit(-1); return false; } ASTRoot.Builder preAst = null; CompilationUnit preCu = null; if (fb.getChange() == ChangeKind.MODIFIED && this.parentIndices.length == 1 && fb.getPreviousIndicesCount() == 1) { AbstractCommit previousCommit = this.connector.revisions.get(fb.getPreviousVersions(0)); ChangedFile.Builder pcf = previousCommit.changedFiles.get(fb.getPreviousIndices(0)); String previousFilePath = pcf.getName(); String previousContent = previousCommit.getFileContents(previousFilePath); FileKind fileKind = pcf.getKind(); org.eclipse.jdt.core.dom.ASTParser previuousParser = JavaASTUtil.buildParser(fileKind); if (previuousParser != null) { try { previuousParser.setSource(previousContent.toCharArray()); preCu = (CompilationUnit) previuousParser.createAST(null); TreedMapper tm = new TreedMapper(preCu, cu); tm.map(); preAst = ASTRoot.newBuilder(); Integer index = (Integer) preCu.getProperty(Java7Visitor.PROPERTY_INDEX); if (index != null) preAst.setKey(index); ChangeKind status = (ChangeKind) preCu.getProperty(TreedConstants.PROPERTY_STATUS); if (status != null) preAst.setChangeKind(status); preAst.setMappedNode((Integer) cu.getProperty(TreedConstants.PROPERTY_INDEX)); final Java7Visitor preVisitor; if (preCu.getAST().apiLevel() == AST.JLS8) preVisitor = new Java8Visitor(previousContent); else preVisitor = new Java7Visitor(previousContent); preAst.addNamespaces(preVisitor.getNamespaces(preCu)); } catch (Throwable e) { preAst = null; preCu = null; } } } Integer index = (Integer) cu.getProperty(Java7Visitor.PROPERTY_INDEX); if (index != null) { ast.setKey(index); if (preCu != null) { ChangeKind status = (ChangeKind) cu.getProperty(TreedConstants.PROPERTY_STATUS); if (status != null) ast.setChangeKind(status); ast.setMappedNode((Integer) preCu.getProperty(TreedConstants.PROPERTY_INDEX)); } } long len = astWriter.getLength(); try { astWriter.append(new LongWritable(len), new BytesWritable(ast.build().toByteArray())); } catch (IOException e) { if (debug) e.printStackTrace(); len = Long.MAX_VALUE; } long plen = astWriter.getLength(); if (preAst != null && plen > len) { try { astWriter.append(new LongWritable(plen), new BytesWritable(preAst.build().toByteArray())); } catch (IOException e) { if (debug) e.printStackTrace(); plen = Long.MAX_VALUE; } } if (preAst != null && astWriter.getLength() > plen) fb.setMappedKey(plen); else fb.setMappedKey(-1); // fb.setComments(comments); } return !errorCheck.hasError; } catch (final Exception e) { if (debug) e.printStackTrace(); return false; } } protected String processLOC(final String path) { String loc = ""; final String lowerPath = path.toLowerCase(); if (!(lowerPath.endsWith(".txt") || lowerPath.endsWith(".xml") || lowerPath.endsWith(".java"))) return loc; final String content = getFileContents(path); final File dir = new File(new File(System.getProperty("java.io.tmpdir")), UUID.randomUUID().toString()); final File tmpPath = new File(dir, path.substring(0, path.lastIndexOf("/"))); tmpPath.mkdirs(); final File tmpFile = new File(tmpPath, path.substring(path.lastIndexOf("/") + 1)); FileIO.writeFileContents(tmpFile, content); try { final Process proc = Runtime.getRuntime() .exec(new String[] { "/home/boa/ohcount/bin/ohcount", "-i", tmpFile.getPath() }); final BufferedReader outStream = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line = null; while ((line = outStream.readLine()) != null) loc += line; outStream.close(); proc.waitFor(); } catch (final IOException e) { e.printStackTrace(); } catch (final InterruptedException e) { e.printStackTrace(); } try { FileIO.delete(dir); } catch (final IOException e) { e.printStackTrace(); } return loc; } protected List<int[]> getPreviousFiles(String parentName, String path) { int commitId = connector.revisionMap.get(parentName); Set<Integer> queuedCommitIds = new HashSet<Integer>(); List<int[]> l = new ArrayList<int[]>(); PriorityQueue<Integer> pq = new PriorityQueue<Integer>(100, new Comparator<Integer>() { @Override public int compare(Integer i1, Integer i2) { return i2 - i1; } }); pq.offer(commitId); queuedCommitIds.add(commitId); while (!pq.isEmpty()) { commitId = pq.poll(); AbstractCommit commit = connector.revisions.get(commitId); Integer i = commit.fileNameIndices.get(path); if (i != null) { ChangedFile.Builder cfb = commit.changedFiles.get(i); if (cfb.getChange() != ChangeKind.DELETED) { l.add(new int[] { i, commitId }); } } else if (commit.parentIndices != null) { for (int parentId : commit.parentIndices) { if (!queuedCommitIds.contains(parentId)) { pq.offer(parentId); queuedCommitIds.add(parentId); } } } } if (l.isEmpty()) { System.err.println("Cannot find previous version!"); System.exit(-1); } return l; } }
un-comment System.exit(-1)
src/java/boa/datagen/scm/AbstractCommit.java
un-comment System.exit(-1)
<ide><path>rc/java/boa/datagen/scm/AbstractCommit.java <ide> if (debug) <ide> System.err.println("Error visiting HTML file: " + path); <ide> e.printStackTrace(); <del> // System.exit(-1); <add> System.exit(-1); <ide> return false; <ide> } <ide> try { <ide> if (debug) <ide> System.err.println("Error visiting HTML file: " + path); <ide> e.printStackTrace(); <del> // System.exit(-1); <add> System.exit(-1); <ide> return false; <ide> } <ide> try { <ide> if (debug) <ide> System.err.println("Error visiting HTML file: " + path); <ide> e.printStackTrace(); <del> // System.exit(-1); <add> System.exit(-1); <ide> return false; <ide> } <ide> try {
Java
apache-2.0
4a58250ed330ee460aa16342e21ed06b0dfde49c
0
lovemomia/mapi,lovemomia/mapi
package cn.momia.mapi.api.v1.im; import cn.momia.api.course.CourseServiceApi; import cn.momia.api.course.dto.CourseSku; import cn.momia.api.im.ImServiceApi; import cn.momia.api.im.dto.Group; import cn.momia.api.im.dto.GroupMember; import cn.momia.api.im.dto.UserGroup; import cn.momia.api.user.UserServiceApi; import cn.momia.api.user.dto.User; import cn.momia.common.core.http.MomiaHttpResponse; import cn.momia.mapi.api.AbstractApi; import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Sets; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; 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 java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @RestController @RequestMapping("/v1/im") public class ImV1Api extends AbstractApi { @Autowired private CourseServiceApi courseServiceApi; @Autowired private ImServiceApi imServiceApi; @Autowired private UserServiceApi userServiceApi; @RequestMapping(value = "/token", method = RequestMethod.POST) public MomiaHttpResponse generateImToken(@RequestParam String utoken) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; User user = userServiceApi.get(utoken); return MomiaHttpResponse.SUCCESS(doGenerateImToken(user)); } private String doGenerateImToken(User user) { String imToken = imServiceApi.generateImToken(user.getId(), user.getNickName(), completeSmallImg(user.getAvatar())); if (!StringUtils.isBlank(imToken)) userServiceApi.updateImToken(user.getToken(), imToken); return imToken; } @RequestMapping(value = "/token", method = RequestMethod.GET) public MomiaHttpResponse getImToken(@RequestParam String utoken) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; User user = userServiceApi.get(utoken); String imToken = user.getImToken(); if (StringUtils.isBlank(imToken)) imToken = doGenerateImToken(user); return MomiaHttpResponse.SUCCESS(imToken); } @RequestMapping(value = "/user", method = RequestMethod.GET) public MomiaHttpResponse getImUserInfo(@RequestParam(value = "uid") long userId) { if (userId <= 0) return MomiaHttpResponse.BAD_REQUEST; User user = userServiceApi.get(userId); JSONObject imUserInfoJson = createImUserInfo(user); List<String> latestImgs = courseServiceApi.getLatestImgs(userId); if (!latestImgs.isEmpty()) { imUserInfoJson.put("imgs", completeMiddleImgs(latestImgs)); } return MomiaHttpResponse.SUCCESS(imUserInfoJson); } private JSONObject createImUserInfo(User user) { JSONObject imUserInfoJson = new JSONObject(); imUserInfoJson.put("id", user.getId()); imUserInfoJson.put("nickName", user.getNickName()); imUserInfoJson.put("avatar", completeSmallImg(user.getAvatar())); imUserInfoJson.put("role", user.getRole()); return imUserInfoJson; } @RequestMapping(value = "/group", method = RequestMethod.GET) public MomiaHttpResponse getGroupInfo(@RequestParam(value = "id") long groupId) { if (groupId <= 0) return MomiaHttpResponse.BAD_REQUEST; Group group = imServiceApi.getGroup(groupId); CourseSku sku = courseServiceApi.getSku(group.getCourseId(), group.getCourseSkuId()); JSONObject groupInfo = new JSONObject(); groupInfo.put("groupId", group.getGroupId()); groupInfo.put("groupName", group.getGroupName()); groupInfo.put("tips", courseServiceApi.queryTips(Sets.newHashSet(group.getCourseId())).get(String.valueOf(group.getCourseId()))); groupInfo.put("time", sku.getTime()); groupInfo.put("route", sku.getRoute()); groupInfo.put("address", sku.getPlace().getAddress()); return MomiaHttpResponse.SUCCESS(groupInfo); } @RequestMapping(value = "/group/member", method = RequestMethod.GET) public MomiaHttpResponse listGroupMembers(@RequestParam String utoken, @RequestParam(value = "id") long groupId) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (groupId <= 0) return MomiaHttpResponse.BAD_REQUEST; User user = userServiceApi.get(utoken); List<GroupMember> groupMembers = imServiceApi.listGroupMembers(user.getId(), groupId); Set<Long> userIds = new HashSet<Long>(); for (GroupMember groupMember : groupMembers) { userIds.add(groupMember.getUserId()); } List<User> users = userServiceApi.list(userIds, User.Type.BASE); Map<Long, User> usersMap = new HashMap<Long, User>(); for (User memberUser : users) { usersMap.put(memberUser.getId(), memberUser); } List<JSONObject> teachers = new ArrayList<JSONObject>(); List<JSONObject> customers = new ArrayList<JSONObject>(); for (GroupMember groupMember : groupMembers) { User memberUser = usersMap.get(groupMember.getUserId()); if (memberUser == null) continue; JSONObject imUserJson = createImUserInfo(memberUser); if (groupMember.isTeacher()) teachers.add(imUserJson); else customers.add(imUserJson); } JSONObject responseJson = new JSONObject(); responseJson.put("teachers", teachers); responseJson.put("customers", customers); return MomiaHttpResponse.SUCCESS(responseJson); } @RequestMapping(value = "/user/group", method = RequestMethod.GET) public MomiaHttpResponse listUserGroups(@RequestParam String utoken) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; User user = userServiceApi.get(utoken); List<UserGroup> userGroups = imServiceApi.listUserGroups(user.getId()); Set<Long> courseIds = new HashSet<Long>(); for (UserGroup userGroup : userGroups) { courseIds.add(userGroup.getCourseId()); } Map<Long, String> tipsOfCourses = courseServiceApi.queryTips(courseIds); for (UserGroup userGroup : userGroups) { userGroup.setTips(tipsOfCourses.get(String.valueOf(userGroup.getCourseId()))); } return MomiaHttpResponse.SUCCESS(userGroups); } }
src/main/java/cn/momia/mapi/api/v1/im/ImV1Api.java
package cn.momia.mapi.api.v1.im; import cn.momia.api.course.CourseServiceApi; import cn.momia.api.course.dto.CourseSku; import cn.momia.api.im.ImServiceApi; import cn.momia.api.im.dto.Group; import cn.momia.api.im.dto.GroupMember; import cn.momia.api.im.dto.UserGroup; import cn.momia.api.user.UserServiceApi; import cn.momia.api.user.dto.User; import cn.momia.common.core.http.MomiaHttpResponse; import cn.momia.mapi.api.AbstractApi; import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Sets; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; 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 java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @RestController @RequestMapping("/v1/im") public class ImV1Api extends AbstractApi { @Autowired private CourseServiceApi courseServiceApi; @Autowired private ImServiceApi imServiceApi; @Autowired private UserServiceApi userServiceApi; @RequestMapping(value = "/token", method = RequestMethod.POST) public MomiaHttpResponse generateImToken(@RequestParam String utoken) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; User user = userServiceApi.get(utoken); return MomiaHttpResponse.SUCCESS(doGenerateImToken(user)); } private String doGenerateImToken(User user) { String imToken = imServiceApi.generateImToken(user.getId(), user.getNickName(), completeSmallImg(user.getAvatar())); if (!StringUtils.isBlank(imToken)) userServiceApi.updateImToken(user.getToken(), imToken); return imToken; } @RequestMapping(value = "/token", method = RequestMethod.GET) public MomiaHttpResponse getImToken(@RequestParam String utoken) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; User user = userServiceApi.get(utoken); String imToken = user.getImToken(); if (StringUtils.isBlank(imToken)) imToken = doGenerateImToken(user); return MomiaHttpResponse.SUCCESS(imToken); } @RequestMapping(value = "/user", method = RequestMethod.GET) public MomiaHttpResponse getImUserInfo(@RequestParam(value = "uid") long userId) { if (userId <= 0) return MomiaHttpResponse.BAD_REQUEST; User user = userServiceApi.get(userId); JSONObject imUserInfoJson = createImUserInfo(user); List<String> latestImgs = courseServiceApi.getLatestImgs(userId); if (!latestImgs.isEmpty()) { imUserInfoJson.put("imgs", completeMiddleImgs(latestImgs)); } return MomiaHttpResponse.SUCCESS(imUserInfoJson); } private JSONObject createImUserInfo(User user) { JSONObject imUserInfoJson = new JSONObject(); imUserInfoJson.put("id", user.getId()); imUserInfoJson.put("nickName", user.getNickName()); imUserInfoJson.put("avatar", completeSmallImg(user.getAvatar())); imUserInfoJson.put("role", user.getRole()); return imUserInfoJson; } @RequestMapping(value = "/group", method = RequestMethod.GET) public MomiaHttpResponse getGroupInfo(@RequestParam(value = "id") long groupId) { if (groupId <= 0) return MomiaHttpResponse.BAD_REQUEST; Group group = imServiceApi.getGroup(groupId); CourseSku sku = courseServiceApi.getSku(group.getCourseId(), group.getCourseSkuId()); JSONObject groupInfo = new JSONObject(); groupInfo.put("groupId", group.getGroupId()); groupInfo.put("groupName", group.getGroupName()); groupInfo.put("tips", courseServiceApi.queryTips(Sets.newHashSet(group.getCourseId())).get(String.valueOf(group.getCourseId()))); groupInfo.put("time", sku.getTime()); groupInfo.put("route", sku.getRoute()); groupInfo.put("address", sku.getPlace().getAddress()); return MomiaHttpResponse.SUCCESS(groupInfo); } @RequestMapping(value = "/group/member", method = RequestMethod.GET) public MomiaHttpResponse listGroupMembers(@RequestParam String utoken, @RequestParam(value = "id") long groupId) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (groupId <= 0) return MomiaHttpResponse.BAD_REQUEST; User user = userServiceApi.get(utoken); List<GroupMember> groupMembers = imServiceApi.listGroupMembers(user.getId(), groupId); Set<Long> userIds = new HashSet<Long>(); for (GroupMember groupMember : groupMembers) { userIds.add(groupMember.getUserId()); } List<User> users = userServiceApi.list(userIds, User.Type.BASE); Map<Long, User> usersMap = new HashMap<Long, User>(); for (User memberUser : users) { usersMap.put(memberUser.getId(), memberUser); } List<JSONObject> teachers = new ArrayList<JSONObject>(); List<JSONObject> customers = new ArrayList<JSONObject>(); for (GroupMember groupMember : groupMembers) { User memberUser = usersMap.get(groupMember.getUserId()); if (memberUser == null) continue; JSONObject imUserJson = createImUserInfo(user); if (groupMember.isTeacher()) teachers.add(imUserJson); else customers.add(imUserJson); } JSONObject responseJson = new JSONObject(); responseJson.put("teachers", teachers); responseJson.put("customers", customers); return MomiaHttpResponse.SUCCESS(responseJson); } @RequestMapping(value = "/user/group", method = RequestMethod.GET) public MomiaHttpResponse listUserGroups(@RequestParam String utoken) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; User user = userServiceApi.get(utoken); List<UserGroup> userGroups = imServiceApi.listUserGroups(user.getId()); Set<Long> courseIds = new HashSet<Long>(); for (UserGroup userGroup : userGroups) { courseIds.add(userGroup.getCourseId()); } Map<Long, String> tipsOfCourses = courseServiceApi.queryTips(courseIds); for (UserGroup userGroup : userGroups) { userGroup.setTips(tipsOfCourses.get(String.valueOf(userGroup.getCourseId()))); } return MomiaHttpResponse.SUCCESS(userGroups); } }
fix bug
src/main/java/cn/momia/mapi/api/v1/im/ImV1Api.java
fix bug
<ide><path>rc/main/java/cn/momia/mapi/api/v1/im/ImV1Api.java <ide> User memberUser = usersMap.get(groupMember.getUserId()); <ide> if (memberUser == null) continue; <ide> <del> JSONObject imUserJson = createImUserInfo(user); <add> JSONObject imUserJson = createImUserInfo(memberUser); <ide> if (groupMember.isTeacher()) teachers.add(imUserJson); <ide> else customers.add(imUserJson); <ide> }
Java
apache-2.0
error: pathspec 'src/main/java/ca/corefacility/bioinformatics/irida/security/permissions/ProjectOwnerPermission.java' did not match any file(s) known to git
81a8a7b148ea5bbb94fd1e9d89cf328dc4cce01e
1
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.security.permissions; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Component; import ca.corefacility.bioinformatics.irida.model.Project; import ca.corefacility.bioinformatics.irida.model.enums.ProjectRole; import ca.corefacility.bioinformatics.irida.model.joins.Join; import ca.corefacility.bioinformatics.irida.model.user.User; import ca.corefacility.bioinformatics.irida.repositories.ProjectRepository; import ca.corefacility.bioinformatics.irida.repositories.joins.project.ProjectUserJoinRepository; import ca.corefacility.bioinformatics.irida.repositories.user.UserRepository; /** * Confirms that a given user is the owner of a project * * @author Thomas Matthews <[email protected]> * */ @Component public class ProjectOwnerPermission extends BasePermission<Project> { private static final Logger logger = LoggerFactory.getLogger(ProjectOwnerPermission.class); private static final String PERMISSION_PROVIDED = "isProjectOwner"; private UserRepository userRepository; private ProjectUserJoinRepository pujRepository; /** * Construct an instance of {@link ReadProjectPermission}. */ @Autowired public ProjectOwnerPermission(ProjectRepository projectRepository, UserRepository userRepository, ProjectUserJoinRepository pujRepository) { super(Project.class, projectRepository); this.userRepository = userRepository; this.pujRepository = pujRepository; } /** * {@inheritDoc} */ @Override public boolean customPermissionAllowed(Authentication authentication, Project p) { logger.trace("Testing permission for [" + authentication + "] has manager permissions on project [" + p + "]"); // check if the user is a project owner for this project User u = userRepository.loadUserByUsername(authentication.getName()); List<Join<Project, User>> projectUsers = pujRepository.getUsersForProjectByRole(p, ProjectRole.PROJECT_OWNER); for (Join<Project, User> projectUser : projectUsers) { if (projectUser.getObject().equals(u)) { logger.trace("Permission GRANTED for [" + authentication + "] on project [" + p + "]"); // this user is an owner for the project. return true; } } logger.trace("Permission DENIED for [" + authentication + "] on project [" + p + "]"); return false; } @Override public String getPermissionProvided() { return PERMISSION_PROVIDED; } }
src/main/java/ca/corefacility/bioinformatics/irida/security/permissions/ProjectOwnerPermission.java
permission for project owners
src/main/java/ca/corefacility/bioinformatics/irida/security/permissions/ProjectOwnerPermission.java
permission for project owners
<ide><path>rc/main/java/ca/corefacility/bioinformatics/irida/security/permissions/ProjectOwnerPermission.java <add>package ca.corefacility.bioinformatics.irida.security.permissions; <add> <add>import java.util.List; <add> <add>import org.slf4j.Logger; <add>import org.slf4j.LoggerFactory; <add>import org.springframework.beans.factory.annotation.Autowired; <add>import org.springframework.security.core.Authentication; <add>import org.springframework.stereotype.Component; <add> <add>import ca.corefacility.bioinformatics.irida.model.Project; <add>import ca.corefacility.bioinformatics.irida.model.enums.ProjectRole; <add>import ca.corefacility.bioinformatics.irida.model.joins.Join; <add>import ca.corefacility.bioinformatics.irida.model.user.User; <add>import ca.corefacility.bioinformatics.irida.repositories.ProjectRepository; <add>import ca.corefacility.bioinformatics.irida.repositories.joins.project.ProjectUserJoinRepository; <add>import ca.corefacility.bioinformatics.irida.repositories.user.UserRepository; <add> <add>/** <add> * Confirms that a given user is the owner of a project <add> * <add> * @author Thomas Matthews <[email protected]> <add> * <add> */ <add>@Component <add>public class ProjectOwnerPermission extends BasePermission<Project> { <add> private static final Logger logger = LoggerFactory.getLogger(ProjectOwnerPermission.class); <add> private static final String PERMISSION_PROVIDED = "isProjectOwner"; <add> <add> private UserRepository userRepository; <add> private ProjectUserJoinRepository pujRepository; <add> <add> /** <add> * Construct an instance of {@link ReadProjectPermission}. <add> */ <add> @Autowired <add> public ProjectOwnerPermission(ProjectRepository projectRepository, UserRepository userRepository, <add> ProjectUserJoinRepository pujRepository) { <add> super(Project.class, projectRepository); <add> this.userRepository = userRepository; <add> this.pujRepository = pujRepository; <add> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> @Override <add> public boolean customPermissionAllowed(Authentication authentication, Project p) { <add> logger.trace("Testing permission for [" + authentication + "] has manager permissions on project [" + p + "]"); <add> // check if the user is a project owner for this project <add> User u = userRepository.loadUserByUsername(authentication.getName()); <add> List<Join<Project, User>> projectUsers = pujRepository.getUsersForProjectByRole(p, ProjectRole.PROJECT_OWNER); <add> <add> for (Join<Project, User> projectUser : projectUsers) { <add> if (projectUser.getObject().equals(u)) { <add> logger.trace("Permission GRANTED for [" + authentication + "] on project [" + p + "]"); <add> // this user is an owner for the project. <add> return true; <add> } <add> } <add> <add> logger.trace("Permission DENIED for [" + authentication + "] on project [" + p + "]"); <add> return false; <add> } <add> <add> @Override <add> public String getPermissionProvided() { <add> return PERMISSION_PROVIDED; <add> } <add>}
Java
apache-2.0
ac583aeeea951319100742a23257501e24b85c11
0
ingokegel/invientcharts,ingokegel/invientcharts
/* * Copyright 2011 Invient (www.invient.com) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.invient.vaadin.charts.widgetset.client.ui; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsArrayNumber; import com.google.gwt.core.client.JsArrayString; import com.invient.vaadin.charts.widgetset.client.ui.GwtInvientChartsConfig.*; import com.invient.vaadin.charts.widgetset.client.ui.GwtInvientChartsConfig.GwtAxisBaseOptions.*; import com.invient.vaadin.charts.widgetset.client.ui.GwtInvientChartsConfig.GwtChartLabels.GwtChartLabelItem; import com.invient.vaadin.charts.widgetset.client.ui.GwtInvientChartsConfig.GwtChartOptions.GwtChartEvents; import com.invient.vaadin.charts.widgetset.client.ui.GwtInvientChartsConfig.GwtPlotOptions.*; import com.invient.vaadin.charts.widgetset.client.ui.GwtInvientChartsConfig.GwtPlotOptions.GwtMarker.GwtMarkerStates; import com.invient.vaadin.charts.widgetset.client.ui.GwtInvientChartsConfig.GwtPlotOptions.GwtMarker.GwtMarkerStates.GwtMarkerState; import com.invient.vaadin.charts.widgetset.client.ui.GwtInvientChartsConfig.GwtPlotOptions.GwtSeriesGeneralOptions.GwtStates; import com.invient.vaadin.charts.widgetset.client.ui.GwtInvientChartsConfig.GwtPlotOptions.GwtSeriesGeneralOptions.GwtStates.GwtHover; import com.invient.vaadin.charts.widgetset.client.ui.GwtInvientChartsConfig.GwtPointOptions.GwtPointEvents; import com.invient.vaadin.charts.widgetset.client.ui.GwtInvientChartsConfig.GwtXAxisOptions.GwtDateTimeLabelFormats; import com.vaadin.terminal.gwt.client.ApplicationConnection; import com.vaadin.terminal.gwt.client.Paintable; import com.vaadin.terminal.gwt.client.UIDL; import com.vaadin.terminal.gwt.client.VConsole; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Client side widget which communicates with the server. Messages from the * server are shown as HTML and mouse clicks are sent to the server. * * Reads data from UIDL and create appropriate JavaScript overlay objects such * as {@link GwtChart}, {@link GwtAxis}, {@link GwtInvientChartsConfig}, * {@link GwtPoint} and {@link GwtSeries} * * Uses a method newChart() of {@link GwtInvientChartsUtil} to create a chart * object of type {@link GwtChart} * * @author Invient */ public class VInvientCharts extends GwtInvientCharts implements Paintable /* * , * ClickHandler * , * ScrollHandler */{ private static final long serialVersionUID = -762763091427791681L; /** Set the CSS class name to allow styling. */ public static final String CLASSNAME = "v-invientcharts"; /** The client side widget identifier */ protected String uidlId; /** Reference to the server connection object. */ protected ApplicationConnection client; /** * The constructor should first call super() to initialize the component and * then handle any initialization relevant to Vaadin. */ public VInvientCharts() { super(); setStyleName(CLASSNAME); publish(); } /** * Called whenever an update is received from the server */ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { VConsole.log("Enter [updateFromUIDL]"); // This call should be made first. // It handles sizes, captions, tooltips, etc. automatically. if (client.updateComponent(this, uidl, true)) { // If client.updateComponent returns true there has been no changes // and we // do not need to update anything. return; } // Save reference to server connection object to be able to send // user interaction later this.client = client; // Save the client side identifier (paintable id) for the widget uidlId = uidl.getId(); // Create chart only once along with chart options // Chart options are set only once. if (chart == null) { // Chart options GwtInvientChartsConfig options = getInvientChartOptions(uidl .getChildUIDL(ChartUIDLIndex.OPTIONS.ordinal())); // Chart events updateOptionsWithEvents(options, uidl.getChildUIDL(ChartUIDLIndex.EVENTS.ordinal())); // Chart data JsArray<GwtSeriesDataOptions> chartData = getChartData(uidl .getChildUIDL(ChartUIDLIndex.DATA.ordinal())); options.setSeriesInstanceOptions(chartData); VConsole.log("Going to create a chart."); createChart(options); } else { resetRedrawChart(); if (uidl.getBooleanAttribute("reloadChartSeries")) { // Get all series and add them to chart JsArray<GwtSeriesDataOptions> chartData = getChartData(uidl .getChildUIDL(ChartUIDLIndex.DATA.ordinal())); int seriesCount = chart.getSeries().length(); VConsole.log("# of series the chart has " + seriesCount); VConsole.log("Going to remove all series of the chart."); for (int ind = seriesCount - 1; ind >= 0; ind--) { setRedrawChart(); chart.getSeries().get(ind).remove(false); } VConsole.log("Goint to add series to the chart."); for (int ind = 0; ind < chartData.length(); ind++) { setRedrawChart(); chart.addSeries(chartData.get(ind), false); } } else { VConsole.log("Going to update chart data."); UIDL chartDataUIDL = uidl.getChildUIDL(ChartUIDLIndex.DATA .ordinal()); UIDL chartDataUpdatesUIDL = uidl .getChildUIDL(ChartUIDLIndex.DATA_UPDATES.ordinal()); updateChartData(chartDataUpdatesUIDL, chartDataUIDL); } // Options UIDL UIDL optionsUIDL = uidl.getChildUIDL(ChartUIDLIndex.OPTIONS .ordinal()); // Update chart title & subtitle setChartTitleAndSubtitle(optionsUIDL); // Size setChartSize(optionsUIDL); VConsole.log("Getting x-axis options..."); JsArray<GwtXAxisOptions> uidlXAxesOptionsArr = getXAxisOptions(optionsUIDL .getChildUIDL(ChartOptionsUIDLIndex.X_AXES.ordinal())); JsArray<GwtXAxisOptions> chartXAxesOptionsArr = JavaScriptObject .createArray().cast(); JsArray<GwtAxis> chartXAxesArr = chart.getXAxes(); if (chart.getOptions().hasXAxesOptions()) { chartXAxesOptionsArr = chart.getOptions().getXAxesOptions(); updateXAxisCategories(chartXAxesArr, chartXAxesOptionsArr, uidlXAxesOptionsArr); } updateAxesPlotBandsAndPlotLines(chartXAxesArr, chartXAxesOptionsArr, uidlXAxesOptionsArr); VConsole.log("Getting y-axis options..."); JsArray<GwtYAxisOptions> uidlYAxesOptionsArr = getYAxisOptions(optionsUIDL .getChildUIDL(ChartOptionsUIDLIndex.Y_AXES.ordinal())); JsArray<GwtYAxisOptions> chartYAxesOptionsArr = JavaScriptObject .createArray().cast(); if (chart.getOptions().hasYAxesOptions()) { chartYAxesOptionsArr = chart.getOptions().getYAxesOptions(); } JsArray<GwtAxis> chartYAxesArr = chart.getYAxes(); updateAxesPlotBandsAndPlotLines(chartYAxesArr, chartYAxesOptionsArr, uidlYAxesOptionsArr); // Update axis extremes if (chart.getOptions().hasXAxesOptions() || chart.getOptions().hasYAxesOptions()) { updateAxisExtremes(chart.getXAxes(), chartXAxesOptionsArr, uidlXAxesOptionsArr); updateAxisExtremes(chart.getYAxes(), chartYAxesOptionsArr, uidlYAxesOptionsArr); } if (isRedrawChart()) { VConsole.log("Going to redraw the chart."); chart.redraw(); } } // Get SVG if required and send it to server handleChartSVG(uidl); handlePrint(uidl); VConsole.log("Exit [updateFromUIDL]"); } // Set title & subtitle private void setChartTitleAndSubtitle(UIDL optionsUIDL) { VConsole.log("Enter [setChartTitleAndSubtitle]"); // There is not need to set redrawChart flag as setting title & subtitle // does not require redrawing of the chart. chart.setTitle( getTitleOptions(optionsUIDL .getChildUIDL(ChartOptionsUIDLIndex.TITLE.ordinal())), getSubtitleOptions(optionsUIDL .getChildUIDL(ChartOptionsUIDLIndex.SUBTITLE.ordinal()))); VConsole.log("Exit [setChartTitleAndSubtitle]"); } // Set chart size private void setChartSize(UIDL optionsUIDL) { // There is not need to set redrawChart flag as setting title & subtitle // does not require redrawing of the chart. GwtChartOptions chartOptions = getChartOptions(optionsUIDL .getChildUIDL(ChartOptionsUIDLIndex.CHART_CONFIG.ordinal())); int newWidth = chartOptions.getWidth(); int newHeight = chartOptions.getHeight(); updateChartSize(newWidth, newHeight); } private void updateChartSize(int newWidth, int newHeight) { int existingWidth = chart.getOptions().getChartOptions().getWidth(); int existingHeight = chart.getOptions().getChartOptions().getHeight(); if ((newWidth != -1 && newWidth != existingWidth) || (newHeight != -1 && newHeight != existingHeight)) { VConsole.log("Set chart size."); chart.getOptions().getChartOptions().setWidth(newWidth); chart.getOptions().getChartOptions().setHeight(newHeight); chart.setSize(newWidth, newHeight); } } @Override public void setHeight(String height) { super.setHeight(height); updateChartSize(); } @Override public void setWidth(String width) { super.setWidth(width); updateChartSize(); } private void updateChartSize() { if (chart != null) { updateChartSize(getElement().getOffsetWidth(), getElement().getOffsetHeight()); } } private void handlePrint(UIDL uidl) { boolean isPrint = uidl.getBooleanAttribute("isPrint"); if (isPrint) { VConsole.log("Going to print the chart..."); chart.printInvientChart(); } } private void handleChartSVG(UIDL uidl) { boolean isRetrieveSVG = uidl.getBooleanAttribute("isRetrieveSVG"); if (isRetrieveSVG) { VConsole.log("Get an svg string..."); String svg = chart.getSVG(null); // send svg to server client.updateVariable(uidlId, "event", "chartSVGAvailable", false); Map<String, Object> eventData = new HashMap<String, Object>(); eventData.put("svg", svg); client.updateVariable(uidlId, "eventData", eventData, true); } } private void updateXAxisCategories(JsArray<GwtAxis> chartAxesArr, JsArray<GwtXAxisOptions> chartXAxesOptionsArr, JsArray<GwtXAxisOptions> uidlXAxesOptionsArr) { VConsole.log("Enter [updateXAxisCategories]"); if (chartXAxesOptionsArr == null || chartXAxesOptionsArr.length() == 0) { VConsole.log("Chart doesn't have any X axis]"); VConsole.log("Exit [updateXAxisCategories]"); return; } int noOfAxis = chartXAxesOptionsArr.length(); for (int ind = 0; ind < noOfAxis; ind++) { GwtAxis chartAxis = chartAxesArr.get(ind); GwtXAxisOptions chartAxisOptions = chartXAxesOptionsArr.get(ind); GwtXAxisOptions uidlAxisOptions = uidlXAxesOptionsArr.get(ind); if (chartAxis != null && chartAxisOptions != null && uidlAxisOptions != null) { // If axis if (!areStringArraysEqual(uidlAxisOptions.getCategories(), chartAxis.getCategories())) { setRedrawChart(); chartAxisOptions.setCategories(uidlAxisOptions .getCategories()); chartAxis.setCategories(uidlAxisOptions.getCategories(), false); } } } VConsole.log("Exit [updateXAxisCategories]"); } private boolean areStringArraysEqual(JsArrayString arrOne, JsArrayString arrTwo) { if (arrOne == arrTwo) { return true; } if ((arrOne != null && arrTwo == null) || (arrOne == null && arrTwo != null)) { return false; } if (arrOne.length() != arrTwo.length()) { return false; } // Compare each array element for (int arrInd = 0; arrInd < arrOne.length(); arrInd++) { String arrOneVal = arrOne.get(arrInd); String arrTwoVal = arrTwo.get(arrInd); if (arrOneVal == null) { if (arrTwoVal != null) { return false; } } else if(!arrOneVal.equals(arrTwoVal)) { return false; } } return true; } private void updateAxisExtremes(JsArray<GwtAxis> chartAxesArr, JsArray<? extends GwtAxisBaseOptions> chartAxesOptionsArr, JsArray<? extends GwtAxisBaseOptions> uidlAxesOptionsArr) { VConsole.log("Enter [updateAxisExtremes]"); if (chartAxesOptionsArr == null || chartAxesOptionsArr.length() == 0) { VConsole.log("Chart doesn't have any X/Y axis]"); VConsole.log("Exit [updateAxisExtremes]"); return; } int noOfAxis = chartAxesOptionsArr.length(); for (int ind = 0; ind < noOfAxis; ind++) { GwtAxis chartAxis = chartAxesArr.get(ind); GwtAxisBaseOptions chartAxisOptions = chartAxesOptionsArr.get(ind); GwtAxisBaseOptions uidlAxisOptions = uidlAxesOptionsArr.get(ind); if (chartAxis != null && chartAxisOptions != null && uidlAxisOptions != null) { double uidlMin = uidlAxisOptions.getMin(); double uidlMax = uidlAxisOptions.getMax(); double chartMin = chartAxisOptions.getMin(); double chartMax = chartAxisOptions.getMax(); // Update chart's axis options as // it is not updated when extremes are set using // axis.setExtremes() if (uidlMin != chartMin) { setRedrawChart(); chartAxisOptions.setMin(uidlMin); } if (uidlMax != chartMax) { setRedrawChart(); chartAxisOptions.setMax(uidlMax); } VConsole.log("[updateAxisExtremes] min " + chartAxisOptions.getMin() + ", max " + chartAxisOptions.getMax()); chartAxis.setExtremes(chartAxisOptions.getMin(), chartAxisOptions.getMax(), false); } } VConsole.log("Exit [updateAxisExtremes]"); } private enum ChartUIDLIndex { OPTIONS, DATA, EVENTS, DATA_UPDATES; } private enum ChartOptionsUIDLIndex { TITLE, SUBTITLE, CREDIT, LEGEND, TOOLTIP, CHART_CONFIG, SERIES_OPTIONS, X_AXES, Y_AXES, LABEL; } private void updateAxesPlotBandsAndPlotLines( JsArray<? extends GwtAxis> chartAxesArr, JsArray<? extends GwtAxisBaseOptions> chartAxesOptionsArr, JsArray<? extends GwtAxisBaseOptions> uidlAxesOptionsArr) { VConsole.log("Enter [updateAxesPlotBandsAndPlotLines]"); int noOfAxis = chartAxesArr.length(); for (int ind = 0; ind < noOfAxis; ind++) { GwtAxis chartAxis = chartAxesArr.get(ind); GwtAxisBaseOptions chartAxisOptions = chartAxesOptionsArr.get(ind); GwtAxisBaseOptions uidlAxisOptions = uidlAxesOptionsArr.get(ind); if (chartAxis != null && chartAxisOptions != null && uidlAxisOptions != null) { updatePlotBands(chartAxis, chartAxisOptions, uidlAxisOptions); updatePlotLines(chartAxis, chartAxisOptions, uidlAxisOptions); } } VConsole.log("Exit [updateAxesPlotBandsAndPlotLines]"); } // private void updatePlotLines(GwtAxis chartAxis, GwtAxisBaseOptions chartAxisOptions, GwtAxisBaseOptions uidlAxisOptions) { VConsole.log("Enter [updatePlotLines]"); // Update chartAxisPlotBands whenever a plotline is added or removed as // the library // does not update chart options by itself. JsArray<GwtPlotLines> chartAxisPlotLines = chartAxisOptions .getPlotLines(); JsArray<GwtPlotLines> uidlAxisPlotLines = uidlAxisOptions .getPlotLines(); if (uidlAxisPlotLines == null && chartAxisPlotLines == null) { VConsole.log("No plotlines found."); VConsole.log("Exit [updatePlotLines]"); return; } if (uidlAxisPlotLines == null) { uidlAxisPlotLines = JavaScriptObject.createArray().cast(); } if (chartAxisPlotLines == null) { chartAxisPlotLines = JavaScriptObject.createArray().cast(); } JsArray<GwtPlotLines> updatedChartAxisPlotLines = JavaScriptObject .createArray().cast(); int numOfChartAxisPlotLines = chartAxisPlotLines.length(); int numOfUIDLAxisPlotLines = uidlAxisPlotLines.length(); boolean updatedAxisPlotLines = false; for (int indOuter = 0; indOuter < numOfChartAxisPlotLines; indOuter++) { GwtPlotLines chartPlotLine = chartAxisPlotLines.get(indOuter); String plotLineId = chartPlotLine.getId(); boolean found = false; for (int indInner = 0; indInner < numOfUIDLAxisPlotLines; indInner++) { GwtPlotLines uidlPlotLine = uidlAxisPlotLines.get(indInner); if (uidlPlotLine != null && uidlPlotLine.getId().equals(plotLineId)) { if (uidlPlotLine.getValue() == chartPlotLine.getValue()) { // PlotLine exists and value is same so no action should // be taken except marking UIDL PlotLine to null. // Setting UIDL PlotLine // to null ensures that remaining PlotLines in UIDL can // be added // safely to the chart. uidlAxisPlotLines.set(indInner, null); updatedChartAxisPlotLines.push(chartPlotLine); found = true; } break; } } if (!found) { // remove plot line as it is not found in UIDL received from the // server updatedAxisPlotLines = true; chartAxis.removePlotLine(plotLineId); } } // Add all remaining plot lines in UIDL to the chart for (int ind = 0; ind < numOfUIDLAxisPlotLines; ind++) { GwtPlotLines uidlPlotLine = uidlAxisPlotLines.get(ind); if (uidlPlotLine != null) { updatedAxisPlotLines = true; chartAxis.addPlotLine(uidlPlotLine); updatedChartAxisPlotLines.push(uidlPlotLine); } } // Update chart axis plotlines if (updatedAxisPlotLines) { setRedrawChart(); chartAxisOptions.setPlotLines(updatedChartAxisPlotLines); } VConsole.log("Exit [updatePlotLines]"); } // private void updatePlotBands(GwtAxis chartAxis, GwtAxisBaseOptions chartAxisOptions, GwtAxisBaseOptions uidlAxisOptions) { VConsole.log("Enter [updatePlotBands]"); // Update chartAxisPlotBands whenever a plotband is added or removed as // the library // does not update chart options by itself. JsArray<GwtPlotBands> chartAxisPlotBands = chartAxisOptions .getPlotBands(); JsArray<GwtPlotBands> uidlAxisPlotBands = uidlAxisOptions .getPlotBands(); if (uidlAxisPlotBands == null && chartAxisPlotBands == null) { VConsole.log("No plotbands found."); VConsole.log("Exit [updatePlotBands]"); return; } if (uidlAxisPlotBands == null) { uidlAxisPlotBands = JavaScriptObject.createArray().cast(); } if (chartAxisPlotBands == null) { chartAxisPlotBands = JavaScriptObject.createArray().cast(); } JsArray<GwtPlotBands> updatedChartAxisPlotBands = JavaScriptObject .createArray().cast(); int numOfChartAxisPlotBands = chartAxisPlotBands.length(); int numOfUIDLAxisPlotBands = uidlAxisPlotBands.length(); boolean updatedAxisPlotBands = false; for (int indOuter = 0; indOuter < numOfChartAxisPlotBands; indOuter++) { GwtPlotBands chartPlotBand = chartAxisPlotBands.get(indOuter); String plotBandId = chartPlotBand.getId(); boolean found = false; for (int indInner = 0; indInner < numOfUIDLAxisPlotBands; indInner++) { GwtPlotBands uidlPlotBand = uidlAxisPlotBands.get(indInner); if (uidlPlotBand != null && uidlPlotBand.getId().equals(plotBandId)) { if (chartPlotBand.getFrom() == uidlPlotBand.getFrom() && chartPlotBand.getTo() == uidlPlotBand.getTo()) { VConsole.log("Plotband id " + plotBandId + " exists in chart as well as in UIDL from the server."); // PlotBand exists and from/to values are same so // nothing to be done. // The UIDL plotband is set to null so that remaining // plotbands // can be safely added to the chart uidlAxisPlotBands.set(indInner, null); updatedChartAxisPlotBands.push(chartPlotBand); VConsole.log("Plotband id " + plotBandId + " exists in both."); found = true; } break; } } if (!found) { // remove plot band as it is not found in UIDL received from the // server VConsole.log("Plotband id " + plotBandId + " removed."); updatedAxisPlotBands = true; chartAxis.removePlotBand(plotBandId); } } // Add all remaining plot bands in UIDL to the chart for (int ind = 0; ind < numOfUIDLAxisPlotBands; ind++) { GwtPlotBands uidlPlotBand = uidlAxisPlotBands.get(ind); if (uidlPlotBand != null) { updatedAxisPlotBands = true; VConsole.log("Plotband id " + uidlPlotBand.getId() + " added with from : " + uidlPlotBand.getFrom() + " and to: " + uidlPlotBand.getTo()); chartAxis.addPlotBand(uidlPlotBand); updatedChartAxisPlotBands.push(uidlPlotBand); } } // Update chart axis plotbands if (updatedAxisPlotBands) { setRedrawChart(); chartAxisOptions.setPlotBands(updatedChartAxisPlotBands); } VConsole.log("Exit [updatePlotBands]"); } private boolean redrawChart = false; private void setRedrawChart() { this.redrawChart = true; } private boolean isRedrawChart() { return this.redrawChart; } private void resetRedrawChart() { this.redrawChart = false; } private void updateChartData(UIDL uidlChartDataUpdates, UIDL uidlChartData) { VConsole.log("Enter [updateChartData]"); JsArrayString seriesToAdd = JavaScriptObject.createArray().cast(); JsArrayString seriesToUpdate = JavaScriptObject.createArray().cast(); List<UIDL> seriesToUpdateList = new ArrayList<UIDL>(); for (int ind = 0; ind < uidlChartDataUpdates.getChildCount(); ind++) { UIDL seriesUpdateUIDL = uidlChartDataUpdates.getChildUIDL(ind); String seriesName = seriesUpdateUIDL .getStringAttribute("seriesName"); String operation = seriesUpdateUIDL.getStringAttribute("operation"); VConsole.log("Series name : " + seriesName + ", operation : " + operation); if (seriesName != null && seriesName.length() > 0 && operation != null && operation.length() > 0) { if (SeriesCURType.REMOVE.getName().equals(operation)) { GwtSeries series = chart.getSeries(seriesName); if (series != null) { VConsole.log("Removing series : " + seriesName); setRedrawChart(); series.remove(false); } } else if (SeriesCURType.ADD.getName().equals(operation)) { seriesToAdd.push(seriesName); } else if (SeriesCURType.UPDATE.getName().equals(operation)) { VConsole.log("Will update series : " + seriesName); seriesToUpdateList.add(seriesUpdateUIDL); seriesToUpdate.push(seriesName); } } } if (seriesToAdd.length() > 0) { setRedrawChart(); JsArray<GwtSeriesDataOptions> uidlChartDataArr = getChartData( uidlChartData, seriesToAdd); for (int ind = 0; ind < uidlChartDataArr.length(); ind++) { VConsole.log("Adding series " + uidlChartDataArr.get(ind).getName()); chart.addSeries(uidlChartDataArr.get(ind), false); } } if (seriesToUpdateList.size() > 0) { setRedrawChart(); JsArray<GwtSeriesDataOptions> uidlChartDataArr = getChartData( uidlChartData, seriesToUpdate); for (int ind = 0; ind < seriesToUpdateList.size(); ind++) { UIDL uidlSeriesToUpdate = seriesToUpdateList.get(ind); GwtSeriesDataOptions uidlSeriesDataOptions = uidlChartDataArr .get(ind); GwtSeries chartSeries = chart.getSeries(uidlSeriesDataOptions .getName()); GwtSeriesGeneralOptions chartSeriesOptions = chartSeries .getSeriesGeneralOptions(); GwtSeriesGeneralOptions uidlSeriesOptions = uidlSeriesDataOptions .getSeriesOptions(); // Update visibility boolean isVisible = (uidlSeriesOptions != null ? uidlSeriesOptions .isVisible() : true); chartSeriesOptions.setVisible(isVisible); if (chartSeriesOptions.isVisible() == true && chartSeries.isVisible() == false) { chartSeries.show(); } if (chartSeriesOptions.isVisible() == false && chartSeries.isVisible() == true) { chartSeries.hide(); } // Update points if (uidlSeriesToUpdate.getBooleanAttribute("isReloadPoints")) { // update all points VConsole.log("Reloading points for series : " + uidlSeriesToUpdate.getStringAttribute("name")); chartSeries.setDataAsPointOptions( uidlSeriesDataOptions.getDataAsPointOptions(), false); } else { UIDL uidlPointsAdded = uidlSeriesToUpdate.getChildUIDL(0); UIDL uidlPointsRemoved = uidlSeriesToUpdate.getChildUIDL(1); updateSeriesData(chartSeries, uidlPointsAdded, uidlPointsRemoved); } } } VConsole.log("Exit [updateChartData]"); } private void updateSeriesData(GwtSeries chartSeries, UIDL uidlPointsAdded, UIDL uidlPointsRemoved) { VConsole.log("Enter [updateSeriesData]"); if (uidlPointsAdded != null && uidlPointsAdded.getChildCount() > 0) { // Add points JsArray<GwtPointOptions> pointsTobeAdded = getSeriesPoints(uidlPointsAdded); VConsole.log("# of points to be added : " + pointsTobeAdded.length()); for (int cnt = 0; cnt < pointsTobeAdded.length(); cnt++) { GwtPointOptions pointOptions = pointsTobeAdded.get(cnt); chartSeries.addPoint(pointOptions, false, pointOptions.isShift()); } } if (uidlPointsRemoved != null && uidlPointsRemoved.getChildCount() > 0) { // Remove points JsArray<GwtPointOptions> pointsTobeRemoved = getSeriesPoints(uidlPointsRemoved); VConsole.log("# of points to be removed : " + pointsTobeRemoved.length()); JsArray<GwtPoint> chartSeriesData = chartSeries.getData(); for (int cnt = 0; cnt < pointsTobeRemoved.length(); cnt++) { GwtPointOptions pointToRemove = pointsTobeRemoved.get(cnt); for (int chartPointCnt = 0; chartPointCnt < chartSeriesData .length(); chartPointCnt++) { GwtPoint chartSeriesPoint = chartSeriesData .get(chartPointCnt); // Using Double.compareTo(another Double) does not result in // appr. code which can be executed in JS correctly. // e.g. x.compareTo(y) results in compare(x.value, y.value) // where x.value is undefined in JS, // Don't know the reason yet but will figure out. So do a // direct comparison if (chartSeriesPoint.getX() == pointToRemove.getX() && chartSeriesPoint.getY() == pointToRemove.getY()) { VConsole.log("Removing point (" + chartSeriesPoint.getX() + ", " + chartSeriesPoint.getY() + ")"); chartSeriesPoint.remove(); break; } } } } VConsole.log("Exit [updateSeriesData]"); } private static enum SeriesCURType { ADD("Add"), UPDATE("Update"), REMOVE("Remove"); private String name; private SeriesCURType(String name) { this.name = name; } public String getName() { return this.name; } } private JsArray<GwtSeriesDataOptions> getChartData(UIDL uidl) { return getChartData(uidl, null); } private boolean doesArrayContainSeriesName( JsArrayString namesOfSeriesToAdd, String seriesName) { for (int ind = 0; ind < namesOfSeriesToAdd.length(); ind++) { if (seriesName.equals(namesOfSeriesToAdd.get(ind))) { return true; } } return false; } private JsArray<GwtSeriesDataOptions> getChartData(UIDL uidl, JsArrayString namesOfSeriesToAdd) { VConsole.log("Enter [getChartData]"); JsArray<GwtSeriesDataOptions> seriesDataArr = JavaScriptObject .createArray().cast(); // Process each series data for (int cnt = 0; cnt < uidl.getChildCount(); cnt++) { GwtSeriesDataOptions seriesData = GwtSeriesDataOptions.create(); UIDL seriesUIDL = uidl.getChildUIDL(cnt); String seriesName = seriesUIDL.getStringAttribute("name"); if (seriesName != null && namesOfSeriesToAdd != null) { if (!doesArrayContainSeriesName(namesOfSeriesToAdd, seriesName)) { continue; } } // From charts series data retrieve only those series data // whose names are specified in the second argument if (seriesUIDL.hasAttribute("name")) { // Setting name automatically sets series id which can later be // used to retrieve using chart.get(id); seriesData.setName(seriesName); } if (seriesUIDL.hasAttribute("stack")) { seriesData.setStack(seriesUIDL.getStringAttribute("stack")); } // FIXME - fallback on chart options type if series doesn't have a // type String seriesType = "line"; if (seriesUIDL.hasAttribute("type")) { seriesType = seriesUIDL.getStringAttribute("type"); seriesData.setType(seriesType); } if (seriesUIDL.hasAttribute("xAxis")) { seriesData.setXAxis(seriesUIDL.getIntAttribute("xAxis")); } if (seriesUIDL.hasAttribute("yAxis")) { seriesData.setYAxis(seriesUIDL.getIntAttribute("yAxis")); } // Get data/points seriesData.setDataAsPointOptions(getSeriesPoints(seriesUIDL .getChildUIDL(1))); // Get series options GwtSeriesGeneralOptions seriesOptions = getSeriesOptions( seriesType, seriesUIDL.getChildUIDL(0)); if (seriesOptions != null) { seriesData.setSeriesOptions(seriesOptions); } seriesDataArr.push(seriesData); } VConsole.log("Exit [getChartData]"); return seriesDataArr; } private JsArray<GwtPointOptions> getSeriesPoints(UIDL pointsUIDL) { VConsole.log("Enter [getSeriesPoints]"); JsArray<GwtPointOptions> pointsArr = JavaScriptObject.createArray() .cast(); for (int cnt = 0; cnt < pointsUIDL.getChildCount(); cnt++) { UIDL pointUIDL = pointsUIDL.getChildUIDL(cnt); GwtPointOptions pointOptions = GwtPointOptions.create(); // If a point doesn't have any attributes then // consider it as a null since a user might want to represent // no activity graph if (pointUIDL.getAttributeNames().size() == 0) { pointOptions.setNullY(); } else { if (pointUIDL.hasAttribute("id")) { pointOptions.setId(pointUIDL.getStringAttribute("id")); } if (pointUIDL.hasAttribute("name")) { pointOptions.setName(pointUIDL.getStringAttribute("name")); } if (pointUIDL.hasAttribute("color")) { pointOptions .setColor(pointUIDL.getStringAttribute("color")); } if (pointUIDL.hasAttribute("sliced")) { pointOptions.setSliced(pointUIDL .getBooleanAttribute("sliced")); } if (pointUIDL.hasAttribute("selected")) { pointOptions.setSelected(pointUIDL .getBooleanAttribute("selected")); } if (pointUIDL.hasAttribute("x")) { pointOptions.setX(pointUIDL.getIntAttribute("x")); } else { pointOptions.setNullX(); } if (pointUIDL.hasAttribute("y")) { pointOptions.setY(pointUIDL.getIntAttribute("y")); } else { pointOptions.setNullY(); } if (pointUIDL.hasAttribute("isShift")) { pointOptions.setShift(pointUIDL .getBooleanAttribute("isShift")); } GwtMarker markerOptions = getMarkerOptions(pointUIDL .getChildUIDL(0)); if (markerOptions != null) { pointOptions.setMarker(markerOptions); } } pointsArr.push(pointOptions); } VConsole.log("Exit [getSeriesPoints]"); return pointsArr; } private GwtInvientChartsConfig getInvientChartOptions(UIDL uidl) { VConsole.log("Enter [getInvientChartOptions]"); VConsole.log("Child UIDL count : " + uidl.getChildCount()); GwtInvientChartsConfig options = GwtInvientChartsConfig.create(); // Get title UIDL VConsole.log("Getting title options..."); // Title options.setTitleOptions(getTitleOptions(uidl .getChildUIDL(ChartOptionsUIDLIndex.TITLE.ordinal()))); VConsole.log("Getting subtitle options..."); // Subtitle options.setSubtitleOptions(getSubtitleOptions(uidl .getChildUIDL(ChartOptionsUIDLIndex.SUBTITLE.ordinal()))); // Credit options.setCreditOptions(getCreditOptions(uidl .getChildUIDL(ChartOptionsUIDLIndex.CREDIT.ordinal()))); // Legend options.setLegendOptions(getLegendOptions(uidl .getChildUIDL(ChartOptionsUIDLIndex.LEGEND.ordinal()))); // Tooltip options.setTooltipOptions(getTooltipOptions(uidl .getChildUIDL(ChartOptionsUIDLIndex.TOOLTIP.ordinal()))); // Then DEMO application VConsole.log("Getting chart options..."); // Chart Options options.setChartOptions(getChartOptions(uidl .getChildUIDL(ChartOptionsUIDLIndex.CHART_CONFIG.ordinal()))); VConsole.log("Getting plot options..."); // Plot Options for various series types options.setPlotOptions(getPlotOptions(uidl .getChildUIDL(ChartOptionsUIDLIndex.SERIES_OPTIONS.ordinal()))); VConsole.log("Getting x-axis options..."); JsArray<GwtXAxisOptions> xAxisOptions = getXAxisOptions(uidl .getChildUIDL(ChartOptionsUIDLIndex.X_AXES.ordinal())); if (xAxisOptions.length() > 0) { options.setXAxesOptions(xAxisOptions); } VConsole.log("Getting y-axis options..."); JsArray<GwtYAxisOptions> yAxisOptions = getYAxisOptions(uidl .getChildUIDL(ChartOptionsUIDLIndex.Y_AXES.ordinal())); if (yAxisOptions.length() > 0) { options.setYAxesOptions(yAxisOptions); } VConsole.log("Getting chart labels..."); GwtChartLabels labels = getChartLabels(uidl .getChildUIDL(ChartOptionsUIDLIndex.LABEL.ordinal())); if (labels != null) { options.setLabels(labels); } VConsole.log("Exit [getInvientChartOptions]"); return options; } private GwtChartLabels getChartLabels(UIDL uidl) { VConsole.log("Enter [getChartLabels]"); VConsole.log("Tag name -> " + uidl.getTag()); if ((uidl.getAttributeNames().size() == 0 && uidl.getChildCount() == 0) || (uidl.getAttributeNames().size() > 0 && uidl.getChildCount() == 0)) { VConsole.log("Exit [getChartLabels]"); return null; } UIDL labelItemsUIDL = uidl.getChildUIDL(0); if (labelItemsUIDL.getChildCount() == 0) { VConsole.log("Exit [getChartLabels]"); return null; } GwtChartLabels labels = GwtChartLabels.create(); if (uidl.hasAttribute("style")) { labels.setStyle(uidl.getStringAttribute("style")); } JsArray<GwtChartLabelItem> chartLabelItemsArr = JavaScriptObject .createArray().cast(); for (int cnt = 0; cnt < labelItemsUIDL.getChildCount(); cnt++) { UIDL labelItemUIDL = labelItemsUIDL.getChildUIDL(cnt); if (labelItemUIDL.hasAttribute("html") || labelItemUIDL.hasAttribute("style")) { GwtChartLabelItem labelItem = GwtChartLabelItem.create(); if (labelItemUIDL.hasAttribute("html")) { labelItem.setHtml(labelItemUIDL.getStringAttribute("html")); } // if (labelItemUIDL.hasAttribute("style")) { labelItem.setStyle(labelItemUIDL .getStringAttribute("style")); } chartLabelItemsArr.push(labelItem); } } labels.setItems(chartLabelItemsArr); VConsole.log("Exit [getChartLabels]"); return labels; } private GwtCreditOptions getCreditOptions(UIDL uidl) { VConsole.log("Enter [getCreditOptions]"); VConsole.log("Tag name -> " + uidl.getTag()); GwtCreditOptions creditOptions = GwtCreditOptions.create(); if (uidl.hasAttribute("enabled")) { creditOptions.setEnabled(uidl.getBooleanAttribute("enabled")); } if (uidl.hasAttribute("href")) { creditOptions.setHref(uidl.getStringAttribute("href")); } if (uidl.hasAttribute("style")) { creditOptions.setStyle(uidl.getStringAttribute("style")); } if (uidl.hasAttribute("text")) { creditOptions.setText(uidl.getStringAttribute("text")); } UIDL positionUIDL = uidl.getChildUIDL(0); GwtPosition position = GwtPosition.create(); if (positionUIDL.hasAttribute("align")) { position.setAlign(positionUIDL.getStringAttribute("align")); } if (positionUIDL.hasAttribute("verticalAlign")) { position.setVerticalAlign(positionUIDL .getStringAttribute("verticalAlign")); } if (positionUIDL.hasAttribute("x")) { position.setX(positionUIDL.getIntAttribute("x")); } if (positionUIDL.hasAttribute("y")) { position.setY(positionUIDL.getIntAttribute("y")); } creditOptions.setPosition(position); VConsole.log("Exit [getCreditOptions]"); return creditOptions; } private GwtLegendOptions getLegendOptions(UIDL uidl) { VConsole.log("Enter [getLegendOptions]"); VConsole.log("Tag name -> " + uidl.getTag()); GwtLegendOptions legendOptions = GwtLegendOptions.create(); if (uidl.hasAttribute("align")) { legendOptions.setAlign(uidl.getStringAttribute("align")); } if (uidl.hasAttribute("backgroundColor")) { legendOptions.setBackgroundColor(uidl .getStringAttribute("backgroundColor")); } if (uidl.hasAttribute("borderColor")) { legendOptions .setBorderColor(uidl.getStringAttribute("borderColor")); } if (uidl.hasAttribute("borderRadius")) { legendOptions.setBorderRadius(uidl.getIntAttribute("borderRadius")); } if (uidl.hasAttribute("borderWidth")) { legendOptions.setBorderWidth(uidl.getIntAttribute("borderWidth")); } if (uidl.hasAttribute("enabled")) { legendOptions.setEnabled(uidl.getBooleanAttribute("enabled")); } if (uidl.hasAttribute("floating")) { legendOptions.setFloating(uidl.getBooleanAttribute("floating")); } if (uidl.hasAttribute("itemHiddenStyle")) { legendOptions.setItemHiddenStyle(uidl .getStringAttribute("itemHiddenStyle")); } if (uidl.hasAttribute("itemHoverStyle")) { legendOptions.setItemHoverStyle(uidl .getStringAttribute("itemHoverStyle")); } if (uidl.hasAttribute("itemStyle")) { legendOptions.setItemStyle(uidl.getStringAttribute("itemStyle")); } if (uidl.hasAttribute("itemWidth")) { legendOptions.setItemWidth(uidl.getIntAttribute("itemWidth")); } if (uidl.hasAttribute("layout")) { legendOptions.setLayout(uidl.getStringAttribute("layout")); } if (uidl.hasAttribute("labelFormatter")) { legendOptions.setLabelFormatter(getExecutableFunction(uidl .getStringAttribute("labelFormatter"))); } if (uidl.hasAttribute("margin")) { legendOptions.setMargin(uidl.getIntAttribute("margin")); } if (uidl.hasAttribute("reversed")) { legendOptions.setReversed(uidl.getBooleanAttribute("reversed")); } if (uidl.hasAttribute("shadow")) { legendOptions.setShadow(uidl.getBooleanAttribute("shadow")); } if (uidl.hasAttribute("symbolPadding")) { legendOptions.setSymbolPadding(uidl .getIntAttribute("symbolPadding")); } if (uidl.hasAttribute("symbolWidth")) { legendOptions.setSymbolWidth(uidl.getIntAttribute("symbolWidth")); } if (uidl.hasAttribute("verticalAlign")) { legendOptions.setVerticalAlign(uidl .getStringAttribute("verticalAlign")); } if (uidl.hasAttribute("width")) { legendOptions.setWidth(uidl.getIntAttribute("width")); } if (uidl.hasAttribute("x")) { legendOptions.setX(uidl.getIntAttribute("x")); } if (uidl.hasAttribute("y")) { legendOptions.setY(uidl.getIntAttribute("y")); } VConsole.log("Exit [getLegendOptions]"); return legendOptions; } private GwtTooltipOptions getTooltipOptions(UIDL uidl) { VConsole.log("Enter [getTooltipOptions]"); VConsole.log("Tag name -> " + uidl.getTag()); GwtTooltipOptions tooltipOptions = GwtTooltipOptions.create(); if (uidl.hasAttribute("backgroundColor")) { tooltipOptions.setBackgroundColor(uidl .getStringAttribute("backgroundColor")); } if (uidl.hasAttribute("borderColor")) { tooltipOptions.setBorderColor(uidl .getStringAttribute("borderColor")); } if (uidl.hasAttribute("borderRadius")) { tooltipOptions .setBorderRadius(uidl.getIntAttribute("borderRadius")); } if (uidl.hasAttribute("borderWidth")) { tooltipOptions.setBorderWidth(uidl.getIntAttribute("borderWidth")); } if (uidl.hasAttribute("crosshairs")) { tooltipOptions .setCrosshairs(uidl.getBooleanAttribute("crosshairs")); } if (uidl.hasAttribute("enabled")) { tooltipOptions.setEnabled(uidl.getBooleanAttribute("enabled")); } if (uidl.hasAttribute("formatter")) { tooltipOptions.setFormatter(getExecutableFunction(uidl .getStringAttribute("formatter"))); } if (uidl.hasAttribute("shadow")) { tooltipOptions.setShadow(uidl.getBooleanAttribute("shadow")); } if (uidl.hasAttribute("shared")) { tooltipOptions.setShared(uidl.getBooleanAttribute("shared")); } if (uidl.hasAttribute("snap")) { tooltipOptions.setSnap(uidl.getIntAttribute("snap")); } if (uidl.hasAttribute("style")) { tooltipOptions.setStyle(uidl.getStringAttribute("style")); } if (uidl.hasAttribute("xDateFormat")) { tooltipOptions.setXDateFormat(uidl.getStringAttribute("xDateFormat")); } if (uidl.hasAttribute("pointFormat")) { tooltipOptions.setPointFormat(uidl.getStringAttribute("pointFormat")); } if (uidl.hasAttribute("valueSuffix")) { tooltipOptions.setValueSuffix(uidl.getStringAttribute("valueSuffix")); } if (uidl.hasAttribute("valuePrefix")) { tooltipOptions.setValuePrefix(uidl.getStringAttribute("valuePrefix")); } if (uidl.hasAttribute("footerFormat")) { tooltipOptions.setFooterFormat(uidl.getStringAttribute("footerFormat")); } if (uidl.hasAttribute("valueDecimals")) { tooltipOptions.setValueDecimals(uidl.getIntAttribute("valueDecimals")); } if (uidl.hasAttribute("useHTML")) { tooltipOptions.setUseHtml(uidl.getBooleanAttribute("useHTML")); } VConsole.log("Exit [getTooltipOptions]"); return tooltipOptions; } private GwtTitleOptions getTitleOptions(UIDL uidl) { VConsole.log("Enter [getTitleOptions]"); VConsole.log("Tag Name : " + uidl.getTag()); GwtTitleOptions titleOptions = GwtTitleOptions.createTitleOptions(); updateTitleBaseOptions(uidl, titleOptions); if (uidl.hasAttribute("margin")) { titleOptions.setMargin(uidl.getIntAttribute("margin")); } VConsole.log("Exit [getTitleOptions]"); return titleOptions; } private GwtSubtitleOptions getSubtitleOptions(UIDL uidl) { VConsole.log("Enter [getSubtitleOptions]"); VConsole.log("Tag Name : " + uidl.getTag()); GwtSubtitleOptions subtitleOptions = GwtSubtitleOptions .createSubtitleOptions(); updateTitleBaseOptions(uidl, subtitleOptions); VConsole.log("Exit [getTitleOptions]"); return subtitleOptions; } private void updateTitleBaseOptions(UIDL uidl, GwtTitleBaseOptions titleBaseOptions) { VConsole.log("Enter [updateTitleBaseOptions]"); VConsole.log("Tag Name : " + uidl.getTag()); if (uidl.hasAttribute("text")) { titleBaseOptions.setText(uidl.getStringAttribute("text")); } if (uidl.hasAttribute("align")) { titleBaseOptions.setAlign(uidl.getStringAttribute("align")); } if (uidl.hasAttribute("floating")) { titleBaseOptions.setFloating(uidl.getBooleanAttribute("floating")); } if (uidl.hasAttribute("style")) { titleBaseOptions.setStyle(uidl.getStringAttribute("style")); } if (uidl.hasAttribute("verticalAlign")) { titleBaseOptions.setVerticalAlign(uidl .getStringAttribute("verticalAlign")); } if (uidl.hasAttribute("x")) { titleBaseOptions.setX(uidl.getIntAttribute("x")); } if (uidl.hasAttribute("y")) { titleBaseOptions.setY(uidl.getIntAttribute("y")); } VConsole.log("Exit [updateTitleBaseOptions]"); } private GwtChartOptions getChartOptions(UIDL uidl) { VConsole.log("Enter [getChartOptions]"); VConsole.log("Tag Name : " + uidl.getTag()); GwtChartOptions chartOptions = GwtChartOptions.create(); // DIV - A container for the InvientChart chartOptions.setRenderTo(super.divId); if (uidl.hasAttribute("type")) { chartOptions.setType(uidl.getStringAttribute("type")); } if (uidl.hasAttribute("width")) { chartOptions.setWidth(uidl.getIntAttribute("width")); } if (uidl.hasAttribute("height")) { chartOptions.setHeight(uidl.getIntAttribute("height")); } if (uidl.hasAttribute("backgroundColor")) { chartOptions.setBackgroundColor(uidl .getStringAttribute("backgroundColor")); } if (uidl.hasAttribute("borderColor")) { chartOptions.setBorderColor(uidl.getStringAttribute("borderColor")); } if (uidl.hasAttribute("borderRadius")) { chartOptions.setBorderRadius(uidl.getIntAttribute("borderRadius")); } if (uidl.hasAttribute("borderWidth")) { chartOptions.setBorderWidth(uidl.getIntAttribute("borderWidth")); } if (uidl.hasAttribute("ignoreHiddenSeries")) { chartOptions.setIgnoreHiddenSeries(uidl .getBooleanAttribute("ignoreHiddenSeries")); } if (uidl.hasAttribute("inverted")) { chartOptions.setInverted(uidl.getBooleanAttribute("inverted")); } if (uidl.hasAttribute("marginTop")) { chartOptions.setMarginTop(uidl.getIntAttribute("marginTop")); } if (uidl.hasAttribute("marginLeft")) { chartOptions.setMarginLeft(uidl.getIntAttribute("marginLeft")); } if (uidl.hasAttribute("marginRight")) { chartOptions.setMarginRight(uidl.getIntAttribute("marginRight")); } if (uidl.hasAttribute("marginBottom")) { chartOptions.setMarginBottom(uidl.getIntAttribute("marginBottom")); } if (uidl.hasAttribute("spacingTop")) { chartOptions.setSpacingTop(uidl.getIntAttribute("spacingTop")); } if (uidl.hasAttribute("spacingLeft")) { chartOptions.setSpacingLeft(uidl.getIntAttribute("spacingLeft")); } if (uidl.hasAttribute("spacingRight")) { chartOptions.setSpacingRight(uidl.getIntAttribute("spacingRight")); } if (uidl.hasAttribute("spacingBottom")) { chartOptions .setSpacingBottom(uidl.getIntAttribute("spacingBottom")); } if (uidl.hasAttribute("showAxes")) { chartOptions.setShowAxes(uidl.getBooleanAttribute("showAxes")); } if (uidl.hasAttribute("zoomType")) { chartOptions.setZoomType(uidl.getStringAttribute("zoomType")); } if (uidl.hasAttribute("clientZoom")) { chartOptions.setClientZoom(uidl.getBooleanAttribute("clientZoom")); } if (uidl.hasAttribute("alignTicks")) { chartOptions.setAlignTicks(uidl.getBooleanAttribute("alignTicks")); } if (uidl.hasAttribute("animation")) { chartOptions.setAnimation(uidl.getBooleanAttribute("animation")); } if (uidl.hasAttribute("className")) { chartOptions.setClassName(uidl.getStringAttribute("className")); } if (uidl.hasAttribute("plotBackgroundColor")) { chartOptions.setPlotBackgroundColor(uidl .getStringAttribute("plotBackgroundColor")); } if (uidl.hasAttribute("plotBorderColor")) { chartOptions.setPlotBorderColor(uidl .getStringAttribute("plotBorderColor")); } if (uidl.hasAttribute("plotBackgroundImage")) { chartOptions.setPlotBackgroundImage(uidl .getStringAttribute("plotBackgroundImage")); } if (uidl.hasAttribute("plotBorderWidth")) { chartOptions.setPlotBorderWidth(uidl .getIntAttribute("plotBorderWidth")); } if (uidl.hasAttribute("plotShadow")) { chartOptions.setPlotShadow(uidl.getBooleanAttribute("plotShadow")); } if (uidl.hasAttribute("reflow")) { chartOptions.setReflow(uidl.getBooleanAttribute("reflow")); } if (uidl.hasAttribute("shadow")) { chartOptions.setShadow(uidl.getBooleanAttribute("shadow")); } if (uidl.hasAttribute("style")) { chartOptions.setStyle(uidl.getStringAttribute("style")); } VConsole.log("Exit [getChartOptions]"); return chartOptions; } private void updateBaseAxisOptions(UIDL axisUIDL, GwtAxisBaseOptions axisBaseOptions) { VConsole.log("Enter [updateBaseAxisOptions]"); if (axisUIDL.hasAttribute("id")) { axisBaseOptions.setId(axisUIDL.getStringAttribute("id")); } if (axisUIDL.hasAttribute("allowDecimals")) { axisBaseOptions.setAllowDecimals(axisUIDL .getBooleanAttribute("allowDecimals")); } if (axisUIDL.hasAttribute("alternateGridColor")) { axisBaseOptions.setAlternateGridColor(axisUIDL .getStringAttribute("alternateGridColor")); } if (axisUIDL.hasAttribute("endOnTick")) { axisBaseOptions.setEndOnTick(axisUIDL .getBooleanAttribute("endOnTick")); } // Grid if (axisUIDL.hasAttribute("gridLineColor")) { axisBaseOptions.setGridLineColor(axisUIDL .getStringAttribute("gridLineColor")); } if (axisUIDL.hasAttribute("gridLineWidth")) { axisBaseOptions.setGridLineWidth(axisUIDL .getIntAttribute("gridLineWidth")); } if (axisUIDL.hasAttribute("gridLineDashStyle")) { axisBaseOptions.setGridLineDashStyle(axisUIDL .getStringAttribute("gridLineDashStyle")); } // Line if (axisUIDL.hasAttribute("lineColor")) { axisBaseOptions.setLineColor(axisUIDL .getStringAttribute("lineColor")); } if (axisUIDL.hasAttribute("lineWidth")) { axisBaseOptions.setLineWidth(axisUIDL.getIntAttribute("lineWidth")); } // if (axisUIDL.hasAttribute("linkedTo")) { axisBaseOptions.setLinkedTo(axisUIDL.getIntAttribute("linkedTo")); } if (axisUIDL.hasAttribute("max")) { axisBaseOptions.setMax(axisUIDL.getDoubleAttribute("max")); } if (axisUIDL.hasAttribute("maxPadding")) { axisBaseOptions.setMaxPadding(axisUIDL .getDoubleAttribute("maxPadding")); } if (axisUIDL.hasAttribute("maxZoom")) { axisBaseOptions.setMaxZoom(axisUIDL.getIntAttribute("maxZoom")); } // if (axisUIDL.hasAttribute("min")) { axisBaseOptions.setMin(axisUIDL.getDoubleAttribute("min")); } if (axisUIDL.hasAttribute("minPadding")) { axisBaseOptions.setMinPadding(axisUIDL .getDoubleAttribute("minPadding")); } // Minor Grid if (axisUIDL.hasAttribute("minorGridLineColor")) { axisBaseOptions.setMinorGridLineColor(axisUIDL .getStringAttribute("minorGridLineColor")); } if (axisUIDL.hasAttribute("minorGridLineWidth")) { axisBaseOptions.setMinorGridLineWidth(axisUIDL .getIntAttribute("minorGridLineWidth")); } if (axisUIDL.hasAttribute("minorGridLineDashStyle")) { axisBaseOptions.setMinorGridLineDashStyle(axisUIDL .getStringAttribute("minorGridLineDashStyle")); } // Minor Ticks if (axisUIDL.hasAttribute("minorTickColor")) { axisBaseOptions.setMinorTickColor(axisUIDL .getStringAttribute("minorTickColor")); } if (axisUIDL.hasAttribute("minorTickInterval")) { axisBaseOptions.setMinorTickInterval(axisUIDL .getDoubleAttribute("minorTickInterval")); } if (axisUIDL.hasAttribute("minorTickLength")) { axisBaseOptions.setMinorTickLength(axisUIDL .getIntAttribute("minorTickLength")); } if (axisUIDL.hasAttribute("minorTickPosition")) { axisBaseOptions.setMinorTickPosition(axisUIDL .getStringAttribute("minorTickPosition")); } if (axisUIDL.hasAttribute("minorTickWidth")) { axisBaseOptions.setMinorTickWidth(axisUIDL .getIntAttribute("minorTickWidth")); } // if (axisUIDL.hasAttribute("offset")) { axisBaseOptions.setOffset(axisUIDL.getIntAttribute("offset")); } if (axisUIDL.hasAttribute("opposite")) { axisBaseOptions.setOpposite(axisUIDL .getBooleanAttribute("opposite")); } if (axisUIDL.hasAttribute("reversed")) { axisBaseOptions.setReversed(axisUIDL .getBooleanAttribute("reversed")); } if (axisUIDL.hasAttribute("showFirstLabel")) { axisBaseOptions.setShowFirstLabel(axisUIDL .getBooleanAttribute("showFirstLabel")); } if (axisUIDL.hasAttribute("showLastLabel")) { axisBaseOptions.setShowLastLabel(axisUIDL .getBooleanAttribute("showLastLabel")); } if (axisUIDL.hasAttribute("startOfWeek")) { axisBaseOptions.setStartOfWeek(axisUIDL .getIntAttribute("startOfWeek")); } if (axisUIDL.hasAttribute("startOnTick")) { axisBaseOptions.setStartOnTick(axisUIDL .getBooleanAttribute("startOnTick")); } // Tick if (axisUIDL.hasAttribute("tickColor")) { axisBaseOptions.setTickColor(axisUIDL .getStringAttribute("tickColor")); } if (axisUIDL.hasAttribute("tickInterval")) { axisBaseOptions.setTickInterval(axisUIDL .getDoubleAttribute("tickInterval")); } if (axisUIDL.hasAttribute("tickLength")) { axisBaseOptions.setTickLength(axisUIDL .getIntAttribute("tickLength")); } if (axisUIDL.hasAttribute("tickPosition")) { axisBaseOptions.setTickPosition(axisUIDL .getStringAttribute("tickPosition")); } if (axisUIDL.hasAttribute("tickWidth")) { axisBaseOptions.setTickWidth(axisUIDL.getIntAttribute("tickWidth")); } if (axisUIDL.hasAttribute("tickPixelInterval")) { axisBaseOptions.setTickPixelInterval(axisUIDL .getIntAttribute("tickPixelInterval")); } if (axisUIDL.hasAttribute("tickmarkPlacement")) { axisBaseOptions.setTickmarkPlacement(axisUIDL .getStringAttribute("tickmarkPlacement")); } if (axisUIDL.hasAttribute("type")) { axisBaseOptions.setType(axisUIDL.getStringAttribute("type")); } // title UIDL titleUIDL = axisUIDL.getChildUIDL(0); GwtAxisTitleOptions titleOptions = getAxisTitleOptions(titleUIDL); if (titleOptions != null) { axisBaseOptions.setTitle(titleOptions); } // label UIDL labelUIDL = axisUIDL.getChildUIDL(1); String axisName = axisUIDL.getTag(); GwtAxisDataLabels axisDataLabels = getAxisDataLabels(labelUIDL, axisName); if (axisDataLabels != null) { axisBaseOptions.setLabels(axisDataLabels); } // plotband UIDL plotBandsUIDL = axisUIDL.getChildUIDL(2); JsArray<GwtPlotBands> plotBands = getPlotBands(plotBandsUIDL); if (plotBands.length() > 0) { axisBaseOptions.setPlotBands(plotBands); } // plotline UIDL plotLinesUIDL = axisUIDL.getChildUIDL(3); JsArray<GwtPlotLines> plotLines = getPlotLines(plotLinesUIDL); if (plotLines.length() > 0) { axisBaseOptions.setPlotLines(plotLines); } VConsole.log("Exit [updateBaseAxisOptions]"); } private GwtAxisTitleOptions getAxisTitleOptions(UIDL axisTitleUIDL) { if (axisTitleUIDL == null || axisTitleUIDL.getAttributeNames().size() == 0) { return null; } GwtAxisTitleOptions titleOptions = GwtAxisTitleOptions.create(); if (axisTitleUIDL.hasAttribute("align")) { titleOptions.setAlign(axisTitleUIDL.getStringAttribute("align")); } if (axisTitleUIDL.hasAttribute("margin")) { titleOptions.setMargin(axisTitleUIDL.getIntAttribute("margin")); } if (axisTitleUIDL.hasAttribute("rotation")) { titleOptions.setRotation(axisTitleUIDL.getIntAttribute("rotation")); } if (axisTitleUIDL.hasAttribute("style")) { titleOptions.setStyle(axisTitleUIDL.getStringAttribute("style")); } if (axisTitleUIDL.hasAttribute("text")) { titleOptions.setText(axisTitleUIDL.getStringAttribute("text")); } return titleOptions; } private JsArray<GwtPlotBands> getPlotBands(UIDL plotBandsUIDL) { JsArray<GwtPlotBands> plotBandsArr = JavaScriptObject.createArray() .cast(); for (int cnt = 0; cnt < plotBandsUIDL.getChildCount(); cnt++) { UIDL plotBandUIDL = plotBandsUIDL.getChildUIDL(cnt); if (plotBandUIDL.getAttributeNames().size() == 0 && plotBandUIDL.getChildCount() == 0) { continue; } GwtPlotBands plotBands = GwtPlotBands.create(); if (plotBandUIDL.hasAttribute("color")) { plotBands.setColor(plotBandUIDL.getStringAttribute("color")); } if (plotBandUIDL.hasAttribute("id")) { plotBands.setId(plotBandUIDL.getStringAttribute("id")); } if (plotBandUIDL.hasAttribute("zIndex")) { plotBands.setZIndex(plotBandUIDL.getIntAttribute("zIndex")); } // label GwtPlotLabel label = getPlotLabel(plotBandUIDL.getChildUIDL(0)); if (label != null) { plotBands.setLabel(label); } // from/to value UIDL valueUIDL = plotBandUIDL.getChildUIDL(1); if (valueUIDL.hasAttribute("valueType")) { String valueType = valueUIDL.getStringAttribute("valueType"); if (valueType.equals("number")) { plotBands.setFrom(valueUIDL.getDoubleAttribute("from")); plotBands.setTo(valueUIDL.getDoubleAttribute("to")); } else { // date // from UIDL fromUIDL = valueUIDL.getChildUIDL(0); int fromYear = fromUIDL.getIntAttribute("year"); int fromMonth = fromUIDL.getIntAttribute("month"); int fromDay = fromUIDL.getIntAttribute("day"); plotBands.setFrom("Date.UTC(" + fromYear + ", " + fromMonth + "," + fromDay + ")"); // to UIDL toUIDL = valueUIDL.getChildUIDL(1); int toYear = toUIDL.getIntAttribute("year"); int toMonth = toUIDL.getIntAttribute("month"); int toDay = toUIDL.getIntAttribute("day"); plotBands.setTo("Date.UTC(" + toYear + ", " + toMonth + "," + toDay + ")"); } } // plotBandsArr.push(plotBands); } return plotBandsArr; } private JsArray<GwtPlotLines> getPlotLines(UIDL plotLinesUIDL) { JsArray<GwtPlotLines> plotLinesArr = JavaScriptObject.createArray() .cast(); for (int cnt = 0; cnt < plotLinesUIDL.getChildCount(); cnt++) { UIDL plotLineUIDL = plotLinesUIDL.getChildUIDL(cnt); if (plotLineUIDL.getAttributeNames().size() == 0 && plotLineUIDL.getChildCount() == 0) { continue; } GwtPlotLines plotLines = GwtPlotLines.create(); if (plotLineUIDL.hasAttribute("color")) { plotLines.setColor(plotLineUIDL.getStringAttribute("color")); } if (plotLineUIDL.hasAttribute("dashStyle")) { plotLines.setDashStyle(plotLineUIDL .getStringAttribute("dashStyle")); } if (plotLineUIDL.hasAttribute("id")) { plotLines.setId(plotLineUIDL.getStringAttribute("id")); } if (plotLineUIDL.hasAttribute("width")) { plotLines.setWidth(plotLineUIDL.getIntAttribute("width")); } if (plotLineUIDL.hasAttribute("zIndex")) { plotLines.setZIndex(plotLineUIDL.getIntAttribute("zIndex")); } // label GwtPlotLabel label = getPlotLabel(plotLineUIDL.getChildUIDL(0)); if (label != null) { plotLines.setLabel(label); } // line value UIDL lineValueUIDL = plotLineUIDL.getChildUIDL(1); if (lineValueUIDL.hasAttribute("valueType")) { String valueType = lineValueUIDL .getStringAttribute("valueType"); if (valueType.equals("number")) { if (lineValueUIDL.hasAttribute("value")) { plotLines.setValue(lineValueUIDL .getDoubleAttribute("value")); } } else { // date int year = lineValueUIDL.getIntAttribute("year"); int month = lineValueUIDL.getIntAttribute("month"); int day = lineValueUIDL.getIntAttribute("day"); plotLines.setValue("Date.UTC(" + year + ", " + month + "," + day + ")"); } } // plotLinesArr.push(plotLines); } return plotLinesArr; } private GwtPlotLabel getPlotLabel(UIDL plotLabelUIDL) { if (plotLabelUIDL == null || plotLabelUIDL.getAttributeNames().size() == 0) { return null; } GwtPlotLabel label = GwtPlotLabel.create(); if (plotLabelUIDL.hasAttribute("align")) { label.setAlign(plotLabelUIDL.getStringAttribute("align")); } if (plotLabelUIDL.hasAttribute("rotation")) { label.setRotation(plotLabelUIDL.getIntAttribute("rotation")); } if (plotLabelUIDL.hasAttribute("style")) { label.setStyle(plotLabelUIDL.getStringAttribute("style")); } if (plotLabelUIDL.hasAttribute("align")) { label.setAlign(plotLabelUIDL.getStringAttribute("align")); } if (plotLabelUIDL.hasAttribute("text")) { label.setText(plotLabelUIDL.getStringAttribute("text")); } if (plotLabelUIDL.hasAttribute("verticalAlign")) { label.setVerticalAlign(plotLabelUIDL .getStringAttribute("verticalAlign")); } if (plotLabelUIDL.hasAttribute("x")) { label.setX(plotLabelUIDL.getIntAttribute("x")); } if (plotLabelUIDL.hasAttribute("y")) { label.setY(plotLabelUIDL.getIntAttribute("y")); } return label; } // FIXME - Code organization private GwtAxisDataLabels getAxisDataLabels(UIDL labelUIDL, String axisName) { if (labelUIDL == null || labelUIDL.getAttributeNames().size() == 0) { return null; } if (axisName.equals("xAxis")) { GwtXAxisDataLabels labels = GwtXAxisDataLabels.createXAxisLabels(); updateDataLabel(labelUIDL, labels); if (labelUIDL.hasAttribute("staggerLines")) { labels.setStaggerLines(labelUIDL .getIntAttribute("staggerLines")); } if (labelUIDL.hasAttribute("step")) { labels.setStep(labelUIDL.getIntAttribute("step")); } return labels; } else { GwtYAxisDataLabels labels = GwtYAxisDataLabels.createYAxisLabels(); updateDataLabel(labelUIDL, labels); return labels; } } private JsArray<GwtXAxisOptions> getXAxisOptions(UIDL uidl) { VConsole.log("Enter [getXAxisOptions]"); VConsole.log("Tag Name : " + uidl.getTag()); JsArray<GwtXAxisOptions> xAxes = JavaScriptObject.createArray().cast(); for (int cnt = 0; cnt < uidl.getChildCount(); cnt++) { GwtXAxisOptions xAxisOptions = GwtXAxisOptions.create(); UIDL axisUIDL = uidl.getChildUIDL(cnt); if (axisUIDL.getAttributeNames().size() == 0 && axisUIDL.getChildCount() == 0) { continue; } updateBaseAxisOptions(axisUIDL, xAxisOptions); UIDL childUIDL = axisUIDL.getChildUIDL(4); if (childUIDL != null) { if (childUIDL.getTag().equals("categories") && childUIDL.getChildCount() > 0) { JsArrayString categories = JavaScriptObject.createArray() .cast(); UIDL categoriesUIDL = childUIDL; for (int idx = 0; idx < categoriesUIDL.getChildCount(); idx++) { categories.push(categoriesUIDL.getChildUIDL(idx) .getStringAttribute("name")); } xAxisOptions.setCategories(categories); } else if (childUIDL.getTag().equals("dateTimeLabelFormats") && childUIDL.getAttributeNames().size() > 0) { UIDL dateTimeLblFmtsUIDL = childUIDL; GwtDateTimeLabelFormats formats = GwtDateTimeLabelFormats .create(); if (dateTimeLblFmtsUIDL.hasAttribute("second")) { formats.setSecond(dateTimeLblFmtsUIDL .getStringAttribute("second")); } if (dateTimeLblFmtsUIDL.hasAttribute("minute")) { formats.setMinute(dateTimeLblFmtsUIDL .getStringAttribute("minute")); } if (dateTimeLblFmtsUIDL.hasAttribute("hour")) { formats.setHour(dateTimeLblFmtsUIDL .getStringAttribute("hour")); } if (dateTimeLblFmtsUIDL.hasAttribute("day")) { formats.setDay(dateTimeLblFmtsUIDL .getStringAttribute("day")); } if (dateTimeLblFmtsUIDL.hasAttribute("week")) { formats.setWeek(dateTimeLblFmtsUIDL .getStringAttribute("week")); } if (dateTimeLblFmtsUIDL.hasAttribute("month")) { formats.setMonth(dateTimeLblFmtsUIDL .getStringAttribute("month")); } if (dateTimeLblFmtsUIDL.hasAttribute("year")) { formats.setYear(dateTimeLblFmtsUIDL .getStringAttribute("year")); } xAxisOptions.setDateTimeLabelFormats(formats); } } xAxes.push(xAxisOptions); } VConsole.log("Exit [getXAxisOptions]"); return xAxes; } private JsArray<GwtYAxisOptions> getYAxisOptions(UIDL uidl) { VConsole.log("Enter [getYAxisOptions]"); VConsole.log("Tag Name : " + uidl.getTag()); JsArray<GwtYAxisOptions> yAxes = JavaScriptObject.createArray().cast(); for (int cnt = 0; cnt < uidl.getChildCount(); cnt++) { GwtYAxisOptions yAxisOptions = GwtYAxisOptions.create(); UIDL axisUIDL = uidl.getChildUIDL(cnt); if (axisUIDL.getAttributeNames().size() == 0 && axisUIDL.getChildCount() == 0) { continue; } updateBaseAxisOptions(axisUIDL, yAxisOptions); yAxes.push(yAxisOptions); } VConsole.log("Exit [getYAxisOptions]"); return yAxes; } private GwtPlotOptions getPlotOptions(UIDL uidl) { VConsole.log("Enter [getPlotOptions]"); VConsole.log("Tag Name : " + uidl.getTag()); GwtPlotOptions plotOptions = GwtPlotOptions.create(); for (int cnt = 0; cnt < uidl.getChildCount(); cnt++) { UIDL seriesUIDL = uidl.getChildUIDL(cnt); String seriesType = seriesUIDL.getTag(); VConsole.log("Series Type : " + seriesType); GwtSeriesGeneralOptions seriesOptions = getSeriesOptions( seriesType, seriesUIDL); if (seriesOptions == null) { continue; } if (seriesType.equals("series")) { plotOptions.setSeries(seriesOptions); } else if (seriesType.equals("line")) { plotOptions.setLine((GwtLineOptions) seriesOptions); } else if (seriesType.equals("scatter")) { plotOptions.setScatter((GwtScatterOptions) seriesOptions); } else if (seriesType.equals("spline")) { plotOptions.setSpline((GwtSplineOptions) seriesOptions); } else if (seriesType.equals("area")) { plotOptions.setArea((GwtAreaOptions) seriesOptions); } else if (seriesType.equals("areaspline")) { plotOptions.setAreaSpline((GwtAreaSplineOptions) seriesOptions); } else if (seriesType.equals("bar")) { plotOptions.setBar((GwtBarOptions) seriesOptions); } else if (seriesType.equals("column")) { plotOptions.setColumn((GwtColumnOptions) seriesOptions); } else if (seriesType.equals("pie")) { plotOptions.setPie((GwtPieOptions) seriesOptions); } } VConsole.log("Exit [getPlotOptions]"); return plotOptions; } private GwtSeriesGeneralOptions getSeriesOptions(String seriesType, UIDL seriesUIDL) { VConsole.log("Enter [getSeriesOptions]"); VConsole.log("Tag Name : " + seriesUIDL.getTag()); if (seriesUIDL.getAttributeNames().size() == 0 && seriesUIDL.getChildCount() == 0) { VConsole.log("No attributes/children found for series type : " + seriesType); VConsole.log("Exit [getSeriesOptions]"); return null; } GwtSeriesGeneralOptions seriesOptions = null; if (seriesType.equals("series")) { seriesOptions = GwtSeriesGeneralOptions.createSeriesOptions(); updateSeriesOptions(seriesUIDL, seriesOptions); } else if (seriesType.equals("line")) { seriesOptions = GwtLineOptions.createLineOptions(); updateLineOptions(seriesUIDL, (GwtLineOptions) seriesOptions); } else if (seriesType.equals("scatter")) { seriesOptions = GwtScatterOptions.createScatterOptions(); updateScatterOptions(seriesUIDL, (GwtScatterOptions) seriesOptions); } else if (seriesType.equals("spline")) { seriesOptions = GwtSplineOptions.createSplineOptions(); updateSplineOptions(seriesUIDL, (GwtSplineOptions) seriesOptions); } else if (seriesType.equals("area")) { seriesOptions = GwtAreaOptions.createAreaOptions(); updateAreaOptions(seriesUIDL, (GwtAreaOptions) seriesOptions); } else if (seriesType.equals("areaspline")) { seriesOptions = GwtAreaSplineOptions.createAreaSplineOptions(); updateAreaSplineOptions(seriesUIDL, (GwtAreaSplineOptions) seriesOptions); } else if (seriesType.equals("bar")) { seriesOptions = GwtBarOptions.createBarOptions(); updateBarOptions(seriesUIDL, (GwtBarOptions) seriesOptions); } else if (seriesType.equals("column")) { seriesOptions = GwtColumnOptions.createColumnOptions(); updateColumnOptions(seriesUIDL, (GwtColumnOptions) seriesOptions); } else if (seriesType.equals("pie")) { seriesOptions = GwtPieOptions.createPieOptions(); updatePieOptions(seriesUIDL, (GwtPieOptions) seriesOptions); } else { // This should not happen VConsole.log("[getSeriesOptions] : Invalid series type " + seriesType); } VConsole.log("Exit [getSeriesOptions]"); return seriesOptions; } private void updateSeriesOptions(UIDL seriesUIDL, GwtSeriesGeneralOptions seriesOptions) { VConsole.log("Enter [updateSeriesOptions]"); VConsole.log("Tag Name : " + seriesUIDL.getTag()); if (seriesUIDL.hasAttribute("allowPointSelect")) { seriesOptions.setAllowPointSelect(seriesUIDL .getBooleanAttribute("allowPointSelect")); } if (seriesUIDL.hasAttribute("animation")) { seriesOptions.setAnimation(seriesUIDL .getBooleanAttribute("animation")); } if (seriesUIDL.hasAttribute("cursor")) { seriesOptions.setCursor(seriesUIDL.getStringAttribute("cursor")); } if (seriesUIDL.hasAttribute("enableMouseTracking")) { seriesOptions.setEnableMouseTracking(seriesUIDL .getBooleanAttribute("enableMouseTracking")); } if (seriesUIDL.hasAttribute("selected")) { seriesOptions.setSelected(seriesUIDL .getBooleanAttribute("selected")); } if (seriesUIDL.hasAttribute("shadow")) { seriesOptions.setShadow(seriesUIDL.getBooleanAttribute("shadow")); } if (seriesUIDL.hasAttribute("showCheckbox")) { seriesOptions.setShowCheckbox(seriesUIDL .getBooleanAttribute("showCheckbox")); } if (seriesUIDL.hasAttribute("showInLegend")) { seriesOptions.setShowInLegend(seriesUIDL .getBooleanAttribute("showInLegend")); } if (seriesUIDL.hasAttribute("stacking")) { seriesOptions .setStacking(seriesUIDL.getStringAttribute("stacking")); } if (seriesUIDL.hasAttribute("visible")) { seriesOptions.setVisible(seriesUIDL.getBooleanAttribute("visible")); } if (seriesUIDL.hasAttribute("color")) { seriesOptions.setColor(seriesUIDL.getStringAttribute("color")); } // FIXME - How to get series type // datalabels GwtDataLabels dataLabels = getSeriesDataLabel( seriesUIDL.getChildUIDL(0), seriesUIDL.getTag()); if (dataLabels != null) { seriesOptions.setDataLabels(dataLabels); } // state GwtStates seriesState = getSeriesState(seriesUIDL.getChildUIDL(1)); if (seriesState != null) { seriesOptions.setStates(seriesState); } VConsole.log("Exit [updateSeriesOptions]"); } private GwtDataLabels getSeriesDataLabel(UIDL dataLabelUIDL, String seriesType) { VConsole.log("Enter [getSeriesDataLabel]"); if (dataLabelUIDL == null || dataLabelUIDL.getAttributeNames().size() == 0) { return null; } GwtDataLabels dataLabel = GwtDataLabels.createDataLabels(); if (seriesType.equals("pie")) { dataLabel = GwtPieDataLabels.createPieDataLabels(); updatePieDataLabel(dataLabelUIDL, (GwtPieDataLabels) dataLabel); } else { updateDataLabel(dataLabelUIDL, dataLabel); } VConsole.log("Exit [getSeriesDataLabel]"); return dataLabel; } private void updatePieDataLabel(UIDL dataLabelUIDL, GwtPieDataLabels pieDataLabel) { updateDataLabel(dataLabelUIDL, pieDataLabel); if (dataLabelUIDL.hasAttribute("connectorColor")) { pieDataLabel.setConnectorColor(dataLabelUIDL .getStringAttribute("connectorColor")); } if (dataLabelUIDL.hasAttribute("connectorWidth")) { pieDataLabel.setConnectorWidth(dataLabelUIDL .getIntAttribute("connectorWidth")); } if (dataLabelUIDL.hasAttribute("connectorPadding")) { pieDataLabel.setConnectorPadding(dataLabelUIDL .getIntAttribute("connectorPadding")); } if (dataLabelUIDL.hasAttribute("distance")) { pieDataLabel.setDistance(dataLabelUIDL.getIntAttribute("distance")); } } private void updateDataLabel(UIDL dataLabelUIDL, GwtDataLabels dataLabel) { if (dataLabelUIDL.hasAttribute("align")) { dataLabel.setAlign(dataLabelUIDL.getStringAttribute("align")); } if (dataLabelUIDL.hasAttribute("enabled")) { dataLabel.setEnabled(dataLabelUIDL.getBooleanAttribute("enabled")); } if (dataLabelUIDL.hasAttribute("formatter")) { dataLabel.setFormatter(getExecutableFunction(dataLabelUIDL .getStringAttribute("formatter"))); } if (dataLabelUIDL.hasAttribute("rotation")) { dataLabel.setRotation(dataLabelUIDL.getIntAttribute("rotation")); } if (dataLabelUIDL.hasAttribute("style")) { dataLabel.setStyle(dataLabelUIDL.getStringAttribute("style")); } if (dataLabelUIDL.hasAttribute("x")) { dataLabel.setX(dataLabelUIDL.getIntAttribute("x")); } if (dataLabelUIDL.hasAttribute("y")) { dataLabel.setY(dataLabelUIDL.getIntAttribute("y")); } if (dataLabelUIDL.hasAttribute("color")) { dataLabel.setColor(dataLabelUIDL.getStringAttribute("color")); } } private GwtStates getSeriesState(UIDL stateUIDL) { if (stateUIDL == null || (stateUIDL != null && stateUIDL.getChildCount() == 0) || (stateUIDL.getChildCount() > 0 && stateUIDL.getChildUIDL(0) .getAttributeNames().size() == 0)) { return null; } GwtStates state = GwtStates.create(); GwtHover hover = GwtHover.create(); state.setHover(hover); UIDL hoverUIDL = stateUIDL.getChildUIDL(0); if (hoverUIDL.hasAttribute("enabled")) { hover.setEnabled(hoverUIDL.getBooleanAttribute("enabled")); } if (hoverUIDL.hasAttribute("lineWidth")) { hover.setLineWidth(hoverUIDL.getIntAttribute("lineWidth")); } if (hoverUIDL.hasAttribute("brightness")) { hover.setBrightness(hoverUIDL.getDoubleAttribute("brightness")); } return state; } private GwtMarker getMarkerOptions(UIDL uidl) { VConsole.log("Enter [getMarkerOptions]"); int noOfAttrs = 0; noOfAttrs = (uidl != null ? uidl.getAttributeNames().size() : 0); if (uidl == null || (noOfAttrs == 0 && uidl.getChildCount() == 0)) { VConsole.log("Exit [getMarkerOptions]"); return null; } GwtMarker marker = GwtMarker.create(); String markerType = uidl.getStringAttribute("markerType"); if (uidl.hasAttribute("enabled")) { marker.setEnabled(uidl.getBooleanAttribute("enabled")); } if (uidl.hasAttribute("lineColor")) { marker.setLineColor(uidl.getStringAttribute("lineColor")); } if (uidl.hasAttribute("fillColor")) { marker.setFillColor(uidl.getStringAttribute("fillColor")); } if (uidl.hasAttribute("lineWidth")) { marker.setLineWidth(uidl.getIntAttribute("lineWidth")); } if (uidl.hasAttribute("radius")) { marker.setRadius(uidl.getIntAttribute("radius")); } if (uidl.hasAttribute("symbol")) { if (markerType.equals("image")) { marker.setSymbol("url(." + uidl.getStringAttribute("symbol") + ")"); } else { marker.setSymbol(uidl.getStringAttribute("symbol")); } } // Marker states exist only in case of SymbolMarker and not ImageMarker if (uidl.getChildCount() > 0) { UIDL statesUIDL = uidl.getChildUIDL(0); UIDL hoverStateUIDL = statesUIDL.getChildUIDL(0); UIDL selectStateUIDL = statesUIDL.getChildUIDL(1); GwtMarkerState markerHoverState = getMarkerState(hoverStateUIDL); GwtMarkerState markerSelectState = getMarkerState(selectStateUIDL); if (markerHoverState != null || markerSelectState != null) { VConsole.log("Setting marker states..."); GwtMarkerStates markerStates = GwtMarkerStates.create(); if (markerHoverState != null) { markerStates.setHover(markerHoverState); } if (markerSelectState != null) { markerStates.setSelect(markerSelectState); } marker.setStates(markerStates); } } VConsole.log("Exit [getMarkerOptions]"); return marker; } private GwtMarkerState getMarkerState(UIDL uidl) { VConsole.log("Enter [getMarkerState]"); if (uidl == null || uidl.getAttributeNames().size() == 0) { VConsole.log("Neither hover nor select states found for a maker."); VConsole.log("Exit [getMarkerState]"); return null; } GwtMarkerState markerState = GwtMarkerState.create(); if (uidl.hasAttribute("enabled")) { markerState.setEnabled(uidl.getBooleanAttribute("enabled")); } if (uidl.hasAttribute("lineColor")) { markerState.setLineColor(uidl.getStringAttribute("lineColor")); } if (uidl.hasAttribute("fillColor")) { markerState.setFillColor(uidl.getStringAttribute("fillColor")); } if (uidl.hasAttribute("lineWidth")) { markerState.setLineWidth(uidl.getIntAttribute("lineWidth")); } if (uidl.hasAttribute("radius")) { markerState.setRadius(uidl.getIntAttribute("radius")); } VConsole.log("Exit [getMarkerState]"); return markerState; } private void updateBaseLineOptions(UIDL lineUIDL, GwtBaseLineOptions lineOptions) { VConsole.log("Enter [updateBaseLineOptions]"); updateSeriesOptions(lineUIDL, lineOptions); if (lineUIDL.hasAttribute("color")) { lineOptions.setColor(lineUIDL.getStringAttribute("color")); } if (lineUIDL.hasAttribute("dashStyle")) { lineOptions.setDashStyle(lineUIDL.getStringAttribute("dashStyle")); } if (lineUIDL.hasAttribute("lineWidth")) { lineOptions.setLineWidth(lineUIDL.getIntAttribute("lineWidth")); } if (lineUIDL.hasAttribute("pointStart")) { lineOptions.setPointStart(lineUIDL.getDoubleAttribute("pointStart")); } if (lineUIDL.hasAttribute("pointInterval")) { lineOptions.setPointInterval(lineUIDL .getIntAttribute("pointInterval")); } if (lineUIDL.hasAttribute("stickyTracking")) { lineOptions.setStickyTracking(lineUIDL .getBooleanAttribute("stickyTracking")); } GwtMarker marker = getMarkerOptions(lineUIDL.getChildUIDL(2)); if (marker != null) { lineOptions.setMarker(marker); } VConsole.log("Exit [updateBaseLineOptions]"); } private void updateLineOptions(UIDL lineUIDL, GwtLineOptions lineOptions) { VConsole.log("Enter [updateLineOptions]"); VConsole.log("Tag Name : " + lineUIDL.getTag()); updateBaseLineOptions(lineUIDL, lineOptions); if (lineUIDL.hasAttribute("step")) { lineOptions.setStep(lineUIDL.getBooleanAttribute("step")); } VConsole.log("Exit [updateBaseLineOptions]"); } private void updateScatterOptions(UIDL scatterUIDL, GwtScatterOptions scatterOptions) { VConsole.log("Enter [updateScatterOptions]"); VConsole.log("Tag Name : " + scatterUIDL.getTag()); updateBaseLineOptions(scatterUIDL, scatterOptions); VConsole.log("Exit [updateScatterOptions]"); } private void updateSplineOptions(UIDL splineUIDL, GwtSplineOptions splineOptions) { VConsole.log("Enter [updateSplineOptions]"); VConsole.log("Tag Name : " + splineUIDL.getTag()); updateBaseLineOptions(splineUIDL, splineOptions); VConsole.log("Exit [updateSplineOptions]"); } private void updateAreaOptions(UIDL areaUIDL, GwtAreaOptions areaOptions) { VConsole.log("Enter [updateAreaOptions]"); VConsole.log("Tag Name : " + areaUIDL.getTag()); updateBaseLineOptions(areaUIDL, areaOptions); if (areaUIDL.hasAttribute("fillColor")) { areaOptions.setFillColor(areaUIDL.getStringAttribute("fillColor")); } if (areaUIDL.hasAttribute("lineColor")) { areaOptions.setLineColor(areaUIDL.getStringAttribute("lineColor")); } if (areaUIDL.hasAttribute("fillOpacity")) { areaOptions.setFillOpacity(areaUIDL .getDoubleAttribute("fillOpacity")); } if (areaUIDL.hasAttribute("threshold")) { areaOptions.setThreshold(areaUIDL.getIntAttribute("threshold")); } VConsole.log("Exit [updateAreaOptions]"); } private void updateAreaSplineOptions(UIDL areaSplineUIDL, GwtAreaSplineOptions areaSplineOptions) { VConsole.log("Enter [updateAreaSplineOptions]"); VConsole.log("Tag Name : " + areaSplineUIDL.getTag()); updateAreaOptions(areaSplineUIDL, areaSplineOptions); VConsole.log("Exit [updateAreaSplineOptions]"); } private void updatePieOptions(UIDL pieUIDL, GwtPieOptions pieOptions) { VConsole.log("Enter [updatePieOptions]"); VConsole.log("Tag Name : " + pieUIDL.getTag()); updateSeriesOptions(pieUIDL, pieOptions); Integer centerX = null; Integer centerY = null; if (pieUIDL.hasAttribute("centerX")) { centerX = pieUIDL.getIntAttribute("centerX"); } if (pieUIDL.hasAttribute("centerY")) { centerY = pieUIDL.getIntAttribute("centerY"); } if (centerX != null || centerY != null) { JsArrayNumber center = JavaScriptObject.createArray().cast(); center.push((centerX == null ? 0 : centerX)); center.push((centerY == null ? 0 : centerY)); pieOptions.setCenter(center); } if (pieUIDL.hasAttribute("borderColor")) { pieOptions .setBorderColor(pieUIDL.getStringAttribute("borderColor")); } if (pieUIDL.hasAttribute("borderWidth")) { pieOptions.setBorderWidth(pieUIDL.getIntAttribute("borderWidth")); } if (pieUIDL.hasAttribute("innerSize")) { pieOptions.setInnerSize(pieUIDL.getIntAttribute("innerSize")); } if (pieUIDL.hasAttribute("size")) { pieOptions.setSize(pieUIDL.getIntAttribute("size")); } if (pieUIDL.hasAttribute("slicedOffset")) { pieOptions.setSlicedOffset(pieUIDL.getIntAttribute("slicedOffset")); } VConsole.log("Exit [updatePieOptions]"); } private void updateBaseBarOptions(UIDL barUIDL, GwtBaseBarOptions baseBarOptions) { VConsole.log("Enter [updateBaseBarOptions]"); updateSeriesOptions(barUIDL, baseBarOptions); if (barUIDL.hasAttribute("borderColor")) { baseBarOptions.setBorderColor(barUIDL .getStringAttribute("borderColor")); } if (barUIDL.hasAttribute("borderWidth")) { baseBarOptions.setBorderWidth(barUIDL .getIntAttribute("borderWidth")); } if (barUIDL.hasAttribute("borderRadius")) { baseBarOptions.setBorderRadius(barUIDL .getIntAttribute("borderRadius")); } if (barUIDL.hasAttribute("colorByPoint")) { baseBarOptions.setColorByPoint(barUIDL .getBooleanAttribute("colorByPoint")); } if (barUIDL.hasAttribute("groupPadding")) { baseBarOptions.setGroupPadding(barUIDL .getDoubleAttribute("groupPadding")); } if (barUIDL.hasAttribute("minPointLength")) { baseBarOptions.setMinPointLength(barUIDL .getDoubleAttribute("minPointLength")); } if (barUIDL.hasAttribute("pointPadding")) { baseBarOptions.setPointPadding(barUIDL .getDoubleAttribute("pointPadding")); } if (barUIDL.hasAttribute("pointWidth")) { baseBarOptions.setPointWidth(barUIDL.getIntAttribute("pointWidth")); } VConsole.log("Exit [updateBaseBarOptions]"); } private void updateBarOptions(UIDL barUIDL, GwtBarOptions barOptions) { VConsole.log("Enter [updateBarOptions]"); VConsole.log("Tag Name : " + barUIDL.getTag()); updateBaseBarOptions(barUIDL, barOptions); VConsole.log("Exit [updateBarOptions]"); } private void updateColumnOptions(UIDL columnUIDL, GwtColumnOptions columnOptions) { VConsole.log("Enter [updateColumnOptions]"); VConsole.log("Tag Name : " + columnUIDL.getTag()); updateBaseBarOptions(columnUIDL, columnOptions); VConsole.log("Exit [updateColumnOptions]"); } private void updateOptionsWithChartEvents(GwtInvientChartsConfig options, UIDL chartEventUIDL) { VConsole.log("Enter [updateOptionsWithChartEvents]"); // Chart events GwtChartEvents chartEvents = GwtChartEvents.create(); if (chartEventUIDL.hasAttribute("addSeries") && chartEventUIDL.getBooleanAttribute("addSeries")) { chartEvents.setAddSeriesEvent(EventCallbacks .getChartAddSeries(this)); } if (chartEventUIDL.hasAttribute("click") && chartEventUIDL.getBooleanAttribute("click")) { chartEvents.setClickEvent(EventCallbacks.getChartClick(this)); } if (chartEventUIDL.hasAttribute("selection") && chartEventUIDL.getBooleanAttribute("selection")) { if (options.getChartOptions().getClientZoom()) { chartEvents.setSelectionEvent(EventCallbacks .getClientChartSelection(this)); } else { chartEvents.setSelectionEvent(EventCallbacks .getServerChartSelection(this)); } } if (options.getChartOptions() == null) { options.setChartOptions(GwtChartOptions.create()); } options.getChartOptions().setEvents(chartEvents); VConsole.log("Exit [updateOptionsWithChartEvents]"); } private GwtSeriesEvents getSeriesEvents(UIDL seriesEventUIDL) { GwtSeriesEvents seriesEvents = GwtSeriesEvents.create(); boolean foundEvt = false; if (seriesEventUIDL.hasAttribute("legendItemClick") && seriesEventUIDL.getBooleanAttribute("legendItemClick")) { seriesEvents.setLegendItemClickEvent(EventCallbacks .getSeriesLegendItemClick(this)); foundEvt = true; } if (seriesEventUIDL.hasAttribute("click") && seriesEventUIDL.getBooleanAttribute("click")) { seriesEvents.setClickEvent(EventCallbacks.getSeriesClick(this)); foundEvt = true; } if (seriesEventUIDL.hasAttribute("show") && seriesEventUIDL.getBooleanAttribute("show")) { seriesEvents.setShowEvent(EventCallbacks.getSeriesShow(this)); foundEvt = true; } if (seriesEventUIDL.hasAttribute("hide") && seriesEventUIDL.getBooleanAttribute("hide")) { seriesEvents.setHideEvent(EventCallbacks.getSeriesHide(this)); foundEvt = true; } if (foundEvt) { return seriesEvents; } return null; } private void updateOptionsWithSeriesAndPoingEvents( GwtInvientChartsConfig options, UIDL chartSeriesEventsUIDL) { VConsole.log("Enter [updateOptionsWithSeriesAndPoingEvents]"); VConsole.log("[updateOptionsWithSeriesEvents] # of series : " + chartSeriesEventsUIDL.getChildCount()); // UIDL seriesEventUIDL = eventUIDL.getChildUIDL(1); if (chartSeriesEventsUIDL.getChildCount() > 0 && options.getPlotOptions() == null) { options.setPlotOptions(GwtPlotOptions.create()); } for (int cnt = 0; cnt < chartSeriesEventsUIDL.getChildCount(); cnt++) { UIDL seriesEventsUIDL = chartSeriesEventsUIDL.getChildUIDL(cnt); String seriesType = seriesEventsUIDL.getTag(); // can be // series/pie/line // etc VConsole.log("Series type " + seriesType); // GwtSeriesEvents seriesEvents = getSeriesEvents(seriesEventsUIDL); // GwtPointEvents pointEvents = null; if (seriesEventsUIDL.getChildCount() > 0) { pointEvents = getPointEvents(options, seriesEventsUIDL.getChildUIDL(0)); } if (seriesEvents == null && pointEvents == null) { VConsole.log("No series/point events found for series type : " + seriesType); continue; } GwtSeriesGeneralOptions seriesOptions = null; if (seriesType.equals("line")) { if (options.getPlotOptions().getLine() == null) { options.getPlotOptions().setLine( GwtLineOptions.createLineOptions()); } seriesOptions = options.getPlotOptions().getLine(); } else if (seriesType.equals("spline")) { if (options.getPlotOptions().getSpline() == null) { options.getPlotOptions().setSpline( GwtSplineOptions.createSplineOptions()); } seriesOptions = options.getPlotOptions().getSpline(); } else if (seriesType.equals("area")) { if (options.getPlotOptions().getArea() == null) { options.getPlotOptions().setArea( GwtAreaOptions.createAreaOptions()); } seriesOptions = options.getPlotOptions().getArea(); } else if (seriesType.equals("areaspline")) { if (options.getPlotOptions().getAreaSpline() == null) { options.getPlotOptions().setAreaSpline( GwtAreaSplineOptions.createAreaSplineOptions()); } seriesOptions = options.getPlotOptions().getAreaSpline(); } else if (seriesType.equals("bar")) { if (options.getPlotOptions().getBar() == null) { options.getPlotOptions().setBar( GwtBarOptions.createBarOptions()); } seriesOptions = options.getPlotOptions().getBar(); } else if (seriesType.equals("column")) { if (options.getPlotOptions().getColumn() == null) { options.getPlotOptions().setColumn( GwtColumnOptions.createColumnOptions()); } seriesOptions = options.getPlotOptions().getColumn(); } else if (seriesType.equals("scatter")) { if (options.getPlotOptions().getScatter() == null) { options.getPlotOptions().setScatter( GwtScatterOptions.createScatterOptions()); } seriesOptions = options.getPlotOptions().getScatter(); } else if (seriesType.equals("pie")) { if (options.getPlotOptions().getPie() == null) { options.getPlotOptions().setPie( GwtPieOptions.createPieOptions()); } seriesOptions = options.getPlotOptions().getPie(); } else { if (options.getPlotOptions().getSeries() == null) { options.getPlotOptions().setSeries( GwtSeriesGeneralOptions.createSeriesOptions()); } seriesOptions = options.getPlotOptions().getSeries(); } // Set series/point events if (seriesEvents != null) { seriesOptions.setEvents(seriesEvents); } if (pointEvents != null) { seriesOptions.setPointEvents(pointEvents); } } VConsole.log("Exit [updateOptionsWithSeriesAndPoingEvents]"); } private GwtPointEvents getPointEvents(GwtInvientChartsConfig options, UIDL pointEventsUIDL) { VConsole.log("Enter [getPointEvents]"); // Point events boolean foundEvt = false; GwtPointEvents pointEvents = GwtPointEvents.create(); if (pointEventsUIDL.hasAttribute("legendItemClick") && pointEventsUIDL.getBooleanAttribute("legendItemClick")) { pointEvents.setLegendItemClickEvent(EventCallbacks .getPieLegendItemClick(this)); foundEvt = true; } if (pointEventsUIDL.hasAttribute("click") && pointEventsUIDL.getBooleanAttribute("click")) { pointEvents.setClickEvent(EventCallbacks.getPointClick(this)); foundEvt = true; } if (pointEventsUIDL.hasAttribute("remove") && pointEventsUIDL.getBooleanAttribute("remove")) { pointEvents.setRemoveEvent(EventCallbacks.getPointRemove(this)); foundEvt = true; } if (pointEventsUIDL.hasAttribute("select") && pointEventsUIDL.getBooleanAttribute("select")) { pointEvents.setSelectEvent(EventCallbacks.getPointSelect(this)); foundEvt = true; } if (pointEventsUIDL.hasAttribute("unselect") && pointEventsUIDL.getBooleanAttribute("unselect")) { pointEvents.setUnselectEvent(EventCallbacks.getPointUnselect(this)); foundEvt = true; } VConsole.log("Exit [getPointEvents]"); if (foundEvt) { return pointEvents; } return null; } private void updateOptionsWithEvents(GwtInvientChartsConfig options, UIDL eventUIDL) { VConsole.log("Enter [updateOptionsWithEvents]"); // Chart events updateOptionsWithChartEvents(options, eventUIDL.getChildUIDL(0)); // Series events updateOptionsWithSeriesAndPoingEvents(options, eventUIDL.getChildUIDL(1)); VConsole.log("Exit [updateOptionsWithEvents]"); } protected void chartAddSeriesListener(GwtChart chart) { VConsole.log("Enter [chartAddSeriesListener]"); client.updateVariable(uidlId, "event", "addSeries", true); VConsole.log("Exit [chartAddSeriesListener]"); } protected void chartClickListener(GwtChart chart, double xAxisPos, double yAxisPos, int pageX, int pageY) { VConsole.log("Enter [chartClickListener]"); VConsole.log("chartClickListener : xAxisPos : " + xAxisPos + ", yAxisPos : " + yAxisPos); client.updateVariable(uidlId, "event", "chartClick", false); Map<String, Object> eventData = new HashMap<String, Object>(); eventData.put("xAxisPos", String.valueOf(xAxisPos)); eventData.put("yAxisPos", String.valueOf(yAxisPos)); updateEventDataWithMousePosition(eventData, pageX, pageY); client.updateVariable(uidlId, "eventData", eventData, true); VConsole.log("Exit [chartClickListener]"); } protected void chartSelectionListener(GwtChart chart, double xAxisMin, double xAxisMax, double yAxisMin, double yAxisMax) { VConsole.log("Enter [chartSelectionListener]"); VConsole.log("[chartSelectionListener] xAxisMin : " + xAxisMin + ", xAxisMax : " + xAxisMax + ", yAxisMin : " + yAxisMin + ", yAxisMax : " + yAxisMax); client.updateVariable(uidlId, "event", "chartZoom", false); Map<String, Object> eventData = new HashMap<String, Object>(); eventData.put("xAxisMin", String.valueOf(xAxisMin)); eventData.put("xAxisMax", String.valueOf(xAxisMax)); eventData.put("yAxisMin", String.valueOf(yAxisMin)); eventData.put("yAxisMax", String.valueOf(yAxisMax)); client.updateVariable(uidlId, "eventData", eventData, true); VConsole.log("Exit [chartSelectionListener]"); } protected void chartResetZoomListener(GwtChart chart) { VConsole.log("Enter [chartResetZoomListener]"); client.updateVariable(uidlId, "event", "chartResetZoom", true); VConsole.log("Exit [chartResetZoomListener]"); } protected void seriesClickListener(GwtSeries series, GwtPoint nearestPoint, int pageX, int pageY) { VConsole.log("Enter [seriesClickListener]"); VConsole.log("[seriesClickListener] point x: " + nearestPoint.getX() + ", point y: " + nearestPoint.getY()); client.updateVariable(uidlId, "event", "seriesClick", false); Map<String, Object> eventData = getEventData(nearestPoint); updateEventDataWithMousePosition(eventData, pageX, pageY); client.updateVariable(uidlId, "eventData", eventData, true); VConsole.log("Exit [seriesClickListener]"); } protected void seriesHideListener(GwtSeries series) { VConsole.log("Enter [seriesHideListener]"); VConsole.log("[seriesHideListener] series name " + series.getName()); client.updateVariable(uidlId, "event", "seriesHide", false); Map<String, Object> eventData = new HashMap<String, Object>(); eventData.put("seriesName", series.getName()); client.updateVariable(uidlId, "eventData", eventData, true); VConsole.log("Exit [seriesHideListener]"); } protected void seriesShowListener(GwtSeries series) { VConsole.log("Enter [seriesShowListener]"); VConsole.log("[seriesShowListener] series name " + series.getName()); client.updateVariable(uidlId, "event", "seriesShow", false); Map<String, Object> eventData = new HashMap<String, Object>(); eventData.put("seriesName", series.getName()); client.updateVariable(uidlId, "eventData", eventData, true); VConsole.log("Exit [seriesShowListener]"); } protected void seriesLegendItemClickListener(GwtSeries series) { VConsole.log("Enter [seriesLegendItemClickListener]"); VConsole.log("[seriesLegendItemClickListener] name " + series.getName()); client.updateVariable(uidlId, "event", "seriesLegendItemClick", false); Map<String, Object> eventData = new HashMap<String, Object>(); eventData.put("seriesName", series.getName()); client.updateVariable(uidlId, "eventData", eventData, true); VConsole.log("Exit [seriesLegendItemClickListener]"); } protected void pieLegendItemClickListener(GwtPoint point) { VConsole.log("Enter [pieLegendItemClickListener]"); client.updateVariable(uidlId, "event", "pieLegendItemClick", false); Map<String, Object> eventData = getEventData(point); client.updateVariable(uidlId, "eventData", eventData, true); VConsole.log("Exit [pieLegendItemClickListener]"); } protected void pointClickListener(GwtPoint point, int pageX, int pageY) { VConsole.log("Enter [pointClickListener]"); client.updateVariable(uidlId, "event", "pointClick", false); Map<String, Object> eventData = getEventData(point); updateEventDataWithMousePosition(eventData, pageX, pageY); client.updateVariable(uidlId, "eventData", eventData, true); VConsole.log("Exit [pointClickListener]"); } protected void pointSelectListener(GwtPoint point) { VConsole.log("Enter [pointSelectListener]"); VConsole.log("[pointSelectListener] point " + point.getX() + ", " + point.getY()); client.updateVariable(uidlId, "event", "pointSelect", false); client.updateVariable(uidlId, "eventData", getEventData(point), true); VConsole.log("Exit [pointSelectListener]"); } protected void pointUnselectListener(GwtPoint point) { VConsole.log("Enter [pointUnselectListener]"); VConsole.log("[pointUnselectListener] point " + point.getX() + ", " + point.getY()); client.updateVariable(uidlId, "event", "pointUnselect", false); client.updateVariable(uidlId, "eventData", getEventData(point), true); VConsole.log("Exit [pointUnselectListener]"); } protected void pointRemoveListener(GwtPoint point) { VConsole.log("Enter [pointRemoveListener]"); VConsole.log("[pointRemoveListener] point " + point.getX() + ", " + point.getY()); client.updateVariable(uidlId, "event", "pointRemove", false); client.updateVariable(uidlId, "eventData", getEventData(point), true); VConsole.log("Exit [pointRemoveListener]"); } private Map<String, Object> getEventData(GwtPoint point) { Map<String, Object> eventData = new HashMap<String, Object>(); eventData.put("seriesName", point.getSeries().getName()); eventData.put("category", point.getCategory()); // The point x and y values are converted into // string value to avoid data conversion issues // for datetime series/axis // It is responsibility of the server to convert string value // into appropriate data type e.g. double or Date eventData.put("pointX", String.valueOf(point.getX())); eventData.put("pointY", String.valueOf(point.getY())); return eventData; } private void updateEventDataWithMousePosition( Map<String, Object> eventData, int pageX, int pageY) { eventData.put("mouseX", pageX); eventData.put("mouseY", pageY); } private String getExecutableFunction(String formatterFunc) { StringBuilder sb = new StringBuilder(""); sb.append("function dummy() { "); sb.append(" return "); sb.append(formatterFunc).append(";"); sb.append(" }"); sb.append(" dummy();"); return sb.toString(); } /** * Define a JS function to be used in order to get mouse coordinates when * click event occurs on a chart/series/point */ private native final void publish() /*-{ // Used in based class GwtInvientCharts.java $wnd.getMouseCoords = function(ev) { if(ev.pageX || ev.pageY){ return {x:ev.pageX, y:ev.pageY}; } else { return { x:ev.clientX + document.documentElement.scrollLeft, y:ev.clientY + document.documentElement.scrollTop }; } }; // Used in class GwtInvientChartsConfig.java $wnd.getInvientChartsColor = function(colorVal) { var colorKey = 'JSOBJ:'; var index = colorVal.indexOf(colorKey); if(index == 0) { return eval('(' + colorVal.substring(index+colorKey.length) + ')'); } return colorVal; }; }-*/; }
src/com/invient/vaadin/charts/widgetset/client/ui/VInvientCharts.java
/* * Copyright 2011 Invient (www.invient.com) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.invient.vaadin.charts.widgetset.client.ui; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsArrayNumber; import com.google.gwt.core.client.JsArrayString; import com.invient.vaadin.charts.widgetset.client.ui.GwtInvientChartsConfig.*; import com.invient.vaadin.charts.widgetset.client.ui.GwtInvientChartsConfig.GwtAxisBaseOptions.*; import com.invient.vaadin.charts.widgetset.client.ui.GwtInvientChartsConfig.GwtChartLabels.GwtChartLabelItem; import com.invient.vaadin.charts.widgetset.client.ui.GwtInvientChartsConfig.GwtChartOptions.GwtChartEvents; import com.invient.vaadin.charts.widgetset.client.ui.GwtInvientChartsConfig.GwtPlotOptions.*; import com.invient.vaadin.charts.widgetset.client.ui.GwtInvientChartsConfig.GwtPlotOptions.GwtMarker.GwtMarkerStates; import com.invient.vaadin.charts.widgetset.client.ui.GwtInvientChartsConfig.GwtPlotOptions.GwtMarker.GwtMarkerStates.GwtMarkerState; import com.invient.vaadin.charts.widgetset.client.ui.GwtInvientChartsConfig.GwtPlotOptions.GwtSeriesGeneralOptions.GwtStates; import com.invient.vaadin.charts.widgetset.client.ui.GwtInvientChartsConfig.GwtPlotOptions.GwtSeriesGeneralOptions.GwtStates.GwtHover; import com.invient.vaadin.charts.widgetset.client.ui.GwtInvientChartsConfig.GwtPointOptions.GwtPointEvents; import com.invient.vaadin.charts.widgetset.client.ui.GwtInvientChartsConfig.GwtXAxisOptions.GwtDateTimeLabelFormats; import com.vaadin.terminal.gwt.client.ApplicationConnection; import com.vaadin.terminal.gwt.client.Paintable; import com.vaadin.terminal.gwt.client.UIDL; import com.vaadin.terminal.gwt.client.VConsole; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Client side widget which communicates with the server. Messages from the * server are shown as HTML and mouse clicks are sent to the server. * * Reads data from UIDL and create appropriate JavaScript overlay objects such * as {@link GwtChart}, {@link GwtAxis}, {@link GwtInvientChartsConfig}, * {@link GwtPoint} and {@link GwtSeries} * * Uses a method newChart() of {@link GwtInvientChartsUtil} to create a chart * object of type {@link GwtChart} * * @author Invient */ public class VInvientCharts extends GwtInvientCharts implements Paintable /* * , * ClickHandler * , * ScrollHandler */{ private static final long serialVersionUID = -762763091427791681L; /** Set the CSS class name to allow styling. */ public static final String CLASSNAME = "v-invientcharts"; /** The client side widget identifier */ protected String uidlId; /** Reference to the server connection object. */ protected ApplicationConnection client; /** * The constructor should first call super() to initialize the component and * then handle any initialization relevant to Vaadin. */ public VInvientCharts() { super(); setStyleName(CLASSNAME); publish(); } /** * Called whenever an update is received from the server */ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { VConsole.log("Enter [updateFromUIDL]"); // This call should be made first. // It handles sizes, captions, tooltips, etc. automatically. if (client.updateComponent(this, uidl, true)) { // If client.updateComponent returns true there has been no changes // and we // do not need to update anything. return; } // Save reference to server connection object to be able to send // user interaction later this.client = client; // Save the client side identifier (paintable id) for the widget uidlId = uidl.getId(); // Create chart only once along with chart options // Chart options are set only once. if (chart == null) { // Chart options GwtInvientChartsConfig options = getInvientChartOptions(uidl .getChildUIDL(ChartUIDLIndex.OPTIONS.ordinal())); // Chart events updateOptionsWithEvents(options, uidl.getChildUIDL(ChartUIDLIndex.EVENTS.ordinal())); // Chart data JsArray<GwtSeriesDataOptions> chartData = getChartData(uidl .getChildUIDL(ChartUIDLIndex.DATA.ordinal())); options.setSeriesInstanceOptions(chartData); VConsole.log("Going to create a chart."); createChart(options); } else { resetRedrawChart(); if (uidl.getBooleanAttribute("reloadChartSeries")) { // Get all series and add them to chart JsArray<GwtSeriesDataOptions> chartData = getChartData(uidl .getChildUIDL(ChartUIDLIndex.DATA.ordinal())); int seriesCount = chart.getSeries().length(); VConsole.log("# of series the chart has " + seriesCount); VConsole.log("Going to remove all series of the chart."); for (int ind = seriesCount - 1; ind >= 0; ind--) { setRedrawChart(); chart.getSeries().get(ind).remove(false); } VConsole.log("Goint to add series to the chart."); for (int ind = 0; ind < chartData.length(); ind++) { setRedrawChart(); chart.addSeries(chartData.get(ind), false); } } else { VConsole.log("Going to update chart data."); UIDL chartDataUIDL = uidl.getChildUIDL(ChartUIDLIndex.DATA .ordinal()); UIDL chartDataUpdatesUIDL = uidl .getChildUIDL(ChartUIDLIndex.DATA_UPDATES.ordinal()); updateChartData(chartDataUpdatesUIDL, chartDataUIDL); } // Options UIDL UIDL optionsUIDL = uidl.getChildUIDL(ChartUIDLIndex.OPTIONS .ordinal()); // Update chart title & subtitle setChartTitleAndSubtitle(optionsUIDL); // Size setChartSize(optionsUIDL); VConsole.log("Getting x-axis options..."); JsArray<GwtXAxisOptions> uidlXAxesOptionsArr = getXAxisOptions(optionsUIDL .getChildUIDL(ChartOptionsUIDLIndex.X_AXES.ordinal())); JsArray<GwtXAxisOptions> chartXAxesOptionsArr = JavaScriptObject .createArray().cast(); JsArray<GwtAxis> chartXAxesArr = chart.getXAxes(); if (chart.getOptions().hasXAxesOptions()) { chartXAxesOptionsArr = chart.getOptions().getXAxesOptions(); updateXAxisCategories(chartXAxesArr, chartXAxesOptionsArr, uidlXAxesOptionsArr); } updateAxesPlotBandsAndPlotLines(chartXAxesArr, chartXAxesOptionsArr, uidlXAxesOptionsArr); VConsole.log("Getting y-axis options..."); JsArray<GwtYAxisOptions> uidlYAxesOptionsArr = getYAxisOptions(optionsUIDL .getChildUIDL(ChartOptionsUIDLIndex.Y_AXES.ordinal())); JsArray<GwtYAxisOptions> chartYAxesOptionsArr = JavaScriptObject .createArray().cast(); if (chart.getOptions().hasYAxesOptions()) { chartYAxesOptionsArr = chart.getOptions().getYAxesOptions(); } JsArray<GwtAxis> chartYAxesArr = chart.getYAxes(); updateAxesPlotBandsAndPlotLines(chartYAxesArr, chartYAxesOptionsArr, uidlYAxesOptionsArr); // Update axis extremes if (chart.getOptions().hasXAxesOptions() || chart.getOptions().hasYAxesOptions()) { updateAxisExtremes(chart.getXAxes(), chartXAxesOptionsArr, uidlXAxesOptionsArr); updateAxisExtremes(chart.getYAxes(), chartYAxesOptionsArr, uidlYAxesOptionsArr); } if (isRedrawChart()) { VConsole.log("Going to redraw the chart."); chart.redraw(); } } // Get SVG if required and send it to server handleChartSVG(uidl); handlePrint(uidl); VConsole.log("Exit [updateFromUIDL]"); } // Set title & subtitle private void setChartTitleAndSubtitle(UIDL optionsUIDL) { VConsole.log("Enter [setChartTitleAndSubtitle]"); // There is not need to set redrawChart flag as setting title & subtitle // does not require redrawing of the chart. chart.setTitle( getTitleOptions(optionsUIDL .getChildUIDL(ChartOptionsUIDLIndex.TITLE.ordinal())), getSubtitleOptions(optionsUIDL .getChildUIDL(ChartOptionsUIDLIndex.SUBTITLE.ordinal()))); VConsole.log("Exit [setChartTitleAndSubtitle]"); } // Set chart size private void setChartSize(UIDL optionsUIDL) { // There is not need to set redrawChart flag as setting title & subtitle // does not require redrawing of the chart. GwtChartOptions chartOptions = getChartOptions(optionsUIDL .getChildUIDL(ChartOptionsUIDLIndex.CHART_CONFIG.ordinal())); int newWidth = chartOptions.getWidth(); int newHeight = chartOptions.getHeight(); int existingWidth = chart.getOptions().getChartOptions().getWidth(); int existingHeight = chart.getOptions().getChartOptions().getHeight(); if ((newWidth != -1 && newWidth != existingWidth) || (newHeight != -1 && newHeight != existingHeight)) { VConsole.log("Set chart size."); chart.getOptions().getChartOptions().setWidth(newWidth); chart.getOptions().getChartOptions().setHeight(newHeight); chart.setSize(newWidth, newHeight); } } private void handlePrint(UIDL uidl) { boolean isPrint = uidl.getBooleanAttribute("isPrint"); if (isPrint) { VConsole.log("Going to print the chart..."); chart.printInvientChart(); } } private void handleChartSVG(UIDL uidl) { boolean isRetrieveSVG = uidl.getBooleanAttribute("isRetrieveSVG"); if (isRetrieveSVG) { VConsole.log("Get an svg string..."); String svg = chart.getSVG(null); // send svg to server client.updateVariable(uidlId, "event", "chartSVGAvailable", false); Map<String, Object> eventData = new HashMap<String, Object>(); eventData.put("svg", svg); client.updateVariable(uidlId, "eventData", eventData, true); } } private void updateXAxisCategories(JsArray<GwtAxis> chartAxesArr, JsArray<GwtXAxisOptions> chartXAxesOptionsArr, JsArray<GwtXAxisOptions> uidlXAxesOptionsArr) { VConsole.log("Enter [updateXAxisCategories]"); if (chartXAxesOptionsArr == null || chartXAxesOptionsArr.length() == 0) { VConsole.log("Chart doesn't have any X axis]"); VConsole.log("Exit [updateXAxisCategories]"); return; } int noOfAxis = chartXAxesOptionsArr.length(); for (int ind = 0; ind < noOfAxis; ind++) { GwtAxis chartAxis = chartAxesArr.get(ind); GwtXAxisOptions chartAxisOptions = chartXAxesOptionsArr.get(ind); GwtXAxisOptions uidlAxisOptions = uidlXAxesOptionsArr.get(ind); if (chartAxis != null && chartAxisOptions != null && uidlAxisOptions != null) { // If axis if (!areStringArraysEqual(uidlAxisOptions.getCategories(), chartAxis.getCategories())) { setRedrawChart(); chartAxisOptions.setCategories(uidlAxisOptions .getCategories()); chartAxis.setCategories(uidlAxisOptions.getCategories(), false); } } } VConsole.log("Exit [updateXAxisCategories]"); } private boolean areStringArraysEqual(JsArrayString arrOne, JsArrayString arrTwo) { if (arrOne == arrTwo) { return true; } if ((arrOne != null && arrTwo == null) || (arrOne == null && arrTwo != null)) { return false; } if (arrOne.length() != arrTwo.length()) { return false; } // Compare each array element for (int arrInd = 0; arrInd < arrOne.length(); arrInd++) { String arrOneVal = arrOne.get(arrInd); String arrTwoVal = arrTwo.get(arrInd); if (arrOneVal == null) { if (arrTwoVal != null) { return false; } } else if(!arrOneVal.equals(arrTwoVal)) { return false; } } return true; } private void updateAxisExtremes(JsArray<GwtAxis> chartAxesArr, JsArray<? extends GwtAxisBaseOptions> chartAxesOptionsArr, JsArray<? extends GwtAxisBaseOptions> uidlAxesOptionsArr) { VConsole.log("Enter [updateAxisExtremes]"); if (chartAxesOptionsArr == null || chartAxesOptionsArr.length() == 0) { VConsole.log("Chart doesn't have any X/Y axis]"); VConsole.log("Exit [updateAxisExtremes]"); return; } int noOfAxis = chartAxesOptionsArr.length(); for (int ind = 0; ind < noOfAxis; ind++) { GwtAxis chartAxis = chartAxesArr.get(ind); GwtAxisBaseOptions chartAxisOptions = chartAxesOptionsArr.get(ind); GwtAxisBaseOptions uidlAxisOptions = uidlAxesOptionsArr.get(ind); if (chartAxis != null && chartAxisOptions != null && uidlAxisOptions != null) { double uidlMin = uidlAxisOptions.getMin(); double uidlMax = uidlAxisOptions.getMax(); double chartMin = chartAxisOptions.getMin(); double chartMax = chartAxisOptions.getMax(); // Update chart's axis options as // it is not updated when extremes are set using // axis.setExtremes() if (uidlMin != chartMin) { setRedrawChart(); chartAxisOptions.setMin(uidlMin); } if (uidlMax != chartMax) { setRedrawChart(); chartAxisOptions.setMax(uidlMax); } VConsole.log("[updateAxisExtremes] min " + chartAxisOptions.getMin() + ", max " + chartAxisOptions.getMax()); chartAxis.setExtremes(chartAxisOptions.getMin(), chartAxisOptions.getMax(), false); } } VConsole.log("Exit [updateAxisExtremes]"); } private enum ChartUIDLIndex { OPTIONS, DATA, EVENTS, DATA_UPDATES; } private enum ChartOptionsUIDLIndex { TITLE, SUBTITLE, CREDIT, LEGEND, TOOLTIP, CHART_CONFIG, SERIES_OPTIONS, X_AXES, Y_AXES, LABEL; } private void updateAxesPlotBandsAndPlotLines( JsArray<? extends GwtAxis> chartAxesArr, JsArray<? extends GwtAxisBaseOptions> chartAxesOptionsArr, JsArray<? extends GwtAxisBaseOptions> uidlAxesOptionsArr) { VConsole.log("Enter [updateAxesPlotBandsAndPlotLines]"); int noOfAxis = chartAxesArr.length(); for (int ind = 0; ind < noOfAxis; ind++) { GwtAxis chartAxis = chartAxesArr.get(ind); GwtAxisBaseOptions chartAxisOptions = chartAxesOptionsArr.get(ind); GwtAxisBaseOptions uidlAxisOptions = uidlAxesOptionsArr.get(ind); if (chartAxis != null && chartAxisOptions != null && uidlAxisOptions != null) { updatePlotBands(chartAxis, chartAxisOptions, uidlAxisOptions); updatePlotLines(chartAxis, chartAxisOptions, uidlAxisOptions); } } VConsole.log("Exit [updateAxesPlotBandsAndPlotLines]"); } // private void updatePlotLines(GwtAxis chartAxis, GwtAxisBaseOptions chartAxisOptions, GwtAxisBaseOptions uidlAxisOptions) { VConsole.log("Enter [updatePlotLines]"); // Update chartAxisPlotBands whenever a plotline is added or removed as // the library // does not update chart options by itself. JsArray<GwtPlotLines> chartAxisPlotLines = chartAxisOptions .getPlotLines(); JsArray<GwtPlotLines> uidlAxisPlotLines = uidlAxisOptions .getPlotLines(); if (uidlAxisPlotLines == null && chartAxisPlotLines == null) { VConsole.log("No plotlines found."); VConsole.log("Exit [updatePlotLines]"); return; } if (uidlAxisPlotLines == null) { uidlAxisPlotLines = JavaScriptObject.createArray().cast(); } if (chartAxisPlotLines == null) { chartAxisPlotLines = JavaScriptObject.createArray().cast(); } JsArray<GwtPlotLines> updatedChartAxisPlotLines = JavaScriptObject .createArray().cast(); int numOfChartAxisPlotLines = chartAxisPlotLines.length(); int numOfUIDLAxisPlotLines = uidlAxisPlotLines.length(); boolean updatedAxisPlotLines = false; for (int indOuter = 0; indOuter < numOfChartAxisPlotLines; indOuter++) { GwtPlotLines chartPlotLine = chartAxisPlotLines.get(indOuter); String plotLineId = chartPlotLine.getId(); boolean found = false; for (int indInner = 0; indInner < numOfUIDLAxisPlotLines; indInner++) { GwtPlotLines uidlPlotLine = uidlAxisPlotLines.get(indInner); if (uidlPlotLine != null && uidlPlotLine.getId().equals(plotLineId)) { if (uidlPlotLine.getValue() == chartPlotLine.getValue()) { // PlotLine exists and value is same so no action should // be taken except marking UIDL PlotLine to null. // Setting UIDL PlotLine // to null ensures that remaining PlotLines in UIDL can // be added // safely to the chart. uidlAxisPlotLines.set(indInner, null); updatedChartAxisPlotLines.push(chartPlotLine); found = true; } break; } } if (!found) { // remove plot line as it is not found in UIDL received from the // server updatedAxisPlotLines = true; chartAxis.removePlotLine(plotLineId); } } // Add all remaining plot lines in UIDL to the chart for (int ind = 0; ind < numOfUIDLAxisPlotLines; ind++) { GwtPlotLines uidlPlotLine = uidlAxisPlotLines.get(ind); if (uidlPlotLine != null) { updatedAxisPlotLines = true; chartAxis.addPlotLine(uidlPlotLine); updatedChartAxisPlotLines.push(uidlPlotLine); } } // Update chart axis plotlines if (updatedAxisPlotLines) { setRedrawChart(); chartAxisOptions.setPlotLines(updatedChartAxisPlotLines); } VConsole.log("Exit [updatePlotLines]"); } // private void updatePlotBands(GwtAxis chartAxis, GwtAxisBaseOptions chartAxisOptions, GwtAxisBaseOptions uidlAxisOptions) { VConsole.log("Enter [updatePlotBands]"); // Update chartAxisPlotBands whenever a plotband is added or removed as // the library // does not update chart options by itself. JsArray<GwtPlotBands> chartAxisPlotBands = chartAxisOptions .getPlotBands(); JsArray<GwtPlotBands> uidlAxisPlotBands = uidlAxisOptions .getPlotBands(); if (uidlAxisPlotBands == null && chartAxisPlotBands == null) { VConsole.log("No plotbands found."); VConsole.log("Exit [updatePlotBands]"); return; } if (uidlAxisPlotBands == null) { uidlAxisPlotBands = JavaScriptObject.createArray().cast(); } if (chartAxisPlotBands == null) { chartAxisPlotBands = JavaScriptObject.createArray().cast(); } JsArray<GwtPlotBands> updatedChartAxisPlotBands = JavaScriptObject .createArray().cast(); int numOfChartAxisPlotBands = chartAxisPlotBands.length(); int numOfUIDLAxisPlotBands = uidlAxisPlotBands.length(); boolean updatedAxisPlotBands = false; for (int indOuter = 0; indOuter < numOfChartAxisPlotBands; indOuter++) { GwtPlotBands chartPlotBand = chartAxisPlotBands.get(indOuter); String plotBandId = chartPlotBand.getId(); boolean found = false; for (int indInner = 0; indInner < numOfUIDLAxisPlotBands; indInner++) { GwtPlotBands uidlPlotBand = uidlAxisPlotBands.get(indInner); if (uidlPlotBand != null && uidlPlotBand.getId().equals(plotBandId)) { if (chartPlotBand.getFrom() == uidlPlotBand.getFrom() && chartPlotBand.getTo() == uidlPlotBand.getTo()) { VConsole.log("Plotband id " + plotBandId + " exists in chart as well as in UIDL from the server."); // PlotBand exists and from/to values are same so // nothing to be done. // The UIDL plotband is set to null so that remaining // plotbands // can be safely added to the chart uidlAxisPlotBands.set(indInner, null); updatedChartAxisPlotBands.push(chartPlotBand); VConsole.log("Plotband id " + plotBandId + " exists in both."); found = true; } break; } } if (!found) { // remove plot band as it is not found in UIDL received from the // server VConsole.log("Plotband id " + plotBandId + " removed."); updatedAxisPlotBands = true; chartAxis.removePlotBand(plotBandId); } } // Add all remaining plot bands in UIDL to the chart for (int ind = 0; ind < numOfUIDLAxisPlotBands; ind++) { GwtPlotBands uidlPlotBand = uidlAxisPlotBands.get(ind); if (uidlPlotBand != null) { updatedAxisPlotBands = true; VConsole.log("Plotband id " + uidlPlotBand.getId() + " added with from : " + uidlPlotBand.getFrom() + " and to: " + uidlPlotBand.getTo()); chartAxis.addPlotBand(uidlPlotBand); updatedChartAxisPlotBands.push(uidlPlotBand); } } // Update chart axis plotbands if (updatedAxisPlotBands) { setRedrawChart(); chartAxisOptions.setPlotBands(updatedChartAxisPlotBands); } VConsole.log("Exit [updatePlotBands]"); } private boolean redrawChart = false; private void setRedrawChart() { this.redrawChart = true; } private boolean isRedrawChart() { return this.redrawChart; } private void resetRedrawChart() { this.redrawChart = false; } private void updateChartData(UIDL uidlChartDataUpdates, UIDL uidlChartData) { VConsole.log("Enter [updateChartData]"); JsArrayString seriesToAdd = JavaScriptObject.createArray().cast(); JsArrayString seriesToUpdate = JavaScriptObject.createArray().cast(); List<UIDL> seriesToUpdateList = new ArrayList<UIDL>(); for (int ind = 0; ind < uidlChartDataUpdates.getChildCount(); ind++) { UIDL seriesUpdateUIDL = uidlChartDataUpdates.getChildUIDL(ind); String seriesName = seriesUpdateUIDL .getStringAttribute("seriesName"); String operation = seriesUpdateUIDL.getStringAttribute("operation"); VConsole.log("Series name : " + seriesName + ", operation : " + operation); if (seriesName != null && seriesName.length() > 0 && operation != null && operation.length() > 0) { if (SeriesCURType.REMOVE.getName().equals(operation)) { GwtSeries series = chart.getSeries(seriesName); if (series != null) { VConsole.log("Removing series : " + seriesName); setRedrawChart(); series.remove(false); } } else if (SeriesCURType.ADD.getName().equals(operation)) { seriesToAdd.push(seriesName); } else if (SeriesCURType.UPDATE.getName().equals(operation)) { VConsole.log("Will update series : " + seriesName); seriesToUpdateList.add(seriesUpdateUIDL); seriesToUpdate.push(seriesName); } } } if (seriesToAdd.length() > 0) { setRedrawChart(); JsArray<GwtSeriesDataOptions> uidlChartDataArr = getChartData( uidlChartData, seriesToAdd); for (int ind = 0; ind < uidlChartDataArr.length(); ind++) { VConsole.log("Adding series " + uidlChartDataArr.get(ind).getName()); chart.addSeries(uidlChartDataArr.get(ind), false); } } if (seriesToUpdateList.size() > 0) { setRedrawChart(); JsArray<GwtSeriesDataOptions> uidlChartDataArr = getChartData( uidlChartData, seriesToUpdate); for (int ind = 0; ind < seriesToUpdateList.size(); ind++) { UIDL uidlSeriesToUpdate = seriesToUpdateList.get(ind); GwtSeriesDataOptions uidlSeriesDataOptions = uidlChartDataArr .get(ind); GwtSeries chartSeries = chart.getSeries(uidlSeriesDataOptions .getName()); GwtSeriesGeneralOptions chartSeriesOptions = chartSeries .getSeriesGeneralOptions(); GwtSeriesGeneralOptions uidlSeriesOptions = uidlSeriesDataOptions .getSeriesOptions(); // Update visibility boolean isVisible = (uidlSeriesOptions != null ? uidlSeriesOptions .isVisible() : true); chartSeriesOptions.setVisible(isVisible); if (chartSeriesOptions.isVisible() == true && chartSeries.isVisible() == false) { chartSeries.show(); } if (chartSeriesOptions.isVisible() == false && chartSeries.isVisible() == true) { chartSeries.hide(); } // Update points if (uidlSeriesToUpdate.getBooleanAttribute("isReloadPoints")) { // update all points VConsole.log("Reloading points for series : " + uidlSeriesToUpdate.getStringAttribute("name")); chartSeries.setDataAsPointOptions( uidlSeriesDataOptions.getDataAsPointOptions(), false); } else { UIDL uidlPointsAdded = uidlSeriesToUpdate.getChildUIDL(0); UIDL uidlPointsRemoved = uidlSeriesToUpdate.getChildUIDL(1); updateSeriesData(chartSeries, uidlPointsAdded, uidlPointsRemoved); } } } VConsole.log("Exit [updateChartData]"); } private void updateSeriesData(GwtSeries chartSeries, UIDL uidlPointsAdded, UIDL uidlPointsRemoved) { VConsole.log("Enter [updateSeriesData]"); if (uidlPointsAdded != null && uidlPointsAdded.getChildCount() > 0) { // Add points JsArray<GwtPointOptions> pointsTobeAdded = getSeriesPoints(uidlPointsAdded); VConsole.log("# of points to be added : " + pointsTobeAdded.length()); for (int cnt = 0; cnt < pointsTobeAdded.length(); cnt++) { GwtPointOptions pointOptions = pointsTobeAdded.get(cnt); chartSeries.addPoint(pointOptions, false, pointOptions.isShift()); } } if (uidlPointsRemoved != null && uidlPointsRemoved.getChildCount() > 0) { // Remove points JsArray<GwtPointOptions> pointsTobeRemoved = getSeriesPoints(uidlPointsRemoved); VConsole.log("# of points to be removed : " + pointsTobeRemoved.length()); JsArray<GwtPoint> chartSeriesData = chartSeries.getData(); for (int cnt = 0; cnt < pointsTobeRemoved.length(); cnt++) { GwtPointOptions pointToRemove = pointsTobeRemoved.get(cnt); for (int chartPointCnt = 0; chartPointCnt < chartSeriesData .length(); chartPointCnt++) { GwtPoint chartSeriesPoint = chartSeriesData .get(chartPointCnt); // Using Double.compareTo(another Double) does not result in // appr. code which can be executed in JS correctly. // e.g. x.compareTo(y) results in compare(x.value, y.value) // where x.value is undefined in JS, // Don't know the reason yet but will figure out. So do a // direct comparison if (chartSeriesPoint.getX() == pointToRemove.getX() && chartSeriesPoint.getY() == pointToRemove.getY()) { VConsole.log("Removing point (" + chartSeriesPoint.getX() + ", " + chartSeriesPoint.getY() + ")"); chartSeriesPoint.remove(); break; } } } } VConsole.log("Exit [updateSeriesData]"); } private static enum SeriesCURType { ADD("Add"), UPDATE("Update"), REMOVE("Remove"); private String name; private SeriesCURType(String name) { this.name = name; } public String getName() { return this.name; } } private JsArray<GwtSeriesDataOptions> getChartData(UIDL uidl) { return getChartData(uidl, null); } private boolean doesArrayContainSeriesName( JsArrayString namesOfSeriesToAdd, String seriesName) { for (int ind = 0; ind < namesOfSeriesToAdd.length(); ind++) { if (seriesName.equals(namesOfSeriesToAdd.get(ind))) { return true; } } return false; } private JsArray<GwtSeriesDataOptions> getChartData(UIDL uidl, JsArrayString namesOfSeriesToAdd) { VConsole.log("Enter [getChartData]"); JsArray<GwtSeriesDataOptions> seriesDataArr = JavaScriptObject .createArray().cast(); // Process each series data for (int cnt = 0; cnt < uidl.getChildCount(); cnt++) { GwtSeriesDataOptions seriesData = GwtSeriesDataOptions.create(); UIDL seriesUIDL = uidl.getChildUIDL(cnt); String seriesName = seriesUIDL.getStringAttribute("name"); if (seriesName != null && namesOfSeriesToAdd != null) { if (!doesArrayContainSeriesName(namesOfSeriesToAdd, seriesName)) { continue; } } // From charts series data retrieve only those series data // whose names are specified in the second argument if (seriesUIDL.hasAttribute("name")) { // Setting name automatically sets series id which can later be // used to retrieve using chart.get(id); seriesData.setName(seriesName); } if (seriesUIDL.hasAttribute("stack")) { seriesData.setStack(seriesUIDL.getStringAttribute("stack")); } // FIXME - fallback on chart options type if series doesn't have a // type String seriesType = "line"; if (seriesUIDL.hasAttribute("type")) { seriesType = seriesUIDL.getStringAttribute("type"); seriesData.setType(seriesType); } if (seriesUIDL.hasAttribute("xAxis")) { seriesData.setXAxis(seriesUIDL.getIntAttribute("xAxis")); } if (seriesUIDL.hasAttribute("yAxis")) { seriesData.setYAxis(seriesUIDL.getIntAttribute("yAxis")); } // Get data/points seriesData.setDataAsPointOptions(getSeriesPoints(seriesUIDL .getChildUIDL(1))); // Get series options GwtSeriesGeneralOptions seriesOptions = getSeriesOptions( seriesType, seriesUIDL.getChildUIDL(0)); if (seriesOptions != null) { seriesData.setSeriesOptions(seriesOptions); } seriesDataArr.push(seriesData); } VConsole.log("Exit [getChartData]"); return seriesDataArr; } private JsArray<GwtPointOptions> getSeriesPoints(UIDL pointsUIDL) { VConsole.log("Enter [getSeriesPoints]"); JsArray<GwtPointOptions> pointsArr = JavaScriptObject.createArray() .cast(); for (int cnt = 0; cnt < pointsUIDL.getChildCount(); cnt++) { UIDL pointUIDL = pointsUIDL.getChildUIDL(cnt); GwtPointOptions pointOptions = GwtPointOptions.create(); // If a point doesn't have any attributes then // consider it as a null since a user might want to represent // no activity graph if (pointUIDL.getAttributeNames().size() == 0) { pointOptions.setNullY(); } else { if (pointUIDL.hasAttribute("id")) { pointOptions.setId(pointUIDL.getStringAttribute("id")); } if (pointUIDL.hasAttribute("name")) { pointOptions.setName(pointUIDL.getStringAttribute("name")); } if (pointUIDL.hasAttribute("color")) { pointOptions .setColor(pointUIDL.getStringAttribute("color")); } if (pointUIDL.hasAttribute("sliced")) { pointOptions.setSliced(pointUIDL .getBooleanAttribute("sliced")); } if (pointUIDL.hasAttribute("selected")) { pointOptions.setSelected(pointUIDL .getBooleanAttribute("selected")); } if (pointUIDL.hasAttribute("x")) { pointOptions.setX(pointUIDL.getIntAttribute("x")); } else { pointOptions.setNullX(); } if (pointUIDL.hasAttribute("y")) { pointOptions.setY(pointUIDL.getIntAttribute("y")); } else { pointOptions.setNullY(); } if (pointUIDL.hasAttribute("isShift")) { pointOptions.setShift(pointUIDL .getBooleanAttribute("isShift")); } GwtMarker markerOptions = getMarkerOptions(pointUIDL .getChildUIDL(0)); if (markerOptions != null) { pointOptions.setMarker(markerOptions); } } pointsArr.push(pointOptions); } VConsole.log("Exit [getSeriesPoints]"); return pointsArr; } private GwtInvientChartsConfig getInvientChartOptions(UIDL uidl) { VConsole.log("Enter [getInvientChartOptions]"); VConsole.log("Child UIDL count : " + uidl.getChildCount()); GwtInvientChartsConfig options = GwtInvientChartsConfig.create(); // Get title UIDL VConsole.log("Getting title options..."); // Title options.setTitleOptions(getTitleOptions(uidl .getChildUIDL(ChartOptionsUIDLIndex.TITLE.ordinal()))); VConsole.log("Getting subtitle options..."); // Subtitle options.setSubtitleOptions(getSubtitleOptions(uidl .getChildUIDL(ChartOptionsUIDLIndex.SUBTITLE.ordinal()))); // Credit options.setCreditOptions(getCreditOptions(uidl .getChildUIDL(ChartOptionsUIDLIndex.CREDIT.ordinal()))); // Legend options.setLegendOptions(getLegendOptions(uidl .getChildUIDL(ChartOptionsUIDLIndex.LEGEND.ordinal()))); // Tooltip options.setTooltipOptions(getTooltipOptions(uidl .getChildUIDL(ChartOptionsUIDLIndex.TOOLTIP.ordinal()))); // Then DEMO application VConsole.log("Getting chart options..."); // Chart Options options.setChartOptions(getChartOptions(uidl .getChildUIDL(ChartOptionsUIDLIndex.CHART_CONFIG.ordinal()))); VConsole.log("Getting plot options..."); // Plot Options for various series types options.setPlotOptions(getPlotOptions(uidl .getChildUIDL(ChartOptionsUIDLIndex.SERIES_OPTIONS.ordinal()))); VConsole.log("Getting x-axis options..."); JsArray<GwtXAxisOptions> xAxisOptions = getXAxisOptions(uidl .getChildUIDL(ChartOptionsUIDLIndex.X_AXES.ordinal())); if (xAxisOptions.length() > 0) { options.setXAxesOptions(xAxisOptions); } VConsole.log("Getting y-axis options..."); JsArray<GwtYAxisOptions> yAxisOptions = getYAxisOptions(uidl .getChildUIDL(ChartOptionsUIDLIndex.Y_AXES.ordinal())); if (yAxisOptions.length() > 0) { options.setYAxesOptions(yAxisOptions); } VConsole.log("Getting chart labels..."); GwtChartLabels labels = getChartLabels(uidl .getChildUIDL(ChartOptionsUIDLIndex.LABEL.ordinal())); if (labels != null) { options.setLabels(labels); } VConsole.log("Exit [getInvientChartOptions]"); return options; } private GwtChartLabels getChartLabels(UIDL uidl) { VConsole.log("Enter [getChartLabels]"); VConsole.log("Tag name -> " + uidl.getTag()); if ((uidl.getAttributeNames().size() == 0 && uidl.getChildCount() == 0) || (uidl.getAttributeNames().size() > 0 && uidl.getChildCount() == 0)) { VConsole.log("Exit [getChartLabels]"); return null; } UIDL labelItemsUIDL = uidl.getChildUIDL(0); if (labelItemsUIDL.getChildCount() == 0) { VConsole.log("Exit [getChartLabels]"); return null; } GwtChartLabels labels = GwtChartLabels.create(); if (uidl.hasAttribute("style")) { labels.setStyle(uidl.getStringAttribute("style")); } JsArray<GwtChartLabelItem> chartLabelItemsArr = JavaScriptObject .createArray().cast(); for (int cnt = 0; cnt < labelItemsUIDL.getChildCount(); cnt++) { UIDL labelItemUIDL = labelItemsUIDL.getChildUIDL(cnt); if (labelItemUIDL.hasAttribute("html") || labelItemUIDL.hasAttribute("style")) { GwtChartLabelItem labelItem = GwtChartLabelItem.create(); if (labelItemUIDL.hasAttribute("html")) { labelItem.setHtml(labelItemUIDL.getStringAttribute("html")); } // if (labelItemUIDL.hasAttribute("style")) { labelItem.setStyle(labelItemUIDL .getStringAttribute("style")); } chartLabelItemsArr.push(labelItem); } } labels.setItems(chartLabelItemsArr); VConsole.log("Exit [getChartLabels]"); return labels; } private GwtCreditOptions getCreditOptions(UIDL uidl) { VConsole.log("Enter [getCreditOptions]"); VConsole.log("Tag name -> " + uidl.getTag()); GwtCreditOptions creditOptions = GwtCreditOptions.create(); if (uidl.hasAttribute("enabled")) { creditOptions.setEnabled(uidl.getBooleanAttribute("enabled")); } if (uidl.hasAttribute("href")) { creditOptions.setHref(uidl.getStringAttribute("href")); } if (uidl.hasAttribute("style")) { creditOptions.setStyle(uidl.getStringAttribute("style")); } if (uidl.hasAttribute("text")) { creditOptions.setText(uidl.getStringAttribute("text")); } UIDL positionUIDL = uidl.getChildUIDL(0); GwtPosition position = GwtPosition.create(); if (positionUIDL.hasAttribute("align")) { position.setAlign(positionUIDL.getStringAttribute("align")); } if (positionUIDL.hasAttribute("verticalAlign")) { position.setVerticalAlign(positionUIDL .getStringAttribute("verticalAlign")); } if (positionUIDL.hasAttribute("x")) { position.setX(positionUIDL.getIntAttribute("x")); } if (positionUIDL.hasAttribute("y")) { position.setY(positionUIDL.getIntAttribute("y")); } creditOptions.setPosition(position); VConsole.log("Exit [getCreditOptions]"); return creditOptions; } private GwtLegendOptions getLegendOptions(UIDL uidl) { VConsole.log("Enter [getLegendOptions]"); VConsole.log("Tag name -> " + uidl.getTag()); GwtLegendOptions legendOptions = GwtLegendOptions.create(); if (uidl.hasAttribute("align")) { legendOptions.setAlign(uidl.getStringAttribute("align")); } if (uidl.hasAttribute("backgroundColor")) { legendOptions.setBackgroundColor(uidl .getStringAttribute("backgroundColor")); } if (uidl.hasAttribute("borderColor")) { legendOptions .setBorderColor(uidl.getStringAttribute("borderColor")); } if (uidl.hasAttribute("borderRadius")) { legendOptions.setBorderRadius(uidl.getIntAttribute("borderRadius")); } if (uidl.hasAttribute("borderWidth")) { legendOptions.setBorderWidth(uidl.getIntAttribute("borderWidth")); } if (uidl.hasAttribute("enabled")) { legendOptions.setEnabled(uidl.getBooleanAttribute("enabled")); } if (uidl.hasAttribute("floating")) { legendOptions.setFloating(uidl.getBooleanAttribute("floating")); } if (uidl.hasAttribute("itemHiddenStyle")) { legendOptions.setItemHiddenStyle(uidl .getStringAttribute("itemHiddenStyle")); } if (uidl.hasAttribute("itemHoverStyle")) { legendOptions.setItemHoverStyle(uidl .getStringAttribute("itemHoverStyle")); } if (uidl.hasAttribute("itemStyle")) { legendOptions.setItemStyle(uidl.getStringAttribute("itemStyle")); } if (uidl.hasAttribute("itemWidth")) { legendOptions.setItemWidth(uidl.getIntAttribute("itemWidth")); } if (uidl.hasAttribute("layout")) { legendOptions.setLayout(uidl.getStringAttribute("layout")); } if (uidl.hasAttribute("labelFormatter")) { legendOptions.setLabelFormatter(getExecutableFunction(uidl .getStringAttribute("labelFormatter"))); } if (uidl.hasAttribute("margin")) { legendOptions.setMargin(uidl.getIntAttribute("margin")); } if (uidl.hasAttribute("reversed")) { legendOptions.setReversed(uidl.getBooleanAttribute("reversed")); } if (uidl.hasAttribute("shadow")) { legendOptions.setShadow(uidl.getBooleanAttribute("shadow")); } if (uidl.hasAttribute("symbolPadding")) { legendOptions.setSymbolPadding(uidl .getIntAttribute("symbolPadding")); } if (uidl.hasAttribute("symbolWidth")) { legendOptions.setSymbolWidth(uidl.getIntAttribute("symbolWidth")); } if (uidl.hasAttribute("verticalAlign")) { legendOptions.setVerticalAlign(uidl .getStringAttribute("verticalAlign")); } if (uidl.hasAttribute("width")) { legendOptions.setWidth(uidl.getIntAttribute("width")); } if (uidl.hasAttribute("x")) { legendOptions.setX(uidl.getIntAttribute("x")); } if (uidl.hasAttribute("y")) { legendOptions.setY(uidl.getIntAttribute("y")); } VConsole.log("Exit [getLegendOptions]"); return legendOptions; } private GwtTooltipOptions getTooltipOptions(UIDL uidl) { VConsole.log("Enter [getTooltipOptions]"); VConsole.log("Tag name -> " + uidl.getTag()); GwtTooltipOptions tooltipOptions = GwtTooltipOptions.create(); if (uidl.hasAttribute("backgroundColor")) { tooltipOptions.setBackgroundColor(uidl .getStringAttribute("backgroundColor")); } if (uidl.hasAttribute("borderColor")) { tooltipOptions.setBorderColor(uidl .getStringAttribute("borderColor")); } if (uidl.hasAttribute("borderRadius")) { tooltipOptions .setBorderRadius(uidl.getIntAttribute("borderRadius")); } if (uidl.hasAttribute("borderWidth")) { tooltipOptions.setBorderWidth(uidl.getIntAttribute("borderWidth")); } if (uidl.hasAttribute("crosshairs")) { tooltipOptions .setCrosshairs(uidl.getBooleanAttribute("crosshairs")); } if (uidl.hasAttribute("enabled")) { tooltipOptions.setEnabled(uidl.getBooleanAttribute("enabled")); } if (uidl.hasAttribute("formatter")) { tooltipOptions.setFormatter(getExecutableFunction(uidl .getStringAttribute("formatter"))); } if (uidl.hasAttribute("shadow")) { tooltipOptions.setShadow(uidl.getBooleanAttribute("shadow")); } if (uidl.hasAttribute("shared")) { tooltipOptions.setShared(uidl.getBooleanAttribute("shared")); } if (uidl.hasAttribute("snap")) { tooltipOptions.setSnap(uidl.getIntAttribute("snap")); } if (uidl.hasAttribute("style")) { tooltipOptions.setStyle(uidl.getStringAttribute("style")); } if (uidl.hasAttribute("xDateFormat")) { tooltipOptions.setXDateFormat(uidl.getStringAttribute("xDateFormat")); } if (uidl.hasAttribute("pointFormat")) { tooltipOptions.setPointFormat(uidl.getStringAttribute("pointFormat")); } if (uidl.hasAttribute("valueSuffix")) { tooltipOptions.setValueSuffix(uidl.getStringAttribute("valueSuffix")); } if (uidl.hasAttribute("valuePrefix")) { tooltipOptions.setValuePrefix(uidl.getStringAttribute("valuePrefix")); } if (uidl.hasAttribute("footerFormat")) { tooltipOptions.setFooterFormat(uidl.getStringAttribute("footerFormat")); } if (uidl.hasAttribute("valueDecimals")) { tooltipOptions.setValueDecimals(uidl.getIntAttribute("valueDecimals")); } if (uidl.hasAttribute("useHTML")) { tooltipOptions.setUseHtml(uidl.getBooleanAttribute("useHTML")); } VConsole.log("Exit [getTooltipOptions]"); return tooltipOptions; } private GwtTitleOptions getTitleOptions(UIDL uidl) { VConsole.log("Enter [getTitleOptions]"); VConsole.log("Tag Name : " + uidl.getTag()); GwtTitleOptions titleOptions = GwtTitleOptions.createTitleOptions(); updateTitleBaseOptions(uidl, titleOptions); if (uidl.hasAttribute("margin")) { titleOptions.setMargin(uidl.getIntAttribute("margin")); } VConsole.log("Exit [getTitleOptions]"); return titleOptions; } private GwtSubtitleOptions getSubtitleOptions(UIDL uidl) { VConsole.log("Enter [getSubtitleOptions]"); VConsole.log("Tag Name : " + uidl.getTag()); GwtSubtitleOptions subtitleOptions = GwtSubtitleOptions .createSubtitleOptions(); updateTitleBaseOptions(uidl, subtitleOptions); VConsole.log("Exit [getTitleOptions]"); return subtitleOptions; } private void updateTitleBaseOptions(UIDL uidl, GwtTitleBaseOptions titleBaseOptions) { VConsole.log("Enter [updateTitleBaseOptions]"); VConsole.log("Tag Name : " + uidl.getTag()); if (uidl.hasAttribute("text")) { titleBaseOptions.setText(uidl.getStringAttribute("text")); } if (uidl.hasAttribute("align")) { titleBaseOptions.setAlign(uidl.getStringAttribute("align")); } if (uidl.hasAttribute("floating")) { titleBaseOptions.setFloating(uidl.getBooleanAttribute("floating")); } if (uidl.hasAttribute("style")) { titleBaseOptions.setStyle(uidl.getStringAttribute("style")); } if (uidl.hasAttribute("verticalAlign")) { titleBaseOptions.setVerticalAlign(uidl .getStringAttribute("verticalAlign")); } if (uidl.hasAttribute("x")) { titleBaseOptions.setX(uidl.getIntAttribute("x")); } if (uidl.hasAttribute("y")) { titleBaseOptions.setY(uidl.getIntAttribute("y")); } VConsole.log("Exit [updateTitleBaseOptions]"); } private GwtChartOptions getChartOptions(UIDL uidl) { VConsole.log("Enter [getChartOptions]"); VConsole.log("Tag Name : " + uidl.getTag()); GwtChartOptions chartOptions = GwtChartOptions.create(); // DIV - A container for the InvientChart chartOptions.setRenderTo(super.divId); if (uidl.hasAttribute("type")) { chartOptions.setType(uidl.getStringAttribute("type")); } if (uidl.hasAttribute("width")) { chartOptions.setWidth(uidl.getIntAttribute("width")); } if (uidl.hasAttribute("height")) { chartOptions.setHeight(uidl.getIntAttribute("height")); } if (uidl.hasAttribute("backgroundColor")) { chartOptions.setBackgroundColor(uidl .getStringAttribute("backgroundColor")); } if (uidl.hasAttribute("borderColor")) { chartOptions.setBorderColor(uidl.getStringAttribute("borderColor")); } if (uidl.hasAttribute("borderRadius")) { chartOptions.setBorderRadius(uidl.getIntAttribute("borderRadius")); } if (uidl.hasAttribute("borderWidth")) { chartOptions.setBorderWidth(uidl.getIntAttribute("borderWidth")); } if (uidl.hasAttribute("ignoreHiddenSeries")) { chartOptions.setIgnoreHiddenSeries(uidl .getBooleanAttribute("ignoreHiddenSeries")); } if (uidl.hasAttribute("inverted")) { chartOptions.setInverted(uidl.getBooleanAttribute("inverted")); } if (uidl.hasAttribute("marginTop")) { chartOptions.setMarginTop(uidl.getIntAttribute("marginTop")); } if (uidl.hasAttribute("marginLeft")) { chartOptions.setMarginLeft(uidl.getIntAttribute("marginLeft")); } if (uidl.hasAttribute("marginRight")) { chartOptions.setMarginRight(uidl.getIntAttribute("marginRight")); } if (uidl.hasAttribute("marginBottom")) { chartOptions.setMarginBottom(uidl.getIntAttribute("marginBottom")); } if (uidl.hasAttribute("spacingTop")) { chartOptions.setSpacingTop(uidl.getIntAttribute("spacingTop")); } if (uidl.hasAttribute("spacingLeft")) { chartOptions.setSpacingLeft(uidl.getIntAttribute("spacingLeft")); } if (uidl.hasAttribute("spacingRight")) { chartOptions.setSpacingRight(uidl.getIntAttribute("spacingRight")); } if (uidl.hasAttribute("spacingBottom")) { chartOptions .setSpacingBottom(uidl.getIntAttribute("spacingBottom")); } if (uidl.hasAttribute("showAxes")) { chartOptions.setShowAxes(uidl.getBooleanAttribute("showAxes")); } if (uidl.hasAttribute("zoomType")) { chartOptions.setZoomType(uidl.getStringAttribute("zoomType")); } if (uidl.hasAttribute("clientZoom")) { chartOptions.setClientZoom(uidl.getBooleanAttribute("clientZoom")); } if (uidl.hasAttribute("alignTicks")) { chartOptions.setAlignTicks(uidl.getBooleanAttribute("alignTicks")); } if (uidl.hasAttribute("animation")) { chartOptions.setAnimation(uidl.getBooleanAttribute("animation")); } if (uidl.hasAttribute("className")) { chartOptions.setClassName(uidl.getStringAttribute("className")); } if (uidl.hasAttribute("plotBackgroundColor")) { chartOptions.setPlotBackgroundColor(uidl .getStringAttribute("plotBackgroundColor")); } if (uidl.hasAttribute("plotBorderColor")) { chartOptions.setPlotBorderColor(uidl .getStringAttribute("plotBorderColor")); } if (uidl.hasAttribute("plotBackgroundImage")) { chartOptions.setPlotBackgroundImage(uidl .getStringAttribute("plotBackgroundImage")); } if (uidl.hasAttribute("plotBorderWidth")) { chartOptions.setPlotBorderWidth(uidl .getIntAttribute("plotBorderWidth")); } if (uidl.hasAttribute("plotShadow")) { chartOptions.setPlotShadow(uidl.getBooleanAttribute("plotShadow")); } if (uidl.hasAttribute("reflow")) { chartOptions.setReflow(uidl.getBooleanAttribute("reflow")); } if (uidl.hasAttribute("shadow")) { chartOptions.setShadow(uidl.getBooleanAttribute("shadow")); } if (uidl.hasAttribute("style")) { chartOptions.setStyle(uidl.getStringAttribute("style")); } VConsole.log("Exit [getChartOptions]"); return chartOptions; } private void updateBaseAxisOptions(UIDL axisUIDL, GwtAxisBaseOptions axisBaseOptions) { VConsole.log("Enter [updateBaseAxisOptions]"); if (axisUIDL.hasAttribute("id")) { axisBaseOptions.setId(axisUIDL.getStringAttribute("id")); } if (axisUIDL.hasAttribute("allowDecimals")) { axisBaseOptions.setAllowDecimals(axisUIDL .getBooleanAttribute("allowDecimals")); } if (axisUIDL.hasAttribute("alternateGridColor")) { axisBaseOptions.setAlternateGridColor(axisUIDL .getStringAttribute("alternateGridColor")); } if (axisUIDL.hasAttribute("endOnTick")) { axisBaseOptions.setEndOnTick(axisUIDL .getBooleanAttribute("endOnTick")); } // Grid if (axisUIDL.hasAttribute("gridLineColor")) { axisBaseOptions.setGridLineColor(axisUIDL .getStringAttribute("gridLineColor")); } if (axisUIDL.hasAttribute("gridLineWidth")) { axisBaseOptions.setGridLineWidth(axisUIDL .getIntAttribute("gridLineWidth")); } if (axisUIDL.hasAttribute("gridLineDashStyle")) { axisBaseOptions.setGridLineDashStyle(axisUIDL .getStringAttribute("gridLineDashStyle")); } // Line if (axisUIDL.hasAttribute("lineColor")) { axisBaseOptions.setLineColor(axisUIDL .getStringAttribute("lineColor")); } if (axisUIDL.hasAttribute("lineWidth")) { axisBaseOptions.setLineWidth(axisUIDL.getIntAttribute("lineWidth")); } // if (axisUIDL.hasAttribute("linkedTo")) { axisBaseOptions.setLinkedTo(axisUIDL.getIntAttribute("linkedTo")); } if (axisUIDL.hasAttribute("max")) { axisBaseOptions.setMax(axisUIDL.getDoubleAttribute("max")); } if (axisUIDL.hasAttribute("maxPadding")) { axisBaseOptions.setMaxPadding(axisUIDL .getDoubleAttribute("maxPadding")); } if (axisUIDL.hasAttribute("maxZoom")) { axisBaseOptions.setMaxZoom(axisUIDL.getIntAttribute("maxZoom")); } // if (axisUIDL.hasAttribute("min")) { axisBaseOptions.setMin(axisUIDL.getDoubleAttribute("min")); } if (axisUIDL.hasAttribute("minPadding")) { axisBaseOptions.setMinPadding(axisUIDL .getDoubleAttribute("minPadding")); } // Minor Grid if (axisUIDL.hasAttribute("minorGridLineColor")) { axisBaseOptions.setMinorGridLineColor(axisUIDL .getStringAttribute("minorGridLineColor")); } if (axisUIDL.hasAttribute("minorGridLineWidth")) { axisBaseOptions.setMinorGridLineWidth(axisUIDL .getIntAttribute("minorGridLineWidth")); } if (axisUIDL.hasAttribute("minorGridLineDashStyle")) { axisBaseOptions.setMinorGridLineDashStyle(axisUIDL .getStringAttribute("minorGridLineDashStyle")); } // Minor Ticks if (axisUIDL.hasAttribute("minorTickColor")) { axisBaseOptions.setMinorTickColor(axisUIDL .getStringAttribute("minorTickColor")); } if (axisUIDL.hasAttribute("minorTickInterval")) { axisBaseOptions.setMinorTickInterval(axisUIDL .getDoubleAttribute("minorTickInterval")); } if (axisUIDL.hasAttribute("minorTickLength")) { axisBaseOptions.setMinorTickLength(axisUIDL .getIntAttribute("minorTickLength")); } if (axisUIDL.hasAttribute("minorTickPosition")) { axisBaseOptions.setMinorTickPosition(axisUIDL .getStringAttribute("minorTickPosition")); } if (axisUIDL.hasAttribute("minorTickWidth")) { axisBaseOptions.setMinorTickWidth(axisUIDL .getIntAttribute("minorTickWidth")); } // if (axisUIDL.hasAttribute("offset")) { axisBaseOptions.setOffset(axisUIDL.getIntAttribute("offset")); } if (axisUIDL.hasAttribute("opposite")) { axisBaseOptions.setOpposite(axisUIDL .getBooleanAttribute("opposite")); } if (axisUIDL.hasAttribute("reversed")) { axisBaseOptions.setReversed(axisUIDL .getBooleanAttribute("reversed")); } if (axisUIDL.hasAttribute("showFirstLabel")) { axisBaseOptions.setShowFirstLabel(axisUIDL .getBooleanAttribute("showFirstLabel")); } if (axisUIDL.hasAttribute("showLastLabel")) { axisBaseOptions.setShowLastLabel(axisUIDL .getBooleanAttribute("showLastLabel")); } if (axisUIDL.hasAttribute("startOfWeek")) { axisBaseOptions.setStartOfWeek(axisUIDL .getIntAttribute("startOfWeek")); } if (axisUIDL.hasAttribute("startOnTick")) { axisBaseOptions.setStartOnTick(axisUIDL .getBooleanAttribute("startOnTick")); } // Tick if (axisUIDL.hasAttribute("tickColor")) { axisBaseOptions.setTickColor(axisUIDL .getStringAttribute("tickColor")); } if (axisUIDL.hasAttribute("tickInterval")) { axisBaseOptions.setTickInterval(axisUIDL .getDoubleAttribute("tickInterval")); } if (axisUIDL.hasAttribute("tickLength")) { axisBaseOptions.setTickLength(axisUIDL .getIntAttribute("tickLength")); } if (axisUIDL.hasAttribute("tickPosition")) { axisBaseOptions.setTickPosition(axisUIDL .getStringAttribute("tickPosition")); } if (axisUIDL.hasAttribute("tickWidth")) { axisBaseOptions.setTickWidth(axisUIDL.getIntAttribute("tickWidth")); } if (axisUIDL.hasAttribute("tickPixelInterval")) { axisBaseOptions.setTickPixelInterval(axisUIDL .getIntAttribute("tickPixelInterval")); } if (axisUIDL.hasAttribute("tickmarkPlacement")) { axisBaseOptions.setTickmarkPlacement(axisUIDL .getStringAttribute("tickmarkPlacement")); } if (axisUIDL.hasAttribute("type")) { axisBaseOptions.setType(axisUIDL.getStringAttribute("type")); } // title UIDL titleUIDL = axisUIDL.getChildUIDL(0); GwtAxisTitleOptions titleOptions = getAxisTitleOptions(titleUIDL); if (titleOptions != null) { axisBaseOptions.setTitle(titleOptions); } // label UIDL labelUIDL = axisUIDL.getChildUIDL(1); String axisName = axisUIDL.getTag(); GwtAxisDataLabels axisDataLabels = getAxisDataLabels(labelUIDL, axisName); if (axisDataLabels != null) { axisBaseOptions.setLabels(axisDataLabels); } // plotband UIDL plotBandsUIDL = axisUIDL.getChildUIDL(2); JsArray<GwtPlotBands> plotBands = getPlotBands(plotBandsUIDL); if (plotBands.length() > 0) { axisBaseOptions.setPlotBands(plotBands); } // plotline UIDL plotLinesUIDL = axisUIDL.getChildUIDL(3); JsArray<GwtPlotLines> plotLines = getPlotLines(plotLinesUIDL); if (plotLines.length() > 0) { axisBaseOptions.setPlotLines(plotLines); } VConsole.log("Exit [updateBaseAxisOptions]"); } private GwtAxisTitleOptions getAxisTitleOptions(UIDL axisTitleUIDL) { if (axisTitleUIDL == null || axisTitleUIDL.getAttributeNames().size() == 0) { return null; } GwtAxisTitleOptions titleOptions = GwtAxisTitleOptions.create(); if (axisTitleUIDL.hasAttribute("align")) { titleOptions.setAlign(axisTitleUIDL.getStringAttribute("align")); } if (axisTitleUIDL.hasAttribute("margin")) { titleOptions.setMargin(axisTitleUIDL.getIntAttribute("margin")); } if (axisTitleUIDL.hasAttribute("rotation")) { titleOptions.setRotation(axisTitleUIDL.getIntAttribute("rotation")); } if (axisTitleUIDL.hasAttribute("style")) { titleOptions.setStyle(axisTitleUIDL.getStringAttribute("style")); } if (axisTitleUIDL.hasAttribute("text")) { titleOptions.setText(axisTitleUIDL.getStringAttribute("text")); } return titleOptions; } private JsArray<GwtPlotBands> getPlotBands(UIDL plotBandsUIDL) { JsArray<GwtPlotBands> plotBandsArr = JavaScriptObject.createArray() .cast(); for (int cnt = 0; cnt < plotBandsUIDL.getChildCount(); cnt++) { UIDL plotBandUIDL = plotBandsUIDL.getChildUIDL(cnt); if (plotBandUIDL.getAttributeNames().size() == 0 && plotBandUIDL.getChildCount() == 0) { continue; } GwtPlotBands plotBands = GwtPlotBands.create(); if (plotBandUIDL.hasAttribute("color")) { plotBands.setColor(plotBandUIDL.getStringAttribute("color")); } if (plotBandUIDL.hasAttribute("id")) { plotBands.setId(plotBandUIDL.getStringAttribute("id")); } if (plotBandUIDL.hasAttribute("zIndex")) { plotBands.setZIndex(plotBandUIDL.getIntAttribute("zIndex")); } // label GwtPlotLabel label = getPlotLabel(plotBandUIDL.getChildUIDL(0)); if (label != null) { plotBands.setLabel(label); } // from/to value UIDL valueUIDL = plotBandUIDL.getChildUIDL(1); if (valueUIDL.hasAttribute("valueType")) { String valueType = valueUIDL.getStringAttribute("valueType"); if (valueType.equals("number")) { plotBands.setFrom(valueUIDL.getDoubleAttribute("from")); plotBands.setTo(valueUIDL.getDoubleAttribute("to")); } else { // date // from UIDL fromUIDL = valueUIDL.getChildUIDL(0); int fromYear = fromUIDL.getIntAttribute("year"); int fromMonth = fromUIDL.getIntAttribute("month"); int fromDay = fromUIDL.getIntAttribute("day"); plotBands.setFrom("Date.UTC(" + fromYear + ", " + fromMonth + "," + fromDay + ")"); // to UIDL toUIDL = valueUIDL.getChildUIDL(1); int toYear = toUIDL.getIntAttribute("year"); int toMonth = toUIDL.getIntAttribute("month"); int toDay = toUIDL.getIntAttribute("day"); plotBands.setTo("Date.UTC(" + toYear + ", " + toMonth + "," + toDay + ")"); } } // plotBandsArr.push(plotBands); } return plotBandsArr; } private JsArray<GwtPlotLines> getPlotLines(UIDL plotLinesUIDL) { JsArray<GwtPlotLines> plotLinesArr = JavaScriptObject.createArray() .cast(); for (int cnt = 0; cnt < plotLinesUIDL.getChildCount(); cnt++) { UIDL plotLineUIDL = plotLinesUIDL.getChildUIDL(cnt); if (plotLineUIDL.getAttributeNames().size() == 0 && plotLineUIDL.getChildCount() == 0) { continue; } GwtPlotLines plotLines = GwtPlotLines.create(); if (plotLineUIDL.hasAttribute("color")) { plotLines.setColor(plotLineUIDL.getStringAttribute("color")); } if (plotLineUIDL.hasAttribute("dashStyle")) { plotLines.setDashStyle(plotLineUIDL .getStringAttribute("dashStyle")); } if (plotLineUIDL.hasAttribute("id")) { plotLines.setId(plotLineUIDL.getStringAttribute("id")); } if (plotLineUIDL.hasAttribute("width")) { plotLines.setWidth(plotLineUIDL.getIntAttribute("width")); } if (plotLineUIDL.hasAttribute("zIndex")) { plotLines.setZIndex(plotLineUIDL.getIntAttribute("zIndex")); } // label GwtPlotLabel label = getPlotLabel(plotLineUIDL.getChildUIDL(0)); if (label != null) { plotLines.setLabel(label); } // line value UIDL lineValueUIDL = plotLineUIDL.getChildUIDL(1); if (lineValueUIDL.hasAttribute("valueType")) { String valueType = lineValueUIDL .getStringAttribute("valueType"); if (valueType.equals("number")) { if (lineValueUIDL.hasAttribute("value")) { plotLines.setValue(lineValueUIDL .getDoubleAttribute("value")); } } else { // date int year = lineValueUIDL.getIntAttribute("year"); int month = lineValueUIDL.getIntAttribute("month"); int day = lineValueUIDL.getIntAttribute("day"); plotLines.setValue("Date.UTC(" + year + ", " + month + "," + day + ")"); } } // plotLinesArr.push(plotLines); } return plotLinesArr; } private GwtPlotLabel getPlotLabel(UIDL plotLabelUIDL) { if (plotLabelUIDL == null || plotLabelUIDL.getAttributeNames().size() == 0) { return null; } GwtPlotLabel label = GwtPlotLabel.create(); if (plotLabelUIDL.hasAttribute("align")) { label.setAlign(plotLabelUIDL.getStringAttribute("align")); } if (plotLabelUIDL.hasAttribute("rotation")) { label.setRotation(plotLabelUIDL.getIntAttribute("rotation")); } if (plotLabelUIDL.hasAttribute("style")) { label.setStyle(plotLabelUIDL.getStringAttribute("style")); } if (plotLabelUIDL.hasAttribute("align")) { label.setAlign(plotLabelUIDL.getStringAttribute("align")); } if (plotLabelUIDL.hasAttribute("text")) { label.setText(plotLabelUIDL.getStringAttribute("text")); } if (plotLabelUIDL.hasAttribute("verticalAlign")) { label.setVerticalAlign(plotLabelUIDL .getStringAttribute("verticalAlign")); } if (plotLabelUIDL.hasAttribute("x")) { label.setX(plotLabelUIDL.getIntAttribute("x")); } if (plotLabelUIDL.hasAttribute("y")) { label.setY(plotLabelUIDL.getIntAttribute("y")); } return label; } // FIXME - Code organization private GwtAxisDataLabels getAxisDataLabels(UIDL labelUIDL, String axisName) { if (labelUIDL == null || labelUIDL.getAttributeNames().size() == 0) { return null; } if (axisName.equals("xAxis")) { GwtXAxisDataLabels labels = GwtXAxisDataLabels.createXAxisLabels(); updateDataLabel(labelUIDL, labels); if (labelUIDL.hasAttribute("staggerLines")) { labels.setStaggerLines(labelUIDL .getIntAttribute("staggerLines")); } if (labelUIDL.hasAttribute("step")) { labels.setStep(labelUIDL.getIntAttribute("step")); } return labels; } else { GwtYAxisDataLabels labels = GwtYAxisDataLabels.createYAxisLabels(); updateDataLabel(labelUIDL, labels); return labels; } } private JsArray<GwtXAxisOptions> getXAxisOptions(UIDL uidl) { VConsole.log("Enter [getXAxisOptions]"); VConsole.log("Tag Name : " + uidl.getTag()); JsArray<GwtXAxisOptions> xAxes = JavaScriptObject.createArray().cast(); for (int cnt = 0; cnt < uidl.getChildCount(); cnt++) { GwtXAxisOptions xAxisOptions = GwtXAxisOptions.create(); UIDL axisUIDL = uidl.getChildUIDL(cnt); if (axisUIDL.getAttributeNames().size() == 0 && axisUIDL.getChildCount() == 0) { continue; } updateBaseAxisOptions(axisUIDL, xAxisOptions); UIDL childUIDL = axisUIDL.getChildUIDL(4); if (childUIDL != null) { if (childUIDL.getTag().equals("categories") && childUIDL.getChildCount() > 0) { JsArrayString categories = JavaScriptObject.createArray() .cast(); UIDL categoriesUIDL = childUIDL; for (int idx = 0; idx < categoriesUIDL.getChildCount(); idx++) { categories.push(categoriesUIDL.getChildUIDL(idx) .getStringAttribute("name")); } xAxisOptions.setCategories(categories); } else if (childUIDL.getTag().equals("dateTimeLabelFormats") && childUIDL.getAttributeNames().size() > 0) { UIDL dateTimeLblFmtsUIDL = childUIDL; GwtDateTimeLabelFormats formats = GwtDateTimeLabelFormats .create(); if (dateTimeLblFmtsUIDL.hasAttribute("second")) { formats.setSecond(dateTimeLblFmtsUIDL .getStringAttribute("second")); } if (dateTimeLblFmtsUIDL.hasAttribute("minute")) { formats.setMinute(dateTimeLblFmtsUIDL .getStringAttribute("minute")); } if (dateTimeLblFmtsUIDL.hasAttribute("hour")) { formats.setHour(dateTimeLblFmtsUIDL .getStringAttribute("hour")); } if (dateTimeLblFmtsUIDL.hasAttribute("day")) { formats.setDay(dateTimeLblFmtsUIDL .getStringAttribute("day")); } if (dateTimeLblFmtsUIDL.hasAttribute("week")) { formats.setWeek(dateTimeLblFmtsUIDL .getStringAttribute("week")); } if (dateTimeLblFmtsUIDL.hasAttribute("month")) { formats.setMonth(dateTimeLblFmtsUIDL .getStringAttribute("month")); } if (dateTimeLblFmtsUIDL.hasAttribute("year")) { formats.setYear(dateTimeLblFmtsUIDL .getStringAttribute("year")); } xAxisOptions.setDateTimeLabelFormats(formats); } } xAxes.push(xAxisOptions); } VConsole.log("Exit [getXAxisOptions]"); return xAxes; } private JsArray<GwtYAxisOptions> getYAxisOptions(UIDL uidl) { VConsole.log("Enter [getYAxisOptions]"); VConsole.log("Tag Name : " + uidl.getTag()); JsArray<GwtYAxisOptions> yAxes = JavaScriptObject.createArray().cast(); for (int cnt = 0; cnt < uidl.getChildCount(); cnt++) { GwtYAxisOptions yAxisOptions = GwtYAxisOptions.create(); UIDL axisUIDL = uidl.getChildUIDL(cnt); if (axisUIDL.getAttributeNames().size() == 0 && axisUIDL.getChildCount() == 0) { continue; } updateBaseAxisOptions(axisUIDL, yAxisOptions); yAxes.push(yAxisOptions); } VConsole.log("Exit [getYAxisOptions]"); return yAxes; } private GwtPlotOptions getPlotOptions(UIDL uidl) { VConsole.log("Enter [getPlotOptions]"); VConsole.log("Tag Name : " + uidl.getTag()); GwtPlotOptions plotOptions = GwtPlotOptions.create(); for (int cnt = 0; cnt < uidl.getChildCount(); cnt++) { UIDL seriesUIDL = uidl.getChildUIDL(cnt); String seriesType = seriesUIDL.getTag(); VConsole.log("Series Type : " + seriesType); GwtSeriesGeneralOptions seriesOptions = getSeriesOptions( seriesType, seriesUIDL); if (seriesOptions == null) { continue; } if (seriesType.equals("series")) { plotOptions.setSeries(seriesOptions); } else if (seriesType.equals("line")) { plotOptions.setLine((GwtLineOptions) seriesOptions); } else if (seriesType.equals("scatter")) { plotOptions.setScatter((GwtScatterOptions) seriesOptions); } else if (seriesType.equals("spline")) { plotOptions.setSpline((GwtSplineOptions) seriesOptions); } else if (seriesType.equals("area")) { plotOptions.setArea((GwtAreaOptions) seriesOptions); } else if (seriesType.equals("areaspline")) { plotOptions.setAreaSpline((GwtAreaSplineOptions) seriesOptions); } else if (seriesType.equals("bar")) { plotOptions.setBar((GwtBarOptions) seriesOptions); } else if (seriesType.equals("column")) { plotOptions.setColumn((GwtColumnOptions) seriesOptions); } else if (seriesType.equals("pie")) { plotOptions.setPie((GwtPieOptions) seriesOptions); } } VConsole.log("Exit [getPlotOptions]"); return plotOptions; } private GwtSeriesGeneralOptions getSeriesOptions(String seriesType, UIDL seriesUIDL) { VConsole.log("Enter [getSeriesOptions]"); VConsole.log("Tag Name : " + seriesUIDL.getTag()); if (seriesUIDL.getAttributeNames().size() == 0 && seriesUIDL.getChildCount() == 0) { VConsole.log("No attributes/children found for series type : " + seriesType); VConsole.log("Exit [getSeriesOptions]"); return null; } GwtSeriesGeneralOptions seriesOptions = null; if (seriesType.equals("series")) { seriesOptions = GwtSeriesGeneralOptions.createSeriesOptions(); updateSeriesOptions(seriesUIDL, seriesOptions); } else if (seriesType.equals("line")) { seriesOptions = GwtLineOptions.createLineOptions(); updateLineOptions(seriesUIDL, (GwtLineOptions) seriesOptions); } else if (seriesType.equals("scatter")) { seriesOptions = GwtScatterOptions.createScatterOptions(); updateScatterOptions(seriesUIDL, (GwtScatterOptions) seriesOptions); } else if (seriesType.equals("spline")) { seriesOptions = GwtSplineOptions.createSplineOptions(); updateSplineOptions(seriesUIDL, (GwtSplineOptions) seriesOptions); } else if (seriesType.equals("area")) { seriesOptions = GwtAreaOptions.createAreaOptions(); updateAreaOptions(seriesUIDL, (GwtAreaOptions) seriesOptions); } else if (seriesType.equals("areaspline")) { seriesOptions = GwtAreaSplineOptions.createAreaSplineOptions(); updateAreaSplineOptions(seriesUIDL, (GwtAreaSplineOptions) seriesOptions); } else if (seriesType.equals("bar")) { seriesOptions = GwtBarOptions.createBarOptions(); updateBarOptions(seriesUIDL, (GwtBarOptions) seriesOptions); } else if (seriesType.equals("column")) { seriesOptions = GwtColumnOptions.createColumnOptions(); updateColumnOptions(seriesUIDL, (GwtColumnOptions) seriesOptions); } else if (seriesType.equals("pie")) { seriesOptions = GwtPieOptions.createPieOptions(); updatePieOptions(seriesUIDL, (GwtPieOptions) seriesOptions); } else { // This should not happen VConsole.log("[getSeriesOptions] : Invalid series type " + seriesType); } VConsole.log("Exit [getSeriesOptions]"); return seriesOptions; } private void updateSeriesOptions(UIDL seriesUIDL, GwtSeriesGeneralOptions seriesOptions) { VConsole.log("Enter [updateSeriesOptions]"); VConsole.log("Tag Name : " + seriesUIDL.getTag()); if (seriesUIDL.hasAttribute("allowPointSelect")) { seriesOptions.setAllowPointSelect(seriesUIDL .getBooleanAttribute("allowPointSelect")); } if (seriesUIDL.hasAttribute("animation")) { seriesOptions.setAnimation(seriesUIDL .getBooleanAttribute("animation")); } if (seriesUIDL.hasAttribute("cursor")) { seriesOptions.setCursor(seriesUIDL.getStringAttribute("cursor")); } if (seriesUIDL.hasAttribute("enableMouseTracking")) { seriesOptions.setEnableMouseTracking(seriesUIDL .getBooleanAttribute("enableMouseTracking")); } if (seriesUIDL.hasAttribute("selected")) { seriesOptions.setSelected(seriesUIDL .getBooleanAttribute("selected")); } if (seriesUIDL.hasAttribute("shadow")) { seriesOptions.setShadow(seriesUIDL.getBooleanAttribute("shadow")); } if (seriesUIDL.hasAttribute("showCheckbox")) { seriesOptions.setShowCheckbox(seriesUIDL .getBooleanAttribute("showCheckbox")); } if (seriesUIDL.hasAttribute("showInLegend")) { seriesOptions.setShowInLegend(seriesUIDL .getBooleanAttribute("showInLegend")); } if (seriesUIDL.hasAttribute("stacking")) { seriesOptions .setStacking(seriesUIDL.getStringAttribute("stacking")); } if (seriesUIDL.hasAttribute("visible")) { seriesOptions.setVisible(seriesUIDL.getBooleanAttribute("visible")); } if (seriesUIDL.hasAttribute("color")) { seriesOptions.setColor(seriesUIDL.getStringAttribute("color")); } // FIXME - How to get series type // datalabels GwtDataLabels dataLabels = getSeriesDataLabel( seriesUIDL.getChildUIDL(0), seriesUIDL.getTag()); if (dataLabels != null) { seriesOptions.setDataLabels(dataLabels); } // state GwtStates seriesState = getSeriesState(seriesUIDL.getChildUIDL(1)); if (seriesState != null) { seriesOptions.setStates(seriesState); } VConsole.log("Exit [updateSeriesOptions]"); } private GwtDataLabels getSeriesDataLabel(UIDL dataLabelUIDL, String seriesType) { VConsole.log("Enter [getSeriesDataLabel]"); if (dataLabelUIDL == null || dataLabelUIDL.getAttributeNames().size() == 0) { return null; } GwtDataLabels dataLabel = GwtDataLabels.createDataLabels(); if (seriesType.equals("pie")) { dataLabel = GwtPieDataLabels.createPieDataLabels(); updatePieDataLabel(dataLabelUIDL, (GwtPieDataLabels) dataLabel); } else { updateDataLabel(dataLabelUIDL, dataLabel); } VConsole.log("Exit [getSeriesDataLabel]"); return dataLabel; } private void updatePieDataLabel(UIDL dataLabelUIDL, GwtPieDataLabels pieDataLabel) { updateDataLabel(dataLabelUIDL, pieDataLabel); if (dataLabelUIDL.hasAttribute("connectorColor")) { pieDataLabel.setConnectorColor(dataLabelUIDL .getStringAttribute("connectorColor")); } if (dataLabelUIDL.hasAttribute("connectorWidth")) { pieDataLabel.setConnectorWidth(dataLabelUIDL .getIntAttribute("connectorWidth")); } if (dataLabelUIDL.hasAttribute("connectorPadding")) { pieDataLabel.setConnectorPadding(dataLabelUIDL .getIntAttribute("connectorPadding")); } if (dataLabelUIDL.hasAttribute("distance")) { pieDataLabel.setDistance(dataLabelUIDL.getIntAttribute("distance")); } } private void updateDataLabel(UIDL dataLabelUIDL, GwtDataLabels dataLabel) { if (dataLabelUIDL.hasAttribute("align")) { dataLabel.setAlign(dataLabelUIDL.getStringAttribute("align")); } if (dataLabelUIDL.hasAttribute("enabled")) { dataLabel.setEnabled(dataLabelUIDL.getBooleanAttribute("enabled")); } if (dataLabelUIDL.hasAttribute("formatter")) { dataLabel.setFormatter(getExecutableFunction(dataLabelUIDL .getStringAttribute("formatter"))); } if (dataLabelUIDL.hasAttribute("rotation")) { dataLabel.setRotation(dataLabelUIDL.getIntAttribute("rotation")); } if (dataLabelUIDL.hasAttribute("style")) { dataLabel.setStyle(dataLabelUIDL.getStringAttribute("style")); } if (dataLabelUIDL.hasAttribute("x")) { dataLabel.setX(dataLabelUIDL.getIntAttribute("x")); } if (dataLabelUIDL.hasAttribute("y")) { dataLabel.setY(dataLabelUIDL.getIntAttribute("y")); } if (dataLabelUIDL.hasAttribute("color")) { dataLabel.setColor(dataLabelUIDL.getStringAttribute("color")); } } private GwtStates getSeriesState(UIDL stateUIDL) { if (stateUIDL == null || (stateUIDL != null && stateUIDL.getChildCount() == 0) || (stateUIDL.getChildCount() > 0 && stateUIDL.getChildUIDL(0) .getAttributeNames().size() == 0)) { return null; } GwtStates state = GwtStates.create(); GwtHover hover = GwtHover.create(); state.setHover(hover); UIDL hoverUIDL = stateUIDL.getChildUIDL(0); if (hoverUIDL.hasAttribute("enabled")) { hover.setEnabled(hoverUIDL.getBooleanAttribute("enabled")); } if (hoverUIDL.hasAttribute("lineWidth")) { hover.setLineWidth(hoverUIDL.getIntAttribute("lineWidth")); } if (hoverUIDL.hasAttribute("brightness")) { hover.setBrightness(hoverUIDL.getDoubleAttribute("brightness")); } return state; } private GwtMarker getMarkerOptions(UIDL uidl) { VConsole.log("Enter [getMarkerOptions]"); int noOfAttrs = 0; noOfAttrs = (uidl != null ? uidl.getAttributeNames().size() : 0); if (uidl == null || (noOfAttrs == 0 && uidl.getChildCount() == 0)) { VConsole.log("Exit [getMarkerOptions]"); return null; } GwtMarker marker = GwtMarker.create(); String markerType = uidl.getStringAttribute("markerType"); if (uidl.hasAttribute("enabled")) { marker.setEnabled(uidl.getBooleanAttribute("enabled")); } if (uidl.hasAttribute("lineColor")) { marker.setLineColor(uidl.getStringAttribute("lineColor")); } if (uidl.hasAttribute("fillColor")) { marker.setFillColor(uidl.getStringAttribute("fillColor")); } if (uidl.hasAttribute("lineWidth")) { marker.setLineWidth(uidl.getIntAttribute("lineWidth")); } if (uidl.hasAttribute("radius")) { marker.setRadius(uidl.getIntAttribute("radius")); } if (uidl.hasAttribute("symbol")) { if (markerType.equals("image")) { marker.setSymbol("url(." + uidl.getStringAttribute("symbol") + ")"); } else { marker.setSymbol(uidl.getStringAttribute("symbol")); } } // Marker states exist only in case of SymbolMarker and not ImageMarker if (uidl.getChildCount() > 0) { UIDL statesUIDL = uidl.getChildUIDL(0); UIDL hoverStateUIDL = statesUIDL.getChildUIDL(0); UIDL selectStateUIDL = statesUIDL.getChildUIDL(1); GwtMarkerState markerHoverState = getMarkerState(hoverStateUIDL); GwtMarkerState markerSelectState = getMarkerState(selectStateUIDL); if (markerHoverState != null || markerSelectState != null) { VConsole.log("Setting marker states..."); GwtMarkerStates markerStates = GwtMarkerStates.create(); if (markerHoverState != null) { markerStates.setHover(markerHoverState); } if (markerSelectState != null) { markerStates.setSelect(markerSelectState); } marker.setStates(markerStates); } } VConsole.log("Exit [getMarkerOptions]"); return marker; } private GwtMarkerState getMarkerState(UIDL uidl) { VConsole.log("Enter [getMarkerState]"); if (uidl == null || uidl.getAttributeNames().size() == 0) { VConsole.log("Neither hover nor select states found for a maker."); VConsole.log("Exit [getMarkerState]"); return null; } GwtMarkerState markerState = GwtMarkerState.create(); if (uidl.hasAttribute("enabled")) { markerState.setEnabled(uidl.getBooleanAttribute("enabled")); } if (uidl.hasAttribute("lineColor")) { markerState.setLineColor(uidl.getStringAttribute("lineColor")); } if (uidl.hasAttribute("fillColor")) { markerState.setFillColor(uidl.getStringAttribute("fillColor")); } if (uidl.hasAttribute("lineWidth")) { markerState.setLineWidth(uidl.getIntAttribute("lineWidth")); } if (uidl.hasAttribute("radius")) { markerState.setRadius(uidl.getIntAttribute("radius")); } VConsole.log("Exit [getMarkerState]"); return markerState; } private void updateBaseLineOptions(UIDL lineUIDL, GwtBaseLineOptions lineOptions) { VConsole.log("Enter [updateBaseLineOptions]"); updateSeriesOptions(lineUIDL, lineOptions); if (lineUIDL.hasAttribute("color")) { lineOptions.setColor(lineUIDL.getStringAttribute("color")); } if (lineUIDL.hasAttribute("dashStyle")) { lineOptions.setDashStyle(lineUIDL.getStringAttribute("dashStyle")); } if (lineUIDL.hasAttribute("lineWidth")) { lineOptions.setLineWidth(lineUIDL.getIntAttribute("lineWidth")); } if (lineUIDL.hasAttribute("pointStart")) { lineOptions.setPointStart(lineUIDL.getDoubleAttribute("pointStart")); } if (lineUIDL.hasAttribute("pointInterval")) { lineOptions.setPointInterval(lineUIDL .getIntAttribute("pointInterval")); } if (lineUIDL.hasAttribute("stickyTracking")) { lineOptions.setStickyTracking(lineUIDL .getBooleanAttribute("stickyTracking")); } GwtMarker marker = getMarkerOptions(lineUIDL.getChildUIDL(2)); if (marker != null) { lineOptions.setMarker(marker); } VConsole.log("Exit [updateBaseLineOptions]"); } private void updateLineOptions(UIDL lineUIDL, GwtLineOptions lineOptions) { VConsole.log("Enter [updateLineOptions]"); VConsole.log("Tag Name : " + lineUIDL.getTag()); updateBaseLineOptions(lineUIDL, lineOptions); if (lineUIDL.hasAttribute("step")) { lineOptions.setStep(lineUIDL.getBooleanAttribute("step")); } VConsole.log("Exit [updateBaseLineOptions]"); } private void updateScatterOptions(UIDL scatterUIDL, GwtScatterOptions scatterOptions) { VConsole.log("Enter [updateScatterOptions]"); VConsole.log("Tag Name : " + scatterUIDL.getTag()); updateBaseLineOptions(scatterUIDL, scatterOptions); VConsole.log("Exit [updateScatterOptions]"); } private void updateSplineOptions(UIDL splineUIDL, GwtSplineOptions splineOptions) { VConsole.log("Enter [updateSplineOptions]"); VConsole.log("Tag Name : " + splineUIDL.getTag()); updateBaseLineOptions(splineUIDL, splineOptions); VConsole.log("Exit [updateSplineOptions]"); } private void updateAreaOptions(UIDL areaUIDL, GwtAreaOptions areaOptions) { VConsole.log("Enter [updateAreaOptions]"); VConsole.log("Tag Name : " + areaUIDL.getTag()); updateBaseLineOptions(areaUIDL, areaOptions); if (areaUIDL.hasAttribute("fillColor")) { areaOptions.setFillColor(areaUIDL.getStringAttribute("fillColor")); } if (areaUIDL.hasAttribute("lineColor")) { areaOptions.setLineColor(areaUIDL.getStringAttribute("lineColor")); } if (areaUIDL.hasAttribute("fillOpacity")) { areaOptions.setFillOpacity(areaUIDL .getDoubleAttribute("fillOpacity")); } if (areaUIDL.hasAttribute("threshold")) { areaOptions.setThreshold(areaUIDL.getIntAttribute("threshold")); } VConsole.log("Exit [updateAreaOptions]"); } private void updateAreaSplineOptions(UIDL areaSplineUIDL, GwtAreaSplineOptions areaSplineOptions) { VConsole.log("Enter [updateAreaSplineOptions]"); VConsole.log("Tag Name : " + areaSplineUIDL.getTag()); updateAreaOptions(areaSplineUIDL, areaSplineOptions); VConsole.log("Exit [updateAreaSplineOptions]"); } private void updatePieOptions(UIDL pieUIDL, GwtPieOptions pieOptions) { VConsole.log("Enter [updatePieOptions]"); VConsole.log("Tag Name : " + pieUIDL.getTag()); updateSeriesOptions(pieUIDL, pieOptions); Integer centerX = null; Integer centerY = null; if (pieUIDL.hasAttribute("centerX")) { centerX = pieUIDL.getIntAttribute("centerX"); } if (pieUIDL.hasAttribute("centerY")) { centerY = pieUIDL.getIntAttribute("centerY"); } if (centerX != null || centerY != null) { JsArrayNumber center = JavaScriptObject.createArray().cast(); center.push((centerX == null ? 0 : centerX)); center.push((centerY == null ? 0 : centerY)); pieOptions.setCenter(center); } if (pieUIDL.hasAttribute("borderColor")) { pieOptions .setBorderColor(pieUIDL.getStringAttribute("borderColor")); } if (pieUIDL.hasAttribute("borderWidth")) { pieOptions.setBorderWidth(pieUIDL.getIntAttribute("borderWidth")); } if (pieUIDL.hasAttribute("innerSize")) { pieOptions.setInnerSize(pieUIDL.getIntAttribute("innerSize")); } if (pieUIDL.hasAttribute("size")) { pieOptions.setSize(pieUIDL.getIntAttribute("size")); } if (pieUIDL.hasAttribute("slicedOffset")) { pieOptions.setSlicedOffset(pieUIDL.getIntAttribute("slicedOffset")); } VConsole.log("Exit [updatePieOptions]"); } private void updateBaseBarOptions(UIDL barUIDL, GwtBaseBarOptions baseBarOptions) { VConsole.log("Enter [updateBaseBarOptions]"); updateSeriesOptions(barUIDL, baseBarOptions); if (barUIDL.hasAttribute("borderColor")) { baseBarOptions.setBorderColor(barUIDL .getStringAttribute("borderColor")); } if (barUIDL.hasAttribute("borderWidth")) { baseBarOptions.setBorderWidth(barUIDL .getIntAttribute("borderWidth")); } if (barUIDL.hasAttribute("borderRadius")) { baseBarOptions.setBorderRadius(barUIDL .getIntAttribute("borderRadius")); } if (barUIDL.hasAttribute("colorByPoint")) { baseBarOptions.setColorByPoint(barUIDL .getBooleanAttribute("colorByPoint")); } if (barUIDL.hasAttribute("groupPadding")) { baseBarOptions.setGroupPadding(barUIDL .getDoubleAttribute("groupPadding")); } if (barUIDL.hasAttribute("minPointLength")) { baseBarOptions.setMinPointLength(barUIDL .getDoubleAttribute("minPointLength")); } if (barUIDL.hasAttribute("pointPadding")) { baseBarOptions.setPointPadding(barUIDL .getDoubleAttribute("pointPadding")); } if (barUIDL.hasAttribute("pointWidth")) { baseBarOptions.setPointWidth(barUIDL.getIntAttribute("pointWidth")); } VConsole.log("Exit [updateBaseBarOptions]"); } private void updateBarOptions(UIDL barUIDL, GwtBarOptions barOptions) { VConsole.log("Enter [updateBarOptions]"); VConsole.log("Tag Name : " + barUIDL.getTag()); updateBaseBarOptions(barUIDL, barOptions); VConsole.log("Exit [updateBarOptions]"); } private void updateColumnOptions(UIDL columnUIDL, GwtColumnOptions columnOptions) { VConsole.log("Enter [updateColumnOptions]"); VConsole.log("Tag Name : " + columnUIDL.getTag()); updateBaseBarOptions(columnUIDL, columnOptions); VConsole.log("Exit [updateColumnOptions]"); } private void updateOptionsWithChartEvents(GwtInvientChartsConfig options, UIDL chartEventUIDL) { VConsole.log("Enter [updateOptionsWithChartEvents]"); // Chart events GwtChartEvents chartEvents = GwtChartEvents.create(); if (chartEventUIDL.hasAttribute("addSeries") && chartEventUIDL.getBooleanAttribute("addSeries")) { chartEvents.setAddSeriesEvent(EventCallbacks .getChartAddSeries(this)); } if (chartEventUIDL.hasAttribute("click") && chartEventUIDL.getBooleanAttribute("click")) { chartEvents.setClickEvent(EventCallbacks.getChartClick(this)); } if (chartEventUIDL.hasAttribute("selection") && chartEventUIDL.getBooleanAttribute("selection")) { if (options.getChartOptions().getClientZoom()) { chartEvents.setSelectionEvent(EventCallbacks .getClientChartSelection(this)); } else { chartEvents.setSelectionEvent(EventCallbacks .getServerChartSelection(this)); } } if (options.getChartOptions() == null) { options.setChartOptions(GwtChartOptions.create()); } options.getChartOptions().setEvents(chartEvents); VConsole.log("Exit [updateOptionsWithChartEvents]"); } private GwtSeriesEvents getSeriesEvents(UIDL seriesEventUIDL) { GwtSeriesEvents seriesEvents = GwtSeriesEvents.create(); boolean foundEvt = false; if (seriesEventUIDL.hasAttribute("legendItemClick") && seriesEventUIDL.getBooleanAttribute("legendItemClick")) { seriesEvents.setLegendItemClickEvent(EventCallbacks .getSeriesLegendItemClick(this)); foundEvt = true; } if (seriesEventUIDL.hasAttribute("click") && seriesEventUIDL.getBooleanAttribute("click")) { seriesEvents.setClickEvent(EventCallbacks.getSeriesClick(this)); foundEvt = true; } if (seriesEventUIDL.hasAttribute("show") && seriesEventUIDL.getBooleanAttribute("show")) { seriesEvents.setShowEvent(EventCallbacks.getSeriesShow(this)); foundEvt = true; } if (seriesEventUIDL.hasAttribute("hide") && seriesEventUIDL.getBooleanAttribute("hide")) { seriesEvents.setHideEvent(EventCallbacks.getSeriesHide(this)); foundEvt = true; } if (foundEvt) { return seriesEvents; } return null; } private void updateOptionsWithSeriesAndPoingEvents( GwtInvientChartsConfig options, UIDL chartSeriesEventsUIDL) { VConsole.log("Enter [updateOptionsWithSeriesAndPoingEvents]"); VConsole.log("[updateOptionsWithSeriesEvents] # of series : " + chartSeriesEventsUIDL.getChildCount()); // UIDL seriesEventUIDL = eventUIDL.getChildUIDL(1); if (chartSeriesEventsUIDL.getChildCount() > 0 && options.getPlotOptions() == null) { options.setPlotOptions(GwtPlotOptions.create()); } for (int cnt = 0; cnt < chartSeriesEventsUIDL.getChildCount(); cnt++) { UIDL seriesEventsUIDL = chartSeriesEventsUIDL.getChildUIDL(cnt); String seriesType = seriesEventsUIDL.getTag(); // can be // series/pie/line // etc VConsole.log("Series type " + seriesType); // GwtSeriesEvents seriesEvents = getSeriesEvents(seriesEventsUIDL); // GwtPointEvents pointEvents = null; if (seriesEventsUIDL.getChildCount() > 0) { pointEvents = getPointEvents(options, seriesEventsUIDL.getChildUIDL(0)); } if (seriesEvents == null && pointEvents == null) { VConsole.log("No series/point events found for series type : " + seriesType); continue; } GwtSeriesGeneralOptions seriesOptions = null; if (seriesType.equals("line")) { if (options.getPlotOptions().getLine() == null) { options.getPlotOptions().setLine( GwtLineOptions.createLineOptions()); } seriesOptions = options.getPlotOptions().getLine(); } else if (seriesType.equals("spline")) { if (options.getPlotOptions().getSpline() == null) { options.getPlotOptions().setSpline( GwtSplineOptions.createSplineOptions()); } seriesOptions = options.getPlotOptions().getSpline(); } else if (seriesType.equals("area")) { if (options.getPlotOptions().getArea() == null) { options.getPlotOptions().setArea( GwtAreaOptions.createAreaOptions()); } seriesOptions = options.getPlotOptions().getArea(); } else if (seriesType.equals("areaspline")) { if (options.getPlotOptions().getAreaSpline() == null) { options.getPlotOptions().setAreaSpline( GwtAreaSplineOptions.createAreaSplineOptions()); } seriesOptions = options.getPlotOptions().getAreaSpline(); } else if (seriesType.equals("bar")) { if (options.getPlotOptions().getBar() == null) { options.getPlotOptions().setBar( GwtBarOptions.createBarOptions()); } seriesOptions = options.getPlotOptions().getBar(); } else if (seriesType.equals("column")) { if (options.getPlotOptions().getColumn() == null) { options.getPlotOptions().setColumn( GwtColumnOptions.createColumnOptions()); } seriesOptions = options.getPlotOptions().getColumn(); } else if (seriesType.equals("scatter")) { if (options.getPlotOptions().getScatter() == null) { options.getPlotOptions().setScatter( GwtScatterOptions.createScatterOptions()); } seriesOptions = options.getPlotOptions().getScatter(); } else if (seriesType.equals("pie")) { if (options.getPlotOptions().getPie() == null) { options.getPlotOptions().setPie( GwtPieOptions.createPieOptions()); } seriesOptions = options.getPlotOptions().getPie(); } else { if (options.getPlotOptions().getSeries() == null) { options.getPlotOptions().setSeries( GwtSeriesGeneralOptions.createSeriesOptions()); } seriesOptions = options.getPlotOptions().getSeries(); } // Set series/point events if (seriesEvents != null) { seriesOptions.setEvents(seriesEvents); } if (pointEvents != null) { seriesOptions.setPointEvents(pointEvents); } } VConsole.log("Exit [updateOptionsWithSeriesAndPoingEvents]"); } private GwtPointEvents getPointEvents(GwtInvientChartsConfig options, UIDL pointEventsUIDL) { VConsole.log("Enter [getPointEvents]"); // Point events boolean foundEvt = false; GwtPointEvents pointEvents = GwtPointEvents.create(); if (pointEventsUIDL.hasAttribute("legendItemClick") && pointEventsUIDL.getBooleanAttribute("legendItemClick")) { pointEvents.setLegendItemClickEvent(EventCallbacks .getPieLegendItemClick(this)); foundEvt = true; } if (pointEventsUIDL.hasAttribute("click") && pointEventsUIDL.getBooleanAttribute("click")) { pointEvents.setClickEvent(EventCallbacks.getPointClick(this)); foundEvt = true; } if (pointEventsUIDL.hasAttribute("remove") && pointEventsUIDL.getBooleanAttribute("remove")) { pointEvents.setRemoveEvent(EventCallbacks.getPointRemove(this)); foundEvt = true; } if (pointEventsUIDL.hasAttribute("select") && pointEventsUIDL.getBooleanAttribute("select")) { pointEvents.setSelectEvent(EventCallbacks.getPointSelect(this)); foundEvt = true; } if (pointEventsUIDL.hasAttribute("unselect") && pointEventsUIDL.getBooleanAttribute("unselect")) { pointEvents.setUnselectEvent(EventCallbacks.getPointUnselect(this)); foundEvt = true; } VConsole.log("Exit [getPointEvents]"); if (foundEvt) { return pointEvents; } return null; } private void updateOptionsWithEvents(GwtInvientChartsConfig options, UIDL eventUIDL) { VConsole.log("Enter [updateOptionsWithEvents]"); // Chart events updateOptionsWithChartEvents(options, eventUIDL.getChildUIDL(0)); // Series events updateOptionsWithSeriesAndPoingEvents(options, eventUIDL.getChildUIDL(1)); VConsole.log("Exit [updateOptionsWithEvents]"); } protected void chartAddSeriesListener(GwtChart chart) { VConsole.log("Enter [chartAddSeriesListener]"); client.updateVariable(uidlId, "event", "addSeries", true); VConsole.log("Exit [chartAddSeriesListener]"); } protected void chartClickListener(GwtChart chart, double xAxisPos, double yAxisPos, int pageX, int pageY) { VConsole.log("Enter [chartClickListener]"); VConsole.log("chartClickListener : xAxisPos : " + xAxisPos + ", yAxisPos : " + yAxisPos); client.updateVariable(uidlId, "event", "chartClick", false); Map<String, Object> eventData = new HashMap<String, Object>(); eventData.put("xAxisPos", String.valueOf(xAxisPos)); eventData.put("yAxisPos", String.valueOf(yAxisPos)); updateEventDataWithMousePosition(eventData, pageX, pageY); client.updateVariable(uidlId, "eventData", eventData, true); VConsole.log("Exit [chartClickListener]"); } protected void chartSelectionListener(GwtChart chart, double xAxisMin, double xAxisMax, double yAxisMin, double yAxisMax) { VConsole.log("Enter [chartSelectionListener]"); VConsole.log("[chartSelectionListener] xAxisMin : " + xAxisMin + ", xAxisMax : " + xAxisMax + ", yAxisMin : " + yAxisMin + ", yAxisMax : " + yAxisMax); client.updateVariable(uidlId, "event", "chartZoom", false); Map<String, Object> eventData = new HashMap<String, Object>(); eventData.put("xAxisMin", String.valueOf(xAxisMin)); eventData.put("xAxisMax", String.valueOf(xAxisMax)); eventData.put("yAxisMin", String.valueOf(yAxisMin)); eventData.put("yAxisMax", String.valueOf(yAxisMax)); client.updateVariable(uidlId, "eventData", eventData, true); VConsole.log("Exit [chartSelectionListener]"); } protected void chartResetZoomListener(GwtChart chart) { VConsole.log("Enter [chartResetZoomListener]"); client.updateVariable(uidlId, "event", "chartResetZoom", true); VConsole.log("Exit [chartResetZoomListener]"); } protected void seriesClickListener(GwtSeries series, GwtPoint nearestPoint, int pageX, int pageY) { VConsole.log("Enter [seriesClickListener]"); VConsole.log("[seriesClickListener] point x: " + nearestPoint.getX() + ", point y: " + nearestPoint.getY()); client.updateVariable(uidlId, "event", "seriesClick", false); Map<String, Object> eventData = getEventData(nearestPoint); updateEventDataWithMousePosition(eventData, pageX, pageY); client.updateVariable(uidlId, "eventData", eventData, true); VConsole.log("Exit [seriesClickListener]"); } protected void seriesHideListener(GwtSeries series) { VConsole.log("Enter [seriesHideListener]"); VConsole.log("[seriesHideListener] series name " + series.getName()); client.updateVariable(uidlId, "event", "seriesHide", false); Map<String, Object> eventData = new HashMap<String, Object>(); eventData.put("seriesName", series.getName()); client.updateVariable(uidlId, "eventData", eventData, true); VConsole.log("Exit [seriesHideListener]"); } protected void seriesShowListener(GwtSeries series) { VConsole.log("Enter [seriesShowListener]"); VConsole.log("[seriesShowListener] series name " + series.getName()); client.updateVariable(uidlId, "event", "seriesShow", false); Map<String, Object> eventData = new HashMap<String, Object>(); eventData.put("seriesName", series.getName()); client.updateVariable(uidlId, "eventData", eventData, true); VConsole.log("Exit [seriesShowListener]"); } protected void seriesLegendItemClickListener(GwtSeries series) { VConsole.log("Enter [seriesLegendItemClickListener]"); VConsole.log("[seriesLegendItemClickListener] name " + series.getName()); client.updateVariable(uidlId, "event", "seriesLegendItemClick", false); Map<String, Object> eventData = new HashMap<String, Object>(); eventData.put("seriesName", series.getName()); client.updateVariable(uidlId, "eventData", eventData, true); VConsole.log("Exit [seriesLegendItemClickListener]"); } protected void pieLegendItemClickListener(GwtPoint point) { VConsole.log("Enter [pieLegendItemClickListener]"); client.updateVariable(uidlId, "event", "pieLegendItemClick", false); Map<String, Object> eventData = getEventData(point); client.updateVariable(uidlId, "eventData", eventData, true); VConsole.log("Exit [pieLegendItemClickListener]"); } protected void pointClickListener(GwtPoint point, int pageX, int pageY) { VConsole.log("Enter [pointClickListener]"); client.updateVariable(uidlId, "event", "pointClick", false); Map<String, Object> eventData = getEventData(point); updateEventDataWithMousePosition(eventData, pageX, pageY); client.updateVariable(uidlId, "eventData", eventData, true); VConsole.log("Exit [pointClickListener]"); } protected void pointSelectListener(GwtPoint point) { VConsole.log("Enter [pointSelectListener]"); VConsole.log("[pointSelectListener] point " + point.getX() + ", " + point.getY()); client.updateVariable(uidlId, "event", "pointSelect", false); client.updateVariable(uidlId, "eventData", getEventData(point), true); VConsole.log("Exit [pointSelectListener]"); } protected void pointUnselectListener(GwtPoint point) { VConsole.log("Enter [pointUnselectListener]"); VConsole.log("[pointUnselectListener] point " + point.getX() + ", " + point.getY()); client.updateVariable(uidlId, "event", "pointUnselect", false); client.updateVariable(uidlId, "eventData", getEventData(point), true); VConsole.log("Exit [pointUnselectListener]"); } protected void pointRemoveListener(GwtPoint point) { VConsole.log("Enter [pointRemoveListener]"); VConsole.log("[pointRemoveListener] point " + point.getX() + ", " + point.getY()); client.updateVariable(uidlId, "event", "pointRemove", false); client.updateVariable(uidlId, "eventData", getEventData(point), true); VConsole.log("Exit [pointRemoveListener]"); } private Map<String, Object> getEventData(GwtPoint point) { Map<String, Object> eventData = new HashMap<String, Object>(); eventData.put("seriesName", point.getSeries().getName()); eventData.put("category", point.getCategory()); // The point x and y values are converted into // string value to avoid data conversion issues // for datetime series/axis // It is responsibility of the server to convert string value // into appropriate data type e.g. double or Date eventData.put("pointX", String.valueOf(point.getX())); eventData.put("pointY", String.valueOf(point.getY())); return eventData; } private void updateEventDataWithMousePosition( Map<String, Object> eventData, int pageX, int pageY) { eventData.put("mouseX", pageX); eventData.put("mouseY", pageY); } private String getExecutableFunction(String formatterFunc) { StringBuilder sb = new StringBuilder(""); sb.append("function dummy() { "); sb.append(" return "); sb.append(formatterFunc).append(";"); sb.append(" }"); sb.append(" dummy();"); return sb.toString(); } /** * Define a JS function to be used in order to get mouse coordinates when * click event occurs on a chart/series/point */ private native final void publish() /*-{ // Used in based class GwtInvientCharts.java $wnd.getMouseCoords = function(ev) { if(ev.pageX || ev.pageY){ return {x:ev.pageX, y:ev.pageY}; } else { return { x:ev.clientX + document.documentElement.scrollLeft, y:ev.clientY + document.documentElement.scrollTop }; } }; // Used in class GwtInvientChartsConfig.java $wnd.getInvientChartsColor = function(colorVal) { var colorKey = 'JSOBJ:'; var index = colorVal.indexOf(colorKey); if(index == 0) { return eval('(' + colorVal.substring(index+colorKey.length) + ')'); } return colorVal; }; }-*/; }
Chart did not resize itself if it the parent container was resized. For example, if the chart was in a split pane, the size was fixed until the window was resized.
src/com/invient/vaadin/charts/widgetset/client/ui/VInvientCharts.java
Chart did not resize itself if it the parent container was resized. For example, if the chart was in a split pane, the size was fixed until the window was resized.
<ide><path>rc/com/invient/vaadin/charts/widgetset/client/ui/VInvientCharts.java <ide> .getChildUIDL(ChartOptionsUIDLIndex.CHART_CONFIG.ordinal())); <ide> int newWidth = chartOptions.getWidth(); <ide> int newHeight = chartOptions.getHeight(); <add> updateChartSize(newWidth, newHeight); <add> } <add> <add> private void updateChartSize(int newWidth, int newHeight) { <ide> int existingWidth = chart.getOptions().getChartOptions().getWidth(); <ide> int existingHeight = chart.getOptions().getChartOptions().getHeight(); <ide> <ide> if ((newWidth != -1 && newWidth != existingWidth) <ide> || (newHeight != -1 && newHeight != existingHeight)) { <del> VConsole.log("Set chart size."); <add> VConsole.log("Set chart size."); <ide> chart.getOptions().getChartOptions().setWidth(newWidth); <ide> chart.getOptions().getChartOptions().setHeight(newHeight); <ide> chart.setSize(newWidth, newHeight); <add> } <add> } <add> <add> @Override <add> public void setHeight(String height) { <add> super.setHeight(height); <add> updateChartSize(); <add> } <add> <add> @Override <add> public void setWidth(String width) { <add> super.setWidth(width); <add> updateChartSize(); <add> } <add> <add> private void updateChartSize() { <add> if (chart != null) { <add> updateChartSize(getElement().getOffsetWidth(), getElement().getOffsetHeight()); <ide> } <ide> } <ide>
Java
epl-1.0
648e4d2337ec8525315e92acd8fcdf7567639391
0
ghillairet/gef-gwt
/******************************************************************************* * Copyright (c) 2000, 2009 IBM Corporation and others. * 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: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jface.resource; import org.eclipse.jface.internal.InternalPolicy; import org.eclipse.swt.SWTException; import org.eclipse.swt.graphics.Device; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; /** * An image descriptor that loads its image information from a file. */ class FileImageDescriptor extends ImageDescriptor { /** * The class whose resource directory contain the file, or <code>null</code> * if none. */ private Class location; /** * The name of the file. */ private String name; /** * Creates a new file image descriptor. The file has the given file name and * is located in the given class's resource directory. If the given class is * <code>null</code>, the file name must be absolute. * <p> * Note that the file is not accessed until its <code>getImageDate</code> * method is called. * </p> * * @param clazz * class for resource directory, or <code>null</code> * @param filename * the name of the file */ FileImageDescriptor(Class clazz, String filename) { this.location = clazz; this.name = filename; } /* * (non-Javadoc) Method declared on Object. */ public boolean equals(Object o) { if (!(o instanceof FileImageDescriptor)) { return false; } FileImageDescriptor other = (FileImageDescriptor) o; if (location != null) { if (!location.equals(other.location)) { return false; } } else { if (other.location != null) { return false; } } return name.equals(other.name); } // /** // * @see org.eclipse.jface.resource.ImageDescriptor#getImageData() The // * FileImageDescriptor implementation of this method is not used by // * {@link ImageDescriptor#createImage(boolean, Device)} as of version // * 3.4 so that the SWT OS optimised loading can be used. // */ public ImageData getImageData() { // InputStream in = getStream(); // ImageData result = null; // if (in != null) { // try { // // result = new ImageData(in); // } catch (SWTException e) { // if (e.code != SWT.ERROR_INVALID_IMAGE) { // throw e; // // fall through otherwise // } // } finally { // try { // in.close(); // } catch (IOException e) { // // System.err.println(getClass().getName()+".getImageData(): // // "+ // // "Exception while closing InputStream : "+e); // } // } // } // return result; return null; } // /** // * Returns a stream on the image contents. Returns null if a stream could // * not be opened. // * // * @return the buffered stream on the file or <code>null</code> if the file // * cannot be found // */ // private InputStream getStream() { // InputStream is = null; // // if (location != null) { // // is = location.getResourceAsStream(name); // // } else { // // try { // // is = new FileInputStream(name); // // } catch (FileNotFoundException e) { // return null; // // } // } // if (is == null) { // return null; // } // // return new BufferedInputStream(is); // return null; // // } /* * (non-Javadoc) Method declared on Object. */ public int hashCode() { int code = name.hashCode(); if (location != null) { code += location.hashCode(); } return code; } /* * (non-Javadoc) Method declared on Object. */ /** * The <code>FileImageDescriptor</code> implementation of this * <code>Object</code> method returns a string representation of this object * which is suitable only for debugging. */ public String toString() { return "FileImageDescriptor(location=" + location + ", name=" + name + ")";//$NON-NLS-3$//$NON-NLS-2$//$NON-NLS-1$ } /* * (non-Javadoc) * * @see org.eclipse.jface.resource.ImageDescriptor#createImage(boolean, * org.eclipse.swt.graphics.Device) */ public Image createImage(boolean returnMissingImageOnError, Device device) { Image img = ImageDescriptorHelper.getInstance() .getImage(location, name); if (img != null) { return img; } String path = getFilePath(); if (path == null) return createDefaultImage(returnMissingImageOnError, device); try { return new Image(device, path); } catch (SWTException exception) { // if we fail try the default way using a stream } return super.createImage(returnMissingImageOnError, device); } /** * Return default image if returnMissingImageOnError is true. * * @param device * @return Image or <code>null</code> */ private Image createDefaultImage(boolean returnMissingImageOnError, Device device) { try { if (returnMissingImageOnError) return new Image(device, DEFAULT_IMAGE_DATA); } catch (SWTException nextException) { return null; } return null; } /** * Returns the filename for the ImageData. * * @return {@link String} or <code>null</code> if the file cannot be found */ private String getFilePath() { if (location == null) // return new Path(name).toOSString(); return null; // URL resource = location.getResource(name); // if (resource == null) // return null; if (!InternalPolicy.OSGI_AVAILABLE) {// Stand-alone case // return new Path(resource.getFile()).toOSString(); return null; } // return new // Path(FileLocator.toFileURL(resource).getPath()).toOSString(); return null; } }
src/main/java/org/eclipse/jface/resource/FileImageDescriptor.java
/******************************************************************************* * Copyright (c) 2000, 2009 IBM Corporation and others. * 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: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jface.resource; import java.io.IOException; import java.io.InputStream; import org.eclipse.jface.internal.InternalPolicy; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTException; import org.eclipse.swt.graphics.Device; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; /** * An image descriptor that loads its image information from a file. */ class FileImageDescriptor extends ImageDescriptor { /** * The class whose resource directory contain the file, or <code>null</code> * if none. */ private Class location; /** * The name of the file. */ private String name; /** * Creates a new file image descriptor. The file has the given file name and * is located in the given class's resource directory. If the given class is * <code>null</code>, the file name must be absolute. * <p> * Note that the file is not accessed until its <code>getImageDate</code> * method is called. * </p> * * @param clazz * class for resource directory, or <code>null</code> * @param filename * the name of the file */ FileImageDescriptor(Class clazz, String filename) { this.location = clazz; this.name = filename; } /* * (non-Javadoc) Method declared on Object. */ public boolean equals(Object o) { if (!(o instanceof FileImageDescriptor)) { return false; } FileImageDescriptor other = (FileImageDescriptor) o; if (location != null) { if (!location.equals(other.location)) { return false; } } else { if (other.location != null) { return false; } } return name.equals(other.name); } /** * @see org.eclipse.jface.resource.ImageDescriptor#getImageData() The * FileImageDescriptor implementation of this method is not used by * {@link ImageDescriptor#createImage(boolean, Device)} as of version * 3.4 so that the SWT OS optimised loading can be used. */ public ImageData getImageData() { InputStream in = getStream(); ImageData result = null; if (in != null) { try { // result = new ImageData(in); } catch (SWTException e) { if (e.code != SWT.ERROR_INVALID_IMAGE) { throw e; // fall through otherwise } } finally { try { in.close(); } catch (IOException e) { // System.err.println(getClass().getName()+".getImageData(): // "+ // "Exception while closing InputStream : "+e); } } } return result; } /** * Returns a stream on the image contents. Returns null if a stream could * not be opened. * * @return the buffered stream on the file or <code>null</code> if the file * cannot be found */ private InputStream getStream() { InputStream is = null; if (location != null) { // is = location.getResourceAsStream(name); } else { // try { // is = new FileInputStream(name); // } catch (FileNotFoundException e) { return null; // } } if (is == null) { return null; } // return new BufferedInputStream(is); return null; } /* * (non-Javadoc) Method declared on Object. */ public int hashCode() { int code = name.hashCode(); if (location != null) { code += location.hashCode(); } return code; } /* * (non-Javadoc) Method declared on Object. */ /** * The <code>FileImageDescriptor</code> implementation of this * <code>Object</code> method returns a string representation of this object * which is suitable only for debugging. */ public String toString() { return "FileImageDescriptor(location=" + location + ", name=" + name + ")";//$NON-NLS-3$//$NON-NLS-2$//$NON-NLS-1$ } /* * (non-Javadoc) * * @see org.eclipse.jface.resource.ImageDescriptor#createImage(boolean, * org.eclipse.swt.graphics.Device) */ public Image createImage(boolean returnMissingImageOnError, Device device) { Image img = ImageDescriptorHelper.getInstance() .getImage(location, name); if (img != null) { return img; } String path = getFilePath(); if (path == null) return createDefaultImage(returnMissingImageOnError, device); try { return new Image(device, path); } catch (SWTException exception) { // if we fail try the default way using a stream } return super.createImage(returnMissingImageOnError, device); } /** * Return default image if returnMissingImageOnError is true. * * @param device * @return Image or <code>null</code> */ private Image createDefaultImage(boolean returnMissingImageOnError, Device device) { try { if (returnMissingImageOnError) return new Image(device, DEFAULT_IMAGE_DATA); } catch (SWTException nextException) { return null; } return null; } /** * Returns the filename for the ImageData. * * @return {@link String} or <code>null</code> if the file cannot be found */ private String getFilePath() { if (location == null) // return new Path(name).toOSString(); return null; // URL resource = location.getResource(name); // if (resource == null) // return null; if (!InternalPolicy.OSGI_AVAILABLE) {// Stand-alone case // return new Path(resource.getFile()).toOSString(); return null; } // return new // Path(FileLocator.toFileURL(resource).getPath()).toOSString(); return null; } }
remove references to java.io.InputStream
src/main/java/org/eclipse/jface/resource/FileImageDescriptor.java
remove references to java.io.InputStream
<ide><path>rc/main/java/org/eclipse/jface/resource/FileImageDescriptor.java <ide> *******************************************************************************/ <ide> package org.eclipse.jface.resource; <ide> <del>import java.io.IOException; <del>import java.io.InputStream; <del> <ide> import org.eclipse.jface.internal.InternalPolicy; <del>import org.eclipse.swt.SWT; <ide> import org.eclipse.swt.SWTException; <ide> import org.eclipse.swt.graphics.Device; <ide> import org.eclipse.swt.graphics.Image; <ide> return name.equals(other.name); <ide> } <ide> <del> /** <del> * @see org.eclipse.jface.resource.ImageDescriptor#getImageData() The <del> * FileImageDescriptor implementation of this method is not used by <del> * {@link ImageDescriptor#createImage(boolean, Device)} as of version <del> * 3.4 so that the SWT OS optimised loading can be used. <del> */ <add>// /** <add>// * @see org.eclipse.jface.resource.ImageDescriptor#getImageData() The <add>// * FileImageDescriptor implementation of this method is not used by <add>// * {@link ImageDescriptor#createImage(boolean, Device)} as of version <add>// * 3.4 so that the SWT OS optimised loading can be used. <add>// */ <ide> public ImageData getImageData() { <del> InputStream in = getStream(); <del> ImageData result = null; <del> if (in != null) { <del> try { <del> // result = new ImageData(in); <del> } catch (SWTException e) { <del> if (e.code != SWT.ERROR_INVALID_IMAGE) { <del> throw e; <del> // fall through otherwise <del> } <del> } finally { <del> try { <del> in.close(); <del> } catch (IOException e) { <del> // System.err.println(getClass().getName()+".getImageData(): <del> // "+ <del> // "Exception while closing InputStream : "+e); <del> } <del> } <del> } <del> return result; <del> } <del> <del> /** <del> * Returns a stream on the image contents. Returns null if a stream could <del> * not be opened. <del> * <del> * @return the buffered stream on the file or <code>null</code> if the file <del> * cannot be found <del> */ <del> private InputStream getStream() { <del> InputStream is = null; <del> <del> if (location != null) { <del> // is = location.getResourceAsStream(name); <del> <del> } else { <del> // try { <del> // is = new FileInputStream(name); <del> // } catch (FileNotFoundException e) { <del> return null; <del> // } <del> } <del> if (is == null) { <del> return null; <del> } <del> // return new BufferedInputStream(is); <add>// InputStream in = getStream(); <add>// ImageData result = null; <add>// if (in != null) { <add>// try { <add>// // result = new ImageData(in); <add>// } catch (SWTException e) { <add>// if (e.code != SWT.ERROR_INVALID_IMAGE) { <add>// throw e; <add>// // fall through otherwise <add>// } <add>// } finally { <add>// try { <add>// in.close(); <add>// } catch (IOException e) { <add>// // System.err.println(getClass().getName()+".getImageData(): <add>// // "+ <add>// // "Exception while closing InputStream : "+e); <add>// } <add>// } <add>// } <add>// return result; <ide> return null; <del> <del> } <add> } <add> <add>// /** <add>// * Returns a stream on the image contents. Returns null if a stream could <add>// * not be opened. <add>// * <add>// * @return the buffered stream on the file or <code>null</code> if the file <add>// * cannot be found <add>// */ <add>// private InputStream getStream() { <add>// InputStream is = null; <add>// <add>// if (location != null) { <add>// // is = location.getResourceAsStream(name); <add>// <add>// } else { <add>// // try { <add>// // is = new FileInputStream(name); <add>// // } catch (FileNotFoundException e) { <add>// return null; <add>// // } <add>// } <add>// if (is == null) { <add>// return null; <add>// } <add>// // return new BufferedInputStream(is); <add>// return null; <add>// <add>// } <ide> <ide> /* <ide> * (non-Javadoc) Method declared on Object.
Java
apache-2.0
f381fb5a5a900cf071a114955e20ac400b71cdca
0
CINERGI/SciGraph,CINERGI/SciGraph,CINERGI/SciGraph,SciGraph/SciGraph,SciGraph/SciGraph,SciGraph/SciGraph,CINERGI/SciGraph
/** * Copyright (C) 2014 The SciGraph 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 io.scigraph.services.resources; import static com.google.common.collect.Lists.newArrayList; import io.scigraph.services.swagger.beans.resource.Apis; import io.scigraph.services.swagger.beans.resource.Resource; import java.util.List; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.codahale.metrics.annotation.Timed; @Path("/api-docs/dynamic") @Produces(MediaType.APPLICATION_JSON) public class DynamicSwaggerService { private final List<Apis> apis; @Inject public DynamicSwaggerService(List<Apis> apis) { this.apis = apis; } @GET @Timed public Resource getDocumentation() { Resource resource = new Resource(); resource.setApiVersion("1.0.1"); resource.setSwaggerVersion("1.2"); resource.setBasePath("/scigraph"); resource.setResourcePath("/dynamic"); resource.setProduces(newArrayList(MediaType.APPLICATION_JSON)); for (Apis api: apis) { resource.getApis().add(api); } return resource; } }
SciGraph-services/src/main/java/io/scigraph/services/resources/DynamicSwaggerService.java
/** * Copyright (C) 2014 The SciGraph 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 io.scigraph.services.resources; import static com.google.common.collect.Lists.newArrayList; import io.scigraph.services.swagger.beans.resource.Apis; import io.scigraph.services.swagger.beans.resource.Resource; import java.util.List; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.codahale.metrics.annotation.Timed; @Path("/api-docs//dynamic") @Produces(MediaType.APPLICATION_JSON) public class DynamicSwaggerService { private final List<Apis> apis; @Inject public DynamicSwaggerService(List<Apis> apis) { this.apis = apis; } @GET @Timed public Resource getDocumentation() { Resource resource = new Resource(); resource.setApiVersion("1.0.1"); resource.setSwaggerVersion("1.2"); resource.setBasePath("../../scigraph"); resource.setResourcePath("/dynamic"); resource.setProduces(newArrayList(MediaType.APPLICATION_JSON)); for (Apis api: apis) { resource.getApis().add(api); } return resource; } }
[#184] fix dynamic query paths
SciGraph-services/src/main/java/io/scigraph/services/resources/DynamicSwaggerService.java
[#184] fix dynamic query paths
<ide><path>ciGraph-services/src/main/java/io/scigraph/services/resources/DynamicSwaggerService.java <ide> <ide> import com.codahale.metrics.annotation.Timed; <ide> <del>@Path("/api-docs//dynamic") <add>@Path("/api-docs/dynamic") <ide> @Produces(MediaType.APPLICATION_JSON) <ide> public class DynamicSwaggerService { <ide> <ide> Resource resource = new Resource(); <ide> resource.setApiVersion("1.0.1"); <ide> resource.setSwaggerVersion("1.2"); <del> resource.setBasePath("../../scigraph"); <add> resource.setBasePath("/scigraph"); <ide> resource.setResourcePath("/dynamic"); <ide> resource.setProduces(newArrayList(MediaType.APPLICATION_JSON)); <ide>
Java
apache-2.0
794d797a0ca4ff89bb6ffae08c172bdef1702de9
0
vibe13/geronimo,meetdestiny/geronimo-trader,meetdestiny/geronimo-trader,apache/geronimo,apache/geronimo,vibe13/geronimo,vibe13/geronimo,apache/geronimo,vibe13/geronimo,meetdestiny/geronimo-trader,apache/geronimo
package org.apache.geronimo.web; import java.util.Arrays; import java.util.List; import org.apache.geronimo.kernel.service.GeronimoAttributeInfo; import org.apache.geronimo.kernel.service.GeronimoMBeanInfo; /** * AbstractWebConnector.java * * * Created: Mon Sep 8 20:39:02 2003 * * @version $Revision: 1.5 $ $Date: 2003/12/30 21:18:35 $ */ public abstract class AbstractWebConnector implements WebConnector { public static final String HTTP_PROTOCOL = "http"; public static final String HTTPS_PROTOCOL = "https"; public static final String AJP13_PROTOCOL = "ajp13"; private int _port = 0; private String _protocol = null; private String _interface = null; private int _maxConnections = 0; private int _maxIdleTime = 0; private List _contexts = null; /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#setPort(int) */ public void setPort(int port) { _port = port; } /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#getPort() */ public int getPort() { return _port; } /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#setProtocol(java.lang.String) */ public void setProtocol(String protocol) { _protocol = protocol; } /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#getProtocol() */ public String getProtocol() { return _protocol; } /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#setInterface(java.lang.String) */ public void setInterface(String iface) { _interface = iface; } /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#getInterface() */ public String getInterface() { return _interface; } /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#setMaxConnections(int) */ public void setMaxConnections(int maxConnects) { _maxConnections = maxConnects; } /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#getMaxConnections() */ public int getMaxConnections() { return _maxConnections; } /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#setMaxIdleTime(int) */ public void setMaxIdleTime(int maxIdleTime) { _maxIdleTime = maxIdleTime; } /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#getMaxIdleTime() */ public int getMaxIdleTime() { return _maxIdleTime; } /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#setContexts(java.lang.String[]) */ public void setContexts(String[] contexts) { _contexts = Arrays.asList(contexts); } /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#getContexts() */ public String[] getContexts() { return (String[])_contexts.toArray(new String[0]); } public static GeronimoMBeanInfo getGeronimoMBeanInfo() throws Exception { GeronimoMBeanInfo mbeanInfo = new GeronimoMBeanInfo(); mbeanInfo.addAttributeInfo(new GeronimoAttributeInfo("Port", true, true, "port to listen on")); mbeanInfo.addAttributeInfo(new GeronimoAttributeInfo("Protocol", true, true, "Protocol (hhtp, https, ftp etc) to use")); mbeanInfo.addAttributeInfo(new GeronimoAttributeInfo("Interface", true, true, "Interface to listen on")); mbeanInfo.addAttributeInfo(new GeronimoAttributeInfo("MaxConnections", true, true, "Maximum number of connections")); mbeanInfo.addAttributeInfo(new GeronimoAttributeInfo("MaxIdleTime", true, true, "Maximum idle time (ms??) a connection can be idle before being closed")); mbeanInfo.addAttributeInfo(new GeronimoAttributeInfo("Contexts", true, true, "Contexts that must be registered in the web container before this connector will start accepting connections")); return mbeanInfo; } }
modules/web/src/java/org/apache/geronimo/web/AbstractWebConnector.java
package org.apache.geronimo.web; import org.apache.geronimo.core.service.AbstractManagedComponent; import org.apache.geronimo.core.service.Container; import org.apache.geronimo.kernel.service.GeronimoMBeanInfo; import org.apache.geronimo.kernel.service.GeronimoAttributeInfo; import java.util.Arrays; import java.util.List; /** * AbstractWebConnector.java * * * Created: Mon Sep 8 20:39:02 2003 * * @version $Revision: 1.4 $ $Date: 2003/12/30 08:28:57 $ */ public abstract class AbstractWebConnector implements WebConnector { public static final String HTTP_PROTOCOL = "http"; public static final String HTTPS_PROTOCOL = "https"; public static final String AJP13_PROTOCOL = "ajp13"; private int _port = 0; private String _protocol = null; private String _interface = null; private int _maxConnections = 0; private int _maxIdleTime = 0; private List _contexts = null; /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#setPort(int) */ public void setPort(int port) { _port = port; } /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#getPort() */ public int getPort() { return _port; } /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#setProtocol(java.lang.String) */ public void setProtocol(String protocol) { _protocol = protocol; } /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#getProtocol() */ public String getProtocol() { return _protocol; } /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#setInterface(java.lang.String) */ public void setInterface(String iface) { _interface = iface; } /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#getInterface() */ public String getInterface() { return _interface; } /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#setMaxConnections(int) */ public void setMaxConnections(int maxConnects) { _maxConnections = maxConnects; } /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#getMaxConnections() */ public int getMaxConnections() { return _maxConnections; } /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#setMaxIdleTime(int) */ public void setMaxIdleTime(int maxIdleTime) { _maxIdleTime = maxIdleTime; } /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#getMaxIdleTime() */ public int getMaxIdleTime() { return _maxIdleTime; } /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#setContexts(java.lang.String[]) */ public void setContexts(String[] contexts) { _contexts = Arrays.asList(contexts); } /* (non-Javadoc) * @see org.apache.geronimo.web.WebConnector#getContexts() */ public String[] getContexts() { return (String[])_contexts.toArray(new String[0]); } public static GeronimoMBeanInfo getGeronimoMBeanInfo() throws Exception { GeronimoMBeanInfo mbeanInfo = new GeronimoMBeanInfo(); mbeanInfo.addAttributeInfo(new GeronimoAttributeInfo("Port", true, true, "port to listen on")); mbeanInfo.addAttributeInfo(new GeronimoAttributeInfo("Protocol", true, true, "Protocol (hhtp, https, ftp etc) to use")); mbeanInfo.addAttributeInfo(new GeronimoAttributeInfo("Interface", true, true, "Interface to listen on")); mbeanInfo.addAttributeInfo(new GeronimoAttributeInfo("MaxConnections", true, true, "Maximum number of connections")); mbeanInfo.addAttributeInfo(new GeronimoAttributeInfo("MaxIdleTime", true, true, "Maximum idle time (ms??) a connection can be idle before being closed")); mbeanInfo.addAttributeInfo(new GeronimoAttributeInfo("Contexts", true, true, "Contexts that must be registered in the web container before this connector will start accepting connections")); return mbeanInfo; } }
import cleanup git-svn-id: d69ffe4ccc4861bf06065bd0072b85c931fba7ed@44721 13f79535-47bb-0310-9956-ffa450edef68
modules/web/src/java/org/apache/geronimo/web/AbstractWebConnector.java
import cleanup
<ide><path>odules/web/src/java/org/apache/geronimo/web/AbstractWebConnector.java <ide> package org.apache.geronimo.web; <del> <del>import org.apache.geronimo.core.service.AbstractManagedComponent; <del>import org.apache.geronimo.core.service.Container; <del>import org.apache.geronimo.kernel.service.GeronimoMBeanInfo; <del>import org.apache.geronimo.kernel.service.GeronimoAttributeInfo; <ide> <ide> import java.util.Arrays; <ide> import java.util.List; <add> <add>import org.apache.geronimo.kernel.service.GeronimoAttributeInfo; <add>import org.apache.geronimo.kernel.service.GeronimoMBeanInfo; <ide> <ide> <ide> /** <ide> * <ide> * Created: Mon Sep 8 20:39:02 2003 <ide> * <del> * @version $Revision: 1.4 $ $Date: 2003/12/30 08:28:57 $ <add> * @version $Revision: 1.5 $ $Date: 2003/12/30 21:18:35 $ <ide> */ <ide> public abstract class AbstractWebConnector implements WebConnector { <ide>
Java
apache-2.0
293f14846176ea4618b8c70b9678eca5a96f04f1
0
vkorenev/RedRadishes
package redradishes; import org.xnio.IoFuture; import org.xnio.IoUtils; import org.xnio.OptionMap; import org.xnio.Pool; import org.xnio.StreamConnection; import org.xnio.XnioWorker; import redradishes.RedisClientConnection.CommandEncoderDecoder; import redradishes.decoder.parser.ReplyParser; import redradishes.encoder.ByteSink; import java.io.IOException; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public abstract class XnioRedisClient<F, SF extends F> implements AutoCloseable { private final BlockingQueue<CommandEncoderDecoder> writerQueue = new LinkedBlockingQueue<>(); private volatile IoFuture<StreamConnection> streamConnectionFuture; private volatile RedisClientConnection redisClientConnection; private volatile IOException failure; private volatile boolean closed = false; protected XnioRedisClient(XnioWorker worker, SocketAddress address, Pool<ByteBuffer> bufferPool, Charset charset) { this.streamConnectionFuture = openConnection(worker, address, bufferPool, charset); } private IoFuture<StreamConnection> openConnection(XnioWorker worker, SocketAddress address, final Pool<ByteBuffer> bufferPool, final Charset charset) { IoFuture<StreamConnection> connectionFuture = worker.openStreamConnection(address, null, OptionMap.EMPTY); connectionFuture.addNotifier(new IoFuture.HandlingNotifier<StreamConnection, Void>() { @Override public void handleFailed(IOException exception, Void v) { failure = exception; CommandEncoderDecoder commandEncoderDecoder; while ((commandEncoderDecoder = writerQueue.poll()) != null) { commandEncoderDecoder.fail(failure); } } @Override public void handleDone(StreamConnection connection, Void v) { redisClientConnection = new RedisClientConnection(connection, bufferPool, charset, writerQueue); if (!writerQueue.isEmpty()) { redisClientConnection.commandAdded(); } connection.setCloseListener(streamConnection -> { if (!closed) { streamConnectionFuture = openConnection(worker, address, bufferPool, charset); } }); } }, null); return connectionFuture; } public <T> F send_(final Request<T> request) { if (closed) { return createCancelledFuture(); } if (failure != null) { return createFailedFuture(failure); } final SF future = createFuture(); writerQueue.add(new CommandEncoderDecoder() { private ReplyParser<? extends T> parser = request.parser(); @Override public void writeTo(ByteSink sink) { request.writeTo(sink); } @Override public boolean parse(ByteBuffer buffer, CharsetDecoder charsetDecoder) throws IOException { return parser.parseReply(buffer, value -> { complete(future, value); return true; }, partial -> { parser = partial; return false; }, exception -> { completeExceptionally(future, exception); return true; }, charsetDecoder); } @Override public void fail(Throwable e) { completeExceptionally(future, e); } @Override public void cancel() { XnioRedisClient.this.cancel(future); } }); if (redisClientConnection != null) { redisClientConnection.commandAdded(); } return future; } protected abstract F createCancelledFuture(); protected abstract F createFailedFuture(Throwable exception); protected abstract SF createFuture(); protected abstract <T> void complete(SF future, T value); protected abstract void completeExceptionally(SF future, Throwable exception); protected abstract void cancel(SF future); @Override public void close() { closed = true; IoUtils.safeClose(streamConnectionFuture); } }
core/src/main/java/redradishes/XnioRedisClient.java
package redradishes; import org.xnio.IoFuture; import org.xnio.IoUtils; import org.xnio.OptionMap; import org.xnio.Pool; import org.xnio.StreamConnection; import org.xnio.XnioWorker; import redradishes.RedisClientConnection.CommandEncoderDecoder; import redradishes.decoder.parser.ReplyParser; import redradishes.encoder.ByteSink; import java.io.IOException; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public abstract class XnioRedisClient<F, SF extends F> implements AutoCloseable { private final BlockingQueue<CommandEncoderDecoder> writerQueue = new LinkedBlockingQueue<>(); private final IoFuture<StreamConnection> streamConnectionFuture; private volatile RedisClientConnection redisClientConnection; private volatile IOException failure; private volatile boolean closed = false; protected XnioRedisClient(XnioWorker worker, SocketAddress address, Pool<ByteBuffer> bufferPool, Charset charset) { this.streamConnectionFuture = openConnection(worker, address, bufferPool, charset); } private IoFuture<StreamConnection> openConnection(XnioWorker worker, SocketAddress address, final Pool<ByteBuffer> bufferPool, final Charset charset) { IoFuture<StreamConnection> connectionFuture = worker.openStreamConnection(address, null, OptionMap.EMPTY); connectionFuture.addNotifier(new IoFuture.HandlingNotifier<StreamConnection, Void>() { @Override public void handleFailed(IOException exception, Void v) { failure = exception; CommandEncoderDecoder commandEncoderDecoder; while ((commandEncoderDecoder = writerQueue.poll()) != null) { commandEncoderDecoder.fail(failure); } } @Override public void handleDone(StreamConnection connection, Void v) { redisClientConnection = new RedisClientConnection(connection, bufferPool, charset, writerQueue); if (!writerQueue.isEmpty()) { redisClientConnection.commandAdded(); } } }, null); return connectionFuture; } public <T> F send_(final Request<T> request) { if (closed) { return createCancelledFuture(); } if (failure != null) { return createFailedFuture(failure); } final SF future = createFuture(); writerQueue.add(new CommandEncoderDecoder() { private ReplyParser<? extends T> parser = request.parser(); @Override public void writeTo(ByteSink sink) { request.writeTo(sink); } @Override public boolean parse(ByteBuffer buffer, CharsetDecoder charsetDecoder) throws IOException { return parser.parseReply(buffer, value -> { complete(future, value); return true; }, partial -> { parser = partial; return false; }, exception -> { completeExceptionally(future, exception); return true; }, charsetDecoder); } @Override public void fail(Throwable e) { completeExceptionally(future, e); } @Override public void cancel() { XnioRedisClient.this.cancel(future); } }); if (redisClientConnection != null) { redisClientConnection.commandAdded(); } return future; } protected abstract F createCancelledFuture(); protected abstract F createFailedFuture(Throwable exception); protected abstract SF createFuture(); protected abstract <T> void complete(SF future, T value); protected abstract void completeExceptionally(SF future, Throwable exception); protected abstract void cancel(SF future); @Override public void close() { closed = true; IoUtils.safeClose(streamConnectionFuture); } }
Reopen connection if it was not closed explicitly
core/src/main/java/redradishes/XnioRedisClient.java
Reopen connection if it was not closed explicitly
<ide><path>ore/src/main/java/redradishes/XnioRedisClient.java <ide> <ide> public abstract class XnioRedisClient<F, SF extends F> implements AutoCloseable { <ide> private final BlockingQueue<CommandEncoderDecoder> writerQueue = new LinkedBlockingQueue<>(); <del> private final IoFuture<StreamConnection> streamConnectionFuture; <add> private volatile IoFuture<StreamConnection> streamConnectionFuture; <ide> private volatile RedisClientConnection redisClientConnection; <ide> private volatile IOException failure; <ide> private volatile boolean closed = false; <ide> if (!writerQueue.isEmpty()) { <ide> redisClientConnection.commandAdded(); <ide> } <add> connection.setCloseListener(streamConnection -> { <add> if (!closed) { <add> streamConnectionFuture = openConnection(worker, address, bufferPool, charset); <add> } <add> }); <ide> } <ide> }, null); <ide> return connectionFuture;
Java
apache-2.0
62a84b99aa8023b2dad75b390fd8b2f7cf5c10c1
0
mccraigmccraig/opennlp,mccraigmccraig/opennlp
/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2002 Jason Baldridge and Gann Bierner // // 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 program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ////////////////////////////////////////////////////////////////////////////// package opennlp.tools.postag; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import opennlp.maxent.DataStream; import opennlp.maxent.GISModel; import opennlp.maxent.io.SuffixSensitiveGISModelReader; import opennlp.tools.dictionary.Dictionary; /** * Invoke a part-of-speech tagging model from the command line. * * @author Jason Baldridge * @version $Revision: 1.7 $, $Date: 2007/01/24 17:13:07 $ */ public class BatchTagger { private static void usage() { System.err.println("Usage: BatchTagger [-dict dict_file] data_file model"); System.err.println("This applies a model to the specified text file."); System.exit(1); } /** * <p> * Applies a pos model. * </p> * * @param args * @throws IOException * */ public static void main (String[] args) throws IOException { if (args.length == 0) { usage(); } int ai=0; try { //String encoding = null; String dictFile = ""; String tagDictFile = ""; //int cutoff = 0; while (args[ai].startsWith("-")) { if (args[ai].equals("-dict")) { ai++; if (ai < args.length) { dictFile = args[ai++]; } else { usage(); } } else if (args[ai].equals("-tag_dict")) { ai++; if (ai < args.length) { tagDictFile = args[ai++]; } else { usage(); } } else { System.err.println("Unknown option "+args[ai]); usage(); } } Dictionary dict = new Dictionary(new FileInputStream(dictFile)); File textFile = new File(args[ai++]); File modelFile = new File(args[ai++]); GISModel mod = new SuffixSensitiveGISModelReader(modelFile).getModel(); POSTagger tagger; if (tagDictFile.equals("")) { tagger = new POSTaggerME(mod, dict); } else { tagger = new POSTaggerME(mod, dict, new POSDictionary(tagDictFile)); } DataStream text = new opennlp.maxent.PlainTextByLineDataStream( new java.io.FileReader(textFile)); while(text.hasNext()) { String str = (String)text.nextToken(); System.out.println(tagger.tag(str)); } } catch (Exception e) { e.printStackTrace(); } } }
src/java/opennlp/tools/postag/BatchTagger.java
/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2002 Jason Baldridge and Gann Bierner // // 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 program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ////////////////////////////////////////////////////////////////////////////// package opennlp.tools.postag; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import opennlp.maxent.DataStream; import opennlp.maxent.GISModel; import opennlp.maxent.io.SuffixSensitiveGISModelReader; import opennlp.tools.dictionary.Dictionary; /** * Invoke a part-of-speech tagging model from the command line. * * @author Jason Baldridge * @version $Revision: 1.6 $, $Date: 2006/11/17 09:37:41 $ */ public class BatchTagger { private static void usage() { System.err.println("Usage: BatchTagger [-dict dict_file] data_file model"); System.err.println("This applies a model to the specified text file."); System.exit(1); } /** * <p>Applies a pos model.</p> * */ public static void main (String[] args) throws IOException { if (args.length == 0) { usage(); } int ai=0; try { //String encoding = null; String dictFile = ""; String tagDictFile = ""; //int cutoff = 0; while (args[ai].startsWith("-")) { if (args[ai].equals("-dict")) { ai++; if (ai < args.length) { dictFile = args[ai++]; } else { usage(); } } else if (args[ai].equals("-tag_dict")) { ai++; if (ai < args.length) { tagDictFile = args[ai++]; } else { usage(); } } else { System.err.println("Unknown option "+args[ai]); usage(); } } Dictionary dict = new Dictionary(new FileInputStream(dictFile)); File textFile = new File(args[ai++]); File modelFile = new File(args[ai++]); GISModel mod = new SuffixSensitiveGISModelReader(modelFile).getModel(); POSTagger tagger; if (tagDictFile.equals("")) { tagger = new POSTaggerME(mod, dict); } else { tagger = new POSTaggerME(mod, dict, new POSDictionary(tagDictFile)); } DataStream text = new opennlp.maxent.PlainTextByLineDataStream( new java.io.FileReader(textFile)); while(text.hasNext()) { String str = (String)text.nextToken(); System.out.println(tagger.tag(str)); } } catch (Exception e) { e.printStackTrace(); } } }
fixed javadoc
src/java/opennlp/tools/postag/BatchTagger.java
fixed javadoc
<ide><path>rc/java/opennlp/tools/postag/BatchTagger.java <ide> * Invoke a part-of-speech tagging model from the command line. <ide> * <ide> * @author Jason Baldridge <del> * @version $Revision: 1.6 $, $Date: 2006/11/17 09:37:41 $ <add> * @version $Revision: 1.7 $, $Date: 2007/01/24 17:13:07 $ <ide> */ <ide> public class BatchTagger { <ide> <ide> } <ide> <ide> /** <del> * <p>Applies a pos model.</p> <del> * <del> */ <add> * <p> <add> * Applies a pos model. <add> * </p> <add> * <add> * @param args <add> * @throws IOException <add> * <add> */ <ide> public static void main (String[] args) throws IOException { <ide> if (args.length == 0) { <ide> usage();
Java
apache-2.0
2d01521fe393c5b4d867999ff4c6ac72ec96a756
0
dimagi/commcare-core,dimagi/commcare,dimagi/commcare-core,dimagi/commcare,dimagi/commcare,dimagi/commcare-core
package org.commcare.xml; import org.commcare.resources.model.Resource; import org.commcare.resources.model.ResourceTable; import org.commcare.suite.model.Detail; import org.commcare.suite.model.Entry; import org.commcare.suite.model.Menu; import org.commcare.suite.model.Suite; import org.javarosa.core.model.instance.FormInstance; import org.javarosa.core.services.storage.IStorageUtilityIndexed; import org.javarosa.core.services.storage.StorageFullException; import org.javarosa.core.services.storage.StorageManager; import org.javarosa.xml.ElementParser; import org.javarosa.xml.util.InvalidStructureException; import org.javarosa.xml.util.UnfullfilledRequirementsException; import org.kxml2.io.KXmlParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; import java.util.Hashtable; import java.util.Vector; /** * Parses a suite file resource and creates the associated object * containing the menu, detail, entry, etc definitions. This parser * will also create models for any resource installers that are defined * by the suite file and add them to the resource table provided * with the suite resource as the parent, that behavior can be skipped * by setting a flag if the resources have already been promised. * * @author ctsims */ public class SuiteParser extends ElementParser<Suite> { private final IStorageUtilityIndexed<FormInstance> fixtureStorage; private ResourceTable table; private String resourceGuid; private int maximumResourceAuthority = -1; /** * If set to true, the parser won't process adding incoming resources to the resource table. * This is helpful if the suite is being processed during a non-install phase */ private final boolean skipResources; private final boolean isValidationPass; private final boolean isUpgrade; public SuiteParser(InputStream suiteStream, ResourceTable table, String resourceGuid) throws IOException { super(ElementParser.instantiateParser(suiteStream)); this.table = table; this.resourceGuid = resourceGuid; this.fixtureStorage = (IStorageUtilityIndexed<FormInstance>)StorageManager.getStorage(FormInstance.STORAGE_KEY); this.skipResources = false; this.isValidationPass = false; this.isUpgrade = false; } protected SuiteParser(InputStream suiteStream, ResourceTable table, String resourceGuid, IStorageUtilityIndexed<FormInstance> fixtureStorage, boolean skipResources, boolean isValidationPass, boolean isUpgrade) throws IOException { super(ElementParser.instantiateParser(suiteStream)); this.table = table; this.resourceGuid = resourceGuid; this.fixtureStorage = fixtureStorage; this.skipResources = skipResources; this.isValidationPass = isValidationPass; this.isUpgrade = isUpgrade; } public Suite parse() throws InvalidStructureException, IOException, XmlPullParserException, UnfullfilledRequirementsException { checkNode("suite"); String sVersion = parser.getAttributeValue(null, "version"); int version = Integer.parseInt(sVersion); Hashtable<String, Detail> details = new Hashtable<>(); Hashtable<String, Entry> entries = new Hashtable<>(); Vector<Menu> menus = new Vector<>(); try { //Now that we've covered being inside of a suite, //start traversing. parser.next(); int eventType = parser.getEventType(); do { if (eventType == KXmlParser.START_TAG) { if (parser.getName().toLowerCase().equals("entry")) { Entry e = EntryParser.buildEntryParser(parser).parse(); entries.put(e.getCommandId(), e); } else if (parser.getName().toLowerCase().equals("view")) { Entry e = EntryParser.buildViewParser(parser).parse(); entries.put(e.getCommandId(), e); } else if (parser.getName().toLowerCase().equals(EntryParser.REMOTE_REQUEST_TAG)) { Entry remoteRequestEntry = EntryParser.buildRemoteSyncParser(parser).parse(); entries.put(remoteRequestEntry.getCommandId(), remoteRequestEntry); } else if (parser.getName().toLowerCase().equals("locale")) { String localeKey = parser.getAttributeValue(null, "language"); //resource def parser.nextTag(); Resource r = new ResourceParser(parser, maximumResourceAuthority).parse(); if(!skipResources) { table.addResource(r, table.getInstallers().getLocaleFileInstaller(localeKey), resourceGuid); } } else if (parser.getName().toLowerCase().equals("media")) { String path = parser.getAttributeValue(null, "path"); //Can be an arbitrary number of resources inside of a media block. while (this.nextTagInBlock("media")) { Resource r = new ResourceParser(parser, maximumResourceAuthority).parse(); if(!skipResources) { table.addResource(r, table.getInstallers().getMediaInstaller(path), resourceGuid); } } } else if (parser.getName().toLowerCase().equals("xform")) { //skip xform stuff for now parser.nextTag(); Resource r = new ResourceParser(parser, maximumResourceAuthority).parse(); if(!skipResources) { table.addResource(r, table.getInstallers().getXFormInstaller(), resourceGuid); } } else if (parser.getName().toLowerCase().equals("detail")) { Detail d = getDetailParser().parse(); details.put(d.getId(), d); } else if (parser.getName().toLowerCase().equals("menu")) { Menu m = new MenuParser(parser).parse(); menus.addElement(m); } else if (parser.getName().toLowerCase().equals("fixture")) { if (!isValidationPass) { // commit fixture to the memory, overwriting existing // fixture only during first init after app upgrade new FixtureXmlParser(parser, isUpgrade, fixtureStorage).parse(); } } else { System.out.println("Unrecognized Tag: " + parser.getName()); } } eventType = parser.next(); } while (eventType != KXmlParser.END_DOCUMENT); return new Suite(version, details, entries, menus); } catch (XmlPullParserException e) { e.printStackTrace(); throw new InvalidStructureException("Pull Parse Exception, malformed XML.", parser); } catch (StorageFullException e) { e.printStackTrace(); //BUT not really! This should maybe be added to the high level declaration //instead? Or maybe there should be a more general Resource Management Exception? throw new InvalidStructureException("Problem storing parser suite XML", parser); } } public void setMaximumAuthority(int authority) { maximumResourceAuthority = authority; } protected DetailParser getDetailParser() { return new DetailParser(parser); } }
backend/src/org/commcare/xml/SuiteParser.java
package org.commcare.xml; import org.commcare.resources.model.Resource; import org.commcare.resources.model.ResourceTable; import org.commcare.suite.model.Detail; import org.commcare.suite.model.Entry; import org.commcare.suite.model.Menu; import org.commcare.suite.model.Suite; import org.javarosa.core.model.instance.FormInstance; import org.javarosa.core.services.storage.IStorageUtilityIndexed; import org.javarosa.core.services.storage.StorageFullException; import org.javarosa.core.services.storage.StorageManager; import org.javarosa.xml.ElementParser; import org.javarosa.xml.util.InvalidStructureException; import org.javarosa.xml.util.UnfullfilledRequirementsException; import org.kxml2.io.KXmlParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; import java.util.Hashtable; import java.util.Vector; /** * Parses a suite file resource and creates the associated object * containing the menu, detail, entry, etc definitions. This parser * will also create models for any resource installers that are defined * by the suite file and add them to the resource table provided * with the suite resource as the parent, that behavior can be skipped * by setting a flag if the resources have already been promised. * * @author ctsims */ public class SuiteParser extends ElementParser<Suite> { private final IStorageUtilityIndexed<FormInstance> fixtureStorage; private ResourceTable table; private String resourceGuid; private int maximumResourceAuthority = -1; /** * If set to true, the parser won't process adding incoming resources to the resource table. * This is helpful if the suite is being processed during a non-install phase */ private final boolean skipResources; private final boolean isValidationPass; private final boolean isUpgrade; public SuiteParser(InputStream suiteStream, ResourceTable table, String resourceGuid) throws IOException { super(ElementParser.instantiateParser(suiteStream)); this.table = table; this.resourceGuid = resourceGuid; this.fixtureStorage = (IStorageUtilityIndexed<FormInstance>)StorageManager.getStorage(FormInstance.STORAGE_KEY); this.skipResources = false; this.isValidationPass = false; this.isUpgrade = false; } protected SuiteParser(InputStream suiteStream, ResourceTable table, String resourceGuid, IStorageUtilityIndexed<FormInstance> fixtureStorage, boolean skipResources, boolean isValidationPass, boolean isUpgrade) throws IOException { super(ElementParser.instantiateParser(suiteStream)); this.table = table; this.resourceGuid = resourceGuid; this.fixtureStorage = fixtureStorage; this.skipResources = skipResources; this.isValidationPass = isValidationPass; this.isUpgrade = isUpgrade; } public Suite parse() throws InvalidStructureException, IOException, XmlPullParserException, UnfullfilledRequirementsException { checkNode("suite"); String sVersion = parser.getAttributeValue(null, "version"); int version = Integer.parseInt(sVersion); Hashtable<String, Detail> details = new Hashtable<>(); Hashtable<String, Entry> entries = new Hashtable<>(); Vector<Menu> menus = new Vector<>(); try { //Now that we've covered being inside of a suite, //start traversing. parser.next(); int eventType = parser.getEventType(); do { if (eventType == KXmlParser.START_TAG) { if (parser.getName().toLowerCase().equals("entry")) { Entry e = EntryParser.buildEntryParser(parser).parse(); entries.put(e.getCommandId(), e); } else if (parser.getName().toLowerCase().equals("view")) { Entry e = EntryParser.buildViewParser(parser).parse(); entries.put(e.getCommandId(), e); } else if (parser.getName().toLowerCase().equals(EntryParser.REMOTE_REQUEST_TAG)) { Entry syncEntry = EntryParser.buildRemoteSyncParser(parser).parse(); entries.put(syncEntry.getCommandId(), syncEntry); } else if (parser.getName().toLowerCase().equals("locale")) { String localeKey = parser.getAttributeValue(null, "language"); //resource def parser.nextTag(); Resource r = new ResourceParser(parser, maximumResourceAuthority).parse(); if(!skipResources) { table.addResource(r, table.getInstallers().getLocaleFileInstaller(localeKey), resourceGuid); } } else if (parser.getName().toLowerCase().equals("media")) { String path = parser.getAttributeValue(null, "path"); //Can be an arbitrary number of resources inside of a media block. while (this.nextTagInBlock("media")) { Resource r = new ResourceParser(parser, maximumResourceAuthority).parse(); if(!skipResources) { table.addResource(r, table.getInstallers().getMediaInstaller(path), resourceGuid); } } } else if (parser.getName().toLowerCase().equals("xform")) { //skip xform stuff for now parser.nextTag(); Resource r = new ResourceParser(parser, maximumResourceAuthority).parse(); if(!skipResources) { table.addResource(r, table.getInstallers().getXFormInstaller(), resourceGuid); } } else if (parser.getName().toLowerCase().equals("detail")) { Detail d = getDetailParser().parse(); details.put(d.getId(), d); } else if (parser.getName().toLowerCase().equals("menu")) { Menu m = new MenuParser(parser).parse(); menus.addElement(m); } else if (parser.getName().toLowerCase().equals("fixture")) { if (!isValidationPass) { // commit fixture to the memory, overwriting existing // fixture only during first init after app upgrade new FixtureXmlParser(parser, isUpgrade, fixtureStorage).parse(); } } else { System.out.println("Unrecognized Tag: " + parser.getName()); } } eventType = parser.next(); } while (eventType != KXmlParser.END_DOCUMENT); return new Suite(version, details, entries, menus); } catch (XmlPullParserException e) { e.printStackTrace(); throw new InvalidStructureException("Pull Parse Exception, malformed XML.", parser); } catch (StorageFullException e) { e.printStackTrace(); //BUT not really! This should maybe be added to the high level declaration //instead? Or maybe there should be a more general Resource Management Exception? throw new InvalidStructureException("Problem storing parser suite XML", parser); } } public void setMaximumAuthority(int authority) { maximumResourceAuthority = authority; } protected DetailParser getDetailParser() { return new DetailParser(parser); } }
Rename intermediate var
backend/src/org/commcare/xml/SuiteParser.java
Rename intermediate var
<ide><path>ackend/src/org/commcare/xml/SuiteParser.java <ide> Entry e = EntryParser.buildViewParser(parser).parse(); <ide> entries.put(e.getCommandId(), e); <ide> } else if (parser.getName().toLowerCase().equals(EntryParser.REMOTE_REQUEST_TAG)) { <del> Entry syncEntry = EntryParser.buildRemoteSyncParser(parser).parse(); <del> entries.put(syncEntry.getCommandId(), syncEntry); <add> Entry remoteRequestEntry = EntryParser.buildRemoteSyncParser(parser).parse(); <add> entries.put(remoteRequestEntry.getCommandId(), remoteRequestEntry); <ide> } else if (parser.getName().toLowerCase().equals("locale")) { <ide> String localeKey = parser.getAttributeValue(null, "language"); <ide> //resource def
Java
agpl-3.0
2ff87a8e32a98a86f8afcbe10e3ff8455365d6d0
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
c8a3f5ec-2e5f-11e5-9284-b827eb9e62be
hello.java
c89e7c16-2e5f-11e5-9284-b827eb9e62be
c8a3f5ec-2e5f-11e5-9284-b827eb9e62be
hello.java
c8a3f5ec-2e5f-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>c89e7c16-2e5f-11e5-9284-b827eb9e62be <add>c8a3f5ec-2e5f-11e5-9284-b827eb9e62be
Java
apache-2.0
error: pathspec 'TeamworkApiDemo/app/src/main/java/com/vishnus1224/teamworkapidemo/ui/presenter/MainPresenter.java' did not match any file(s) known to git
cbaf099e8a27a2f7e52e37a5b72cab6d2ea5847e
1
vishnus1224/RxJavaTeamworkClient
package com.vishnus1224.teamworkapidemo.ui.presenter; import com.vishnus1224.teamworkapidemo.ui.view.MainView; import javax.inject.Inject; /** * Handles presentation logic for the main screen. * Created by Vishnu on 8/16/2016. */ public class MainPresenter implements BasePresenter<MainView> { private MainView mainView; /** * Item position of the currently selected navigation drawer item. */ private int selectedItemPosition; @Inject public MainPresenter(){ } @Override public void onViewAttached(MainView mainView) { if(mainView == null){ throw new IllegalArgumentException("View cannot be null"); } this.mainView = mainView; } @Override public void onViewDetached(MainView mainView) { this.mainView = null; } public void drawerItemClicked(int position){ //do not take any action if the new position is same as the selectedItemPosition if(selectedItemPosition == position){ return; } setSelectedItemPosition(position); showScreen(position); } /** * Show the correct screen based on the selected item position. * @param position The position of the selected item. */ private void showScreen(int position) { switch (position){ case 0: mainView.showLatestActivityScreen(); break; case 1: mainView.showProjectsScreen(); break; case 2: mainView.showTaskScreen(); break; } } private void setSelectedItemPosition(int position) { selectedItemPosition = position; } }
TeamworkApiDemo/app/src/main/java/com/vishnus1224/teamworkapidemo/ui/presenter/MainPresenter.java
presenter for the main screen
TeamworkApiDemo/app/src/main/java/com/vishnus1224/teamworkapidemo/ui/presenter/MainPresenter.java
presenter for the main screen
<ide><path>eamworkApiDemo/app/src/main/java/com/vishnus1224/teamworkapidemo/ui/presenter/MainPresenter.java <add>package com.vishnus1224.teamworkapidemo.ui.presenter; <add> <add>import com.vishnus1224.teamworkapidemo.ui.view.MainView; <add> <add>import javax.inject.Inject; <add> <add>/** <add> * Handles presentation logic for the main screen. <add> * Created by Vishnu on 8/16/2016. <add> */ <add>public class MainPresenter implements BasePresenter<MainView> { <add> <add> private MainView mainView; <add> <add> /** <add> * Item position of the currently selected navigation drawer item. <add> */ <add> private int selectedItemPosition; <add> <add> @Inject <add> public MainPresenter(){ <add> <add> <add> } <add> <add> @Override <add> public void onViewAttached(MainView mainView) { <add> <add> if(mainView == null){ <add> <add> throw new IllegalArgumentException("View cannot be null"); <add> <add> } <add> <add> this.mainView = mainView; <add> <add> } <add> <add> @Override <add> public void onViewDetached(MainView mainView) { <add> <add> this.mainView = null; <add> <add> } <add> <add> public void drawerItemClicked(int position){ <add> <add> //do not take any action if the new position is same as the selectedItemPosition <add> if(selectedItemPosition == position){ <add> <add> return; <add> <add> } <add> <add> setSelectedItemPosition(position); <add> <add> showScreen(position); <add> <add> <add> } <add> <add> /** <add> * Show the correct screen based on the selected item position. <add> * @param position The position of the selected item. <add> */ <add> private void showScreen(int position) { <add> <add> switch (position){ <add> <add> case 0: <add> <add> mainView.showLatestActivityScreen(); <add> <add> break; <add> case 1: <add> <add> mainView.showProjectsScreen(); <add> <add> break; <add> case 2: <add> <add> mainView.showTaskScreen(); <add> <add> break; <add> <add> } <add> <add> } <add> <add> private void setSelectedItemPosition(int position) { <add> <add> selectedItemPosition = position; <add> <add> } <add>}
Java
agpl-3.0
086796a8ed0a3d078b30eff2d08b5450fe7a8fa9
0
smith750/kfs,ua-eas/kfs,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,kuali/kfs,bhutchinson/kfs,bhutchinson/kfs,smith750/kfs,ua-eas/kfs,quikkian-ua-devops/will-financials,kkronenb/kfs,quikkian-ua-devops/kfs,bhutchinson/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials,kuali/kfs,ua-eas/kfs-devops-automation-fork,kkronenb/kfs,smith750/kfs,kuali/kfs,UniversityOfHawaii/kfs,kkronenb/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,kuali/kfs,ua-eas/kfs,bhutchinson/kfs,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/kfs,ua-eas/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,kuali/kfs,kkronenb/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,smith750/kfs,ua-eas/kfs-devops-automation-fork
/* * Copyright 2008 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.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.module.budget.service.impl; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.kuali.core.service.BusinessObjectService; import org.kuali.kfs.KFSPropertyConstants; import org.kuali.module.budget.bo.BudgetConstructionAdministrativePost; import org.kuali.module.budget.bo.BudgetConstructionIntendedIncumbent; import org.kuali.module.budget.bo.BudgetConstructionMonthSummary; import org.kuali.module.budget.bo.BudgetConstructionObjectDump; import org.kuali.module.budget.bo.BudgetConstructionObjectPick; import org.kuali.module.budget.bo.BudgetConstructionPosition; import org.kuali.module.budget.bo.PendingBudgetConstructionAppointmentFunding; import org.kuali.module.budget.service.BudgetConstructionOrganizationReportsService; import org.kuali.module.budget.service.BudgetConstructionReportsServiceHelper; import org.kuali.module.chart.bo.ObjectCode; import org.springframework.transaction.annotation.Transactional; @Transactional public class BudgetConstructionReportsServiceHelperImpl implements BudgetConstructionReportsServiceHelper { BudgetConstructionOrganizationReportsService budgetConstructionOrganizationReportsService; BusinessObjectService businessObjectService; public Collection getDataForBuildingReports(Class clazz, String personUserIdentifier, List<String> orderList){ //build searchCriteria Map searchCriteria = new HashMap(); searchCriteria.put(KFSPropertyConstants.KUALI_USER_PERSON_UNIVERSAL_IDENTIFIER, personUserIdentifier); // build order list return budgetConstructionOrganizationReportsService.getBySearchCriteriaOrderByList(clazz, searchCriteria, orderList); } public Collection getDataForBuildingReports(Class clazz, Map searchCriteria, List<String> orderList){ return budgetConstructionOrganizationReportsService.getBySearchCriteriaOrderByList(clazz, searchCriteria, orderList); } public ObjectCode getObjectCode(Integer universityFiscalYear, String chartOfAccountsCode, String financialObjectCode){ Map searchCriteria = new HashMap(); searchCriteria.put(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR, universityFiscalYear); searchCriteria.put(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode); searchCriteria.put(KFSPropertyConstants.FINANCIAL_OBJECT_CODE, financialObjectCode); return (ObjectCode) businessObjectService.findByPrimaryKey(ObjectCode.class, searchCriteria); } public String getSelectedObjectCodes (String personUserIdentifier){ Map searchCriteria = new HashMap(); searchCriteria.put(KFSPropertyConstants.PERSON_UNIVERSAL_IDENTIFIER, personUserIdentifier); searchCriteria.put(KFSPropertyConstants.SELECT_FLAG, 1); Collection<BudgetConstructionObjectPick> objectPickList = businessObjectService.findMatching(BudgetConstructionObjectPick.class, searchCriteria); String objectCodes = ""; for (BudgetConstructionObjectPick objectPick : objectPickList) { objectCodes += objectPick.getFinancialObjectCode() + " "; } return objectCodes; } public BudgetConstructionAdministrativePost getBudgetConstructionAdministrativePost(PendingBudgetConstructionAppointmentFunding appointmentFundingEntry) { Map searchCriteria = new HashMap(); searchCriteria.put(KFSPropertyConstants.EMPLID, appointmentFundingEntry.getEmplid()); searchCriteria.put(KFSPropertyConstants.POSITION_NUMBER, appointmentFundingEntry.getPositionNumber()); return (BudgetConstructionAdministrativePost) businessObjectService.findByPrimaryKey(BudgetConstructionAdministrativePost.class, searchCriteria); } public BudgetConstructionPosition getBudgetConstructionPosition(Integer universityFiscalYear, PendingBudgetConstructionAppointmentFunding appointmentFundingEntry) { Map searchCriteria = new HashMap(); searchCriteria.put(KFSPropertyConstants.POSITION_NUMBER, appointmentFundingEntry.getPositionNumber()); searchCriteria.put(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR, universityFiscalYear); return (BudgetConstructionPosition) businessObjectService.findByPrimaryKey(BudgetConstructionPosition.class, searchCriteria); } public BudgetConstructionIntendedIncumbent getBudgetConstructionIntendedIncumbent(PendingBudgetConstructionAppointmentFunding appointmentFundingEntry) { Map searchCriteria = new HashMap(); searchCriteria.put(KFSPropertyConstants.EMPLID, appointmentFundingEntry.getEmplid()); return (BudgetConstructionIntendedIncumbent) businessObjectService.findByPrimaryKey(BudgetConstructionIntendedIncumbent.class, searchCriteria); } public Collection<PendingBudgetConstructionAppointmentFunding> getPendingBudgetConstructionAppointmentFundingList(Integer universityFiscalYear, BudgetConstructionObjectDump budgetConstructionObjectDump) { Map searchCriteria = new HashMap(); searchCriteria.put(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR, universityFiscalYear); searchCriteria.put(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE, budgetConstructionObjectDump.getChartOfAccountsCode()); searchCriteria.put(KFSPropertyConstants.ACCOUNT_NUMBER, budgetConstructionObjectDump.getAccountNumber()); searchCriteria.put(KFSPropertyConstants.SUB_ACCOUNT_NUMBER, budgetConstructionObjectDump.getSubAccountNumber()); searchCriteria.put(KFSPropertyConstants.FINANCIAL_OBJECT_CODE, budgetConstructionObjectDump.getFinancialObjectCode()); List<String> orderList = new ArrayList(); orderList.add(KFSPropertyConstants.FINANCIAL_OBJECT_CODE); orderList.add(KFSPropertyConstants.FINANCIAL_SUB_OBJECT_CODE); orderList.add(KFSPropertyConstants.POSITION_NUMBER); orderList.add(KFSPropertyConstants.EMPLID); return budgetConstructionOrganizationReportsService.getBySearchCriteriaOrderByList(PendingBudgetConstructionAppointmentFunding.class, searchCriteria, orderList); } public void setBudgetConstructionOrganizationReportsService(BudgetConstructionOrganizationReportsService budgetConstructionOrganizationReportsService) { this.budgetConstructionOrganizationReportsService = budgetConstructionOrganizationReportsService; } public void setBusinessObjectService(BusinessObjectService businessObjectService) { this.businessObjectService = businessObjectService; } }
work/src/org/kuali/kfs/module/bc/document/service/impl/BudgetConstructionReportsServiceHelperImpl.java
/* * Copyright 2008 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.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.module.budget.service.impl; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.kuali.core.service.BusinessObjectService; import org.kuali.kfs.KFSPropertyConstants; import org.kuali.module.budget.bo.BudgetConstructionAdministrativePost; import org.kuali.module.budget.bo.BudgetConstructionIntendedIncumbent; import org.kuali.module.budget.bo.BudgetConstructionMonthSummary; import org.kuali.module.budget.bo.BudgetConstructionObjectPick; import org.kuali.module.budget.bo.BudgetConstructionPosition; import org.kuali.module.budget.bo.PendingBudgetConstructionAppointmentFunding; import org.kuali.module.budget.service.BudgetConstructionOrganizationReportsService; import org.kuali.module.budget.service.BudgetConstructionReportsServiceHelper; import org.kuali.module.chart.bo.ObjectCode; import org.springframework.transaction.annotation.Transactional; @Transactional public class BudgetConstructionReportsServiceHelperImpl implements BudgetConstructionReportsServiceHelper { BudgetConstructionOrganizationReportsService budgetConstructionOrganizationReportsService; BusinessObjectService businessObjectService; public Collection getDataForBuildingReports(Class clazz, String personUserIdentifier, List<String> orderList){ //build searchCriteria Map searchCriteria = new HashMap(); searchCriteria.put(KFSPropertyConstants.KUALI_USER_PERSON_UNIVERSAL_IDENTIFIER, personUserIdentifier); // build order list return budgetConstructionOrganizationReportsService.getBySearchCriteriaOrderByList(clazz, searchCriteria, orderList); } public Collection getDataForBuildingReports(Class clazz, Map searchCriteria, List<String> orderList){ return budgetConstructionOrganizationReportsService.getBySearchCriteriaOrderByList(clazz, searchCriteria, orderList); } public ObjectCode getObjectCode(Integer universityFiscalYear, String chartOfAccountsCode, String financialObjectCode){ Map searchCriteria = new HashMap(); searchCriteria.put(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR, universityFiscalYear); searchCriteria.put(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode); searchCriteria.put(KFSPropertyConstants.FINANCIAL_OBJECT_CODE, financialObjectCode); return (ObjectCode) businessObjectService.findByPrimaryKey(ObjectCode.class, searchCriteria); } public String getSelectedObjectCodes (String personUserIdentifier){ Map searchCriteria = new HashMap(); searchCriteria.put(KFSPropertyConstants.PERSON_UNIVERSAL_IDENTIFIER, personUserIdentifier); searchCriteria.put(KFSPropertyConstants.SELECT_FLAG, 1); Collection<BudgetConstructionObjectPick> objectPickList = businessObjectService.findMatching(BudgetConstructionObjectPick.class, searchCriteria); String objectCodes = ""; for (BudgetConstructionObjectPick objectPick : objectPickList) { objectCodes += objectPick.getFinancialObjectCode() + " "; } return objectCodes; } public BudgetConstructionAdministrativePost getBudgetConstructionAdministrativePost(PendingBudgetConstructionAppointmentFunding appointmentFundingEntry) { Map searchCriteria = new HashMap(); searchCriteria.put(KFSPropertyConstants.EMPLID, appointmentFundingEntry.getEmplid()); searchCriteria.put(KFSPropertyConstants.POSITION_NUMBER, appointmentFundingEntry.getPositionNumber()); return (BudgetConstructionAdministrativePost) businessObjectService.findByPrimaryKey(BudgetConstructionAdministrativePost.class, searchCriteria); } public BudgetConstructionPosition getBudgetConstructionPosition(Integer universityFiscalYear, PendingBudgetConstructionAppointmentFunding appointmentFundingEntry) { Map searchCriteria = new HashMap(); searchCriteria.put(KFSPropertyConstants.POSITION_NUMBER, appointmentFundingEntry.getPositionNumber()); searchCriteria.put(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR, universityFiscalYear); return (BudgetConstructionPosition) businessObjectService.findByPrimaryKey(BudgetConstructionPosition.class, searchCriteria); } public BudgetConstructionIntendedIncumbent getBudgetConstructionIntendedIncumbent(PendingBudgetConstructionAppointmentFunding appointmentFundingEntry) { Map searchCriteria = new HashMap(); searchCriteria.put(KFSPropertyConstants.EMPLID, appointmentFundingEntry.getEmplid()); return (BudgetConstructionIntendedIncumbent) businessObjectService.findByPrimaryKey(BudgetConstructionIntendedIncumbent.class, searchCriteria); } public void setBudgetConstructionOrganizationReportsService(BudgetConstructionOrganizationReportsService budgetConstructionOrganizationReportsService) { this.budgetConstructionOrganizationReportsService = budgetConstructionOrganizationReportsService; } public void setBusinessObjectService(BusinessObjectService businessObjectService) { this.businessObjectService = businessObjectService; } }
added a helper method
work/src/org/kuali/kfs/module/bc/document/service/impl/BudgetConstructionReportsServiceHelperImpl.java
added a helper method
<ide><path>ork/src/org/kuali/kfs/module/bc/document/service/impl/BudgetConstructionReportsServiceHelperImpl.java <ide> */ <ide> package org.kuali.module.budget.service.impl; <ide> <add>import java.util.ArrayList; <ide> import java.util.Collection; <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import org.kuali.module.budget.bo.BudgetConstructionAdministrativePost; <ide> import org.kuali.module.budget.bo.BudgetConstructionIntendedIncumbent; <ide> import org.kuali.module.budget.bo.BudgetConstructionMonthSummary; <add>import org.kuali.module.budget.bo.BudgetConstructionObjectDump; <ide> import org.kuali.module.budget.bo.BudgetConstructionObjectPick; <ide> import org.kuali.module.budget.bo.BudgetConstructionPosition; <ide> import org.kuali.module.budget.bo.PendingBudgetConstructionAppointmentFunding; <ide> searchCriteria.put(KFSPropertyConstants.EMPLID, appointmentFundingEntry.getEmplid()); <ide> return (BudgetConstructionIntendedIncumbent) businessObjectService.findByPrimaryKey(BudgetConstructionIntendedIncumbent.class, searchCriteria); <ide> } <add> <add> public Collection<PendingBudgetConstructionAppointmentFunding> getPendingBudgetConstructionAppointmentFundingList(Integer universityFiscalYear, BudgetConstructionObjectDump budgetConstructionObjectDump) { <add> Map searchCriteria = new HashMap(); <add> searchCriteria.put(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR, universityFiscalYear); <add> searchCriteria.put(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE, budgetConstructionObjectDump.getChartOfAccountsCode()); <add> searchCriteria.put(KFSPropertyConstants.ACCOUNT_NUMBER, budgetConstructionObjectDump.getAccountNumber()); <add> searchCriteria.put(KFSPropertyConstants.SUB_ACCOUNT_NUMBER, budgetConstructionObjectDump.getSubAccountNumber()); <add> searchCriteria.put(KFSPropertyConstants.FINANCIAL_OBJECT_CODE, budgetConstructionObjectDump.getFinancialObjectCode()); <add> <add> List<String> orderList = new ArrayList(); <add> orderList.add(KFSPropertyConstants.FINANCIAL_OBJECT_CODE); <add> orderList.add(KFSPropertyConstants.FINANCIAL_SUB_OBJECT_CODE); <add> orderList.add(KFSPropertyConstants.POSITION_NUMBER); <add> orderList.add(KFSPropertyConstants.EMPLID); <add> return budgetConstructionOrganizationReportsService.getBySearchCriteriaOrderByList(PendingBudgetConstructionAppointmentFunding.class, searchCriteria, orderList); <add> } <add> <ide> <ide> <ide> public void setBudgetConstructionOrganizationReportsService(BudgetConstructionOrganizationReportsService budgetConstructionOrganizationReportsService) {
JavaScript
bsd-3-clause
017d510b3b9cadbde799ab04300d3b89c8b30915
0
itsa/useragent,ItsAsbreuk/useragent
"use strict"; /** * * * * <i>Copyright (c) 2014 ITSA - https://github.com/itsa</i> * New BSD License - http://choosealicense.com/licenses/bsd-3-clause/ * * @module useragent * @class USERAGENT * @since 0.0.1 */ require('polyfill'); require('js-ext/lib/object.js'); var createHashMap = require('js-ext/extra/hashmap.js').createMap; module.exports = function (window) { var UserAgent, navigator = window.navigator; window._ITSAmodules || Object.protectedProp(window, '_ITSAmodules', createHashMap()); /*jshint boss:true */ if (UserAgent=window._ITSAmodules.UserAgent) { /*jshint boss:false */ return UserAgent; // UserAgent was already created } window._ITSAmodules.UserAgent = UserAgent = { isMobile: ('ontouchstart' in window) || (window.navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0) }; return UserAgent; };
useragent.js
"use strict"; /** * * * * <i>Copyright (c) 2014 ITSA - https://github.com/itsa</i> * New BSD License - http://choosealicense.com/licenses/bsd-3-clause/ * * @module useragent * @class USERAGENT * @since 0.0.1 */ require('polyfill'); require('js-ext/lib/object.js'); var NAME = '[useragent]: ', createHashMap = require('js-ext/extra/hashmap.js').createMap; module.exports = function (window) { var UserAgent, navigator = window.navigator; window._ITSAmodules || Object.protectedProp(window, '_ITSAmodules', createHashMap()); /*jshint boss:true */ if (UserAgent=window._ITSAmodules.UserAgent) { /*jshint boss:false */ return UserAgent; // UserAgent was already created } window._ITSAmodules.UserAgent = UserAgent = { isMobile: ('ontouchstart' in window) || (window.navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0) }; return UserAgent; };
cleanup vars
useragent.js
cleanup vars
<ide><path>seragent.js <ide> require('polyfill'); <ide> require('js-ext/lib/object.js'); <ide> <del>var NAME = '[useragent]: ', <del> createHashMap = require('js-ext/extra/hashmap.js').createMap; <add>var createHashMap = require('js-ext/extra/hashmap.js').createMap; <ide> <ide> module.exports = function (window) { <ide>
Java
mit
84dac0bd1e4fd2f7ad463458e842839ce7dda509
0
castle/castle-java
package io.castle.client.model; import com.google.gson.JsonElement; /** * Model of the outcome of an authenticate call to the Castle API. */ public class Verdict { /** * AuthenticateAction returned by a call to the CastleAPI, or configured by a failover strategy. */ private AuthenticateAction action; /** * String representing a user ID associated with an authenticate call. */ private String userId; /** * True if the SDK resorted the {@code AuthenticateFailoverStrategy} configured. */ private boolean failover; /** * Explains the reason why the {@code AuthenticateFailoverStrategy} was used. */ private String failoverReason; /** * String representing a device ID associated with an authenticate call. */ private String deviceToken; /** * Flott representing risk value associated with an authenticate call. */ private float risk; /** * RiskPolicyResult representing risk policy used for generating this verdict. */ private RiskPolicyResult riskPolicy; /** * JsonElement representing the full response of the server request */ private JsonElement internal; public AuthenticateAction getAction() { return action; } public void setAction(AuthenticateAction action) { this.action = action; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public boolean isFailover() { return failover; } public void setFailover(boolean failover) { this.failover = failover; } public String getFailoverReason() { return failoverReason; } public void setFailoverReason(String failoverReason) { this.failoverReason = failoverReason; } public String getDeviceToken() { return deviceToken; } public void setRisk(float risk) { this.risk = risk; } public float getRisk() { return risk; } public void setDeviceToken(String deviceToken) { this.deviceToken = deviceToken; } public void setInternal(JsonElement internal) { this.internal = internal; } public RiskPolicyResult getRiskPolicy() { return riskPolicy; } public void setRiskPolicy(RiskPolicyResult riskPolicy) { this.riskPolicy = riskPolicy; } public JsonElement getInternal() { return internal; } }
src/main/java/io/castle/client/model/Verdict.java
package io.castle.client.model; import com.google.gson.JsonElement; /** * Model of the outcome of an authenticate call to the Castle API. */ public class Verdict { /** * AuthenticateAction returned by a call to the CastleAPI, or configured by a failover strategy. */ private AuthenticateAction action; /** * String representing a user ID associated with an authenticate call. */ private String userId; /** * True if the SDK resorted the {@code AuthenticateFailoverStrategy} configured. */ private boolean failover; /** * Explains the reason why the {@code AuthenticateFailoverStrategy} was used. */ private String failoverReason; /** * String representing a device ID associated with an authenticate call. */ private String deviceToken; /** * Flott representing risk value associated with an authenticate call. */ private float risk; /** * RiskPolicyResult representing risk policy used for generating this verdict. */ private RiskPolicyResult riskPolicy; /** * JsonElement representing the full response of the server request */ private JsonElement internal; public AuthenticateAction getAction() { return action; } public void setAction(AuthenticateAction action) { this.action = action; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public boolean isFailover() { return failover; } public void setFailover(boolean failover) { this.failover = failover; } public String getFailoverReason() { return failoverReason; } public void setFailoverReason(String failoverReason) { this.failoverReason = failoverReason; } public String getDeviceToken() { return deviceToken; } public void setRisk(float risk) { this.risk = risk; } public float getRisk() { return risk; } public void setDeviceToken(String deviceToken) { this.deviceToken = deviceToken; } public void setInternal(JsonElement internal) { this.internal = internal; } public RiskPolicyResult getRiskPolicy() { return riskPolicy; } public void setRiskPolicy(RiskPolicyResult riskPolicy) { this.riskPolicy = riskPolicy; } }
Add getter for internal json object in Verdict (#92)
src/main/java/io/castle/client/model/Verdict.java
Add getter for internal json object in Verdict (#92)
<ide><path>rc/main/java/io/castle/client/model/Verdict.java <ide> public void setRiskPolicy(RiskPolicyResult riskPolicy) { <ide> this.riskPolicy = riskPolicy; <ide> } <add> <add> public JsonElement getInternal() { <add> return internal; <add> } <ide> }
Java
lgpl-2.1
857d54b6d235db487a1f3121fb12278945c252e7
0
languagetool-org/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,languagetool-org/languagetool
/* LanguageTool, a natural language style checker * Copyright (C) 2012 Daniel Naber (http://www.danielnaber.de) * * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.rules.de; import de.danielnaber.jwordsplitter.GermanWordSplitter; import de.danielnaber.jwordsplitter.InputTooLongException; import org.apache.commons.lang3.RegExUtils; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.languagetool.*; import org.languagetool.language.German; import org.languagetool.languagemodel.LanguageModel; import org.languagetool.rules.Example; import org.languagetool.rules.RuleMatch; import org.languagetool.rules.SuggestedReplacement; import org.languagetool.rules.ngrams.Probability; import org.languagetool.rules.patterns.StringMatcher; import org.languagetool.rules.spelling.CommonFileTypes; import org.languagetool.rules.spelling.hunspell.CompoundAwareHunspellRule; import org.languagetool.rules.spelling.morfologik.MorfologikMultiSpeller; import org.languagetool.synthesis.Synthesizer; import org.languagetool.tagging.Tagger; import org.languagetool.tokenizers.de.GermanCompoundTokenizer; import org.languagetool.tools.StringTools; import java.io.*; import java.util.*; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Collections.singletonList; import static org.apache.commons.lang3.StringUtils.removeEnd; import static org.languagetool.rules.SuggestedReplacement.topMatch; import static org.languagetool.tools.StringTools.startsWithUppercase; import static org.languagetool.tools.StringTools.uppercaseFirstChar; public class GermanSpellerRule extends CompoundAwareHunspellRule { public static final String RULE_ID = "GERMAN_SPELLER_RULE"; private static final int MAX_EDIT_DISTANCE = 2; private static final String adjSuffix = "(basiert|konform|widrig|fähig|haltig|bedingt|gerecht|würdig|relevant|" + "übergreifend|tauglich|artig|bezogen|orientiert|berechtigt|fremd|liebend|bildend|hemmend|abhängig|" + "förmig|mäßig|pflichtig|ähnlich|spezifisch|technisch|typisch|frei|arm|freundlicher|gemäß)"; private static final Pattern missingAdjPattern = Pattern.compile("[a-zöäüß]{3,25}" + adjSuffix + "(er|es|en|em|e)?"); private final static Set<String> lcDoNotSuggestWords = new HashSet<>(Arrays.asList( // some of these are taken fom hunspell's dictionary where non-suggested words use tag "/n": "verjuden", "verjudet", "verjudeter", "verjudetes", "verjudeter", "verjudeten", "verjudetem", "entjuden", "entjudet", "entjudete", "entjudetes", "entjudeter", "entjudeten", "entjudetem", "auschwitzmythos", "judensippe", "judensippen", "judensippschaft", "judensippschaften", "nigger", "niggern", "niggers", "rassejude", "rassejuden", "rassejüdin", "rassejüdinnen", "möse", "mösen", "fotze", "fotzen", "judenfrei", "judenfreie", "judenfreier", "judenfreies", "judenfreien", "judenfreiem", "judenrein", "judenreine", "judenreiner", "judenreines", "judenreinen", "judenreinem", "judenmord", "judenmorden", "judenmörder" )); // some exceptions for changes to the spelling in 2017 - just a workaround so we don't have to touch the binary dict: private static final Pattern PREVENT_SUGGESTION = Pattern.compile( ".*(Majonäse|Bravur|Anschovis|Belkanto|Campagne|Frotté|Grisli|Jockei|Joga|Kalvinismus|Kanossa|Kargo|Ketschup|" + "Kollier|Kommunikee|Masurka|Negligee|Nessessär|Poulard|Varietee|Wandalismus|kalvinist|[Ff]ick).*"); private static final int MAX_TOKEN_LENGTH = 200; private final Set<String> wordsToBeIgnoredInCompounds = new HashSet<>(); private final Set<String> wordStartsToBeProhibited = new HashSet<>(); private final Set<String> wordEndingsToBeProhibited = new HashSet<>(); private static final Map<StringMatcher, Function<String,List<String>>> ADDITIONAL_SUGGESTIONS = new HashMap<>(); static { put("lieder", w -> Arrays.asList("leider", "Lieder")); put("frägst", "fragst"); put("Impflicht", "Impfpflicht"); put("Wandererin", "Wanderin"); put("daß", "dass"); put("eien", "eine"); put("wiederrum", "wiederum"); put("ne", w -> Arrays.asList("'ne", "eine", "nein", "oder")); put("ner", "einer"); put("isses", w -> Arrays.asList("ist es", "Risses")); put("isser", "ist er"); put("Vieleicht", "Vielleicht"); put("inbetracht", "in Betracht"); put("überwhatsapp", "über WhatsApp"); put("überzoom", "über Zoom"); put("überweißt", "überweist"); put("übergoogle", "über Google"); put("einlogen", "einloggen"); put("Kruks", "Krux"); put("Filterbubble", "Filterblase"); put("Filterbubbles", "Filterblasen"); putRepl("Analgen.*", "Analgen", "Anlagen"); putRepl("wiedersteh(en|st|t)", "wieder", "wider"); putRepl("wiederstan(d|den|dest)", "wieder", "wider"); putRepl("wiedersprech(e|t|en)?", "wieder", "wider"); putRepl("wiedersprich(st|t)?", "wieder", "wider"); putRepl("wiedersprach(st|t|en)?", "wieder", "wider"); putRepl("wiederruf(e|st|t|en)?", "wieder", "wider"); putRepl("wiederrief(st|t|en)?", "wieder", "wider"); putRepl("wiederleg(e|st|t|en|te|ten)?", "wieder", "wider"); putRepl("wiederhall(e|st|t|en|te|ten)?", "wieder", "wider"); putRepl("wiedersetz(e|t|en|te|ten)?", "wieder", "wider"); putRepl("wiederstreb(e|st|t|en|te|ten)?", "wieder", "wider"); put("bekomms", "bekomm es"); put("liegts", "liegt es"); put("gesynct", "synchronisiert"); put("gesynced", "synchronisiert"); put("gesyncht", "synchronisiert"); put("gesyngt", "synchronisiert"); put("synce", "synchronisiere"); put("synche", "synchronisiere"); put("syncen", "synchronisieren"); put("synchen", "synchronisieren"); put("wiederspiegelten", "widerspiegelten"); put("wiedererwarten", "wider Erwarten"); put("widerholen", "wiederholen"); put("wiederhohlen", "wiederholen"); put("herrunterladen", "herunterladen"); put("dastellen", "darstellen"); put("zuviel", "zu viel"); put("abgekatertes", "abgekartetes"); put("wiederspiegelt", "widerspiegelt"); put("Komplexheit", "Komplexität"); put("unterschiedet", "unterscheidet"); put("einzigst", "einzig"); put("Einzigst", "Einzig"); put("geschumpfen", "geschimpft"); put("Geschumpfen", "Geschimpft"); put("Oke", "Okay"); put("Mü", "My"); put("abschiednehmen", "Abschied nehmen"); put("wars", w -> Arrays.asList("war's", "war es", "warst")); put("[aA]wa", w -> Arrays.asList("AWA", "ach was", "aber")); put("[aA]lsallerersten?s", w -> Arrays.asList(w.replaceFirst("lsallerersten?s", "ls allererstes"), w.replaceFirst("lsallerersten?s", "ls Allererstes"))); putRepl("(an|auf|ein|zu)gehangen(e[mnrs]?)?$", "hangen", "hängt"); putRepl("[oO]key", "ey$", "ay"); put("packet", "Paket"); put("Thanks", "Danke"); put("Ghanesen?", "Ghanaer"); put("Thumberg", "Thunberg"); put("Allalei", "Allerlei"); put("geupdate[dt]$", "upgedatet"); //put("gefaked", "gefakt"); -- don't suggest put("[pP]roblemhaft(e[nmrs]?)?", w -> Arrays.asList(w.replaceFirst("haft", "behaftet"), w.replaceFirst("haft", "atisch"))); put("rosane[mnrs]?$", w -> Arrays.asList("rosa", w.replaceFirst("^rosan", "rosafarben"))); put("Erbung", w -> Arrays.asList("Vererbung", "Erbschaft")); put("Energiesparung", w -> Arrays.asList("Energieeinsparung", "Energieersparnis")); put("Abbrechung", "Abbruch"); put("Abbrechungen", w -> Arrays.asList("Abbrüche", "Abbrüchen")); put("Urteilung", w -> Arrays.asList("Urteil", "Verurteilung")); put("allmöglichen?", w -> Arrays.asList("alle möglichen", "alle mögliche")); put("Krankenhausen", w -> Arrays.asList("Krankenhäusern", "Krankenhäuser")); put("vorr?auss?etzlich", w -> Arrays.asList("voraussichtlich", "vorausgesetzt")); put("nichtmals", w -> Arrays.asList("nicht mal", "nicht einmal")); put("eingepeilt", "angepeilt"); put("gekukt", "geguckt"); put("nem", w -> Arrays.asList("'nem", "einem")); put("nen", w -> Arrays.asList("'nen", "einen")); put("geb", "gebe"); put("überhaut", "überhaupt"); put("nacher", "nachher"); put("jeztz", "jetzt"); put("les", "lese"); put("wr", "wir"); put("bezweifel", "bezweifle"); put("verzweifel", "verzweifle"); put("zweifel", "zweifle"); put("[wW]ah?rscheindlichkeit", "Wahrscheinlichkeit"); put("Hijab", "Hidschāb"); put("[lL]eerequiment", "Leerequipment"); put("unauslässlich", w -> Arrays.asList("unerlässlich", "unablässig", "unauslöschlich")); put("Registration", "Registrierung"); put("Registrationen", "Registrierungen"); put("Spinnenweben", "Spinnweben"); putRepl("[Ww]ar ne", "ne", "eine"); putRepl("[Ää]nliche[rnms]?", "nlich", "hnlich"); putRepl("[Gg]arnix", "nix", "nichts"); putRepl("[Ww]i", "i", "ie"); putRepl("[uU]nauslässlich(e[mnrs]?)?", "aus", "er"); putRepl("[vV]erewiglicht(e[mnrs]?)?", "lich", ""); putRepl("[zZ]eritifiert(e[mnrs]?)?", "eritifiert", "ertifiziert"); putRepl("gerähten?", "geräht", "Gerät"); putRepl("leptops?", "lep", "Lap"); putRepl("[pP]ie?rsings?", "[pP]ie?rsing", "Piercing"); putRepl("for?melar(en?)?", "for?me", "Formu"); putRepl("näste[mnrs]?$", "^näs", "nächs"); putRepl("Erdogans?$", "^Erdogan", "Erdoğan"); put("Germanistiker[ns]", "Germanisten"); putRepl("Germanistikerin(nen)?", "Germanistiker", "Germanist"); putRepl("[iI]ns?z[ie]nie?rung(en)?", "[iI]ns?z[ie]nie?", "Inszenie"); putRepl("[eE]rhöherung(en)?", "[eE]rhöherung", "Erhöhung"); putRepl("[vV]erspäterung(en)?", "später", "spät"); putRepl("[vV]orallendingen", "orallendingen", "or allen Dingen"); putRepl("[aA]ufjede[nm]fall", "jede[nm]fall$", " jeden Fall"); putRepl("[aA]us[vf]ersehen[dt]lich", "[vf]ersehen[dt]lich", " Versehen"); putRepl("^funk?z[ou]nier.+", "funk?z[ou]nier", "funktionier"); putRepl("[wW]öruber", "öru", "orü"); putRepl("[lL]einensamens?", "[lL]einen", "Lein"); putRepl("Feinleiner[ns]?", "Feinlei", "Fineli"); putRepl("[hH]eilei[td]s?", "[hH]eilei[td]", "Highlight"); putRepl("Oldheimer[ns]?", "he", "t"); putRepl("[tT]räner[ns]?", "[tT]rä", "Trai"); putRepl("[tT]eimings?", "[tT]e", "T"); putRepl("unternehmensl[uü]stig(e[mnrs]?)?", "mensl[uü]st", "mungslust"); // "unternehmenslüstig" -> "unternehmungslustig" putRepl("proff?ess?ional(e[mnrs]?)?", "ff?ess?ional", "fessionell"); putRepl("zuverlässlich(e[mnrs]?)?", "lich", "ig"); putRepl("fluoreszenzierend(e[mnrs]?)?", "zen", ""); putRepl("revalierend(e[mnrs]?)?", "^reval", "rivalis"); putRepl("verhäuft(e[mnrs]?)?", "^ver", "ge"); putRepl("stürmig(e[mnrs]?)?", "mig", "misch"); putRepl("größeste[mnrs]?", "ßes", "ß"); putRepl("n[aä]heste[mnrs]?", "n[aä]he", "näch"); putRepl("gesundlich(e[mnrs]?)?", "lich", "heitlich"); putRepl("eckel(e|t(en?)?|st)?", "^eck", "ek"); putRepl("unhervorgesehen(e[mnrs]?)?", "hervor", "vorher"); putRepl("entt?euscht(e[mnrs]?)?", "entt?eusch", "enttäusch"); putRepl("Phählen?", "^Ph", "Pf"); putRepl("Kattermesser[ns]?", "Ka", "Cu"); putRepl("gehe?rr?t(e[mnrs]?)?", "he?rr?", "ehr"); // "geherte" -> "geehrte" putRepl("gehrter?", "^ge", "gee"); putRepl("[nN]amenhaft(e[mnrs]?)?", "amen", "am"); putRepl("hom(o?e|ö)ophatisch(e[mnrs]?)?", "hom(o?e|ö)ophat", "homöopath"); putRepl("Geschwindlichkeit(en)?", "lich", "ig"); putRepl("Jänners?", "Jänner", "Januar"); putRepl("[äÄ]hlich(e[mnrs]?)?", "lich", "nlich"); putRepl("entf[ai]ngen?", "ent", "emp"); putRepl("entf[äi]ngs?t", "ent", "emp"); putRepl("[Bb]ehilfreich(e[rnms]?)", "reich", "lich"); putRepl("[Bb]zgl", "zgl", "zgl."); putRepl("kaltnass(e[rnms]?)", "kaltnass", "nasskalt"); putRepl("Kaltnass(e[rnms]?)", "Kaltnass", "Nasskalt"); put("check", "checke"); put("Rückrad", "Rückgrat"); put("ala", "à la"); put("Ala", "À la"); put("Reinfolge", "Reihenfolge"); put("Schloß", "Schloss"); put("Investion", "Investition"); put("Beleidung", "Beleidigung"); put("Bole", "Bowle"); put("letzens", "letztens"); put("Pakur", w -> Arrays.asList("Parcours", "Parkuhr")); put("Erstsemesterin", w -> Arrays.asList("Erstsemester", "Erstsemesters", "Erstsemesterstudentin")); put("Erstsemesterinnen", w -> Arrays.asList("Erstsemesterstudentinnen", "Erstsemester", "Erstsemestern")); put("kreativlos(e[nmrs]?)?", w -> Arrays.asList(w.replaceFirst("kreativ", "fantasie"), w.replaceFirst("kreativ", "einfalls"), w.replaceFirst("kreativlos", "unkreativ"), w.replaceFirst("kreativlos", "uninspiriert"))); put("Kreativlosigkeit", "Unkreativität"); put("hinund?her", "hin und her"); put("[lL]ymph?trie?nasche", "Lymphdrainage"); put("Interdeterminismus", "Indeterminismus"); put("elektrität", "Elektrizität"); put("ausgeboten", "ausgebootet"); put("nocheinmall", "noch einmal"); put("aüßerst", "äußerst"); put("Grrösse", "Größe"); put("misverständniss", "Missverständnis"); put("warheit", "Wahrheit"); put("[pP]okemon", "Pokémon"); put("kreigt", "kriegt"); put("Fritöse", "Fritteuse"); put("unerkennlich", "unkenntlich"); put("rückg[äe]nglich", "rückgängig"); put("em?men[sz]", "immens"); put("verhing", "verhängte"); put("verhingen", "verhängten"); put("fangte", "fing"); put("fangten", "fingen"); put("schlie[sß]te", "schloss"); put("schlie[sß]ten", "schlossen"); put("past", "passt"); put("eingetragt", "eingetragen"); put("getrunkt", "getrunken"); put("veräht", "verrät"); put("helfte", "half"); put("helften", "halfen"); put("lad", "lade"); put("befehlte", "befahl"); put("befehlten", "befahlen"); put("angelügt", "angelogen"); put("lügte", "log"); put("lügten", "logen"); put("bratete", "briet"); put("brateten", "brieten"); put("gefahl", "gefiel"); put("Komplexibilität", "Komplexität"); put("abbonement", "Abonnement"); put("zugegebenerweise", "zugegebenermaßen"); put("perse", "per se"); put("Schwitch", "Switch"); put("[aA]nwesenzeiten", "Anwesenheitszeiten"); put("[gG]eizigkeit", "Geiz"); put("[fF]leißigkeit", "Fleiß"); put("[bB]equemheit", "Bequemlichkeit"); put("[mM]issionarie?sie?rung", "Missionierung"); put("[sS]chee?selonge?", "Chaiselongue"); put("Re[kc]amiere", "Récamière"); put("Singel", "Single"); put("legen[td]lich", "lediglich"); put("ein[ua]ndhalb", "eineinhalb"); put("[mM]illion(en)?mal", w -> singletonList(uppercaseFirstChar(w.replaceFirst("mal", " Mal")))); put("Mysql", "MySQL"); put("MWST", "MwSt"); put("Opelarena", "Opel Arena"); put("Toll-Collect", "Toll Collect"); put("[pP][qQ]-Formel", "p-q-Formel"); put("desweitere?m", "des Weiteren"); put("handzuhaben", "zu handhaben"); put("nachvollzuziehe?n", "nachzuvollziehen"); put("Porto?folien", "Portfolios"); put("[sS]chwie?ri?chkeiten", "Schwierigkeiten"); put("[üÜ]bergrifflichkeiten", "Übergriffigkeiten"); put("[aA]r?th?rie?th?is", "Arthritis"); put("zugesand", "zugesandt"); put("weibt", "weißt"); put("fress", "friss"); put("Mamma", "Mama"); put("Präse", "Präsentation"); put("Präsen", "Präsentationen"); put("Orga", "Organisation"); put("Orgas", "Organisationen"); put("Reorga", "Reorganisation"); put("Reorgas", "Reorganisationen"); put("instande?zusetzen", "instand zu setzen"); put("Lia(si|is)onen", "Liaisons"); put("[cC]asemana?ge?ment", "Case Management"); put("[aA]nn?[ou]ll?ie?rung", "Annullierung"); put("[sS]charm", "Charme"); put("[zZ]auberlich(e[mnrs]?)?", w -> Arrays.asList(w.replaceFirst("lich", "isch"), w.replaceFirst("lich", "haft"))); put("[eE]rledung", "Erledigung"); put("erledigigung", "Erledigung"); put("woltest", "wolltest"); put("[iI]ntranzparentheit", "Intransparenz"); put("dunkellilane[mnrs]?", "dunkellila"); put("helllilane[mnrs]?", "helllila"); put("Behauptungsthese", "Behauptung"); put("genzut", "genutzt"); put("[eEäÄ]klerung", "Erklärung"); put("[wW]eh?wechen", "Wehwehchen"); put("nocheinmals", "noch einmal"); put("unverantwortungs?los(e[mnrs]?)?", w -> Arrays.asList(w.replaceFirst("unverantwortungs?", "verantwortungs"), w.replaceFirst("ungs?los", "lich"))); putRepl("[eE]rhaltbar(e[mnrs]?)?", "haltbar", "hältlich"); putRepl("[aA]ufkeinenfall?", "keinenfall?", " keinen Fall"); putRepl("[Dd]rumrum", "rum$", "herum"); putRepl("([uU]n)?proff?esionn?ell?(e[mnrs]?)?", "proff?esionn?ell?", "professionell"); putRepl("[kK]inderlich(e[mnrs]?)?", "inder", "ind"); putRepl("[wW]iedersprichs?t", "ieder", "ider"); putRepl("[wW]hite-?[Ll]abels", "[wW]hite-?[Ll]abel", "White Label"); putRepl("[wW]iederstand", "ieder", "ider"); putRepl("[kK]önntes", "es$", "est"); putRepl("[aA]ssess?oare?s?", "[aA]ssess?oare?", "Accessoire"); putRepl("indifiziert(e[mnrs]?)?", "ind", "ident"); putRepl("dreite[mnrs]?", "dreit", "dritt"); putRepl("verblüte[mnrs]?", "blü", "blüh"); putRepl("Einzigste[mnrs]?", "zigst", "zig"); putRepl("Invests?", "Invest", "Investment"); putRepl("(aller)?einzie?gste[mnrs]?", "(aller)?einzie?gst", "einzig"); putRepl("[iI]nterkurell(e[nmrs]?)?", "ku", "kultu"); putRepl("[iI]ntersannt(e[mnrs]?)?", "sannt", "essant"); putRepl("ubera(g|sch)end(e[nmrs]?)?", "uber", "überr"); putRepl("[Hh]ello", "ello", "allo"); putRepl("[Gg]etagged", "gged", "ggt"); putRepl("[wW]olt$", "lt", "llt"); putRepl("[zZ]uende", "ue", "u E"); putRepl("[iI]nbälde", "nb", "n B"); putRepl("[lL]etztenendes", "ene", "en E"); putRepl("[nN]achwievor", "wievor", " wie vor"); putRepl("[zZ]umbeispiel", "beispiel", " Beispiel"); putRepl("[gG]ottseidank", "[gG]ottseidank", "Gott sei Dank"); putRepl("[gG]rundauf", "[gG]rundauf", "Grund auf"); putRepl("[aA]nsichtnach", "[aA]nsicht", "Ansicht "); putRepl("[uU]n[sz]war", "[sz]war", "d zwar"); putRepl("[wW]aschte(s?t)?", "aschte", "usch"); putRepl("[wW]aschten", "ascht", "usch"); putRepl("Probiren?", "ir", "ier"); putRepl("[gG]esetztreu(e[nmrs]?)?", "tz", "tzes"); putRepl("[wW]ikich(e[nmrs]?)?", "k", "rkl"); putRepl("[uU]naufbesichtigt(e[nmrs]?)?", "aufbe", "beauf"); putRepl("[nN]utzvoll(e[nmrs]?)?", "utzvoll", "ützlich"); putRepl("Lezte[mnrs]?", "Lez", "Letz"); putRepl("Letze[mnrs]?", "Letz", "Letzt"); putRepl("[nN]i[vw]os?", "[nN]i[vw]o", "Niveau"); putRepl("[dD]illetant(en)?", "[dD]ille", "Dilet"); putRepl("Frauenhofer-(Institut|Gesellschaft)", "Frauen", "Fraun"); putRepl("Add-?Ons?", "Add-?On", "Add-on"); putRepl("Addons?", "on", "-on"); putRepl("Internetkaffees?", "kaffee", "café"); putRepl("[gG]ehorsamkeitsverweigerung(en)?", "[gG]ehorsamkeit", "Gehorsam"); putRepl("[wW]ochende[ns]?", "[wW]ochend", "Wochenend"); putRepl("[kK]ongratulier(en?|t(en?)?|st)", "[kK]on", ""); putRepl("[wWkKdD]an$", "n$", "nn"); putRepl("geh?neh?m[ie]gung(en)?", "geh?neh?m[ie]gung", "Genehmigung"); putRepl("Korrigierung(en)?", "igierung", "ektur"); putRepl("[kK]orregierung(en)?", "[kK]orregierung", "Korrektur"); putRepl("[kK]orrie?girung(en)?", "[kK]orrie?girung", "Korrektur"); putRepl("[nN]ocheimal", "eimal", " einmal"); putRepl("[aA]benzu", "enzu", " und zu"); putRepl("[kK]onflikation(en)?", "[kK]onfli", "Kompli"); putRepl("[mM]itanader", "ana", "einan"); putRepl("[mM]itenand", "enand", "einander"); putRepl("Gelangenheitsbestätigung(en)?", "heit", ""); putRepl("[jJ]edwillige[mnrs]?", "willig", "wed"); putRepl("[qQ]ualitäts?bewußt(e[mnrs]?)?", "ts?bewußt", "tsbewusst"); putRepl("[vV]oraussichtig(e[nmrs]?)?", "sichtig", "sichtlich"); putRepl("[gG]leichrechtig(e[nmrs]?)?", "rechtig", "berechtigt"); putRepl("[uU]nnützlich(e[nmrs]?)?", "nützlich", "nütz"); putRepl("[uU]nzerbrechbar(e[nmrs]?)?", "bar", "lich"); putRepl("kolegen?", "ko", "Kol"); putRepl("tableten?", "tablet", "Tablett"); putRepl("verswinde(n|s?t)", "^vers", "versch"); putRepl("unverantwortungsvoll(e[nmrs]?)?", "unverantwortungsvoll", "verantwortungslos"); putRepl("[gG]erechtlichkeit", "[gG]erechtlich", "Gerechtig"); putRepl("[zZ]uverlässlichkeit", "lich", "ig"); putRepl("[uU]nverzeilig(e[mnrs]?)?", "zeilig", "zeihlich"); putRepl("[zZ]uk(ue?|ü)nftlich(e[mnrs]?)?", "uk(ue?|ü)nftlich", "ukünftig"); putRepl("[rR]eligiösisch(e[nmrs]?)?", "isch", ""); putRepl("[fF]olklorisch(e[nmrs]?)?", "isch", "istisch"); putRepl("[eE]infühlsvoll(e[nmrs]?)?", "voll", "am"); putRepl("Unstimmlichkeit(en)?", "lich", "ig"); putRepl("Strebergartens?", "Stre", "Schre"); putRepl("[hH]ähern(e[mnrs]?)?", "ähern", "ären"); putRepl("todesbedroh(end|lich)(e[nmrs]?)?", "todes", "lebens"); putRepl("^[uU]nabsichtig(e[nmrs]?)?", "ig", "lich"); putRepl("[aA]ntisemitistisch(e[mnrs]?)?", "tist", "t"); putRepl("[uU]nvorsehbar(e[mnrs]?)?", "vor", "vorher"); putRepl("([eE]r|[bB]e|unter|[aA]uf)?hälst", "hälst", "hältst"); put("[wW]ohlfühlseins?", w -> Arrays.asList("Wellness", w.replaceFirst("[wW]ohlfühlsein", "Wohlbefinden"), w.replaceFirst("[wW]ohlfühlsein", "Wohlfühlen"))); putRepl("[sS]chmett?e?rling(s|en?)?", "[sS]chmett?e?rling", "Schmetterling"); putRepl("^[eE]inlamie?nie?r(st|en?|(t(e[nmrs]?)?))?", "^einlamie?nie?r", "laminier"); putRepl("[bB]ravurös(e[nrms]?)?", "vur", "vour"); putRepl("[aA]ss?ecoires?", "[aA]ss?ec", "Access"); putRepl("[aA]ufwechse?lungsreich(er|st)?(e[nmrs]?)?", "ufwechse?lung", "bwechslung"); putRepl("[iI]nordnung", "ordnung", " Ordnung"); putRepl("[iI]mmoment", "moment", " Moment"); putRepl("[hH]euteabend", "abend", " Abend"); putRepl("[wW]ienerschnitzel[ns]?", "[wW]ieners", "Wiener S"); putRepl("[sS]chwarzwälderkirschtorten?", "[sS]chwarzwälderk", "Schwarzwälder K"); putRepl("[kK]oxial(e[nmrs]?)?", "x", "ax"); putRepl("([üÜ]ber|[uU]unter)?[dD]urs?chnitt?lich(e[nmrs]?)?", "s?chnitt?", "chschnitt"); putRepl("[dD]urs?chnitts?", "s?chnitt", "chschnitt"); putRepl("[sS]triktlich(e[mnrs]?)?", "lich", ""); putRepl("[hH]öchstwahrlich(e[mnrs]?)?", "wahr", "wahrschein"); putRepl("[oO]rganisativ(e[nmrs]?)?", "tiv", "torisch"); putRepl("[kK]ontaktfreundlich(e[nmrs]?)?", "ndlich", "dig"); putRepl("Helfer?s-Helfer[ns]?", "Helfer?s-H", "Helfersh"); putRepl("[iI]ntell?igentsbestien?", "[iI]ntell?igents", "Intelligenz"); putRepl("[aA]vantgardisch(e[mnrs]?)?", "gard", "gardist"); putRepl("[gG]ewohnheitsbedürftig(e[mnrs]?)?", "wohnheit", "wöhnung"); putRepl("[eE]infühlungsvoll(e[mnrs]?)?", "fühlungsvoll", "fühlsam"); putRepl("[vV]erwant(e[mnrs]?)?", "want", "wandt"); putRepl("[bB]eanstandigung(en)?", "ig", ""); putRepl("[eE]inba(hn|nd)frei(e[mnrs]?)?", "ba(hn|nd)", "wand"); putRepl("[äÄaAeE]rtzten?", "[äÄaAeE]rt", "Är"); putRepl("pdf-Datei(en)?", "pdf", "PDF"); putRepl("rumänern?", "rumäner", "Rumäne"); putRepl("[cCKk]o?usengs?", "[cCKk]o?useng", "Cousin"); putRepl("Influenzer(in(nen)?|[ns])?", "zer", "cer"); putRepl("[vV]ersantdienstleister[ns]?", "[vV]ersant", "Versand"); putRepl("[pP]atrolier(s?t|t?en?)", "atrolier", "atrouillier"); putRepl("[pP]ropagandiert(e[mnrs]?)?", "and", ""); putRepl("[pP]ropagandier(en|st)", "and", ""); putRepl("[kK]app?erzität(en)?", "^[kK]app?er", "Kapa"); putRepl("känzel(n|s?t)", "känzel", "cancel"); put("gekänzelt", "gecancelt"); putRepl("[üÜ]berstreitung(en)?", "[üÜ]berst", "Übersch"); putRepl("anschliess?lich(e(mnrs)?)?", "anschliess?lich", "anschließend"); putRepl("[rR]ethorisch(e(mnrs)?)?", "eth", "het"); putRepl("änlich(e(mnrs)?)?", "än", "ähn"); putRepl("spätmöglichste(mnrs)?", "spätmöglichst", "spätestmöglich"); put("mogen", "morgen"); put("[fF]uss?ill?ien", "Fossilien"); put("übrings", "übrigens"); put("[rR]evü", "Revue"); put("eingänglich", "eingangs"); put("geerthe", "geehrte"); put("interrese", "Interesse"); put("[rR]eschärschen", "Recherchen"); put("[rR]eschärsche", "Recherche"); put("ic", "ich"); put("w[eä]hret", "wäret"); put("mahte", "Mathe"); put("letzdenendes", "letzten Endes"); put("aufgesteht", "aufgestanden"); put("ganichts", "gar nichts"); put("gesich", "Gesicht"); put("glass", "Glas"); put("muter", "Mutter"); put("[pP]appa", "Papa"); put("dier", "dir"); put("Referenz-Nr", "Referenz-Nr."); put("Matrikelnr.", "Matrikel-Nr."); put("Rekrutings?prozess", "Recruitingprozess"); put("sumarum", "summarum"); put("schein", "scheine"); put("Innzahlung", w -> Arrays.asList("In Zahlung", "in Zahlung")); put("änderen", w -> Arrays.asList("ändern", "anderen")); put("wanderen", w -> Arrays.asList("wandern", "Wanderern")); put("Dutzen", w -> Arrays.asList("Duzen", "Dutzend")); put("patien", w -> Arrays.asList("Partien", "Patient")); put("Teammitgliederinnen", w -> Arrays.asList("Teammitgliedern", "Teammitglieder")); put("beidige[mnrs]?", w -> Arrays.asList(w.replaceFirst("ig", ""), w.replaceFirst("beid", "beiderseit"), "beeidigen")); //beide, beiderseitige, beeidigen put("Wissbegierigkeit", w -> Arrays.asList("Wissbegier", "Wissbegierde")); put("Nabend", "'n Abend"); put("gie?bts", "gibt's"); put("vs", "vs."); put("[kK]affeeteria", "Cafeteria"); put("[kK]affeeterien", "Cafeterien"); put("berücksicht", "berücksichtigt"); put("must", "musst"); put("kaffe", "Kaffee"); put("zetel", "Zettel"); put("wie?daholung", "Wiederholung"); put("vie?d(er|a)sehen", "wiedersehen"); put("pr[eä]ventiert", "verhindert"); put("pr[eä]ventieren", "verhindern"); put("zur?verfügung", "zur Verfügung"); put("Verwahrlosigkeit", "Verwahrlosung"); put("[oO]r?ganisazion", "Organisation"); put("[oO]rganisative", "Organisation"); put("Emall?iearbeit", "Emaillearbeit"); put("[aA]petitt", "Appetit"); put("bezuggenommen", "Bezug genommen"); put("mägt", "mögt"); put("frug", "fragte"); put("gesäht", "gesät"); put("verennt", "verrennt"); put("überrant", "überrannt"); put("Gallop", "Galopp"); put("Stop", "Stopp"); put("Schertz", "Scherz"); put("geschied", "geschieht"); put("Aku", "Akku"); put("Migrationspackt", "Migrationspakt"); put("[zZ]ulaufror", "Zulaufrohr"); put("[gG]ebrauchss?puhren", "Gebrauchsspuren"); put("[pP]reisnachlassung", "Preisnachlass"); put("[mM]edikamentation", "Medikation"); put("[nN][ei]gliche", "Negligé"); put("palletten?", w -> Arrays.asList(w.replaceFirst("pall", "Pal"), w.replaceFirst("pa", "Pai"))); put("[pP]allete", "Palette"); put("Geräuch", w -> Arrays.asList("Geräusch", "Gesträuch")); put("[sS]chull?igung", "Entschuldigung"); put("Geerte", "geehrte"); put("versichen", "versichern"); put("hobb?ies", "Hobbys"); put("Begierigkeiten", "Begehrlichkeiten"); put("selblosigkeit", "Selbstlosigkeit"); put("gestyled", "gestylt"); put("umstimigkeiten", "Unstimmigkeiten"); put("unann?äh?ml?ichkeiten", "Unannehmlichkeiten"); put("unn?ann?ehmichkeiten", "Unannehmlichkeiten"); put("übertr[äa]gte", "übertrug"); put("übertr[äa]gten", "übertrugen"); put("NodeJS", "Node.js"); put("Express", "Express.js"); put("erlas", "Erlass"); put("schlagte", "schlug"); put("schlagten", "schlugen"); put("überwissen", "überwiesen"); put("einpar", "ein paar"); put("sreiben", "schreiben"); put("routiene", "Routine"); put("ect", "etc"); put("giept", "gibt"); put("Pann?acott?a", "Panna cotta"); put("Fußgängerunterwegs?", "Fußgängerunterführung"); put("angeschriehen", "angeschrien"); put("vieviel", "wie viel"); put("entäscht", "enttäuscht"); put("Rämchen", "Rähmchen"); put("Seminarbeit", "Seminararbeit"); put("Seminarbeiten", "Seminararbeiten"); put("[eE]ngangment", "Engagement"); put("[lL]eichtah?tleh?t", "Leichtathlet"); put("[pP]fane", "Pfanne"); put("[iI]ngini?eue?r", "Ingenieur"); put("[aA]nligen", "Anliegen"); put("Tankungen", w -> Arrays.asList("Betankungen", "Tankvorgänge")); put("Ärcker", w -> Arrays.asList("Erker", "Ärger")); put("überlasstet", w -> Arrays.asList("überlastet", "überließt")); put("zeren", w -> Arrays.asList("zerren", "zehren")); put("Hänchen", w -> Arrays.asList("Hähnchen", "Hänschen")); put("[sS]itwazion", "Situation"); put("geschriehen", "geschrien"); put("beratete", "beriet"); put("Hälst", "Hältst"); put("[kK]aos", "Chaos"); put("[pP]upatät", "Pubertät"); put("überwendet", "überwindet"); put("[bB]esichtung", "Besichtigung"); put("[hH]ell?owi[eh]?n", "Halloween"); put("geschmelt?zt", "geschmolzen"); put("gewunschen", "gewünscht"); put("bittete", "bat"); put("nehm", "nimm"); put("möchst", "möchtest"); put("Win", "Windows"); put("anschein[dt]", "anscheinend"); put("Subvestitionen", "Subventionen"); put("angeschaffen", "angeschafft"); put("Rechtspruch", "Rechtsspruch"); put("Second-Hand", "Secondhand"); put("[jJ]ahundert", "Jahrhundert"); put("Gesochse", "Gesocks"); put("Vorraus", "Voraus"); put("[vV]orgensweise", "Vorgehensweise"); put("[kK]autsch", "Couch"); put("guterletzt", "guter Letzt"); put("Seminares", "Seminars"); put("Mousepad", "Mauspad"); put("Mousepads", "Mauspads"); put("Wi[Ff]i-Router", "Wi-Fi-Router"); putRepl("[Ll]ilane[srm]?", "ilane[srm]?", "ila"); putRepl("[zZ]uguterletzt", "guterletzt", " guter Letzt"); putRepl("Nootbooks?", "Noot", "Note"); putRepl("[vV]ersendlich(e[mnrs]?)?", "send", "sehent"); putRepl("[uU]nfäh?r(e[mnrs]?)?", "fäh?r", "fair"); putRepl("[mM]edikatös(e[mnrs]?)?", "ka", "kamen"); putRepl("(ein|zwei|drei|vier|fünf|sechs|sieben|acht|neun|zehn|elf|zwölf)undhalb", "und", "ein"); putRepl("[gG]roßzüge[mnrs]?", "züg", "zügig"); putRepl("[äÄ]rtlich(e[mnrs]?)?", "rt", "rzt"); putRepl("[sS]chnelligkeitsfehler[ns]?", "[sS]chnell", "Flücht"); putRepl("[sS]chweinerosane[mnrs]?", "weinerosane[mnrs]?", "weinchenrosa"); putRepl("[aA]nstecklich(e[mnrs]?)?", "lich", "end"); putRepl("[gG]eflechtet(e[mnrs]?)?", "flechtet", "flochten"); putRepl("[gG]enrealistisch(e[mnrs]?)?", "re", "er"); putRepl("überträgt(e[mnrs]?)?", "^überträgt", "übertragen"); putRepl("[iI]nterresent(e[mnrs]?)?", "rresent", "ressant"); putRepl("Simkartenleser[ns]?", "^Simkartenl", "SIM-Karten-L"); putRepl("Hilfstmittel[ns]?", "^Hilfst", "Hilfs"); putRepl("trationell(e[mnrs]?)?", "^tra", "tradi"); putRepl("[bB]erreichs?", "^[bB]er", "Be"); putRepl("[fF]uscher[ns]?", "^[fF]u", "Pfu"); putRepl("[uU]nausweichbar(e[mnrs]?)?", "bar", "lich"); putRepl("[uU]nabdinglich(e[mnrs]?)?", "lich", "bar"); putRepl("[eE]ingänglich(e[mnrs]?)?", "lich", "ig"); putRepl("ausgewöh?nlich(e[mnrs]?)?", "^ausgewöh?n", "außergewöhn"); putRepl("achsial(e[mnrs]?)?", "^achs", "ax"); putRepl("famielen?", "^famiel", "Famili"); putRepl("miter[ns]?", "^mi", "Mie"); putRepl("besig(t(e[mnrs]?)?|en?)", "sig", "sieg"); putRepl("[vV]erziehr(t(e[mnrs]?)?|en?)", "ieh", "ie"); putRepl("^[pP]iek(s?t|en?)", "iek", "ik"); putRepl("[mM]atschscheiben?", "[mM]atschsch", "Mattsch"); put("schafen?", w -> Arrays.asList(w.replaceFirst("sch", "schl"), w.replaceFirst("af", "arf"), w.replaceFirst("af", "aff"))); put("zuschafen", "zu schaffen"); putRepl("[hH]ofen?", "of", "off"); putRepl("[sS]ommerverien?", "[sS]ommerverien?", "Sommerferien"); putRepl("[rR]ecourcen?", "[rR]ec", "Ress"); putRepl("[fF]amm?ill?i?[aä]risch(e[mnrs]?)?", "amm?ill?i?[aä]risch", "amiliär"); putRepl("Sim-Karten?", "^Sim", "SIM"); putRepl("Spax-Schrauben?", "^Spax", "SPAX"); putRepl("[aA]leine", "l", "ll"); putRepl("Kaput", "t", "tt"); putRepl("[fF]estell(s?t|en?)", "est", "estst"); putRepl("[Ee]igtl", "igtl", "igtl."); putRepl("(Baden-)?Würtenbergs?", "Würten", "Württem"); putRepl("Betriebsratzimmer[ns]?", "rat", "rats"); putRepl("Rechts?schreibungsfehler[ns]?", "Rechts?schreibungs", "Rechtschreib"); putRepl("Open[aA]ir-Konzert(en?)?", "Open[aA]ir", "Open-Air"); putRepl("Jugenschuhen?", "Jug", "Jung"); putRepl("TODO-Listen?", "TODO", "To-do"); putRepl("ausiehs?t", "aus", "auss"); putRepl("unterbemittel(nd|t)(e[nmrs]?)?", "unterbemittel(nd|t)", "minderbemittelt"); putRepl("[xX]te[mnrs]?", "te", "-te"); putRepl("verheielt(e[mnrs]?)?", "heiel", "heil"); putRepl("[rR]evolutionie?sier(s?t|en?)", "ie?s", ""); putRepl("Kohleaustiegs?", "aus", "auss"); putRepl("[jJ]urististisch(e[mnrs]?)?", "istist", "ist"); putRepl("gehäckelt(e[nmrs]?)?", "ck", "k"); putRepl("deutsprachig(e[nmrs]?)?", "deut", "deutsch"); putRepl("angesehend(st)?e[nmrs]?", "end", "en"); putRepl("[iI]slamophobisch(e[mnrs]?)?", "isch", ""); putRepl("[vV]erharkt(e[mnrs]?)?", "ar", "a"); putRepl("[dD]esöfterer?[nm]", "öfterer?[nm]", " Öfteren"); putRepl("[dD]eswei[dt]ere?[mn]", "wei[dt]ere?[mn]", " Weiteren"); putRepl("Einkaufstachen?", "ch", "sch"); putRepl("Bortmesser[ns]?", "Bor", "Bro"); putRepl("Makeupstylist(in(nen)?|en)?", "Makeups", "Make-up-S"); putRepl("Fee?dbäcks?", "Fee?dbäck", "Feedback"); putRepl("weirete[nmrs]?", "ret", "ter"); putRepl("Ni[vw]oschalter[ns]?", "Ni[vw]o", "Niveau"); putRepl("[eE]xhibitionisch(e[nmrs]?)?", "isch", "istisch"); putRepl("(ein|aus)?[gG]eschalten(e[nmrs]?)?", "ten", "tet"); putRepl("[uU]nterschiebene[nmrs]?", "sch", "schr"); putRepl("[uU]nbequemlich(st)?e[nmrs]?", "lich", ""); putRepl("[uU][nm]bekweh?m(e[nmrs]?)?", "[nm]bekweh?m", "nbequem"); putRepl("[dD]esatör(s|en?)?", "satör", "serteur"); put("Panelen?", w -> Arrays.asList(w.replaceFirst("Panel", "Paneel"), "Panels")); put("D[eèé]ja-?[vV]o?ue?", "Déjà-vu"); put("Cr[eèé]me-?fra[iî]che", "Crème fraîche"); put("[aA]rr?an?gemont", "Arrangement"); put("[aA]ngagemon", "Engagement"); put("Phyrr?ussieg", "Pyrrhussieg"); put("Mio", "Mio."); put("Datein", "Dateien"); put("[pP]u(zz|ss)el", "Puzzle"); put("Smilies", "Smileys"); put("[dD]iseing?", "Design"); put("[lL]ieradd?ress?e", "Lieferadresse"); put("[bB]o[yi]kutierung", "Boykottierung"); put("Mouseclick", "Mausklick"); put("[aA]ktuelli?esie?rung", "Aktualisierung"); put("Händy", "Handy"); put("gewertschätzt", "wertgeschätzt"); put("tieger", "Tiger"); put("Rollade", w -> Arrays.asList("Rollladen", "Roulade")); put("garnichtmehr", "gar nicht mehr"); put("vileich", "vielleicht"); put("vll?t", "vielleicht"); put("aufgewägt", "aufgewogen"); put("[rR]eflektion", "Reflexion"); put("momentmal", "Moment mal"); put("satzt", "Satz"); put("Büff?(ee|é)", w -> Arrays.asList("Buffet", "Büfett")); put("[fF]rühstücksb[uü]ff?(é|ee)", "Frühstücksbuffet"); put("[aA]lterego", "Alter Ego"); put("Copyride", "Copyright"); put("Analysierung", "Analyse"); put("Exel", "Excel"); put("Glücklichkeit", "Glück"); put("Begierigkeit", "Begierde"); put("voralem", "vor allem"); put("Unorganisation", w -> Arrays.asList("Desorganisation", "Unorganisiertheit")); put("Cand(el|le)lightdinner", "Candle-Light-Dinner"); put("wertgelegt", "Wert gelegt"); put("Deluxe", "de luxe"); put("antuhen", "antun"); put("komen", "kommen"); put("genißen", "genießen"); put("Stationskrankenpflegerin", "Stationsschwester"); put("[iIüÜuU]b[ea]w[ae]isung", "Überweisung"); put("[bB]oxhorn", "Bockshorn"); put("[zZ]oolophie", "Zoophilie"); put("Makieren", "Markieren"); put("Altersheimer", "Alzheimer"); put("gesen", "gesehen"); put("Neugierigkeit", w -> Arrays.asList("Neugier", "Neugierde")); put("[kK]onn?ekt?schen", "Connection"); put("E-Maul", "E-Mail"); put("E-Mauls", "E-Mails"); put("E-Mal", "E-Mail"); put("E-Mals", "E-Mails"); put("[nN]ah?richt", "Nachricht"); put("[nN]ah?richten", "Nachrichten"); put("Getrixe", "Getrickse"); put("Ausage", "Aussage"); put("gelessen", "gelesen"); put("Kanst", "Kannst"); put("Unwohlbefinden", "Unwohlsein"); put("leiwagen", "Leihwagen"); put("krahn", "Kran"); put("[hH]ifi", "Hi-Fi"); put("chouch", "Couch"); put("eh?rgeit?z", "Ehrgeiz"); put("solltes", "solltest"); put("geklabt", "geklappt"); put("angefangt", "angefangen"); put("beinhält", "beinhaltet"); put("beinhielt", "beinhaltete"); put("beinhielten", "beinhalteten"); put("einhaltest", "einhältst"); put("angeruft", "angerufen"); put("erhaltete", "erhielt"); put("übersäht", "übersät"); put("staats?angehoe?rigkeit", "Staatsangehörigkeit"); put("[uU]nangeneh?mheiten", "Unannehmlichkeiten"); put("Humuspaste", "Hummuspaste"); put("afarung", "Erfahrung"); put("bescheid?t", "Bescheid"); put("[mM]iteillung", "Mitteilung"); put("Revisionierung", "Revision"); put("[eE]infühlvermögen", "Einfühlungsvermögen"); put("[sS]peziellisierung", "Spezialisierung"); put("[cC]hangse", "Chance"); put("untergangen", "untergegangen"); put("geliegt", "gelegen"); put("BluRay", "Blu-ray"); put("Freiwilligerin", "Freiwillige"); put("Mitgliederinnen", w -> Arrays.asList("Mitglieder", "Mitgliedern")); put("Hautreinheiten", "Hautunreinheiten"); put("Durfüh?rung", "Durchführung"); put("tuhen", "tun"); put("tuhe", "tue"); put("tip", "Tipp"); put("ccm", "cm³"); put("Kilimand?jaro", "Kilimandscharo"); put("[hH]erausfor?dung", "Herausforderung"); put("[bB]erücksichtung", "Berücksichtigung"); put("artzt?", "Arzt"); put("[tT]h?elepath?ie", "Telepathie"); put("Wi-?Fi-Dire[ck]t", "Wi-Fi Direct"); put("gans", "ganz"); put("Pearl-Harbou?r", "Pearl Harbor"); put("[aA]utonomität", "Autonomie"); put("[fF]r[uü]h?st[uü]c?k", "Frühstück"); putRepl("(ge)?fr[uü]h?st[uü](c?k|g)t", "fr[uü]h?st[uü](c?k|g)t", "frühstückt"); put("zucc?h?inis?", "Zucchini"); put("[mM]itag", "Mittag"); put("Lexion", "Lexikon"); put("[mM]otorisation", "Motorisierung"); put("[fF]ormalisation", "Formalisierung"); put("ausprache", "Aussprache"); put("[mM]enegment", "Management"); put("[gG]ebrauspuren", "Gebrauchsspuren"); put("viedeo", "Video"); put("[hH]erstammung", "Abstammung"); put("[iI]nstall?atör", "Installateur"); put("maletriert", "malträtiert"); put("abgeschaffen", "abgeschafft"); put("Verschiden", "Verschieden"); put("Anschovis", "Anchovis"); put("Bravur", "Bravour"); put("Grisli", "Grizzly"); put("Grislibär", "Grizzlybär"); put("Grislibären", "Grizzlybären"); put("Frotté", "Frottee"); put("Joga", "Yoga"); put("Kalvinismus", "Calvinismus"); put("Kollier", "Collier"); put("Kolliers", "Colliers"); put("Ketschup", "Ketchup"); put("Kommunikee", "Kommuniqué"); put("Negligee", "Negligé"); put("Nessessär", "Necessaire"); put("passee", "passé"); put("Varietee", "Varieté"); put("Varietees", "Varietés"); put("Wandalismus", "Vandalismus"); put("Campagne", "Kampagne"); put("Campagnen", "Kampagnen"); put("Jockei", "Jockey"); put("Roulett", "Roulette"); put("Bestellungsdaten", "Bestelldaten"); put("Package", "Paket"); put("E-mail", "E-Mail"); put("geleased", "geleast"); put("released", "releast"); putRepl("Ballets?", "llet", "llett"); putRepl("Saudiarabiens?", "Saudiarabien", "Saudi-Arabien"); putRepl("eMail-Adressen?", "eMail-", "E-Mail-"); putRepl("[Ww]ieviele?", "ieviel", "ie viel"); putRepl("[Aa]dhoc", "dhoc", "d hoc"); put("As", "Ass"); put("[bB]i[sß](s?[ij]|ch)en", "bisschen"); putRepl("Todos?", "Todo", "To-do"); put("Kovult", "Konvolut"); putRepl("blog(t?en?|t(es?t)?)$", "g", "gg"); put("Zombiefizierungen", "Zombifizierungen"); put("Hühne", w -> Arrays.asList("Bühne", "Hüne", "Hühner")); put("Hühnen", w -> Arrays.asList("Bühnen", "Hünen", "Hühnern")); put("tiptop", "tiptopp"); put("Briese", "Brise"); put("Rechtsschreibreformen", "Rechtschreibreformen"); putRepl("gewertschätzte(([mnrs]|re[mnrs]?)?)$", "gewertschätzt", "wertgeschätzt"); putRepl("knapps(t?en?|t(es?t)?)$", "pp", "p"); put("geknappst", "geknapst"); putRepl("gepiekste[mnrs]?$", "ie", "i"); putRepl("Yings?", "ng", "n"); put("Wiederstandes", "Widerstandes"); putRepl("veganisch(e?[mnrs]?)$", "isch", ""); putRepl("totlangweiligste[mnrs]?$", "tot", "tod"); putRepl("tottraurigste[mnrs]?$", "tot", "tod"); putRepl("kreir(n|e?nd)(e[mnrs]?)?$", "ire?n", "ieren"); putRepl("Pepps?", "pp", "p"); putRepl("Pariahs?", "h", ""); putRepl("Oeuvres?", "Oe", "Œ"); put("Margarite", "Margerite"); put("Kücken", w -> Arrays.asList("Rücken", "Küken")); put("Kompanten", w -> Arrays.asList("Kompasse", "Kompassen")); put("Kandarren", "Kandaren"); put("kniehen", "knien"); putRepl("infisziertes?t$", "fisz", "fiz"); putRepl("Imbusse(n|s)?$", "m", "n"); put("Hollundern", "Holundern"); putRepl("handgehabt(e?[mnrs]?)?$", "handgehabt", "gehandhabt"); put("Funieres", "Furniers"); put("Frohndiensts", "Frondiensts"); put("fithälst", "fit hältst"); putRepl("fitzuhalten(de?[mnrs]?)?$", "fitzuhalten", "fit zu halten"); putRepl("(essen|schlafen|schwimmen|spazieren)zugehen$", "zugehen", " zu gehen"); put("dilettant", w -> Arrays.asList("Dilettant", "dilettantisch")); putRepl("dilettante[mnrs]?$", "te", "tische"); put("Disastern", "Desastern"); putRepl("Brandwein(en?|s)$", "d", "nt"); putRepl("Böhen?$", "h", ""); putRepl("Aufständige[mnr]?$", "ig", "isch"); putRepl("aufständig(e[mnrs]?)?$", "ig", "isch"); putRepl("duzend(e[mnrs]?)?$", "uzend", "utzend"); putRepl("unrelevant(e[mnrs]?)?$", "un", "ir"); putRepl("Unrelevant(e[mnrs]?)?$", "Un", "Ir"); put("aufgrundedessen", "aufgrund dessen"); put("Amalgane", "Amalgame"); put("Kafe", w -> Arrays.asList("Kaffee", "Café")); put("Dammbock", w -> Arrays.asList("Dambock", "Rammbock")); put("Dammhirsch", "Damhirsch"); put("Fairnis", "Fairness"); put("auschluss", w -> Arrays.asList("Ausschluss", "Ausschuss")); put("derikter", w -> Arrays.asList("direkter", "Direktor")); put("[iI]dentifierung", "Identifikation"); put("[eE]mphatie", "Empathie"); put("[eE]iskrem", "Eiscreme"); put("[fF]lüchtung", "Flucht"); put("einamen", "Einnahmen"); put("[eE]inbu(ss|ß)ung", "Einbuße"); put("[eE]inbu(ss|ß)ungen", "Einbußen"); put("nachichten", "Nachrichten"); put("gegehen", "gegangen"); put("Ethnocid", "Ethnozid"); put("Exikose", "Exsikkose"); put("Schonvermögengrenze", "Schonvermögensgrenze"); put("kontest", "konntest"); put("pitza", "Pizza"); put("Tütü", "Tutu"); put("gebittet", "gebeten"); put("gekricht", "gekriegt"); put("Krankenheit", "Krankheit"); put("Krankenheiten", "Krankheiten"); put("[hH]udd[yi]", "Hoodie"); put("Treibel", "Tribal"); put("vorort", "vor Ort"); put("Brotwürfelcro[uû]tons", "Croûtons"); put("bess?tetigung", "Bestätigung"); put("[mM]ayonaisse", "Mayonnaise"); put("misverstaendnis", "Missverständnis"); put("[vV]erlu(ss|ß)t", "Verlust"); put("glückigerweise", "glücklicherweise"); put("[sS]tandtart", "Standard"); put("Mainzerstrasse", "Mainzer Straße"); put("Genehmigerablauf", "Genehmigungsablauf"); put("Bestellerurkunde", "Bestellungsurkunde"); put("Selbstmitleidigkeit", "Selbstmitleid"); put("[iI]ntuion", "Intuition"); put("[cCkK]ontener", "Container"); put("Barcadi", "Bacardi"); put("Unnanehmigkeit", "Unannehmlichkeit"); put("[wW]ischmöppen?", "Wischmopps"); putRepl("[oO]rdnungswiedrichkeit(en)?", "[oO]rdnungswiedrich", "Ordnungswidrig"); putRepl("Mauntenbiker[ns]?", "^Maunten", "Mountain"); putRepl("Mauntenbikes?", "Maunten", "Mountain"); putRepl("[nN]euhichkeit(en)?", "[nN]euhich", "Neuig"); putRepl("Prokopfverbrauchs?", "Prokopfv", "Pro-Kopf-V"); // Duden putRepl("[Gg]ilst", "ilst", "iltst"); putRepl("[vV]ollrichtung(en)?", "[vV]oll", "Ver"); putRepl("[vV]ollrichtest", "oll", "er"); putRepl("[vV]ollrichten?", "oll", "er"); putRepl("[vV]ollrichtet(e([mnrs])?)?", "oll", "er"); putRepl("[bB]edingslos(e([mnrs])?)?", "ding", "dingung"); putRepl("[eE]insichtbar(e[mnrs]?)?", "sicht", "seh"); putRepl("asymetrisch(ere|ste)[mnrs]?$", "ym", "ymm"); putRepl("alterwürdig(ere|ste)[mnrs]?$", "lter", "ltehr"); putRepl("aufständig(ere|ste)[mnrs]?$", "ig", "isch"); putRepl("blutdurstig(ere|ste)[mnrs]?$", "ur", "ür"); putRepl("dilettant(ere|este)[mnrs]?$", "nt", "ntisch"); putRepl("eliptisch(ere|ste)[mnrs]?$", "l", "ll"); putRepl("angegröhlt(e([mnrs])?)?$", "öh", "ö"); putRepl("gothisch(ere|ste)[mnrs]?$", "th", "t"); putRepl("kollossal(ere|ste)[mnrs]?$", "ll", "l"); putRepl("paralel(lere|lste)[mnrs]?$", "paralel", "paralle"); putRepl("symetrischste[mnrs]?$", "ym", "ymm"); putRepl("rethorisch(ere|ste)[mnrs]?$", "rethor", "rhetor"); putRepl("repetativ(ere|ste)[mnrs]?$", "repetat", "repetit"); putRepl("voluptös(e|ere|este)?[mnrs]?$", "tös", "tuös"); putRepl("[pP]flanzig(e[mnrs]?)?", "ig", "lich"); putRepl("geblogt(e[mnrs]?)?$", "gt", "ggt"); putRepl("herraus.*", "herraus", "heraus"); putRepl("[aA]bbonier(en?|s?t|te[mnrst]?)", "bbo", "bon"); putRepl("[aA]pelier(en?|s?t|te[nt]?)", "pel", "ppell"); putRepl("[vV]oltie?schier(en?|s?t|te[nt]?)", "ie?sch", "ig"); putRepl("[mM]eistverkaufteste[mnrs]?", "teste", "te"); putRepl("[uU]nleshaft(e[mnrs]?)?", "haft", "erlich"); putRepl("[gG]laubenswürdig(e[mnrs]?)?", "ens", ""); putRepl("[nN]i[vw]ovoll(e[mnrs]?)?", "[vw]ovoll", "veauvoll"); putRepl("[nN]otgezwungend?(e[mnrs]?)?", "zwungend?", "drungen"); putRepl("[mM]isstraurig(e[mnrs]?)?", "rig", "isch"); putRepl("[iI]nflagrantie?", "flagrantie?", " flagranti"); putRepl("Aux-Anschl(uss(es)?|üssen?)", "Aux", "AUX"); putRepl("desinfektiert(e[mnrs]?)?", "fekt", "fiz"); putRepl("desinfektierend(e[mnrs]?)?", "fekt", "fiz"); putRepl("desinfektieren?", "fekt", "fiz"); putRepl("[dD]esinfektionier(en?|t(e[mnrs]?)?|st)", "fektionier", "fizier"); putRepl("[dD]esinfektionierend(e[mnrs]?)?", "fektionier", "fizier"); putRepl("[kK]ompensionier(en?|t(e[mnrs]?)?|st)", "ion", ""); putRepl("neuliche[mnrs]?", "neu", "neuer"); putRepl("ausbüchsen?", "chs", "x"); putRepl("aus(ge)?büchst(en?)?", "chs", "x"); putRepl("innoff?iziell?(e[mnrs]?)?", "innoff?iziell?", "inoffiziell"); putRepl("[gG]roesste[mnrs]?", "oess", "öß"); putRepl("[tT]efonisch(e[mnrs]?)?", "efon", "elefon"); putRepl("[oO]ptimalisiert", "alis", ""); putRepl("[iI]ntrovertisch(e[mnrs]?)?", "isch", "iert"); putRepl("[aA]miert(e[mnrs]?)?", "mi", "rmi"); putRepl("[vV]ersiehrt(e[mnrs]?)?", "h", ""); putRepl("[dD]urchsichtbar(e[mnrs]?)?", "bar", "ig"); putRepl("[oO]ffensichtig(e[mnrs]?)?", "ig", "lich"); putRepl("[zZ]urverfühgung", "verfühgung", " Verfügung"); putRepl("[vV]erständlichkeitsfragen?", "lichkeits", "nis"); putRepl("[sS]pendeangebot(e[ns]?)?", "[sS]pende", "Spenden"); putRepl("gahrnichts?", "gahr", "gar "); putRepl("[aA]ugensichtlich(e[mnrs]?)?", "sicht", "schein"); putRepl("[lL]eidensvoll(e[mnrs]?)?", "ens", ""); putRepl("[bB]ewusstlich(e[mnrs]?)?", "lich", ""); putRepl("[vV]erschmerzlich(e[mnrs]?)?", "lich", "bar"); putRepl("Krankenbruders?", "bruder", "pfleger"); putRepl("Krankenbrüdern?", "brüder", "pfleger"); putRepl("Lan-(Kabel[ns]?|Verbindung)", "Lan", "LAN"); putRepl("[sS]epalastschriftmandat(s|en?)?", "[sS]epal", "SEPA-L"); putRepl("Pinn?eingaben?", "Pinn?e", "PIN-E"); putRepl("[sS]imkarten?", "[sS]imk", "SIM-K"); putRepl("[vV]orsich(geht|gehen|ging(en)?|gegangen)", "sich", " sich "); putRepl("mitsich(bringt|bringen|brachten?|gebracht)", "sich", " sich "); putRepl("[ck]arnivorisch(e[mnrs]?)?", "[ck]arnivorisch", "karnivor"); putRepl("[pP]erfektest(e[mnrs]?)?", "est", ""); putRepl("[gG]leichtig(e[mnrs]?)?", "tig", "zeitig"); putRepl("[uU]n(her)?vorgesehen(e[mnrs]?)?", "(her)?vor", "vorher"); putRepl("([cC]orona|[gG]rippe)viruss?es", "viruss?es", "virus"); putRepl("Zaubererin(nen)?", "er", ""); putRepl("Second-Hand-L[äa]dens?", "Second-Hand-L", "Secondhandl"); putRepl("Second-Hand-Shops?", "Second-Hand-S", "Secondhands"); putRepl("[mM]editerranisch(e[mnrs]?)?", "isch", ""); putRepl("interplementier(s?t|en?)", "inter", "im"); putRepl("[hH]ochalterlich(e[mnrs]?)?", "alter", "mittelalter"); putRepl("posiniert(e[mnrs]?)?", "si", "sitio"); putRepl("[rR]ussophobisch(e[mnrs]?)?", "isch", ""); putRepl("[uU]nsachmä(ß|ss?)ig(e[mnrs]?)?", "mä(ß|ss?)ig", "gemäß"); putRepl("[mM]odernisch(e[mnrs]?)?", "isch", ""); putRepl("intapretation(en)?", "inta", "Inter"); putRepl("[rR]ethorikkurs(e[ns]?)?", "eth", "het"); putRepl("[uU]nterschreibungsfähig(e[mnrs]?)?", "schreibung", "schrift"); putRepl("[eE]rrorier(en?|t(e[mnrs]?)?|st)", "ror", "u"); putRepl("malediert(e[mnrs]?)?", "malediert", "malträtiert"); putRepl("maletriert(e[mnrs]?)?", "maletriert", "malträtiert"); putRepl("Ausbildereignerprüfung(en)?", "eigner", "eignungs"); putRepl("abtrakt(e[mnrs]?)?", "ab", "abs"); putRepl("unerfolgreich(e[mnrs]?)?", "unerfolgreich", "erfolglos"); putRepl("[bB]attalion(en?|s)?", "[bB]attalion", "Bataillon"); putRepl("[bB]esuchungsverbot(e[ns]?)?", "ung", ""); putRepl("spätrig(e[mnrs]?)?", "rig", "er"); putRepl("angehangene[mnrs]?", "hangen", "hängt"); putRepl("[ck]amel[ie]onhaft(e[mnrs]?)?", "[ck]am[ie]lion", "chamäleon"); putRepl("[wW]idersprüchig(e[mnrs]?)?", "ig", "lich"); putRepl("[fF]austig(e[mnrs]?)?", "austig", "austdick"); putRepl("Belastungsekgs?", "ekg", "-EKG"); putRepl("Flektion(en)?", "Flektion", "Flexion"); putRepl("Off-[Ss]hore-[A-Z].+", "Off-[Ss]hore-", "Offshore"); put("Deis", "Dies"); put("fr", "für"); put("abe", w -> Arrays.asList("habe", "aber", "ab")); put("Oster", w -> Arrays.asList("Ostern", "Osten")); put("richen", w -> Arrays.asList("riechen", "reichen", "richten")); put("deien", w -> Arrays.asList("deine", "dein")); put("meien", w -> Arrays.asList("meine", "mein", "meinen")); put("berüht", w -> Arrays.asList("berühmt", "berührt", "bemüht")); put("herlich", w -> Arrays.asList("ehrlich", "herrlich")); put("erzeiht", w -> Arrays.asList("erzieht", "verzeiht")); put("schalfen", w -> Arrays.asList("schlafen", "schaffen", "scharfen")); put("Anfage", w -> Arrays.asList("Anfrage", "Anlage")); put("Formulares", "Formulars"); put("Danl", "Dank"); put("umbennen", "umbenennen"); put("bevorzugs", "bevorzugst"); put("einhergend", "einhergehend"); put("dos", w -> Arrays.asList("das", "des", "DOS", "DoS")); put("mch", w -> Arrays.asList("mich", "ich", "ach")); put("Ihc", w -> Arrays.asList("Ich", "Ihr", "Ihm")); put("ihc", w -> Arrays.asList("ich", "ihr", "ihm")); put("ioch", "ich"); put("of", "oft"); put("mi", w -> Arrays.asList("im", "mit", "mir")); put("wier", w -> Arrays.asList("wie", "wir", "vier", "hier", "wer")); put("ander", w -> Arrays.asList("an der", "andere", "änder", "anders")); put("ech", w -> Arrays.asList("euch", "ich")); put("letzt", w -> Arrays.asList("letzte", "jetzt")); put("beu", w -> Arrays.asList("bei", "peu", "neu")); put("darn", w -> Arrays.asList("daran", "darin", "dann", "dar")); put("zwie", w -> Arrays.asList("zwei", "wie", "sie", "sowie")); put("gebten", w -> Arrays.asList("gebeten", "gaben", "geboten", "gelten")); put("dea", w -> Arrays.asList("der", "den", "des", "dem")); put("neune", w -> Arrays.asList("neuen", "neue", "Neune")); put("geren", w -> Arrays.asList("gegen", "gerne", "gären")); put("wuerden", w -> Arrays.asList("würden", "wurden")); put("wuerde", w -> Arrays.asList("würde", "wurde")); put("git", w -> Arrays.asList("gut", "gibt", "gilt", "mit")); put("voher", w -> Arrays.asList("vorher", "woher", "hoher")); put("hst", w -> Arrays.asList("hast", "ist", "hat")); put("Hst", w -> Arrays.asList("Hast", "Ist", "Hat")); put("herlichen", w -> Arrays.asList("herzlichen", "ehrlichen", "herrlichen")); put("Herlichen", w -> Arrays.asList("Herzlichen", "Ehrlichen", "Herrlichen")); put("herliche", w -> Arrays.asList("herzliche", "ehrliche", "herrliche")); put("Herliche", w -> Arrays.asList("Herzliche", "Ehrliche", "Herrliche")); put("it", w -> Arrays.asList("ist", "IT", "in", "im")); put("ads", w -> Arrays.asList("das", "ADS", "Ads", "als", "aus")); put("hats", w -> Arrays.asList("hat es", "hast", "hat")); put("Hats", w -> Arrays.asList("Hat es", "Hast", "Hat")); put("och", w -> Arrays.asList("ich", "noch", "doch")); put("bein", w -> Arrays.asList("Bein", "beim", "ein", "bei")); put("ser", w -> Arrays.asList("der", "sehr", "er", "sei")); put("Monatg", w -> Arrays.asList("Montag", "Monate", "Monats")); put("leiben", w -> Arrays.asList("lieben", "bleiben", "leben")); put("grad", w -> Arrays.asList("grade", "Grad", "gerade")); put("dnn", w -> Arrays.asList("dann", "denn", "den")); put("vn", w -> Arrays.asList("von", "an", "in")); put("sin", w -> Arrays.asList("ein", "sind", "sie", "in")); put("schein", w -> Arrays.asList("scheine", "Schein", "scheint", "schien")); put("wil", w -> Arrays.asList("will", "wie", "weil", "wir")); put("Ihen", w -> Arrays.asList("Ihren", "Ihnen", "Ihn", "Iren")); put("Iher", w -> Arrays.asList("Ihre", "Ihr")); put("neunen", w -> Arrays.asList("neuen", "neunten")); put("wiel", w -> Arrays.asList("weil", "wie", "viel")); put("brauchts", w -> Arrays.asList("braucht es", "brauchst", "braucht")); put("schöen", w -> Arrays.asList("schönen", "schön")); put("ihne", w -> Arrays.asList("ihn", "ihnen")); put("af", w -> Arrays.asList("auf", "an", "an", "als")); put("mächte", w -> Arrays.asList("möchte", "Mächte")); put("öffen", w -> Arrays.asList("öffnen", "offen")); put("fernsehgucken", w -> Arrays.asList("fernsehen", "Fernsehen gucken")); put("Mien", w -> Arrays.asList("Mein", "Wien", "Miene")); put("abgeharkt", w -> Arrays.asList("abgehakt", "abgehackt")); put("beiten", w -> Arrays.asList("beiden", "bieten")); put("ber", w -> Arrays.asList("über", "per", "der", "BER")); put("ehr", w -> Arrays.asList("eher", "mehr", "sehr", "er")); put("Meien", w -> Arrays.asList("Meine", "Meinen", "Mein", "Medien")); put("neus", w -> Arrays.asList("neues", "neue", "neu")); put("Sunden", w -> Arrays.asList("Sünden", "Stunden", "Kunden")); put("Bitt", w -> Arrays.asList("Bitte", "Bett", "Bist")); put("bst", w -> Arrays.asList("bist", "ist")); put("ds", w -> Arrays.asList("des", "das", "es")); put("mn", w -> Arrays.asList("man", "in", "an")); put("hilt", w -> Arrays.asList("gilt", "hilft", "hielt", "hält")); put("nei", w -> Arrays.asList("bei", "nie", "ein", "neu")); put("riesen", w -> Arrays.asList("riesigen", "diesen", "Riesen", "reisen")); put("Artal", "Ahrtal"); put("wuste", "wusste"); put("Kuden", "Kunden"); put("austehenden", "ausstehenden"); put("eingelogt", "eingeloggt"); put("kapput", "kaputt"); put("geeehrte", "geehrte"); put("geeehrter", "geehrter"); put("startup", "Start-up"); put("startups", "Start-ups"); put("Biite", "Bitte"); put("Gutn", "Guten"); put("gutn", "guten"); put("Ettiket", "Etikett"); put("iht", "ihr"); put("ligt", "liegt"); put("gester", "gestern"); put("veraten", "verraten"); put("dienem", "deinem"); put("Bite", "Bitte"); put("Serh", "Sehr"); put("serh", "sehr"); put("fargen", "fragen"); put("abrechen", "abbrechen"); put("aufzeichen", "aufzeichnen"); put("Geraet", "Gerät"); put("Geraets", "Geräts"); put("Geraete", "Geräte"); put("Geraeten", "Geräten"); put("Fals", "Falls"); put("soche", "solche"); put("verückt", "verrückt"); put("austellen", "ausstellen"); put("klapt", w -> Arrays.asList("klappt", "klagt")); put("denks", w -> Arrays.asList("denkst", "denkt", "denke", "denk")); put("geerhte", "geehrte"); put("geerte", "geehrte"); put("gehn", "gehen"); put("Spß", "Spaß"); put("kanst", "kannst"); put("fregen", "fragen"); put("Bingerloch", "Binger Loch"); put("[nN]or[dt]rh?einwest(f|ph)alen", "Nordrhein-Westfalen"); put("abzusolvieren", "zu absolvieren"); put("Schutzfließ", "Schutzvlies"); put("Simlock", "SIM-Lock"); put("fäschungen", "Fälschungen"); put("Weinverköstigung", "Weinverkostung"); put("vertag", "Vertrag"); put("geauessert", "geäußert"); put("gestriffen", "gestreift"); put("gefäh?ten", "Gefährten"); put("gefäh?te", "Gefährte"); put("immenoch", "immer noch"); put("sevice", "Service"); put("verhälst", "verhältst"); put("[sS]äusche", "Seuche"); put("Schalottenburg", "Charlottenburg"); put("senora", "Señora"); put("widerrum", "wiederum"); put("[dD]epp?risonen", "Depressionen"); put("Defribilator", "Defibrillator"); put("Defribilatoren", "Defibrillatoren"); put("SwatchGroup", "Swatch Group"); put("achtungslo[ßs]", "achtlos"); put("Boomerang", "Bumerang"); put("Boomerangs", "Bumerangs"); put("Lg", w -> Arrays.asList("LG", "Liebe Grüße")); put("gildet", "gilt"); put("gleitete", "glitt"); put("gleiteten", "glitten"); put("Standbay", "Stand-by"); put("[vV]ollkommnung", "Vervollkommnung"); put("femist", "vermisst"); put("stantepede", "stante pede"); put("[kK]ostarika", "Costa Rica"); put("[kK]ostarikas", "Costa Ricas"); put("[aA]uthenzität", "Authentizität"); put("anlässig", "anlässlich"); put("[sS]tieft", "Stift"); put("[Ii]nspruchnahme", "Inanspruchnahme"); put("höstwah?rsch[ea]inlich", "höchstwahrscheinlich"); put("[aA]lterschbeschränkung", "Altersbeschränkung"); put("[kK]unstoff", "Kunststoff"); put("[iI]nstergramm?", "Instagram"); put("fleicht", "vielleicht"); put("[eE]rartens", "Erachtens"); put("laufte", "lief"); put("lauften", "liefen"); put("malzeit", "Mahlzeit"); put("[wW]ahts?app", "WhatsApp"); put("[wW]elan", w -> Arrays.asList("WLAN", "W-LAN")); put("Pinn", w -> Arrays.asList("Pin", "PIN")); put("Geldmachung", w -> Arrays.asList("Geltendmachung", "Geldmacherei")); put("[uU]nstimm?ichkeiten", "Unstimmigkeiten"); put("Teilnehmung", "Teilnahme"); put("Teilnehmungen", "Teilnahmen"); put("waser", "Wasser"); put("Bekennung", "Bekenntnis"); put("[hH]irar?chie", "Hierarchie"); put("Chr", "Chr."); put("Tiefbaumt", "Tiefbauamt"); put("getäucht", "getäuscht"); put("[hH]ähme", "Häme"); put("Wochendruhezeiten", "Wochenendruhezeiten"); put("Studiumplatzt?", "Studienplatz"); put("Permanent-Make-Up", "Permanent-Make-up"); put("woltet", "wolltet"); put("Bäckei", "Bäckerei"); put("Bäckeien", "Bäckereien"); put("warmweis", "warmweiß"); put("kaltweis", "kaltweiß"); put("jez", "jetzt"); put("hendis", "Handys"); put("wie?derwarten", "wider Erwarten"); put("[eE]ntercott?e", "Entrecôte"); put("[eE]rwachtung", "Erwartung"); put("[aA]nung", "Ahnung"); put("[uU]nreimlichkeiten", "Ungereimtheiten"); put("[uU]nangeneh?mlichkeiten", "Unannehmlichkeiten"); put("Messy", "Messie"); put("Polover", "Pullover"); put("heilwegs", "halbwegs"); put("undsoweiter", "und so weiter"); put("Gladbeckerstrasse", "Gladbecker Straße"); put("Bonnerstra(ß|ss)e", "Bonner Straße"); put("[bB]range", "Branche"); put("Gewebtrauma", "Gewebetrauma"); put("aufgehangen", "aufgehängt"); put("Ehrenamtpauschale", "Ehrenamtspauschale"); put("Essenzubereitung", "Essenszubereitung"); put("[gG]eborgsamkeit", "Geborgenheit"); put("gekommt", "gekommen"); put("hinweißen", "hinweisen"); put("Importation", "Import"); put("lädest", "lädst"); put("Themabereich", "Themenbereich"); put("Werksresett", "Werksreset"); put("wiederfahren", "widerfahren"); put("wiederspiegelten", "widerspiegelten"); put("weicheinlich", "wahrscheinlich"); put("schnäpchen", "Schnäppchen"); put("Hinduist", "Hindu"); put("Hinduisten", "Hindus"); put("Konzeptierung", "Konzipierung"); put("Phyton", "Python"); put("nochnichtmals?", "noch nicht einmal"); put("Refelektion", "Reflexion"); put("Refelektionen", "Reflexionen"); put("[sS]chanse", "Chance"); put("nich", w -> Arrays.asList("nicht", "noch")); put("Nich", w -> Arrays.asList("Nicht", "Noch")); put("wat", "was"); put("[Ee][Ss]ports", "E-Sports"); put("gerelaunch(ed|t)", "relauncht"); put("Gerelaunch(ed|t)", "Relauncht"); put("Bowl", "Bowle"); put("Dark[Ww]eb", "Darknet"); put("Sachs?en-Anhal?t", "Sachsen-Anhalt"); put("[Ss]chalgen", "schlagen"); put("[Ss]chalge", "schlage"); put("[dD]eutsche?sprache", "deutsche Sprache"); put("eigl", "eigtl"); put("ma", "mal"); put("leidete", "litt"); put("leidetest", "littest"); put("leideten", "litten"); put("Hoody", "Hoodie"); put("Hoodys", "Hoodies"); put("Staatsexam", "Staatsexamen"); put("Staatsexams", "Staatsexamens"); put("Exam", "Examen"); put("Exams", "Examens"); put("[Rr]eviewing", "Review"); put("[Bb]aldmöglich", "baldmöglichst"); put("[Bb]rudi", "Bruder"); put("ih", w -> Arrays.asList("ich", "in", "im", "ah")); put("Ih", w -> Arrays.asList("Ich", "In", "Im", "Ah")); put("[qQ]uicky", "Quickie"); put("[qQ]uickys", "Quickies"); put("bissl", w -> Arrays.asList("bissel", "bisserl")); put("Keywort", w -> Arrays.asList("Keyword", "Stichwort")); put("Keyworts", w -> Arrays.asList("Keywords", "Stichworts")); put("Keywörter", w -> Arrays.asList("Keywords", "Stichwörter")); put("strang", w -> Arrays.asList("Strang", "strengte")); put("Gym", w -> Arrays.asList("Fitnessstudio", "Gymnasium")); put("Gyms", w -> Arrays.asList("Fitnessstudios", "Gymnasiums")); put("gäng", w -> Arrays.asList("ging", "gang")); put("di", w -> Arrays.asList("du", "die", "Di.", "der", "den")); put("Di", w -> Arrays.asList("Du", "Die", "Di.", "Der", "Den")); put("Aufn", w -> Arrays.asList("Auf den", "Auf einen", "Auf")); put("aufn", w -> Arrays.asList("auf den", "auf einen", "auf")); put("Aufm", w -> Arrays.asList("Auf dem", "Auf einem", "Auf")); put("aufm", w -> Arrays.asList("auf dem", "auf einem", "auf")); put("Ausm", w -> Arrays.asList("Aus dem", "Aus einem", "Aus")); put("ausm", w -> Arrays.asList("aus dem", "aus einem", "aus")); put("Bs", "Bis"); put("Biß", "Biss"); put("bs", "bis"); put("sehn", "sehen"); put("zutun", "zu tun"); put("Müllhalte", "Müllhalde"); put("Entäuschung", "Enttäuschung"); put("Entäuschungen", "Enttäuschungen"); put("kanns", w -> Arrays.asList("kann es", "kannst")); put("funktionierts", "funktioniert es"); put("hbat", "habt"); put("ichs", "ich es"); put("folgendermassen", "folgendermaßen"); put("Adon", "Add-on"); put("Adons", "Add-ons"); put("ud", "und"); put("vertaggt", w -> Arrays.asList("vertagt", "getaggt")); put("keinsten", w -> Arrays.asList("keinen", "kleinsten")); put("Angehensweise", "Vorgehensweise"); put("Angehensweisen", "Vorgehensweisen"); put("Neudefinierung", "Neudefinition"); put("Definierung", "Definition"); put("Definierungen", "Definitionen"); putRepl("[Üü]bergrifflich(e[mnrs]?)?", "lich", "ig"); put("löchen", w -> Arrays.asList("löschen", "löchern", "Köchen")); put("wergen", w -> Arrays.asList("werfen", "werben", "werten")); } private static void putRepl(String wordPattern, String pattern, String replacement) { ADDITIONAL_SUGGESTIONS.put(StringMatcher.regexp(wordPattern), w -> singletonList(w.replaceFirst(pattern, replacement))); } private static void put(String pattern, String replacement) { ADDITIONAL_SUGGESTIONS.put(StringMatcher.regexp(pattern), w -> singletonList(replacement)); } private static void put(String pattern, Function<String, List<String>> f) { ADDITIONAL_SUGGESTIONS.put(StringMatcher.regexp(pattern), f); } private static final GermanWordSplitter splitter = getSplitter(); private static GermanWordSplitter getSplitter() { try { return new GermanWordSplitter(false); } catch (IOException e) { throw new RuntimeException(e); } } private final LineExpander lineExpander = new LineExpander(); private final GermanCompoundTokenizer compoundTokenizer; private final Synthesizer synthesizer; private final Tagger tagger; public GermanSpellerRule(ResourceBundle messages, German language) { this(messages, language, null, null); } /** * @since 4.2 */ public GermanSpellerRule(ResourceBundle messages, German language, UserConfig userConfig, String languageVariantPlainTextDict) { this(messages, language, userConfig, languageVariantPlainTextDict, Collections.emptyList(), null); } /** * @since 4.3 */ public GermanSpellerRule(ResourceBundle messages, German language, UserConfig userConfig, String languageVariantPlainTextDict, List<Language> altLanguages, LanguageModel languageModel) { super(messages, language, language.getNonStrictCompoundSplitter(), getSpeller(language, userConfig, languageVariantPlainTextDict), userConfig, altLanguages, languageModel); addExamplePair(Example.wrong("LanguageTool kann mehr als eine <marker>nromale</marker> Rechtschreibprüfung."), Example.fixed("LanguageTool kann mehr als eine <marker>normale</marker> Rechtschreibprüfung.")); compoundTokenizer = language.getStrictCompoundTokenizer(); tagger = language.getTagger(); synthesizer = language.getSynthesizer(); } @Override protected synchronized void init() throws IOException { super.init(); super.ignoreWordsWithLength = 1; String pattern = "(" + nonWordPattern.pattern() + "|(?<=[\\d°])-|-(?=\\d+))"; nonWordPattern = Pattern.compile(pattern); } @Override public String getId() { return RULE_ID; } @Override protected boolean isIgnoredNoCase(String word) { return wordsToBeIgnored.contains(word) || // words from spelling.txt also accepted in uppercase (e.g. sentence start, bullet list items): (word.matches("[A-ZÖÄÜ][a-zöäüß-]+") && wordsToBeIgnored.contains(word.toLowerCase(language.getLocale()))) || (ignoreWordsWithLength > 0 && word.length() <= ignoreWordsWithLength); } @Override public List<String> getCandidates(String word) { List<List<String>> partList; try { partList = splitter.getAllSplits(word); } catch (InputTooLongException e) { partList = new ArrayList<>(); } List<String> candidates = new ArrayList<>(); for (List<String> parts : partList) { List<String> tmp = super.getCandidates(parts); tmp = tmp.stream().filter(k -> !k.matches("[A-ZÖÄÜ][a-zöäüß]+-[\\-\\s]?[a-zöäüß]+") && !k.matches("[a-zöäüß]+-[\\-\\s][A-ZÖÄÜa-zöäüß]+")).collect(Collectors.toList()); // avoid e.g. "Direkt-weg" tmp = tmp.stream().filter(k -> !k.contains("-s-")).collect(Collectors.toList()); // avoid e.g. "Geheimnis-s-voll" if (!word.endsWith("-")) { tmp = tmp.stream().filter(k -> !k.endsWith("-")).collect(Collectors.toList()); // avoid "xyz-" unless the input word ends in "-" } candidates.addAll(tmp); if (parts.size() == 2) { // e.g. "inneremedizin" -> "innere Medizin", "gleichgroß" -> "gleich groß" candidates.add(parts.get(0) + " " + parts.get(1)); if (isNounOrProperNoun(uppercaseFirstChar(parts.get(1)))) { candidates.add(parts.get(0) + " " + uppercaseFirstChar(parts.get(1))); } } if (parts.size() == 2 && !parts.get(0).endsWith("s")) { // so we get e.g. Einzahlungschein -> Einzahlungsschein candidates.add(parts.get(0) + "s" + parts.get(1)); } if (parts.size() == 2 && parts.get(1).startsWith("s")) { // so we get e.g. Ordnungshütter -> Ordnungshüter (Ordnungshütter is split as Ordnung + shütter) String firstPart = parts.get(0); String secondPart = parts.get(1); candidates.addAll(super.getCandidates(Arrays.asList(firstPart + "s", secondPart.substring(1)))); } } return candidates; } @Override protected boolean isProhibited(String word) { return super.isProhibited(word) || wordStartsToBeProhibited.stream().anyMatch(w -> word.startsWith(w)) || wordEndingsToBeProhibited.stream().anyMatch(w -> word.endsWith(w)); } @Override protected void addIgnoreWords(String origLine) { // hack: Swiss German doesn't use "ß" but always "ss" - replace this, otherwise // misspellings (from Swiss point-of-view) like "äußere" wouldn't be found: String line = language.getShortCodeWithCountryAndVariant().equals("de-CH") ? origLine.replace("ß", "ss") : origLine; if (origLine.endsWith("-*")) { // words whose line ends with "-*" are only allowed in hyphenated compounds wordsToBeIgnoredInCompounds.add(line.substring(0, line.length() - 2)); return; } List<String> words = expandLine(line); for (String word : words) { super.addIgnoreWords(word); } } @Override protected List<String> expandLine(String line) { return lineExpander.expandLine(line); } @Override protected RuleMatch createWrongSplitMatch(AnalyzedSentence sentence, List<RuleMatch> ruleMatchesSoFar, int pos, String coveredWord, String suggestion1, String suggestion2, int prevPos) { if (suggestion2.matches("[a-zöäü]-.+")) { // avoid confusing matches for e.g. "haben -sehr" (was: "habe n-sehr") return null; } return super.createWrongSplitMatch(sentence, ruleMatchesSoFar, pos, coveredWord, suggestion1, suggestion2, prevPos); } /* * @since 3.6 */ @Override public List<String> getSuggestions(String word) throws IOException { /* Do not just comment in because of https://github.com/languagetool-org/languagetool/issues/3757 if (word.length() < 18 && word.matches("[a-zA-Zöäüß-]+.?")) { for (String prefix : VerbPrefixes.get()) { if (word.startsWith(prefix)) { String lastPart = word.substring(prefix.length()); if (lastPart.length() > 3 && !isMisspelled(lastPart)) { // as these are only single words and both the first part and the last part are spelled correctly // (but the combination is not), it's okay to log the words from a privacy perspective: logger.info("UNKNOWN: {}", word); } } } }*/ List<String> suggestions = super.getSuggestions(word); suggestions = suggestions.stream().filter(this::acceptSuggestion).collect(Collectors.toList()); if (word.endsWith(".")) { // To avoid losing the "." of "word" if it is at the end of a sentence. suggestions.replaceAll(s -> s.endsWith(".") ? s : s + "."); } suggestions = suggestions.stream().filter(k -> !k.equals(word) && (!k.endsWith("-") || word.endsWith("-")) && // no "-" at end (#2450) !k.matches("\\p{L} \\p{L}+") // single chars like in "ü berstenden" (#2610) ).collect(Collectors.toList()); return suggestions; } @Override protected boolean acceptSuggestion(String s) { return !PREVENT_SUGGESTION.matcher(s).matches() && !s.matches(".+[*_:]in") // only suggested when using "..._in" in spelling.txt, so rather never offer this suggestion && !s.matches(".+[*_:]innen") && !s.contains("--") && !s.endsWith("roulett") && !s.matches(".+\\szigste[srnm]") // do not suggest "ein zigste" for "einzigste" && !s.matches("[\\wöäüÖÄÜß]+ [a-zöäüß]-[\\wöäüÖÄÜß]+") // e.g. "Mediation s-Background" && !s.matches("[\\wöäüÖÄÜß]+- [\\wöäüÖÄÜß]+") // e.g. "Pseudo- Rebellentum" && !s.matches("[A-ZÄÖÜ][a-zäöüß]+-[a-zäöüß]+-[a-zäöüß]+") // e.g. "Kapuze-over-teil" && !s.matches("[A-ZÄÖÜ][a-zäöüß]+- [a-zäöüßA-ZÄÖÜ\\-]+") // e.g. "Tuchs-N-Harmonie" && !s.matches("[\\wöäüÖÄÜß]+ -[\\wöäüÖÄÜß]+") // e.g. "ALT -TARIF" && !s.endsWith("-s") // https://github.com/languagetool-org/languagetool/issues/4042 && !s.endsWith(" de") // https://github.com/languagetool-org/languagetool/issues/4042 && !s.endsWith(" en") // https://github.com/languagetool-org/languagetool/issues/4042 && !s.matches("[A-ZÖÄÜa-zöäüß] .+") // z.B. nicht "I Tand" für "IT and Services" && !s.matches(".+ [a-zöäüßA-ZÖÄÜ]"); // z.B. nicht "rauchen e" für "rauche ne" vorschlagen } @NotNull protected static List<String> getSpellingFilePaths(String langCode) { List<String> paths = new ArrayList<>(CompoundAwareHunspellRule.getSpellingFilePaths(langCode)); paths.add( "/" + langCode + "/hunspell/spelling_recommendation.txt"); return paths; } @Nullable protected static MorfologikMultiSpeller getSpeller(Language language, UserConfig userConfig, String languageVariantPlainTextDict) { try { String langCode = language.getShortCode(); String morfoFile = "/" + langCode + "/hunspell/" + langCode + "_" + language.getCountries()[0] + JLanguageTool.DICTIONARY_FILENAME_EXTENSION; if (JLanguageTool.getDataBroker().resourceExists(morfoFile)) { // spell data will not exist in LibreOffice/OpenOffice context List<String> paths = new ArrayList<>(getSpellingFilePaths(langCode)); if (languageVariantPlainTextDict != null) { paths.add(languageVariantPlainTextDict); } List<InputStream> streams = getStreams(paths); try (BufferedReader br = new BufferedReader( new InputStreamReader(new SequenceInputStream(Collections.enumeration(streams)), UTF_8))) { BufferedReader variantReader = getVariantReader(languageVariantPlainTextDict); return new MorfologikMultiSpeller(morfoFile, new ExpandingReader(br), paths, variantReader, languageVariantPlainTextDict, userConfig, MAX_EDIT_DISTANCE); } } else { return null; } } catch (IOException e) { throw new RuntimeException("Could not set up morfologik spell checker", e); } } @Nullable private static BufferedReader getVariantReader(String languageVariantPlainTextDict) { BufferedReader variantReader = null; if (languageVariantPlainTextDict != null && !languageVariantPlainTextDict.isEmpty()) { InputStream variantStream = JLanguageTool.getDataBroker().getFromResourceDirAsStream(languageVariantPlainTextDict); variantReader = new ExpandingReader(new BufferedReader(new InputStreamReader(variantStream, UTF_8))); } return variantReader; } @Override protected void filterForLanguage(List<String> suggestions) { if (language.getShortCodeWithCountryAndVariant().equals("de-CH")) { for (int i = 0; i < suggestions.size(); i++) { String s = suggestions.get(i); suggestions.set(i, s.replace("ß", "ss")); } } // Remove suggestions like "Mafiosi s" and "Mafiosi s.": suggestions.removeIf(s -> Arrays.stream(s.split(" ")).anyMatch(k -> k.matches("\\w\\p{Punct}?"))); // This is not quite correct as it might remove valid suggestions that start with "-", // but without this we get too many strange suggestions that start with "-" for no apparent reason // (e.g. for "Gratifikationskrisem" -> "-Gratifikationskrisen"): suggestions.removeIf(s -> s.length() > 1 && s.startsWith("-")); } @Override protected List<String> sortSuggestionByQuality(String misspelling, List<String> suggestions) { List<String> result = new ArrayList<>(); List<String> topSuggestions = new ArrayList<>(); // candidates from suggestions that get boosted to the top for (String suggestion : suggestions) { if (misspelling.equalsIgnoreCase(suggestion)) { // this should be preferred - only case differs topSuggestions.add(suggestion); } else if (suggestion.contains(" ")) { // this should be preferred - prefer e.g. "vor allem": // suggestions at the sentence end include a period sometimes, clean up for ngram lookup String[] words = suggestion.replaceFirst("\\.$", "").split(" ", 2); if (languageModel != null && words.length == 2) { // language model available, test if split word occurs at all / more frequently than alternative Probability nonSplit = languageModel.getPseudoProbability(singletonList(words[0] + words[1])); Probability split = languageModel.getPseudoProbability(Arrays.asList(words)); //System.out.printf("Probability - %s vs %s: %.12f (%d) vs %.12f (%d)%n", // words[0] + words[1], suggestion, if (nonSplit.getProb() > split.getProb() || split.getProb() == 0) { result.add(suggestion); } else { topSuggestions.add(suggestion); } } else { topSuggestions.add(suggestion); } } else { result.add(suggestion); } } result.addAll(0, topSuggestions); return result; } @Override protected List<String> getFilteredSuggestions(List<String> wordsOrPhrases) { List<String> result = new ArrayList<>(); for (String wordOrPhrase : wordsOrPhrases) { String[] words = tokenizeText(wordOrPhrase); if (words.length >= 2 && isAdjOrNounOrUnknown(words[0]) && isNounOrUnknown(words[1]) && startsWithUppercase(words[0]) && startsWithUppercase(words[1])) { // ignore, seems to be in the form "Release Prozess" which is *probably* wrong } else { result.add(wordOrPhrase); } } return result; } private boolean isNounOrUnknown(String word) { try { List<AnalyzedTokenReadings> readings = tagger.tag(singletonList(word)); return readings.stream().anyMatch(reading -> reading.hasPosTagStartingWith("SUB") || reading.isPosTagUnknown()); } catch (IOException e) { throw new RuntimeException(e); } } private boolean isOnlyNoun(String word) { try { List<AnalyzedTokenReadings> readings = tagger.tag(singletonList(word)); for (AnalyzedTokenReadings reading : readings) { boolean accept = reading.getReadings().stream().allMatch(k -> k.getPOSTag() != null && k.getPOSTag().startsWith("SUB:")); if (!accept) { return false; } } return readings.stream().allMatch(reading -> reading.matchesPosTagRegex("SUB:.*")); } catch (IOException e) { throw new RuntimeException(e); } } private boolean isAdjOrNounOrUnknown(String word) { try { List<AnalyzedTokenReadings> readings = tagger.tag(singletonList(word)); return readings.stream().anyMatch(reading -> reading.hasPosTagStartingWith("SUB") || reading.hasPosTagStartingWith("ADJ") || reading.isPosTagUnknown()); } catch (IOException e) { throw new RuntimeException(e); } } private boolean isNounOrProperNoun(String word) { try { List<AnalyzedTokenReadings> readings = tagger.tag(singletonList(word)); return readings.stream().anyMatch(reading -> reading.hasPosTagStartingWith("SUB") || reading.hasPosTagStartingWith("EIG")); } catch (IOException e) { throw new RuntimeException(e); } } private boolean ignoreElative(String word) { if (StringUtils.startsWithAny(word, "bitter", "dunkel", "erz", "extra", "früh", "gemein", "hyper", "lau", "mega", "minder", "stock", "super", "tod", "ultra", "ur")) { String lastPart = RegExUtils.removePattern(word, "^(bitter|dunkel|erz|extra|früh|gemein|grund|hyper|lau|mega|minder|stock|super|tod|ultra|ur|voll)"); return lastPart.length() >= 3 && !isMisspelled(lastPart); } return false; } @Override public boolean isMisspelled(String word) { if (word.startsWith("Spielzug") && !word.matches("Spielzugs?|Spielzugangs?|Spielzuganges|Spielzugbuchs?|Spielzugbüchern?|Spielzuges|Spielzugverluste?|Spielzugverluste[ns]")) { return true; } if (word.startsWith("Standart") && !word.equals("Standarte") && !word.equals("Standarten") && !word.startsWith("Standartenträger") && !word.startsWith("Standartenführer")) { return true; } if (word.endsWith("schafte") && word.matches("[A-ZÖÄÜ][a-zöäß-]+schafte")) { return true; } return super.isMisspelled(word); } @Override protected boolean ignoreWord(List<String> words, int idx) throws IOException { String word = words.get(idx); if (word.length() > MAX_TOKEN_LENGTH) { return true; } boolean ignore = super.ignoreWord(words, idx); boolean ignoreUncapitalizedWord = !ignore && idx == 0 && super.ignoreWord(StringUtils.uncapitalize(words.get(0))); boolean ignoreByHyphen = false; boolean ignoreBulletPointCase = false; if (!ignoreUncapitalizedWord) { // happens e.g. with list items in Google Docs, which introduce \uFEFF, which here appears as // an empty token: ignoreBulletPointCase = !ignore && idx == 1 && words.get(0).isEmpty() && startsWithUppercase(word) && isMisspelled(word) && !isMisspelled(word.toLowerCase()); } boolean ignoreHyphenatedCompound = false; if (!ignore && !ignoreUncapitalizedWord) { if (word.contains("-")) { if (idx > 0 && "".equals(words.get(idx-1)) && StringUtils.startsWithAny(word, "stel-", "tel-") ) { // accept compounds such as '100stel-Millimeter' or '5tel-Gramm' return !isMisspelled(StringUtils.substringAfter(word, "-")); } else { ignoreByHyphen = word.endsWith("-") && ignoreByHangingHyphen(words, idx); } } ignoreHyphenatedCompound = !ignoreByHyphen && ignoreCompoundWithIgnoredWord(word); } if (CommonFileTypes.getSuffixPattern().matcher(word).matches()) { return true; } if (missingAdjPattern.matcher(word).matches()) { String firstPart = StringTools.uppercaseFirstChar(word.replaceFirst(adjSuffix + "(er|es|en|em|e)?", "")); // We append "test" to see if the word plus "test" is accepted as a compound. This way, we get the // infix 's" handled properly (e.g. "arbeitsartig" is okay, "arbeitartig" is not). It does not accept // all compounds, though, as hunspell's compound detection is limited ("Zwiebacktest"): // TODO: see isNeedingFugenS() // https://www.sekada.de/korrespondenz/rechtschreibung/artikel/grammatik-in-diesen-faellen-steht-das-fugen-s/ /*if (!isMisspelled(firstPart) && !isMisspelled(firstPart + "test")) { System.out.println("accept1: " + word + " [" + !isMisspelled(word) + "]"); //return true; } else if (firstPart.endsWith("s") && !isMisspelled(firstPart.replaceFirst("s$", "")) && !isMisspelled(firstPart + "test")) { // "handlungsartig" System.out.println("accept2: " + word + " [" + !isMisspelled(word) + "]"); //return true; }*/ if (isMisspelled(word)) { if (!isMisspelled(firstPart) && !firstPart.matches(".{3,25}(tum|ing|ling|heit|keit|schaft|ung|ion|tät|at|um)") && isOnlyNoun(firstPart) && !isMisspelled(firstPart + "test")) { // does hunspell accept this? takes infex-s into account automatically //System.out.println("will accept: " + word); return true; } else if (!isMisspelled(firstPart) && !firstPart.matches(".{3,25}(tum|ing|ling|heit|keit|schaft|ung|ion|tät|at|um)")) { //System.out.println("will not accept: " + word); } else if (firstPart.endsWith("s") && !isMisspelled(firstPart.replaceFirst("s$", "")) && firstPart.matches(".{3,25}(tum|ing|ling|heit|keit|schaft|ung|ion|tät|at|um)s") && // "handlungsartig" isOnlyNoun(firstPart.replaceFirst("s$", "")) && !isMisspelled(firstPart + "test")) { // does hunspell accept this? takes infex-s into account automatically //System.out.println("will accept: " + word); return true; } else if (firstPart.endsWith("s") && !isMisspelled(firstPart.replaceFirst("s$", "")) && firstPart.matches(".{3,25}(tum|ing|ling|heit|keit|schaft|ung|ion|tät|at|um)s")) { //System.out.println("will not accept: " + word); } } } if ((idx+1 < words.size() && (word.endsWith(".mp") || word.endsWith(".woff")) && words.get(idx+1).equals("")) || (idx > 0 && "".equals(words.get(idx-1)) && StringUtils.equalsAny(word, "sat", "stel", "tel", "stels", "tels") )) { // e.g. ".mp3", "3sat", "100stel", "5tel" - the check for the empty string is because digits were removed during // hunspell-style tokenization before return true; } return ignore || ignoreUncapitalizedWord || ignoreBulletPointCase || ignoreByHyphen || ignoreHyphenatedCompound || ignoreElative(word); } @Override protected List<SuggestedReplacement> getAdditionalTopSuggestions(List<SuggestedReplacement> suggestions, String word) throws IOException { List<String> suggestionsList = suggestions.stream() .map(SuggestedReplacement::getReplacement).collect(Collectors.toList()); return SuggestedReplacement.convert(getAdditionalTopSuggestionsString(suggestionsList, word)); } private List<String> getAdditionalTopSuggestionsString(List<String> suggestions, String word) throws IOException { String suggestion; if ("WIFI".equalsIgnoreCase(word)) { return singletonList("Wi-Fi"); } else if ("W-Lan".equalsIgnoreCase(word)) { return singletonList("WLAN"); } else if ("genomen".equals(word)) { return singletonList("genommen"); } else if ("Preis-Leistungsverhältnis".equals(word)) { return singletonList("Preis-Leistungs-Verhältnis"); } else if ("getz".equals(word)) { return Arrays.asList("jetzt", "geht's"); } else if ("Trons".equals(word)) { return singletonList("Trance"); } else if ("ei".equals(word)) { return singletonList("ein"); } else if ("jo".equals(word) || "jepp".equals(word) || "jopp".equals(word)) { return singletonList("ja"); } else if ("Jo".equals(word) || "Jepp".equals(word) || "Jopp".equals(word)) { return singletonList("Ja"); } else if ("Ne".equals(word)) { // "Ne einfach Frage!" // "Ne, das musst du machen!" return Arrays.asList("Nein", "Eine"); } else if ("is".equals(word)) { return singletonList("ist"); } else if ("Is".equals(word)) { return singletonList("Ist"); } else if ("un".equals(word)) { return singletonList("und"); } else if ("Un".equals(word)) { return singletonList("Und"); } else if ("Std".equals(word)) { return singletonList("Std."); } else if (word.matches(".*ibel[hk]eit$")) { suggestion = word.replaceFirst("el[hk]eit$", "ilität"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.endsWith("aquise")) { suggestion = word.replaceFirst("aquise$", "akquise"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.endsWith("standart")) { suggestion = word.replaceFirst("standart$", "standard"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.endsWith("standarts")) { suggestion = word.replaceFirst("standarts$", "standards"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.endsWith("tips")) { suggestion = word.replaceFirst("tips$", "tipps"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.endsWith("tip")) { suggestion = word + "p"; if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.endsWith("entfehlung")) { suggestion = word.replaceFirst("ent", "emp"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.endsWith("oullie")) { suggestion = word.replaceFirst("oullie$", "ouille"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.startsWith("[dD]urschnitt")) { suggestion = word.replaceFirst("^urschnitt", "urchschnitt"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.startsWith("Bundstift")) { suggestion = word.replaceFirst("^Bundstift", "Buntstift"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.matches("[aA]llmähll?i(g|ch)(e[mnrs]?)?")) { suggestion = word.replaceFirst("llmähll?i(g|ch)", "llmählich"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.matches(".*[mM]a[jy]onn?[äe]se.*")) { suggestion = word.replaceFirst("a[jy]onn?[äe]se", "ayonnaise"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.matches(".*[rR]es(a|er)[vw]i[he]?rung(en)?")) { suggestion = word.replaceFirst("es(a|er)[vw]i[he]?rung", "eservierung"); if (hunspell.spell(suggestion)) { // suggest e.g. 'Ticketreservierung', but not 'Blödsinnsquatschreservierung' return singletonList(suggestion); } } else if (word.matches("[rR]eschaschier.+")) { suggestion = word.replaceFirst("schaschier", "cherchier"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.matches(".*[lL]aborants$")) { suggestion = word.replaceFirst("ts$", "ten"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.matches("[pP]roff?ess?ion([äe])h?ll?(e[mnrs]?)?")) { suggestion = word.replaceFirst("roff?ess?ion([äe])h?l{1,2}", "rofessionell"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.matches("[vV]erstehendniss?(es?)?")) { suggestion = word.replaceFirst("[vV]erstehendnis", "Verständnis"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.startsWith("koregier")) { suggestion = word.replace("reg", "rrig"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.matches("diagno[sz]ier.*")) { suggestion = word.replaceAll("gno[sz]ier", "gnostizier"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.contains("eiss")) { suggestion = word.replace("eiss", "eiß"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.contains("uess")) { suggestion = word.replace("uess", "üß"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.equals("gin")) { return singletonList("ging"); } else if (word.equals("dh") || word.equals("dh.")) { return singletonList("d.\u202fh."); } else if (word.equals("ua") || word.equals("ua.")) { return singletonList("u.\u202fa."); } else if (word.matches("z[bB]") || word.matches("z[bB].")) { return singletonList("z.\u202fB."); } else if (word.equals("uvm") || word.equals("uvm.")) { return singletonList("u.\u202fv.\u202fm."); } else if (word.equals("udgl") || word.equals("udgl.")) { return singletonList("u.\u202fdgl."); } else if (word.equals("Ruhigkeit")) { return singletonList("Ruhe"); } else if (word.equals("angepreist")) { return singletonList("angepriesen"); } else if (word.equals("halo")) { return singletonList("hallo"); } else if (word.equalsIgnoreCase("zumindestens")) { return singletonList(word.replace("ens", "")); } else if (word.equals("ca")) { return singletonList("ca."); } else if (word.equals("Jezt")) { return singletonList("Jetzt"); } else if (word.equals("Wollst")) { return singletonList("Wolltest"); } else if (word.equals("wollst")) { return singletonList("wolltest"); } else if (word.equals("Rolladen")) { return singletonList("Rollladen"); } else if (word.equals("Maßname")) { return singletonList("Maßnahme"); } else if (word.equals("Maßnamen")) { return singletonList("Maßnahmen"); } else if (word.equals("nanten")) { return singletonList("nannten"); } else if (word.endsWith("ies")) { if (word.equals("Lobbies")) { return singletonList("Lobbys"); } else if (word.equals("Parties")) { return singletonList("Partys"); } else if (word.equals("Babies")) { return singletonList("Babys"); } else if (word.endsWith("derbies")) { suggestion = word.replaceFirst("derbies$", "derbys"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.endsWith("stories")) { suggestion = word.replaceFirst("stories$", "storys"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.endsWith("parties")) { suggestion = word.replaceFirst("parties$", "partys"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } } else if (word.equals("Hallochen")) { return Arrays.asList("Hallöchen", "hallöchen"); } else if (word.equals("hallochen")) { return singletonList("hallöchen"); } else if (word.equals("ok")) { return Arrays.asList("okay", "O.\u202fK."); // Duden-like suggestion with no-break space } else if (word.equals("gesuchen")) { return Arrays.asList("gesuchten", "gesucht"); } else if (word.equals("Germanistiker")) { return Arrays.asList("Germanist", "Germanisten"); } else if (word.equals("Abschlepper")) { return Arrays.asList("Abschleppdienst", "Abschleppwagen"); } else if (word.equals("par")) { return singletonList("paar"); } else if (word.equals("vllt")) { return singletonList("vielleicht"); } else if (word.equals("iwie")) { return singletonList("irgendwie"); } else if (word.equals("bzgl")) { return singletonList("bzgl."); } else if (word.equals("bau")) { return singletonList("baue"); } else if (word.equals("sry")) { return singletonList("sorry"); } else if (word.equals("Sry")) { return singletonList("Sorry"); } else if (word.equals("thx")) { return singletonList("danke"); } else if (word.equals("Thx")) { return singletonList("Danke"); } else if (word.equals("Zynik")) { return singletonList("Zynismus"); } else if (word.equalsIgnoreCase("email")) { return singletonList("E-Mail"); } else if (word.length() > 9 && word.startsWith("Email")) { String suffix = word.substring(5); if (!hunspell.spell(suffix)) { List<String> suffixSuggestions = hunspell.suggest(uppercaseFirstChar(suffix)); suffix = suffixSuggestions.isEmpty() ? suffix : suffixSuggestions.get(0); } return singletonList("E-Mail-"+Character.toUpperCase(suffix.charAt(0))+suffix.substring(1)); } else if (word.equals("wiederspiegeln")) { return singletonList("widerspiegeln"); } else if (word.equals("ch")) { return singletonList("ich"); } else { for (Map.Entry<StringMatcher, Function<String, List<String>>> entry : ADDITIONAL_SUGGESTIONS.entrySet()) { if (entry.getKey().matches(word)) { return entry.getValue().apply(word); } } } if (!startsWithUppercase(word)) { String ucWord = uppercaseFirstChar(word); if (!suggestions.contains(ucWord) && hunspell.spell(ucWord) && !ucWord.endsWith(".")) { // Hunspell doesn't always automatically offer the most obvious suggestion for compounds: return singletonList(ucWord); } } String verbSuggestion = getPastTenseVerbSuggestion(word); if (verbSuggestion != null) { return singletonList(verbSuggestion); } String participleSuggestion = getParticipleSuggestion(word); if (participleSuggestion != null) { return singletonList(participleSuggestion); } String abbreviationSuggestion = getAbbreviationSuggestion(word); if (abbreviationSuggestion != null) { return singletonList(abbreviationSuggestion); } // hyphenated compounds words (e.g., "Netflix-Flm") if (suggestions.isEmpty() && word.contains("-")) { String[] words = word.split("-"); if (words.length > 1) { List<List<String>> suggestionLists = new ArrayList<>(words.length); int startAt = 0; int stopAt = words.length; String partialWord = words[0] + "-" + words[1]; if (super.ignoreWord(partialWord) || wordsToBeIgnoredInCompounds.contains(partialWord)) { // "Au-pair-Agentr" startAt = 2; suggestionLists.add(singletonList(words[0] + "-" + words[1])); } partialWord = words[words.length-2] + "-" + words[words.length-1]; if (super.ignoreWord(partialWord) || wordsToBeIgnoredInCompounds.contains(partialWord)) { // "Seniren-Au-pair" stopAt = words.length-2; } for (int idx = startAt; idx < stopAt; idx++) { if (!hunspell.spell(words[idx])) { List<String> list = sortSuggestionByQuality(words[idx], super.getSuggestions(words[idx])); suggestionLists.add(list); } else { suggestionLists.add(singletonList(words[idx])); } } if (stopAt < words.length-1) { suggestionLists.add(singletonList(partialWord)); } if (suggestionLists.size() <= 3) { // avoid OutOfMemory on words like "free-and-open-source-and-cross-platform" List<String> additionalSuggestions = suggestionLists.get(0); for (int idx = 1; idx < suggestionLists.size(); idx++) { List<String> suggestionList = suggestionLists.get(idx); List<String> newList = new ArrayList<>(additionalSuggestions.size() * suggestionList.size()); for (String additionalSuggestion : additionalSuggestions) { for (String aSuggestionList : suggestionList) { newList.add(additionalSuggestion + "-" + aSuggestionList); } } additionalSuggestions = newList; } // avoid overly long lists of suggestions (we just take the first results, although we don't know whether they are better): return additionalSuggestions.subList(0, Math.min(5, additionalSuggestions.size())); } } } return Collections.emptyList(); } // Get a correct suggestion for invalid words like greifte, denkte, gehte: useful for // non-native speakers and cannot be found by just looking for similar words. @Nullable private String getPastTenseVerbSuggestion(String word) { if (word.endsWith("e")) { // strip trailing "e" String wordStem = word.substring(0, word.length()-1); try { String lemma = baseForThirdPersonSingularVerb(wordStem); if (lemma != null) { AnalyzedToken token = new AnalyzedToken(lemma, null, lemma); String[] forms = synthesizer.synthesize(token, "VER:3:SIN:PRT:.*", true); if (forms.length > 0) { return forms[0]; } } } catch (IOException e) { throw new RuntimeException(e); } } return null; } @Nullable private String baseForThirdPersonSingularVerb(String word) throws IOException { List<AnalyzedTokenReadings> readings = tagger.tag(singletonList(word)); for (AnalyzedTokenReadings reading : readings) { if (reading.hasPosTagStartingWith("VER:3:SIN")) { return reading.getReadings().get(0).getLemma(); } } return null; } // Get a correct suggestion for invalid words like geschwimmt, geruft: useful for // non-native speakers and cannot be found by just looking for similar words. @Nullable private String getParticipleSuggestion(String word) { if (word.startsWith("ge") && word.endsWith("t")) { // strip leading "ge" and replace trailing "t" with "en": String baseform = word.substring(2, word.length()-1) + "en"; try { String participle = getParticipleForBaseform(baseform); if (participle != null) { return participle; } } catch (IOException e) { throw new RuntimeException(e); } } return null; } @Nullable private String getParticipleForBaseform(String baseform) throws IOException { AnalyzedToken token = new AnalyzedToken(baseform, null, baseform); String[] forms = synthesizer.synthesize(token, "VER:PA2:.*", true); if (forms.length > 0 && hunspell.spell(forms[0])) { return forms[0]; } return null; } private String getAbbreviationSuggestion(String word) throws IOException { if (word.length() < 5) { List<AnalyzedTokenReadings> readings = tagger.tag(singletonList(word)); for (AnalyzedTokenReadings reading : readings) { if (reading.hasPosTagStartingWith("ABK")) { return word+"."; } } } return null; } private boolean ignoreByHangingHyphen(List<String> words, int idx) throws IOException { String word = words.get(idx); String nextWord = getWordAfterEnumerationOrNull(words, idx+1); nextWord = removeEnd(nextWord, "."); boolean isCompound = nextWord != null && (compoundTokenizer.tokenize(nextWord).size() > 1 || nextWord.indexOf('-') > 0 || nextWord.matches("[A-ZÖÄÜ][a-zöäüß]{2,}(ei|öl)$")); // compound tokenizer will only split compounds where each part is >= 3 characters... if (isCompound) { word = removeEnd(word, "-"); boolean isMisspelled = !hunspell.spell(word); // "Stil- und Grammatikprüfung" or "Stil-, Text- und Grammatikprüfung" if (isMisspelled && (super.ignoreWord(word) || wordsToBeIgnoredInCompounds.contains(word))) { isMisspelled = false; } else if (isMisspelled && word.endsWith("s") && isNeedingFugenS(removeEnd(word, "s"))) { // Vertuschungs- und Bespitzelungsmaßnahmen: remove trailing "s" before checking "Vertuschungs" so that the spell checker finds it isMisspelled = !hunspell.spell(removeEnd(word, "s")); } return !isMisspelled; } return false; } private boolean isNeedingFugenS(String word) { // according to http://www.spiegel.de/kultur/zwiebelfisch/zwiebelfisch-der-gebrauch-des-fugen-s-im-ueberblick-a-293195.html return StringUtils.endsWithAny(word, "tum", "ling", "ion", "tät", "keit", "schaft", "sicht", "ung", "en"); } // for "Stil- und Grammatikprüfung", get "Grammatikprüfung" when at position of "Stil-" @Nullable private String getWordAfterEnumerationOrNull(List<String> words, int idx) { for (int i = idx; i < words.size(); i++) { String word = words.get(i); if (!(word.endsWith("-") || StringUtils.equalsAny(word, ",", "und", "oder", "sowie") || word.trim().isEmpty())) { return word; } } return null; } // check whether a <code>word<code> is a valid compound (e.g., "Feynmandiagramm" or "Feynman-Diagramm") // that contains an ignored word from spelling.txt (e.g., "Feynman") private boolean ignoreCompoundWithIgnoredWord(String word) throws IOException { if (!startsWithUppercase(word) && !StringUtils.startsWithAny(word, "nord", "west", "ost", "süd")) { // otherwise stuff like "rumfangreichen" gets accepted return false; } String[] words = word.split("-"); if (words.length < 2) { // non-hyphenated compound (e.g., "Feynmandiagramm"): // only search for compounds that start(!) with a word from spelling.txt int end = super.startsWithIgnoredWord(word, true); if (end < 3) { // support for geographical adjectives - although "süd/ost/west/nord" are not in spelling.txt // to accept sentences such as // "Der westperuanische Ferienort, das ostargentinische Städtchen, das südukrainische Brauchtum, der nordägyptische Staudamm." if (word.startsWith("ost") || word.startsWith("süd")) { end = 3; } else if (word.startsWith("west") || word.startsWith("nord")) { end = 4; } else { return false; } } String ignoredWord = word.substring(0, end); String partialWord = word.substring(end); partialWord = partialWord.endsWith(".") ? partialWord.substring(0, partialWord.length()-1) : partialWord; boolean isCandidateForNonHyphenatedCompound = !StringUtils.isAllUpperCase(ignoredWord) && (StringUtils.isAllLowerCase(partialWord) || ignoredWord.endsWith("-")); boolean needFugenS = isNeedingFugenS(ignoredWord); if (isCandidateForNonHyphenatedCompound && !needFugenS && partialWord.length() > 2) { return hunspell.spell(partialWord) || hunspell.spell(StringUtils.capitalize(partialWord)); } else if (isCandidateForNonHyphenatedCompound && needFugenS && partialWord.length() > 2) { partialWord = partialWord.startsWith("s") ? partialWord.substring(1) : partialWord; return hunspell.spell(partialWord) || hunspell.spell(StringUtils.capitalize(partialWord)); } return false; } // hyphenated compound (e.g., "Feynman-Diagramm"): boolean hasIgnoredWord = false; List<String> toSpellCheck = new ArrayList<>(3); String stripFirst = word.substring(words[0].length()+1); // everything after the first "-" String stripLast = word.substring(0, word.length()-words[words.length-1].length()-1); // everything up to the last "-" if (super.ignoreWord(stripFirst) || wordsToBeIgnoredInCompounds.contains(stripFirst)) { // e.g., "Senioren-Au-pair" hasIgnoredWord = true; if (!super.ignoreWord(words[0])) { toSpellCheck.add(words[0]); } } else if (super.ignoreWord(stripLast) || wordsToBeIgnoredInCompounds.contains(stripLast)) { // e.g., "Au-pair-Agentur" hasIgnoredWord = true; if (!super.ignoreWord(words[words.length-1])){ toSpellCheck.add(words[words.length-1]); } } else { for (String word1 : words) { if (super.ignoreWord(word1) || wordsToBeIgnoredInCompounds.contains(word1)) { hasIgnoredWord = true; } else { toSpellCheck.add(word1); } } } if (hasIgnoredWord) { for (String w : toSpellCheck) { if (!hunspell.spell(w)) { return false; } } } return hasIgnoredWord; } static class ExpandingReader extends BufferedReader { private final List<String> buffer = new ArrayList<>(); private final LineExpander lineExpander = new LineExpander(); ExpandingReader(Reader in) { super(in); } @Override public String readLine() throws IOException { if (buffer.isEmpty()) { String line = super.readLine(); if (line == null) { return null; } buffer.addAll(lineExpander.expandLine(line)); } return buffer.remove(0); } } @Override protected boolean isQuotedCompound(AnalyzedSentence analyzedSentence, int idx, String token) { if (idx > 3 && token.startsWith("-")) { return StringUtils.equalsAny(analyzedSentence.getTokens()[idx-1].getToken(), "“", "\"") && StringUtils.equalsAny(analyzedSentence.getTokens()[idx-3].getToken(), "„", "\""); } return false; } /* (non-Javadoc) * @see org.languagetool.rules.spelling.SpellingCheckRule#addProhibitedWords(java.util.List) */ @Override protected void addProhibitedWords(List<String> words) { if (words.size() == 1 && words.get(0).endsWith(".*")) { wordStartsToBeProhibited.add(words.get(0).substring(0, words.get(0).length()-2)); } else if (words.get(0).startsWith(".*")) { words.stream().forEach(word -> wordEndingsToBeProhibited.add(word.substring(2))); } else { super.addProhibitedWords(words); } } @Override protected List<SuggestedReplacement> filterNoSuggestWords(List<SuggestedReplacement> l) { return l.stream() .filter(k -> !lcDoNotSuggestWords.contains(k.getReplacement().toLowerCase())) .filter(k -> !k.getReplacement().toLowerCase().matches("neger.*")) .filter(k -> !k.getReplacement().toLowerCase().matches(".+neger(s|n|in|innen)?")) .collect(Collectors.toList()); } @Override protected List<SuggestedReplacement> getOnlySuggestions(String word) { if (word.matches("[Aa]utentisch(e[nmsr]?|ste[nmsr]?|ere[nmsr]?)?")) { return topMatch(word.replaceFirst("utent", "uthent")); } if (word.matches("brilliant(e[nmsr]?|ere[nmsr]?|este[nmsr]?)?")) { return topMatch(word.replaceFirst("brilliant", "brillant")); } switch (word) { case "Reiszwecke": return topMatch("Reißzwecke", "kurzer Nagel mit flachem Kopf"); case "Reiszwecken": return topMatch("Reißzwecken", "kurzer Nagel mit flachem Kopf"); case "up-to-date": return topMatch("up to date"); case "falscherweise": return topMatch("fälschlicherweise"); case "daß": return topMatch("dass"); case "Daß": return topMatch("Dass"); case "mußt": return topMatch("musst"); case "Mußt": return topMatch("Musst"); case "müßt": return topMatch("müsst"); case "Müßt": return topMatch("Müsst"); case "mußten": return topMatch("mussten"); case "mußte": return topMatch("musste"); case "mußtest": return topMatch("musstest"); case "müßtest": return topMatch("müsstest"); case "müßen": return topMatch("müssen"); case "müßten": return topMatch("müssten"); case "müßte": return topMatch("müsste"); case "wüßte": return topMatch("wüsste"); case "wüßten": return topMatch("wüssten"); case "bescheid": return topMatch("Bescheid"); case "ausversehen": return topMatch("aus Versehen"); case "Stückweit": return topMatch("Stück weit"); case "Uranium": return topMatch("Uran"); case "Uraniums": return topMatch("Urans"); case "Luxenburg": return topMatch("Luxemburg"); case "Luxenburgs": return topMatch("Luxemburgs"); case "Lichtenstein": return topMatch("Liechtenstein"); case "Lichtensteins": return topMatch("Liechtensteins"); case "immernoch": return topMatch("immer noch"); case "Rechtshcreibfehler": return topMatch("Rechtschreibfehler"); // for demo text on home page case "markirt": return topMatch("markiert"); // for demo text on home page case "Johannesbeere": return topMatch("Johannisbeere"); case "Johannesbeeren": return topMatch("Johannisbeeren"); case "Endgeld": return topMatch("Entgeld"); case "Entäuschung": return topMatch("Enttäuschung"); case "Entäuschungen": return topMatch("Enttäuschungen"); case "Triologie": return topMatch("Trilogie", "Werk (z.B. Film), das aus drei Teilen besteht"); case "ausserdem": return topMatch("außerdem"); case "Ausserdem": return topMatch("Außerdem"); case "bischen": return topMatch("bisschen"); case "bißchen": return topMatch("bisschen"); case "meißt": return topMatch("meist"); case "meißten": return topMatch("meisten"); case "meißtens": return topMatch("meistens"); case "Babyphone": return topMatch("Babyfon"); case "Baby-Phone": return topMatch("Babyfon"); case "gescheint": return topMatch("geschienen"); case "staubgesaugt": return topMatch("gestaubsaugt"); case "gedownloadet": return topMatch("downgeloadet"); case "gedownloadete": return topMatch("downgeloadete"); case "gedownloadeter": return topMatch("downgeloadeter"); case "gedownloadetes": return topMatch("downgeloadetes"); case "gedownloadeten": return topMatch("downgeloadeten"); case "gedownloadetem": return topMatch("downgeloadetem"); case "geuploadet": return topMatch("upgeloadet"); case "geuploadete": return topMatch("upgeloadete"); case "geuploadeter": return topMatch("upgeloadeter"); case "geuploadetes": return topMatch("upgeloadetes"); case "geuploadeten": return topMatch("upgeloadeten"); case "geuploadetem": return topMatch("upgeloadetem"); case "Frauenhofer": return topMatch("Fraunhofer"); case "Mwst": return topMatch("MwSt"); case "MwSt": return topMatch("MwSt."); case "exkl": return topMatch("exkl."); case "inkl": return topMatch("inkl."); case "hälst": return topMatch("hältst"); case "Rythmus": return topMatch("Rhythmus"); case "Rhytmus": return topMatch("Rhythmus"); case "Rhytmen": return topMatch("Rhythmen"); case "Hobbies": return topMatch("Hobbys"); case "Stehgreif": return topMatch("Stegreif"); case "brilliant": return topMatch("brillant"); case "brilliante": return topMatch("brillante"); case "brilliantes": return topMatch("brillantes"); case "brillianter": return topMatch("brillanter"); case "brillianten": return topMatch("brillanten"); case "brilliantem": return topMatch("brillantem"); case "Billiard": return topMatch("Billard"); case "garnicht": return topMatch("gar nicht"); case "garnich": return topMatch("gar nicht"); case "garnichts": return topMatch("gar nichts"); case "assozial": return topMatch("asozial"); case "assoziale": return topMatch("asoziale"); case "assoziales": return topMatch("asoziales"); case "assozialer": return topMatch("asozialer"); case "assozialen": return topMatch("asozialen"); case "assozialem": return topMatch("asozialem"); case "Verwandschaft": return topMatch("Verwandtschaft"); case "vorraus": return topMatch("voraus"); case "Vorraus": return topMatch("Voraus"); case "Reperatur": return topMatch("Reparatur"); case "Reperaturen": return topMatch("Reparaturen"); case "Bzgl": return topMatch("Bzgl."); case "bzgl": return topMatch("bzgl."); case "Eigtl": return topMatch("Eigtl."); case "eigtl": return topMatch("eigtl."); case "Mo-Di": return topMatch("Mo.–Di."); case "Mo-Mi": return topMatch("Mo.–Mi."); case "Mo-Do": return topMatch("Mo.–Do."); case "Mo-Fr": return topMatch("Mo.–Fr."); case "Mo-Sa": return topMatch("Mo.–Sa."); case "Mo-So": return topMatch("Mo.–So."); case "Di-Mi": return topMatch("Di.–Mi."); case "Di-Do": return topMatch("Di.–Do."); case "Di-Fr": return topMatch("Di.–Fr."); case "Di-Sa": return topMatch("Di.–Sa."); case "Di-So": return topMatch("Di.–So."); case "Mi-Do": return topMatch("Mi.–Do."); case "Mi-Fr": return topMatch("Mi.–Fr."); case "Mi-Sa": return topMatch("Mi.–Sa."); case "Mi-So": return topMatch("Mi.–So."); case "Do-Fr": return topMatch("Do.–Fr."); case "Do-Sa": return topMatch("Do.–Sa."); case "Do-So": return topMatch("Do.–So."); case "Fr-Sa": return topMatch("Fr.–Sa."); case "Fr-So": return topMatch("Fr.–So."); case "Sa-So": return topMatch("Sa.–So."); case "Achso": return topMatch("Ach so"); case "achso": return topMatch("ach so"); case "Huskies": return topMatch("Huskys"); case "Jedesmal": return topMatch("Jedes Mal"); case "jedesmal": return topMatch("jedes Mal"); case "Lybien": return topMatch("Libyen"); case "Lybiens": return topMatch("Libyens"); case "Youtube": return topMatch("YouTube"); case "Youtuber": return topMatch("YouTuber"); case "Youtuberin": return topMatch("YouTuberin"); case "Youtuberinnen": return topMatch("YouTuberinnen"); case "Youtubers": return topMatch("YouTubers"); case "Reflektion": return topMatch("Reflexion"); case "Reflektionen": return topMatch("Reflexionen"); case "unrelevant": return topMatch("irrelevant"); case "inflagranti": return topMatch("in flagranti"); case "Storie": return topMatch("Story"); case "Stories": return topMatch("Storys"); case "Ladies": return topMatch("Ladys"); case "Parties": return topMatch("Partys"); case "Lobbies": return topMatch("Lobbys"); case "Nestle": return topMatch("Nestlé"); case "Nestles": return topMatch("Nestlés"); case "vollzeit": return topMatch("Vollzeit"); case "teilzeit": return topMatch("Teilzeit"); case "Dnake": return topMatch("Danke"); case "Muehe": return topMatch("Mühe"); case "Muehen": return topMatch("Mühen"); case "Torschusspanik": return topMatch("Torschlusspanik"); case "ggf": return topMatch("ggf."); case "Ggf": return topMatch("Ggf."); case "zzgl": return topMatch("zzgl."); case "Zzgl": return topMatch("Zzgl."); case "aufgehangen": return topMatch("aufgehängt"); case "Pieks": return topMatch("Piks"); case "Piekse": return topMatch("Pikse"); case "Piekses": return topMatch("Pikses"); case "Pieksen": return topMatch("Piksen"); case "Annektion": return topMatch("Annexion"); case "Annektionen": return topMatch("Annexionen"); case "unkonsistent": return topMatch("inkonsistent"); case "Weißheitszahn": return topMatch("Weisheitszahn"); case "Weissheitszahn": return topMatch("Weisheitszahn"); case "Weißheitszahns": return topMatch("Weisheitszahns"); case "Weissheitszahns": return topMatch("Weisheitszahns"); case "Weißheitszähne": return topMatch("Weisheitszähne"); case "Weissheitszähne": return topMatch("Weisheitszähne"); case "Weißheitszähnen": return topMatch("Weisheitszähnen"); case "Weissheitszähnen": return topMatch("Weisheitszähnen"); case "raufschauen": return topMatch("draufschauen"); case "raufzuschauen": return topMatch("draufzuschauen"); case "raufgeschaut": return topMatch("draufgeschaut"); case "raufschaue": return topMatch("draufschaue"); case "raufschaust": return topMatch("draufschaust"); case "raufschaut": return topMatch("draufschaut"); case "raufschaute": return topMatch("draufschaute"); case "raufschauten": return topMatch("draufschauten"); case "raufgucken": return topMatch("draufgucken"); case "raufzugucken": return topMatch("draufzugucken"); case "raufgeguckt": return topMatch("draufgeguckt"); case "raufgucke": return topMatch("draufgucke"); case "raufguckst": return topMatch("draufguckst"); case "raufguckt": return topMatch("draufguckt"); case "raufguckte": return topMatch("draufguckte"); case "raufguckten": return topMatch("draufguckten"); case "raufhauen": return topMatch("draufhauen"); case "raufzuhauen": return topMatch("draufzuhauen"); case "raufgehaut": return topMatch("draufgehaut"); case "raufhaue": return topMatch("draufhaue"); case "raufhaust": return topMatch("draufhaust"); case "raufhaut": return topMatch("draufhaut"); case "raufhaute": return topMatch("draufhaute"); case "raufhauten": return topMatch("draufhauten"); case "wohlmöglich": return topMatch("womöglich"); case "Click": return topMatch("Klick"); case "Clicks": return topMatch("Klicks"); case "jenachdem": return topMatch("je nachdem"); case "bsp": return topMatch("bspw"); case "vorallem": return topMatch("vor allem"); case "draussen": return topMatch("draußen"); case "ürbigens": return topMatch("übrigens"); case "Whatsapp": return topMatch("WhatsApp"); case "kucken": return topMatch("gucken"); case "kuckten": return topMatch("guckten"); case "kucke": return topMatch("gucke"); case "aelter": return topMatch("älter"); case "äussern": return topMatch("äußern"); case "äusserst": return topMatch("äußerst"); case "Dnk": return topMatch("Dank"); case "schleswig-holstein": return topMatch("Schleswig-Holstein"); case "Stahlkraft": return topMatch("Strahlkraft"); case "trümmern": return topMatch("Trümmern"); case "gradeaus": return topMatch("geradeaus"); case "Anschliessend": return topMatch("Anschließend"); case "anschliessend": return topMatch("anschließend"); case "Abschliessend": return topMatch("Abschließend"); case "abschliessend": return topMatch("abschließend"); case "Ruckmeldung": return topMatch("Rückmeldung"); case "Gepaeck": return topMatch("Gepäck"); case "Grüsse": return topMatch("Grüße"); case "Grüssen": return topMatch("Grüßen"); case "entgültig": return topMatch("endgültig"); case "entgültige": return topMatch("endgültige"); case "entgültiges": return topMatch("endgültiges"); case "entgültiger": return topMatch("endgültiger"); case "entgültigen": return topMatch("endgültigen"); case "desöfteren": return topMatch("des Öfteren"); case "desweiteren": return topMatch("des Weiteren"); case "weitesgehend": return topMatch("weitestgehend"); case "Tiktok": return topMatch("TikTok"); case "Tiktoks": return topMatch("TikToks"); case "sodaß": return topMatch("sodass"); case "regelmässig": return topMatch("regelmäßig"); case "Carplay": return topMatch("CarPlay"); case "Tiktoker": return topMatch("TikToker"); case "Tiktokerin": return topMatch("TikTokerin"); case "Tiktokerinnen": return topMatch("TikTokerinnen"); case "Tiktokers": return topMatch("TikTokers"); case "Tiktokern": return topMatch("TikTokern"); case "languagetool": return topMatch("LanguageTool"); case "languagetools": return topMatch("LanguageTools"); case "Languagetool": return topMatch("LanguageTool"); case "Languagetools": return topMatch("LanguageTools"); case "liket": return topMatch("likt"); } return Collections.emptyList(); } }
languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/GermanSpellerRule.java
/* LanguageTool, a natural language style checker * Copyright (C) 2012 Daniel Naber (http://www.danielnaber.de) * * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.rules.de; import de.danielnaber.jwordsplitter.GermanWordSplitter; import de.danielnaber.jwordsplitter.InputTooLongException; import org.apache.commons.lang3.RegExUtils; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.languagetool.*; import org.languagetool.language.German; import org.languagetool.languagemodel.LanguageModel; import org.languagetool.rules.Example; import org.languagetool.rules.RuleMatch; import org.languagetool.rules.SuggestedReplacement; import org.languagetool.rules.ngrams.Probability; import org.languagetool.rules.patterns.StringMatcher; import org.languagetool.rules.spelling.CommonFileTypes; import org.languagetool.rules.spelling.hunspell.CompoundAwareHunspellRule; import org.languagetool.rules.spelling.morfologik.MorfologikMultiSpeller; import org.languagetool.synthesis.Synthesizer; import org.languagetool.tagging.Tagger; import org.languagetool.tokenizers.de.GermanCompoundTokenizer; import org.languagetool.tools.StringTools; import java.io.*; import java.util.*; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Collections.singletonList; import static org.apache.commons.lang3.StringUtils.removeEnd; import static org.languagetool.rules.SuggestedReplacement.topMatch; import static org.languagetool.tools.StringTools.startsWithUppercase; import static org.languagetool.tools.StringTools.uppercaseFirstChar; public class GermanSpellerRule extends CompoundAwareHunspellRule { public static final String RULE_ID = "GERMAN_SPELLER_RULE"; private static final int MAX_EDIT_DISTANCE = 2; private static final String adjSuffix = "(basiert|konform|widrig|fähig|haltig|bedingt|gerecht|würdig|relevant|" + "übergreifend|tauglich|artig|bezogen|orientiert|berechtigt|fremd|liebend|bildend|hemmend|abhängig|" + "förmig|mäßig|pflichtig|ähnlich|spezifisch|technisch|typisch|frei|arm|freundlicher|gemäß)"; private static final Pattern missingAdjPattern = Pattern.compile("[a-zöäüß]{3,25}" + adjSuffix + "(er|es|en|em|e)?"); private final static Set<String> lcDoNotSuggestWords = new HashSet<>(Arrays.asList( // some of these are taken fom hunspell's dictionary where non-suggested words use tag "/n": "verjuden", "verjudet", "verjudeter", "verjudetes", "verjudeter", "verjudeten", "verjudetem", "entjuden", "entjudet", "entjudete", "entjudetes", "entjudeter", "entjudeten", "entjudetem", "auschwitzmythos", "judensippe", "judensippen", "judensippschaft", "judensippschaften", "nigger", "niggern", "niggers", "rassejude", "rassejuden", "rassejüdin", "rassejüdinnen", "möse", "mösen", "fotze", "fotzen", "judenfrei", "judenfreie", "judenfreier", "judenfreies", "judenfreien", "judenfreiem", "judenrein", "judenreine", "judenreiner", "judenreines", "judenreinen", "judenreinem", "judenmord", "judenmorden", "judenmörder" )); // some exceptions for changes to the spelling in 2017 - just a workaround so we don't have to touch the binary dict: private static final Pattern PREVENT_SUGGESTION = Pattern.compile( ".*(Majonäse|Bravur|Anschovis|Belkanto|Campagne|Frotté|Grisli|Jockei|Joga|Kalvinismus|Kanossa|Kargo|Ketschup|" + "Kollier|Kommunikee|Masurka|Negligee|Nessessär|Poulard|Varietee|Wandalismus|kalvinist).*"); private static final int MAX_TOKEN_LENGTH = 200; private final Set<String> wordsToBeIgnoredInCompounds = new HashSet<>(); private final Set<String> wordStartsToBeProhibited = new HashSet<>(); private final Set<String> wordEndingsToBeProhibited = new HashSet<>(); private static final Map<StringMatcher, Function<String,List<String>>> ADDITIONAL_SUGGESTIONS = new HashMap<>(); static { put("lieder", w -> Arrays.asList("leider", "Lieder")); put("frägst", "fragst"); put("Impflicht", "Impfpflicht"); put("Wandererin", "Wanderin"); put("daß", "dass"); put("eien", "eine"); put("wiederrum", "wiederum"); put("ne", w -> Arrays.asList("'ne", "eine", "nein", "oder")); put("ner", "einer"); put("isses", w -> Arrays.asList("ist es", "Risses")); put("isser", "ist er"); put("Vieleicht", "Vielleicht"); put("inbetracht", "in Betracht"); put("überwhatsapp", "über WhatsApp"); put("überzoom", "über Zoom"); put("überweißt", "überweist"); put("übergoogle", "über Google"); put("einlogen", "einloggen"); put("Kruks", "Krux"); put("Filterbubble", "Filterblase"); put("Filterbubbles", "Filterblasen"); putRepl("Analgen.*", "Analgen", "Anlagen"); putRepl("wiedersteh(en|st|t)", "wieder", "wider"); putRepl("wiederstan(d|den|dest)", "wieder", "wider"); putRepl("wiedersprech(e|t|en)?", "wieder", "wider"); putRepl("wiedersprich(st|t)?", "wieder", "wider"); putRepl("wiedersprach(st|t|en)?", "wieder", "wider"); putRepl("wiederruf(e|st|t|en)?", "wieder", "wider"); putRepl("wiederrief(st|t|en)?", "wieder", "wider"); putRepl("wiederleg(e|st|t|en|te|ten)?", "wieder", "wider"); putRepl("wiederhall(e|st|t|en|te|ten)?", "wieder", "wider"); putRepl("wiedersetz(e|t|en|te|ten)?", "wieder", "wider"); putRepl("wiederstreb(e|st|t|en|te|ten)?", "wieder", "wider"); put("bekomms", "bekomm es"); put("liegts", "liegt es"); put("gesynct", "synchronisiert"); put("gesynced", "synchronisiert"); put("gesyncht", "synchronisiert"); put("gesyngt", "synchronisiert"); put("synce", "synchronisiere"); put("synche", "synchronisiere"); put("syncen", "synchronisieren"); put("synchen", "synchronisieren"); put("wiederspiegelten", "widerspiegelten"); put("wiedererwarten", "wider Erwarten"); put("widerholen", "wiederholen"); put("wiederhohlen", "wiederholen"); put("herrunterladen", "herunterladen"); put("dastellen", "darstellen"); put("zuviel", "zu viel"); put("abgekatertes", "abgekartetes"); put("wiederspiegelt", "widerspiegelt"); put("Komplexheit", "Komplexität"); put("unterschiedet", "unterscheidet"); put("einzigst", "einzig"); put("Einzigst", "Einzig"); put("geschumpfen", "geschimpft"); put("Geschumpfen", "Geschimpft"); put("Oke", "Okay"); put("Mü", "My"); put("abschiednehmen", "Abschied nehmen"); put("wars", w -> Arrays.asList("war's", "war es", "warst")); put("[aA]wa", w -> Arrays.asList("AWA", "ach was", "aber")); put("[aA]lsallerersten?s", w -> Arrays.asList(w.replaceFirst("lsallerersten?s", "ls allererstes"), w.replaceFirst("lsallerersten?s", "ls Allererstes"))); putRepl("(an|auf|ein|zu)gehangen(e[mnrs]?)?$", "hangen", "hängt"); putRepl("[oO]key", "ey$", "ay"); put("packet", "Paket"); put("Thanks", "Danke"); put("Ghanesen?", "Ghanaer"); put("Thumberg", "Thunberg"); put("Allalei", "Allerlei"); put("geupdate[dt]$", "upgedatet"); //put("gefaked", "gefakt"); -- don't suggest put("[pP]roblemhaft(e[nmrs]?)?", w -> Arrays.asList(w.replaceFirst("haft", "behaftet"), w.replaceFirst("haft", "atisch"))); put("rosane[mnrs]?$", w -> Arrays.asList("rosa", w.replaceFirst("^rosan", "rosafarben"))); put("Erbung", w -> Arrays.asList("Vererbung", "Erbschaft")); put("Energiesparung", w -> Arrays.asList("Energieeinsparung", "Energieersparnis")); put("Abbrechung", "Abbruch"); put("Abbrechungen", w -> Arrays.asList("Abbrüche", "Abbrüchen")); put("Urteilung", w -> Arrays.asList("Urteil", "Verurteilung")); put("allmöglichen?", w -> Arrays.asList("alle möglichen", "alle mögliche")); put("Krankenhausen", w -> Arrays.asList("Krankenhäusern", "Krankenhäuser")); put("vorr?auss?etzlich", w -> Arrays.asList("voraussichtlich", "vorausgesetzt")); put("nichtmals", w -> Arrays.asList("nicht mal", "nicht einmal")); put("eingepeilt", "angepeilt"); put("gekukt", "geguckt"); put("nem", w -> Arrays.asList("'nem", "einem")); put("nen", w -> Arrays.asList("'nen", "einen")); put("geb", "gebe"); put("überhaut", "überhaupt"); put("nacher", "nachher"); put("jeztz", "jetzt"); put("les", "lese"); put("wr", "wir"); put("bezweifel", "bezweifle"); put("verzweifel", "verzweifle"); put("zweifel", "zweifle"); put("[wW]ah?rscheindlichkeit", "Wahrscheinlichkeit"); put("Hijab", "Hidschāb"); put("[lL]eerequiment", "Leerequipment"); put("unauslässlich", w -> Arrays.asList("unerlässlich", "unablässig", "unauslöschlich")); put("Registration", "Registrierung"); put("Registrationen", "Registrierungen"); put("Spinnenweben", "Spinnweben"); putRepl("[Ww]ar ne", "ne", "eine"); putRepl("[Ää]nliche[rnms]?", "nlich", "hnlich"); putRepl("[Gg]arnix", "nix", "nichts"); putRepl("[Ww]i", "i", "ie"); putRepl("[uU]nauslässlich(e[mnrs]?)?", "aus", "er"); putRepl("[vV]erewiglicht(e[mnrs]?)?", "lich", ""); putRepl("[zZ]eritifiert(e[mnrs]?)?", "eritifiert", "ertifiziert"); putRepl("gerähten?", "geräht", "Gerät"); putRepl("leptops?", "lep", "Lap"); putRepl("[pP]ie?rsings?", "[pP]ie?rsing", "Piercing"); putRepl("for?melar(en?)?", "for?me", "Formu"); putRepl("näste[mnrs]?$", "^näs", "nächs"); putRepl("Erdogans?$", "^Erdogan", "Erdoğan"); put("Germanistiker[ns]", "Germanisten"); putRepl("Germanistikerin(nen)?", "Germanistiker", "Germanist"); putRepl("[iI]ns?z[ie]nie?rung(en)?", "[iI]ns?z[ie]nie?", "Inszenie"); putRepl("[eE]rhöherung(en)?", "[eE]rhöherung", "Erhöhung"); putRepl("[vV]erspäterung(en)?", "später", "spät"); putRepl("[vV]orallendingen", "orallendingen", "or allen Dingen"); putRepl("[aA]ufjede[nm]fall", "jede[nm]fall$", " jeden Fall"); putRepl("[aA]us[vf]ersehen[dt]lich", "[vf]ersehen[dt]lich", " Versehen"); putRepl("^funk?z[ou]nier.+", "funk?z[ou]nier", "funktionier"); putRepl("[wW]öruber", "öru", "orü"); putRepl("[lL]einensamens?", "[lL]einen", "Lein"); putRepl("Feinleiner[ns]?", "Feinlei", "Fineli"); putRepl("[hH]eilei[td]s?", "[hH]eilei[td]", "Highlight"); putRepl("Oldheimer[ns]?", "he", "t"); putRepl("[tT]räner[ns]?", "[tT]rä", "Trai"); putRepl("[tT]eimings?", "[tT]e", "T"); putRepl("unternehmensl[uü]stig(e[mnrs]?)?", "mensl[uü]st", "mungslust"); // "unternehmenslüstig" -> "unternehmungslustig" putRepl("proff?ess?ional(e[mnrs]?)?", "ff?ess?ional", "fessionell"); putRepl("zuverlässlich(e[mnrs]?)?", "lich", "ig"); putRepl("fluoreszenzierend(e[mnrs]?)?", "zen", ""); putRepl("revalierend(e[mnrs]?)?", "^reval", "rivalis"); putRepl("verhäuft(e[mnrs]?)?", "^ver", "ge"); putRepl("stürmig(e[mnrs]?)?", "mig", "misch"); putRepl("größeste[mnrs]?", "ßes", "ß"); putRepl("n[aä]heste[mnrs]?", "n[aä]he", "näch"); putRepl("gesundlich(e[mnrs]?)?", "lich", "heitlich"); putRepl("eckel(e|t(en?)?|st)?", "^eck", "ek"); putRepl("unhervorgesehen(e[mnrs]?)?", "hervor", "vorher"); putRepl("entt?euscht(e[mnrs]?)?", "entt?eusch", "enttäusch"); putRepl("Phählen?", "^Ph", "Pf"); putRepl("Kattermesser[ns]?", "Ka", "Cu"); putRepl("gehe?rr?t(e[mnrs]?)?", "he?rr?", "ehr"); // "geherte" -> "geehrte" putRepl("gehrter?", "^ge", "gee"); putRepl("[nN]amenhaft(e[mnrs]?)?", "amen", "am"); putRepl("hom(o?e|ö)ophatisch(e[mnrs]?)?", "hom(o?e|ö)ophat", "homöopath"); putRepl("Geschwindlichkeit(en)?", "lich", "ig"); putRepl("Jänners?", "Jänner", "Januar"); putRepl("[äÄ]hlich(e[mnrs]?)?", "lich", "nlich"); putRepl("entf[ai]ngen?", "ent", "emp"); putRepl("entf[äi]ngs?t", "ent", "emp"); putRepl("[Bb]ehilfreich(e[rnms]?)", "reich", "lich"); putRepl("[Bb]zgl", "zgl", "zgl."); putRepl("kaltnass(e[rnms]?)", "kaltnass", "nasskalt"); putRepl("Kaltnass(e[rnms]?)", "Kaltnass", "Nasskalt"); put("check", "checke"); put("Rückrad", "Rückgrat"); put("ala", "à la"); put("Ala", "À la"); put("Reinfolge", "Reihenfolge"); put("Schloß", "Schloss"); put("Investion", "Investition"); put("Beleidung", "Beleidigung"); put("Bole", "Bowle"); put("letzens", "letztens"); put("Pakur", w -> Arrays.asList("Parcours", "Parkuhr")); put("Erstsemesterin", w -> Arrays.asList("Erstsemester", "Erstsemesters", "Erstsemesterstudentin")); put("Erstsemesterinnen", w -> Arrays.asList("Erstsemesterstudentinnen", "Erstsemester", "Erstsemestern")); put("kreativlos(e[nmrs]?)?", w -> Arrays.asList(w.replaceFirst("kreativ", "fantasie"), w.replaceFirst("kreativ", "einfalls"), w.replaceFirst("kreativlos", "unkreativ"), w.replaceFirst("kreativlos", "uninspiriert"))); put("Kreativlosigkeit", "Unkreativität"); put("hinund?her", "hin und her"); put("[lL]ymph?trie?nasche", "Lymphdrainage"); put("Interdeterminismus", "Indeterminismus"); put("elektrität", "Elektrizität"); put("ausgeboten", "ausgebootet"); put("nocheinmall", "noch einmal"); put("aüßerst", "äußerst"); put("Grrösse", "Größe"); put("misverständniss", "Missverständnis"); put("warheit", "Wahrheit"); put("[pP]okemon", "Pokémon"); put("kreigt", "kriegt"); put("Fritöse", "Fritteuse"); put("unerkennlich", "unkenntlich"); put("rückg[äe]nglich", "rückgängig"); put("em?men[sz]", "immens"); put("verhing", "verhängte"); put("verhingen", "verhängten"); put("fangte", "fing"); put("fangten", "fingen"); put("schlie[sß]te", "schloss"); put("schlie[sß]ten", "schlossen"); put("past", "passt"); put("eingetragt", "eingetragen"); put("getrunkt", "getrunken"); put("veräht", "verrät"); put("helfte", "half"); put("helften", "halfen"); put("lad", "lade"); put("befehlte", "befahl"); put("befehlten", "befahlen"); put("angelügt", "angelogen"); put("lügte", "log"); put("lügten", "logen"); put("bratete", "briet"); put("brateten", "brieten"); put("gefahl", "gefiel"); put("Komplexibilität", "Komplexität"); put("abbonement", "Abonnement"); put("zugegebenerweise", "zugegebenermaßen"); put("perse", "per se"); put("Schwitch", "Switch"); put("[aA]nwesenzeiten", "Anwesenheitszeiten"); put("[gG]eizigkeit", "Geiz"); put("[fF]leißigkeit", "Fleiß"); put("[bB]equemheit", "Bequemlichkeit"); put("[mM]issionarie?sie?rung", "Missionierung"); put("[sS]chee?selonge?", "Chaiselongue"); put("Re[kc]amiere", "Récamière"); put("Singel", "Single"); put("legen[td]lich", "lediglich"); put("ein[ua]ndhalb", "eineinhalb"); put("[mM]illion(en)?mal", w -> singletonList(uppercaseFirstChar(w.replaceFirst("mal", " Mal")))); put("Mysql", "MySQL"); put("MWST", "MwSt"); put("Opelarena", "Opel Arena"); put("Toll-Collect", "Toll Collect"); put("[pP][qQ]-Formel", "p-q-Formel"); put("desweitere?m", "des Weiteren"); put("handzuhaben", "zu handhaben"); put("nachvollzuziehe?n", "nachzuvollziehen"); put("Porto?folien", "Portfolios"); put("[sS]chwie?ri?chkeiten", "Schwierigkeiten"); put("[üÜ]bergrifflichkeiten", "Übergriffigkeiten"); put("[aA]r?th?rie?th?is", "Arthritis"); put("zugesand", "zugesandt"); put("weibt", "weißt"); put("fress", "friss"); put("Mamma", "Mama"); put("Präse", "Präsentation"); put("Präsen", "Präsentationen"); put("Orga", "Organisation"); put("Orgas", "Organisationen"); put("Reorga", "Reorganisation"); put("Reorgas", "Reorganisationen"); put("instande?zusetzen", "instand zu setzen"); put("Lia(si|is)onen", "Liaisons"); put("[cC]asemana?ge?ment", "Case Management"); put("[aA]nn?[ou]ll?ie?rung", "Annullierung"); put("[sS]charm", "Charme"); put("[zZ]auberlich(e[mnrs]?)?", w -> Arrays.asList(w.replaceFirst("lich", "isch"), w.replaceFirst("lich", "haft"))); put("[eE]rledung", "Erledigung"); put("erledigigung", "Erledigung"); put("woltest", "wolltest"); put("[iI]ntranzparentheit", "Intransparenz"); put("dunkellilane[mnrs]?", "dunkellila"); put("helllilane[mnrs]?", "helllila"); put("Behauptungsthese", "Behauptung"); put("genzut", "genutzt"); put("[eEäÄ]klerung", "Erklärung"); put("[wW]eh?wechen", "Wehwehchen"); put("nocheinmals", "noch einmal"); put("unverantwortungs?los(e[mnrs]?)?", w -> Arrays.asList(w.replaceFirst("unverantwortungs?", "verantwortungs"), w.replaceFirst("ungs?los", "lich"))); putRepl("[eE]rhaltbar(e[mnrs]?)?", "haltbar", "hältlich"); putRepl("[aA]ufkeinenfall?", "keinenfall?", " keinen Fall"); putRepl("[Dd]rumrum", "rum$", "herum"); putRepl("([uU]n)?proff?esionn?ell?(e[mnrs]?)?", "proff?esionn?ell?", "professionell"); putRepl("[kK]inderlich(e[mnrs]?)?", "inder", "ind"); putRepl("[wW]iedersprichs?t", "ieder", "ider"); putRepl("[wW]hite-?[Ll]abels", "[wW]hite-?[Ll]abel", "White Label"); putRepl("[wW]iederstand", "ieder", "ider"); putRepl("[kK]önntes", "es$", "est"); putRepl("[aA]ssess?oare?s?", "[aA]ssess?oare?", "Accessoire"); putRepl("indifiziert(e[mnrs]?)?", "ind", "ident"); putRepl("dreite[mnrs]?", "dreit", "dritt"); putRepl("verblüte[mnrs]?", "blü", "blüh"); putRepl("Einzigste[mnrs]?", "zigst", "zig"); putRepl("Invests?", "Invest", "Investment"); putRepl("(aller)?einzie?gste[mnrs]?", "(aller)?einzie?gst", "einzig"); putRepl("[iI]nterkurell(e[nmrs]?)?", "ku", "kultu"); putRepl("[iI]ntersannt(e[mnrs]?)?", "sannt", "essant"); putRepl("ubera(g|sch)end(e[nmrs]?)?", "uber", "überr"); putRepl("[Hh]ello", "ello", "allo"); putRepl("[Gg]etagged", "gged", "ggt"); putRepl("[wW]olt$", "lt", "llt"); putRepl("[zZ]uende", "ue", "u E"); putRepl("[iI]nbälde", "nb", "n B"); putRepl("[lL]etztenendes", "ene", "en E"); putRepl("[nN]achwievor", "wievor", " wie vor"); putRepl("[zZ]umbeispiel", "beispiel", " Beispiel"); putRepl("[gG]ottseidank", "[gG]ottseidank", "Gott sei Dank"); putRepl("[gG]rundauf", "[gG]rundauf", "Grund auf"); putRepl("[aA]nsichtnach", "[aA]nsicht", "Ansicht "); putRepl("[uU]n[sz]war", "[sz]war", "d zwar"); putRepl("[wW]aschte(s?t)?", "aschte", "usch"); putRepl("[wW]aschten", "ascht", "usch"); putRepl("Probiren?", "ir", "ier"); putRepl("[gG]esetztreu(e[nmrs]?)?", "tz", "tzes"); putRepl("[wW]ikich(e[nmrs]?)?", "k", "rkl"); putRepl("[uU]naufbesichtigt(e[nmrs]?)?", "aufbe", "beauf"); putRepl("[nN]utzvoll(e[nmrs]?)?", "utzvoll", "ützlich"); putRepl("Lezte[mnrs]?", "Lez", "Letz"); putRepl("Letze[mnrs]?", "Letz", "Letzt"); putRepl("[nN]i[vw]os?", "[nN]i[vw]o", "Niveau"); putRepl("[dD]illetant(en)?", "[dD]ille", "Dilet"); putRepl("Frauenhofer-(Institut|Gesellschaft)", "Frauen", "Fraun"); putRepl("Add-?Ons?", "Add-?On", "Add-on"); putRepl("Addons?", "on", "-on"); putRepl("Internetkaffees?", "kaffee", "café"); putRepl("[gG]ehorsamkeitsverweigerung(en)?", "[gG]ehorsamkeit", "Gehorsam"); putRepl("[wW]ochende[ns]?", "[wW]ochend", "Wochenend"); putRepl("[kK]ongratulier(en?|t(en?)?|st)", "[kK]on", ""); putRepl("[wWkKdD]an$", "n$", "nn"); putRepl("geh?neh?m[ie]gung(en)?", "geh?neh?m[ie]gung", "Genehmigung"); putRepl("Korrigierung(en)?", "igierung", "ektur"); putRepl("[kK]orregierung(en)?", "[kK]orregierung", "Korrektur"); putRepl("[kK]orrie?girung(en)?", "[kK]orrie?girung", "Korrektur"); putRepl("[nN]ocheimal", "eimal", " einmal"); putRepl("[aA]benzu", "enzu", " und zu"); putRepl("[kK]onflikation(en)?", "[kK]onfli", "Kompli"); putRepl("[mM]itanader", "ana", "einan"); putRepl("[mM]itenand", "enand", "einander"); putRepl("Gelangenheitsbestätigung(en)?", "heit", ""); putRepl("[jJ]edwillige[mnrs]?", "willig", "wed"); putRepl("[qQ]ualitäts?bewußt(e[mnrs]?)?", "ts?bewußt", "tsbewusst"); putRepl("[vV]oraussichtig(e[nmrs]?)?", "sichtig", "sichtlich"); putRepl("[gG]leichrechtig(e[nmrs]?)?", "rechtig", "berechtigt"); putRepl("[uU]nnützlich(e[nmrs]?)?", "nützlich", "nütz"); putRepl("[uU]nzerbrechbar(e[nmrs]?)?", "bar", "lich"); putRepl("kolegen?", "ko", "Kol"); putRepl("tableten?", "tablet", "Tablett"); putRepl("verswinde(n|s?t)", "^vers", "versch"); putRepl("unverantwortungsvoll(e[nmrs]?)?", "unverantwortungsvoll", "verantwortungslos"); putRepl("[gG]erechtlichkeit", "[gG]erechtlich", "Gerechtig"); putRepl("[zZ]uverlässlichkeit", "lich", "ig"); putRepl("[uU]nverzeilig(e[mnrs]?)?", "zeilig", "zeihlich"); putRepl("[zZ]uk(ue?|ü)nftlich(e[mnrs]?)?", "uk(ue?|ü)nftlich", "ukünftig"); putRepl("[rR]eligiösisch(e[nmrs]?)?", "isch", ""); putRepl("[fF]olklorisch(e[nmrs]?)?", "isch", "istisch"); putRepl("[eE]infühlsvoll(e[nmrs]?)?", "voll", "am"); putRepl("Unstimmlichkeit(en)?", "lich", "ig"); putRepl("Strebergartens?", "Stre", "Schre"); putRepl("[hH]ähern(e[mnrs]?)?", "ähern", "ären"); putRepl("todesbedroh(end|lich)(e[nmrs]?)?", "todes", "lebens"); putRepl("^[uU]nabsichtig(e[nmrs]?)?", "ig", "lich"); putRepl("[aA]ntisemitistisch(e[mnrs]?)?", "tist", "t"); putRepl("[uU]nvorsehbar(e[mnrs]?)?", "vor", "vorher"); putRepl("([eE]r|[bB]e|unter|[aA]uf)?hälst", "hälst", "hältst"); put("[wW]ohlfühlseins?", w -> Arrays.asList("Wellness", w.replaceFirst("[wW]ohlfühlsein", "Wohlbefinden"), w.replaceFirst("[wW]ohlfühlsein", "Wohlfühlen"))); putRepl("[sS]chmett?e?rling(s|en?)?", "[sS]chmett?e?rling", "Schmetterling"); putRepl("^[eE]inlamie?nie?r(st|en?|(t(e[nmrs]?)?))?", "^einlamie?nie?r", "laminier"); putRepl("[bB]ravurös(e[nrms]?)?", "vur", "vour"); putRepl("[aA]ss?ecoires?", "[aA]ss?ec", "Access"); putRepl("[aA]ufwechse?lungsreich(er|st)?(e[nmrs]?)?", "ufwechse?lung", "bwechslung"); putRepl("[iI]nordnung", "ordnung", " Ordnung"); putRepl("[iI]mmoment", "moment", " Moment"); putRepl("[hH]euteabend", "abend", " Abend"); putRepl("[wW]ienerschnitzel[ns]?", "[wW]ieners", "Wiener S"); putRepl("[sS]chwarzwälderkirschtorten?", "[sS]chwarzwälderk", "Schwarzwälder K"); putRepl("[kK]oxial(e[nmrs]?)?", "x", "ax"); putRepl("([üÜ]ber|[uU]unter)?[dD]urs?chnitt?lich(e[nmrs]?)?", "s?chnitt?", "chschnitt"); putRepl("[dD]urs?chnitts?", "s?chnitt", "chschnitt"); putRepl("[sS]triktlich(e[mnrs]?)?", "lich", ""); putRepl("[hH]öchstwahrlich(e[mnrs]?)?", "wahr", "wahrschein"); putRepl("[oO]rganisativ(e[nmrs]?)?", "tiv", "torisch"); putRepl("[kK]ontaktfreundlich(e[nmrs]?)?", "ndlich", "dig"); putRepl("Helfer?s-Helfer[ns]?", "Helfer?s-H", "Helfersh"); putRepl("[iI]ntell?igentsbestien?", "[iI]ntell?igents", "Intelligenz"); putRepl("[aA]vantgardisch(e[mnrs]?)?", "gard", "gardist"); putRepl("[gG]ewohnheitsbedürftig(e[mnrs]?)?", "wohnheit", "wöhnung"); putRepl("[eE]infühlungsvoll(e[mnrs]?)?", "fühlungsvoll", "fühlsam"); putRepl("[vV]erwant(e[mnrs]?)?", "want", "wandt"); putRepl("[bB]eanstandigung(en)?", "ig", ""); putRepl("[eE]inba(hn|nd)frei(e[mnrs]?)?", "ba(hn|nd)", "wand"); putRepl("[äÄaAeE]rtzten?", "[äÄaAeE]rt", "Är"); putRepl("pdf-Datei(en)?", "pdf", "PDF"); putRepl("rumänern?", "rumäner", "Rumäne"); putRepl("[cCKk]o?usengs?", "[cCKk]o?useng", "Cousin"); putRepl("Influenzer(in(nen)?|[ns])?", "zer", "cer"); putRepl("[vV]ersantdienstleister[ns]?", "[vV]ersant", "Versand"); putRepl("[pP]atrolier(s?t|t?en?)", "atrolier", "atrouillier"); putRepl("[pP]ropagandiert(e[mnrs]?)?", "and", ""); putRepl("[pP]ropagandier(en|st)", "and", ""); putRepl("[kK]app?erzität(en)?", "^[kK]app?er", "Kapa"); putRepl("känzel(n|s?t)", "känzel", "cancel"); put("gekänzelt", "gecancelt"); putRepl("[üÜ]berstreitung(en)?", "[üÜ]berst", "Übersch"); putRepl("anschliess?lich(e(mnrs)?)?", "anschliess?lich", "anschließend"); putRepl("[rR]ethorisch(e(mnrs)?)?", "eth", "het"); putRepl("änlich(e(mnrs)?)?", "än", "ähn"); putRepl("spätmöglichste(mnrs)?", "spätmöglichst", "spätestmöglich"); put("mogen", "morgen"); put("[fF]uss?ill?ien", "Fossilien"); put("übrings", "übrigens"); put("[rR]evü", "Revue"); put("eingänglich", "eingangs"); put("geerthe", "geehrte"); put("interrese", "Interesse"); put("[rR]eschärschen", "Recherchen"); put("[rR]eschärsche", "Recherche"); put("ic", "ich"); put("w[eä]hret", "wäret"); put("mahte", "Mathe"); put("letzdenendes", "letzten Endes"); put("aufgesteht", "aufgestanden"); put("ganichts", "gar nichts"); put("gesich", "Gesicht"); put("glass", "Glas"); put("muter", "Mutter"); put("[pP]appa", "Papa"); put("dier", "dir"); put("Referenz-Nr", "Referenz-Nr."); put("Matrikelnr.", "Matrikel-Nr."); put("Rekrutings?prozess", "Recruitingprozess"); put("sumarum", "summarum"); put("schein", "scheine"); put("Innzahlung", w -> Arrays.asList("In Zahlung", "in Zahlung")); put("änderen", w -> Arrays.asList("ändern", "anderen")); put("wanderen", w -> Arrays.asList("wandern", "Wanderern")); put("Dutzen", w -> Arrays.asList("Duzen", "Dutzend")); put("patien", w -> Arrays.asList("Partien", "Patient")); put("Teammitgliederinnen", w -> Arrays.asList("Teammitgliedern", "Teammitglieder")); put("beidige[mnrs]?", w -> Arrays.asList(w.replaceFirst("ig", ""), w.replaceFirst("beid", "beiderseit"), "beeidigen")); //beide, beiderseitige, beeidigen put("Wissbegierigkeit", w -> Arrays.asList("Wissbegier", "Wissbegierde")); put("Nabend", "'n Abend"); put("gie?bts", "gibt's"); put("vs", "vs."); put("[kK]affeeteria", "Cafeteria"); put("[kK]affeeterien", "Cafeterien"); put("berücksicht", "berücksichtigt"); put("must", "musst"); put("kaffe", "Kaffee"); put("zetel", "Zettel"); put("wie?daholung", "Wiederholung"); put("vie?d(er|a)sehen", "wiedersehen"); put("pr[eä]ventiert", "verhindert"); put("pr[eä]ventieren", "verhindern"); put("zur?verfügung", "zur Verfügung"); put("Verwahrlosigkeit", "Verwahrlosung"); put("[oO]r?ganisazion", "Organisation"); put("[oO]rganisative", "Organisation"); put("Emall?iearbeit", "Emaillearbeit"); put("[aA]petitt", "Appetit"); put("bezuggenommen", "Bezug genommen"); put("mägt", "mögt"); put("frug", "fragte"); put("gesäht", "gesät"); put("verennt", "verrennt"); put("überrant", "überrannt"); put("Gallop", "Galopp"); put("Stop", "Stopp"); put("Schertz", "Scherz"); put("geschied", "geschieht"); put("Aku", "Akku"); put("Migrationspackt", "Migrationspakt"); put("[zZ]ulaufror", "Zulaufrohr"); put("[gG]ebrauchss?puhren", "Gebrauchsspuren"); put("[pP]reisnachlassung", "Preisnachlass"); put("[mM]edikamentation", "Medikation"); put("[nN][ei]gliche", "Negligé"); put("palletten?", w -> Arrays.asList(w.replaceFirst("pall", "Pal"), w.replaceFirst("pa", "Pai"))); put("[pP]allete", "Palette"); put("Geräuch", w -> Arrays.asList("Geräusch", "Gesträuch")); put("[sS]chull?igung", "Entschuldigung"); put("Geerte", "geehrte"); put("versichen", "versichern"); put("hobb?ies", "Hobbys"); put("Begierigkeiten", "Begehrlichkeiten"); put("selblosigkeit", "Selbstlosigkeit"); put("gestyled", "gestylt"); put("umstimigkeiten", "Unstimmigkeiten"); put("unann?äh?ml?ichkeiten", "Unannehmlichkeiten"); put("unn?ann?ehmichkeiten", "Unannehmlichkeiten"); put("übertr[äa]gte", "übertrug"); put("übertr[äa]gten", "übertrugen"); put("NodeJS", "Node.js"); put("Express", "Express.js"); put("erlas", "Erlass"); put("schlagte", "schlug"); put("schlagten", "schlugen"); put("überwissen", "überwiesen"); put("einpar", "ein paar"); put("sreiben", "schreiben"); put("routiene", "Routine"); put("ect", "etc"); put("giept", "gibt"); put("Pann?acott?a", "Panna cotta"); put("Fußgängerunterwegs?", "Fußgängerunterführung"); put("angeschriehen", "angeschrien"); put("vieviel", "wie viel"); put("entäscht", "enttäuscht"); put("Rämchen", "Rähmchen"); put("Seminarbeit", "Seminararbeit"); put("Seminarbeiten", "Seminararbeiten"); put("[eE]ngangment", "Engagement"); put("[lL]eichtah?tleh?t", "Leichtathlet"); put("[pP]fane", "Pfanne"); put("[iI]ngini?eue?r", "Ingenieur"); put("[aA]nligen", "Anliegen"); put("Tankungen", w -> Arrays.asList("Betankungen", "Tankvorgänge")); put("Ärcker", w -> Arrays.asList("Erker", "Ärger")); put("überlasstet", w -> Arrays.asList("überlastet", "überließt")); put("zeren", w -> Arrays.asList("zerren", "zehren")); put("Hänchen", w -> Arrays.asList("Hähnchen", "Hänschen")); put("[sS]itwazion", "Situation"); put("geschriehen", "geschrien"); put("beratete", "beriet"); put("Hälst", "Hältst"); put("[kK]aos", "Chaos"); put("[pP]upatät", "Pubertät"); put("überwendet", "überwindet"); put("[bB]esichtung", "Besichtigung"); put("[hH]ell?owi[eh]?n", "Halloween"); put("geschmelt?zt", "geschmolzen"); put("gewunschen", "gewünscht"); put("bittete", "bat"); put("nehm", "nimm"); put("möchst", "möchtest"); put("Win", "Windows"); put("anschein[dt]", "anscheinend"); put("Subvestitionen", "Subventionen"); put("angeschaffen", "angeschafft"); put("Rechtspruch", "Rechtsspruch"); put("Second-Hand", "Secondhand"); put("[jJ]ahundert", "Jahrhundert"); put("Gesochse", "Gesocks"); put("Vorraus", "Voraus"); put("[vV]orgensweise", "Vorgehensweise"); put("[kK]autsch", "Couch"); put("guterletzt", "guter Letzt"); put("Seminares", "Seminars"); put("Mousepad", "Mauspad"); put("Mousepads", "Mauspads"); put("Wi[Ff]i-Router", "Wi-Fi-Router"); putRepl("[Ll]ilane[srm]?", "ilane[srm]?", "ila"); putRepl("[zZ]uguterletzt", "guterletzt", " guter Letzt"); putRepl("Nootbooks?", "Noot", "Note"); putRepl("[vV]ersendlich(e[mnrs]?)?", "send", "sehent"); putRepl("[uU]nfäh?r(e[mnrs]?)?", "fäh?r", "fair"); putRepl("[mM]edikatös(e[mnrs]?)?", "ka", "kamen"); putRepl("(ein|zwei|drei|vier|fünf|sechs|sieben|acht|neun|zehn|elf|zwölf)undhalb", "und", "ein"); putRepl("[gG]roßzüge[mnrs]?", "züg", "zügig"); putRepl("[äÄ]rtlich(e[mnrs]?)?", "rt", "rzt"); putRepl("[sS]chnelligkeitsfehler[ns]?", "[sS]chnell", "Flücht"); putRepl("[sS]chweinerosane[mnrs]?", "weinerosane[mnrs]?", "weinchenrosa"); putRepl("[aA]nstecklich(e[mnrs]?)?", "lich", "end"); putRepl("[gG]eflechtet(e[mnrs]?)?", "flechtet", "flochten"); putRepl("[gG]enrealistisch(e[mnrs]?)?", "re", "er"); putRepl("überträgt(e[mnrs]?)?", "^überträgt", "übertragen"); putRepl("[iI]nterresent(e[mnrs]?)?", "rresent", "ressant"); putRepl("Simkartenleser[ns]?", "^Simkartenl", "SIM-Karten-L"); putRepl("Hilfstmittel[ns]?", "^Hilfst", "Hilfs"); putRepl("trationell(e[mnrs]?)?", "^tra", "tradi"); putRepl("[bB]erreichs?", "^[bB]er", "Be"); putRepl("[fF]uscher[ns]?", "^[fF]u", "Pfu"); putRepl("[uU]nausweichbar(e[mnrs]?)?", "bar", "lich"); putRepl("[uU]nabdinglich(e[mnrs]?)?", "lich", "bar"); putRepl("[eE]ingänglich(e[mnrs]?)?", "lich", "ig"); putRepl("ausgewöh?nlich(e[mnrs]?)?", "^ausgewöh?n", "außergewöhn"); putRepl("achsial(e[mnrs]?)?", "^achs", "ax"); putRepl("famielen?", "^famiel", "Famili"); putRepl("miter[ns]?", "^mi", "Mie"); putRepl("besig(t(e[mnrs]?)?|en?)", "sig", "sieg"); putRepl("[vV]erziehr(t(e[mnrs]?)?|en?)", "ieh", "ie"); putRepl("^[pP]iek(s?t|en?)", "iek", "ik"); putRepl("[mM]atschscheiben?", "[mM]atschsch", "Mattsch"); put("schafen?", w -> Arrays.asList(w.replaceFirst("sch", "schl"), w.replaceFirst("af", "arf"), w.replaceFirst("af", "aff"))); put("zuschafen", "zu schaffen"); putRepl("[hH]ofen?", "of", "off"); putRepl("[sS]ommerverien?", "[sS]ommerverien?", "Sommerferien"); putRepl("[rR]ecourcen?", "[rR]ec", "Ress"); putRepl("[fF]amm?ill?i?[aä]risch(e[mnrs]?)?", "amm?ill?i?[aä]risch", "amiliär"); putRepl("Sim-Karten?", "^Sim", "SIM"); putRepl("Spax-Schrauben?", "^Spax", "SPAX"); putRepl("[aA]leine", "l", "ll"); putRepl("Kaput", "t", "tt"); putRepl("[fF]estell(s?t|en?)", "est", "estst"); putRepl("[Ee]igtl", "igtl", "igtl."); putRepl("(Baden-)?Würtenbergs?", "Würten", "Württem"); putRepl("Betriebsratzimmer[ns]?", "rat", "rats"); putRepl("Rechts?schreibungsfehler[ns]?", "Rechts?schreibungs", "Rechtschreib"); putRepl("Open[aA]ir-Konzert(en?)?", "Open[aA]ir", "Open-Air"); putRepl("Jugenschuhen?", "Jug", "Jung"); putRepl("TODO-Listen?", "TODO", "To-do"); putRepl("ausiehs?t", "aus", "auss"); putRepl("unterbemittel(nd|t)(e[nmrs]?)?", "unterbemittel(nd|t)", "minderbemittelt"); putRepl("[xX]te[mnrs]?", "te", "-te"); putRepl("verheielt(e[mnrs]?)?", "heiel", "heil"); putRepl("[rR]evolutionie?sier(s?t|en?)", "ie?s", ""); putRepl("Kohleaustiegs?", "aus", "auss"); putRepl("[jJ]urististisch(e[mnrs]?)?", "istist", "ist"); putRepl("gehäckelt(e[nmrs]?)?", "ck", "k"); putRepl("deutsprachig(e[nmrs]?)?", "deut", "deutsch"); putRepl("angesehend(st)?e[nmrs]?", "end", "en"); putRepl("[iI]slamophobisch(e[mnrs]?)?", "isch", ""); putRepl("[vV]erharkt(e[mnrs]?)?", "ar", "a"); putRepl("[dD]esöfterer?[nm]", "öfterer?[nm]", " Öfteren"); putRepl("[dD]eswei[dt]ere?[mn]", "wei[dt]ere?[mn]", " Weiteren"); putRepl("Einkaufstachen?", "ch", "sch"); putRepl("Bortmesser[ns]?", "Bor", "Bro"); putRepl("Makeupstylist(in(nen)?|en)?", "Makeups", "Make-up-S"); putRepl("Fee?dbäcks?", "Fee?dbäck", "Feedback"); putRepl("weirete[nmrs]?", "ret", "ter"); putRepl("Ni[vw]oschalter[ns]?", "Ni[vw]o", "Niveau"); putRepl("[eE]xhibitionisch(e[nmrs]?)?", "isch", "istisch"); putRepl("(ein|aus)?[gG]eschalten(e[nmrs]?)?", "ten", "tet"); putRepl("[uU]nterschiebene[nmrs]?", "sch", "schr"); putRepl("[uU]nbequemlich(st)?e[nmrs]?", "lich", ""); putRepl("[uU][nm]bekweh?m(e[nmrs]?)?", "[nm]bekweh?m", "nbequem"); putRepl("[dD]esatör(s|en?)?", "satör", "serteur"); put("Panelen?", w -> Arrays.asList(w.replaceFirst("Panel", "Paneel"), "Panels")); put("D[eèé]ja-?[vV]o?ue?", "Déjà-vu"); put("Cr[eèé]me-?fra[iî]che", "Crème fraîche"); put("[aA]rr?an?gemont", "Arrangement"); put("[aA]ngagemon", "Engagement"); put("Phyrr?ussieg", "Pyrrhussieg"); put("Mio", "Mio."); put("Datein", "Dateien"); put("[pP]u(zz|ss)el", "Puzzle"); put("Smilies", "Smileys"); put("[dD]iseing?", "Design"); put("[lL]ieradd?ress?e", "Lieferadresse"); put("[bB]o[yi]kutierung", "Boykottierung"); put("Mouseclick", "Mausklick"); put("[aA]ktuelli?esie?rung", "Aktualisierung"); put("Händy", "Handy"); put("gewertschätzt", "wertgeschätzt"); put("tieger", "Tiger"); put("Rollade", w -> Arrays.asList("Rollladen", "Roulade")); put("garnichtmehr", "gar nicht mehr"); put("vileich", "vielleicht"); put("vll?t", "vielleicht"); put("aufgewägt", "aufgewogen"); put("[rR]eflektion", "Reflexion"); put("momentmal", "Moment mal"); put("satzt", "Satz"); put("Büff?(ee|é)", w -> Arrays.asList("Buffet", "Büfett")); put("[fF]rühstücksb[uü]ff?(é|ee)", "Frühstücksbuffet"); put("[aA]lterego", "Alter Ego"); put("Copyride", "Copyright"); put("Analysierung", "Analyse"); put("Exel", "Excel"); put("Glücklichkeit", "Glück"); put("Begierigkeit", "Begierde"); put("voralem", "vor allem"); put("Unorganisation", w -> Arrays.asList("Desorganisation", "Unorganisiertheit")); put("Cand(el|le)lightdinner", "Candle-Light-Dinner"); put("wertgelegt", "Wert gelegt"); put("Deluxe", "de luxe"); put("antuhen", "antun"); put("komen", "kommen"); put("genißen", "genießen"); put("Stationskrankenpflegerin", "Stationsschwester"); put("[iIüÜuU]b[ea]w[ae]isung", "Überweisung"); put("[bB]oxhorn", "Bockshorn"); put("[zZ]oolophie", "Zoophilie"); put("Makieren", "Markieren"); put("Altersheimer", "Alzheimer"); put("gesen", "gesehen"); put("Neugierigkeit", w -> Arrays.asList("Neugier", "Neugierde")); put("[kK]onn?ekt?schen", "Connection"); put("E-Maul", "E-Mail"); put("E-Mauls", "E-Mails"); put("E-Mal", "E-Mail"); put("E-Mals", "E-Mails"); put("[nN]ah?richt", "Nachricht"); put("[nN]ah?richten", "Nachrichten"); put("Getrixe", "Getrickse"); put("Ausage", "Aussage"); put("gelessen", "gelesen"); put("Kanst", "Kannst"); put("Unwohlbefinden", "Unwohlsein"); put("leiwagen", "Leihwagen"); put("krahn", "Kran"); put("[hH]ifi", "Hi-Fi"); put("chouch", "Couch"); put("eh?rgeit?z", "Ehrgeiz"); put("solltes", "solltest"); put("geklabt", "geklappt"); put("angefangt", "angefangen"); put("beinhält", "beinhaltet"); put("beinhielt", "beinhaltete"); put("beinhielten", "beinhalteten"); put("einhaltest", "einhältst"); put("angeruft", "angerufen"); put("erhaltete", "erhielt"); put("übersäht", "übersät"); put("staats?angehoe?rigkeit", "Staatsangehörigkeit"); put("[uU]nangeneh?mheiten", "Unannehmlichkeiten"); put("Humuspaste", "Hummuspaste"); put("afarung", "Erfahrung"); put("bescheid?t", "Bescheid"); put("[mM]iteillung", "Mitteilung"); put("Revisionierung", "Revision"); put("[eE]infühlvermögen", "Einfühlungsvermögen"); put("[sS]peziellisierung", "Spezialisierung"); put("[cC]hangse", "Chance"); put("untergangen", "untergegangen"); put("geliegt", "gelegen"); put("BluRay", "Blu-ray"); put("Freiwilligerin", "Freiwillige"); put("Mitgliederinnen", w -> Arrays.asList("Mitglieder", "Mitgliedern")); put("Hautreinheiten", "Hautunreinheiten"); put("Durfüh?rung", "Durchführung"); put("tuhen", "tun"); put("tuhe", "tue"); put("tip", "Tipp"); put("ccm", "cm³"); put("Kilimand?jaro", "Kilimandscharo"); put("[hH]erausfor?dung", "Herausforderung"); put("[bB]erücksichtung", "Berücksichtigung"); put("artzt?", "Arzt"); put("[tT]h?elepath?ie", "Telepathie"); put("Wi-?Fi-Dire[ck]t", "Wi-Fi Direct"); put("gans", "ganz"); put("Pearl-Harbou?r", "Pearl Harbor"); put("[aA]utonomität", "Autonomie"); put("[fF]r[uü]h?st[uü]c?k", "Frühstück"); putRepl("(ge)?fr[uü]h?st[uü](c?k|g)t", "fr[uü]h?st[uü](c?k|g)t", "frühstückt"); put("zucc?h?inis?", "Zucchini"); put("[mM]itag", "Mittag"); put("Lexion", "Lexikon"); put("[mM]otorisation", "Motorisierung"); put("[fF]ormalisation", "Formalisierung"); put("ausprache", "Aussprache"); put("[mM]enegment", "Management"); put("[gG]ebrauspuren", "Gebrauchsspuren"); put("viedeo", "Video"); put("[hH]erstammung", "Abstammung"); put("[iI]nstall?atör", "Installateur"); put("maletriert", "malträtiert"); put("abgeschaffen", "abgeschafft"); put("Verschiden", "Verschieden"); put("Anschovis", "Anchovis"); put("Bravur", "Bravour"); put("Grisli", "Grizzly"); put("Grislibär", "Grizzlybär"); put("Grislibären", "Grizzlybären"); put("Frotté", "Frottee"); put("Joga", "Yoga"); put("Kalvinismus", "Calvinismus"); put("Kollier", "Collier"); put("Kolliers", "Colliers"); put("Ketschup", "Ketchup"); put("Kommunikee", "Kommuniqué"); put("Negligee", "Negligé"); put("Nessessär", "Necessaire"); put("passee", "passé"); put("Varietee", "Varieté"); put("Varietees", "Varietés"); put("Wandalismus", "Vandalismus"); put("Campagne", "Kampagne"); put("Campagnen", "Kampagnen"); put("Jockei", "Jockey"); put("Roulett", "Roulette"); put("Bestellungsdaten", "Bestelldaten"); put("Package", "Paket"); put("E-mail", "E-Mail"); put("geleased", "geleast"); put("released", "releast"); putRepl("Ballets?", "llet", "llett"); putRepl("Saudiarabiens?", "Saudiarabien", "Saudi-Arabien"); putRepl("eMail-Adressen?", "eMail-", "E-Mail-"); putRepl("[Ww]ieviele?", "ieviel", "ie viel"); putRepl("[Aa]dhoc", "dhoc", "d hoc"); put("As", "Ass"); put("[bB]i[sß](s?[ij]|ch)en", "bisschen"); putRepl("Todos?", "Todo", "To-do"); put("Kovult", "Konvolut"); putRepl("blog(t?en?|t(es?t)?)$", "g", "gg"); put("Zombiefizierungen", "Zombifizierungen"); put("Hühne", w -> Arrays.asList("Bühne", "Hüne", "Hühner")); put("Hühnen", w -> Arrays.asList("Bühnen", "Hünen", "Hühnern")); put("tiptop", "tiptopp"); put("Briese", "Brise"); put("Rechtsschreibreformen", "Rechtschreibreformen"); putRepl("gewertschätzte(([mnrs]|re[mnrs]?)?)$", "gewertschätzt", "wertgeschätzt"); putRepl("knapps(t?en?|t(es?t)?)$", "pp", "p"); put("geknappst", "geknapst"); putRepl("gepiekste[mnrs]?$", "ie", "i"); putRepl("Yings?", "ng", "n"); put("Wiederstandes", "Widerstandes"); putRepl("veganisch(e?[mnrs]?)$", "isch", ""); putRepl("totlangweiligste[mnrs]?$", "tot", "tod"); putRepl("tottraurigste[mnrs]?$", "tot", "tod"); putRepl("kreir(n|e?nd)(e[mnrs]?)?$", "ire?n", "ieren"); putRepl("Pepps?", "pp", "p"); putRepl("Pariahs?", "h", ""); putRepl("Oeuvres?", "Oe", "Œ"); put("Margarite", "Margerite"); put("Kücken", w -> Arrays.asList("Rücken", "Küken")); put("Kompanten", w -> Arrays.asList("Kompasse", "Kompassen")); put("Kandarren", "Kandaren"); put("kniehen", "knien"); putRepl("infisziertes?t$", "fisz", "fiz"); putRepl("Imbusse(n|s)?$", "m", "n"); put("Hollundern", "Holundern"); putRepl("handgehabt(e?[mnrs]?)?$", "handgehabt", "gehandhabt"); put("Funieres", "Furniers"); put("Frohndiensts", "Frondiensts"); put("fithälst", "fit hältst"); putRepl("fitzuhalten(de?[mnrs]?)?$", "fitzuhalten", "fit zu halten"); putRepl("(essen|schlafen|schwimmen|spazieren)zugehen$", "zugehen", " zu gehen"); put("dilettant", w -> Arrays.asList("Dilettant", "dilettantisch")); putRepl("dilettante[mnrs]?$", "te", "tische"); put("Disastern", "Desastern"); putRepl("Brandwein(en?|s)$", "d", "nt"); putRepl("Böhen?$", "h", ""); putRepl("Aufständige[mnr]?$", "ig", "isch"); putRepl("aufständig(e[mnrs]?)?$", "ig", "isch"); putRepl("duzend(e[mnrs]?)?$", "uzend", "utzend"); putRepl("unrelevant(e[mnrs]?)?$", "un", "ir"); putRepl("Unrelevant(e[mnrs]?)?$", "Un", "Ir"); put("aufgrundedessen", "aufgrund dessen"); put("Amalgane", "Amalgame"); put("Kafe", w -> Arrays.asList("Kaffee", "Café")); put("Dammbock", w -> Arrays.asList("Dambock", "Rammbock")); put("Dammhirsch", "Damhirsch"); put("Fairnis", "Fairness"); put("auschluss", w -> Arrays.asList("Ausschluss", "Ausschuss")); put("derikter", w -> Arrays.asList("direkter", "Direktor")); put("[iI]dentifierung", "Identifikation"); put("[eE]mphatie", "Empathie"); put("[eE]iskrem", "Eiscreme"); put("[fF]lüchtung", "Flucht"); put("einamen", "Einnahmen"); put("[eE]inbu(ss|ß)ung", "Einbuße"); put("[eE]inbu(ss|ß)ungen", "Einbußen"); put("nachichten", "Nachrichten"); put("gegehen", "gegangen"); put("Ethnocid", "Ethnozid"); put("Exikose", "Exsikkose"); put("Schonvermögengrenze", "Schonvermögensgrenze"); put("kontest", "konntest"); put("pitza", "Pizza"); put("Tütü", "Tutu"); put("gebittet", "gebeten"); put("gekricht", "gekriegt"); put("Krankenheit", "Krankheit"); put("Krankenheiten", "Krankheiten"); put("[hH]udd[yi]", "Hoodie"); put("Treibel", "Tribal"); put("vorort", "vor Ort"); put("Brotwürfelcro[uû]tons", "Croûtons"); put("bess?tetigung", "Bestätigung"); put("[mM]ayonaisse", "Mayonnaise"); put("misverstaendnis", "Missverständnis"); put("[vV]erlu(ss|ß)t", "Verlust"); put("glückigerweise", "glücklicherweise"); put("[sS]tandtart", "Standard"); put("Mainzerstrasse", "Mainzer Straße"); put("Genehmigerablauf", "Genehmigungsablauf"); put("Bestellerurkunde", "Bestellungsurkunde"); put("Selbstmitleidigkeit", "Selbstmitleid"); put("[iI]ntuion", "Intuition"); put("[cCkK]ontener", "Container"); put("Barcadi", "Bacardi"); put("Unnanehmigkeit", "Unannehmlichkeit"); put("[wW]ischmöppen?", "Wischmopps"); putRepl("[oO]rdnungswiedrichkeit(en)?", "[oO]rdnungswiedrich", "Ordnungswidrig"); putRepl("Mauntenbiker[ns]?", "^Maunten", "Mountain"); putRepl("Mauntenbikes?", "Maunten", "Mountain"); putRepl("[nN]euhichkeit(en)?", "[nN]euhich", "Neuig"); putRepl("Prokopfverbrauchs?", "Prokopfv", "Pro-Kopf-V"); // Duden putRepl("[Gg]ilst", "ilst", "iltst"); putRepl("[vV]ollrichtung(en)?", "[vV]oll", "Ver"); putRepl("[vV]ollrichtest", "oll", "er"); putRepl("[vV]ollrichten?", "oll", "er"); putRepl("[vV]ollrichtet(e([mnrs])?)?", "oll", "er"); putRepl("[bB]edingslos(e([mnrs])?)?", "ding", "dingung"); putRepl("[eE]insichtbar(e[mnrs]?)?", "sicht", "seh"); putRepl("asymetrisch(ere|ste)[mnrs]?$", "ym", "ymm"); putRepl("alterwürdig(ere|ste)[mnrs]?$", "lter", "ltehr"); putRepl("aufständig(ere|ste)[mnrs]?$", "ig", "isch"); putRepl("blutdurstig(ere|ste)[mnrs]?$", "ur", "ür"); putRepl("dilettant(ere|este)[mnrs]?$", "nt", "ntisch"); putRepl("eliptisch(ere|ste)[mnrs]?$", "l", "ll"); putRepl("angegröhlt(e([mnrs])?)?$", "öh", "ö"); putRepl("gothisch(ere|ste)[mnrs]?$", "th", "t"); putRepl("kollossal(ere|ste)[mnrs]?$", "ll", "l"); putRepl("paralel(lere|lste)[mnrs]?$", "paralel", "paralle"); putRepl("symetrischste[mnrs]?$", "ym", "ymm"); putRepl("rethorisch(ere|ste)[mnrs]?$", "rethor", "rhetor"); putRepl("repetativ(ere|ste)[mnrs]?$", "repetat", "repetit"); putRepl("voluptös(e|ere|este)?[mnrs]?$", "tös", "tuös"); putRepl("[pP]flanzig(e[mnrs]?)?", "ig", "lich"); putRepl("geblogt(e[mnrs]?)?$", "gt", "ggt"); putRepl("herraus.*", "herraus", "heraus"); putRepl("[aA]bbonier(en?|s?t|te[mnrst]?)", "bbo", "bon"); putRepl("[aA]pelier(en?|s?t|te[nt]?)", "pel", "ppell"); putRepl("[vV]oltie?schier(en?|s?t|te[nt]?)", "ie?sch", "ig"); putRepl("[mM]eistverkaufteste[mnrs]?", "teste", "te"); putRepl("[uU]nleshaft(e[mnrs]?)?", "haft", "erlich"); putRepl("[gG]laubenswürdig(e[mnrs]?)?", "ens", ""); putRepl("[nN]i[vw]ovoll(e[mnrs]?)?", "[vw]ovoll", "veauvoll"); putRepl("[nN]otgezwungend?(e[mnrs]?)?", "zwungend?", "drungen"); putRepl("[mM]isstraurig(e[mnrs]?)?", "rig", "isch"); putRepl("[iI]nflagrantie?", "flagrantie?", " flagranti"); putRepl("Aux-Anschl(uss(es)?|üssen?)", "Aux", "AUX"); putRepl("desinfektiert(e[mnrs]?)?", "fekt", "fiz"); putRepl("desinfektierend(e[mnrs]?)?", "fekt", "fiz"); putRepl("desinfektieren?", "fekt", "fiz"); putRepl("[dD]esinfektionier(en?|t(e[mnrs]?)?|st)", "fektionier", "fizier"); putRepl("[dD]esinfektionierend(e[mnrs]?)?", "fektionier", "fizier"); putRepl("[kK]ompensionier(en?|t(e[mnrs]?)?|st)", "ion", ""); putRepl("neuliche[mnrs]?", "neu", "neuer"); putRepl("ausbüchsen?", "chs", "x"); putRepl("aus(ge)?büchst(en?)?", "chs", "x"); putRepl("innoff?iziell?(e[mnrs]?)?", "innoff?iziell?", "inoffiziell"); putRepl("[gG]roesste[mnrs]?", "oess", "öß"); putRepl("[tT]efonisch(e[mnrs]?)?", "efon", "elefon"); putRepl("[oO]ptimalisiert", "alis", ""); putRepl("[iI]ntrovertisch(e[mnrs]?)?", "isch", "iert"); putRepl("[aA]miert(e[mnrs]?)?", "mi", "rmi"); putRepl("[vV]ersiehrt(e[mnrs]?)?", "h", ""); putRepl("[dD]urchsichtbar(e[mnrs]?)?", "bar", "ig"); putRepl("[oO]ffensichtig(e[mnrs]?)?", "ig", "lich"); putRepl("[zZ]urverfühgung", "verfühgung", " Verfügung"); putRepl("[vV]erständlichkeitsfragen?", "lichkeits", "nis"); putRepl("[sS]pendeangebot(e[ns]?)?", "[sS]pende", "Spenden"); putRepl("gahrnichts?", "gahr", "gar "); putRepl("[aA]ugensichtlich(e[mnrs]?)?", "sicht", "schein"); putRepl("[lL]eidensvoll(e[mnrs]?)?", "ens", ""); putRepl("[bB]ewusstlich(e[mnrs]?)?", "lich", ""); putRepl("[vV]erschmerzlich(e[mnrs]?)?", "lich", "bar"); putRepl("Krankenbruders?", "bruder", "pfleger"); putRepl("Krankenbrüdern?", "brüder", "pfleger"); putRepl("Lan-(Kabel[ns]?|Verbindung)", "Lan", "LAN"); putRepl("[sS]epalastschriftmandat(s|en?)?", "[sS]epal", "SEPA-L"); putRepl("Pinn?eingaben?", "Pinn?e", "PIN-E"); putRepl("[sS]imkarten?", "[sS]imk", "SIM-K"); putRepl("[vV]orsich(geht|gehen|ging(en)?|gegangen)", "sich", " sich "); putRepl("mitsich(bringt|bringen|brachten?|gebracht)", "sich", " sich "); putRepl("[ck]arnivorisch(e[mnrs]?)?", "[ck]arnivorisch", "karnivor"); putRepl("[pP]erfektest(e[mnrs]?)?", "est", ""); putRepl("[gG]leichtig(e[mnrs]?)?", "tig", "zeitig"); putRepl("[uU]n(her)?vorgesehen(e[mnrs]?)?", "(her)?vor", "vorher"); putRepl("([cC]orona|[gG]rippe)viruss?es", "viruss?es", "virus"); putRepl("Zaubererin(nen)?", "er", ""); putRepl("Second-Hand-L[äa]dens?", "Second-Hand-L", "Secondhandl"); putRepl("Second-Hand-Shops?", "Second-Hand-S", "Secondhands"); putRepl("[mM]editerranisch(e[mnrs]?)?", "isch", ""); putRepl("interplementier(s?t|en?)", "inter", "im"); putRepl("[hH]ochalterlich(e[mnrs]?)?", "alter", "mittelalter"); putRepl("posiniert(e[mnrs]?)?", "si", "sitio"); putRepl("[rR]ussophobisch(e[mnrs]?)?", "isch", ""); putRepl("[uU]nsachmä(ß|ss?)ig(e[mnrs]?)?", "mä(ß|ss?)ig", "gemäß"); putRepl("[mM]odernisch(e[mnrs]?)?", "isch", ""); putRepl("intapretation(en)?", "inta", "Inter"); putRepl("[rR]ethorikkurs(e[ns]?)?", "eth", "het"); putRepl("[uU]nterschreibungsfähig(e[mnrs]?)?", "schreibung", "schrift"); putRepl("[eE]rrorier(en?|t(e[mnrs]?)?|st)", "ror", "u"); putRepl("malediert(e[mnrs]?)?", "malediert", "malträtiert"); putRepl("maletriert(e[mnrs]?)?", "maletriert", "malträtiert"); putRepl("Ausbildereignerprüfung(en)?", "eigner", "eignungs"); putRepl("abtrakt(e[mnrs]?)?", "ab", "abs"); putRepl("unerfolgreich(e[mnrs]?)?", "unerfolgreich", "erfolglos"); putRepl("[bB]attalion(en?|s)?", "[bB]attalion", "Bataillon"); putRepl("[bB]esuchungsverbot(e[ns]?)?", "ung", ""); putRepl("spätrig(e[mnrs]?)?", "rig", "er"); putRepl("angehangene[mnrs]?", "hangen", "hängt"); putRepl("[ck]amel[ie]onhaft(e[mnrs]?)?", "[ck]am[ie]lion", "chamäleon"); putRepl("[wW]idersprüchig(e[mnrs]?)?", "ig", "lich"); putRepl("[fF]austig(e[mnrs]?)?", "austig", "austdick"); putRepl("Belastungsekgs?", "ekg", "-EKG"); putRepl("Flektion(en)?", "Flektion", "Flexion"); putRepl("Off-[Ss]hore-[A-Z].+", "Off-[Ss]hore-", "Offshore"); put("Deis", "Dies"); put("fr", "für"); put("abe", w -> Arrays.asList("habe", "aber", "ab")); put("Oster", w -> Arrays.asList("Ostern", "Osten")); put("richen", w -> Arrays.asList("riechen", "reichen", "richten")); put("deien", w -> Arrays.asList("deine", "dein")); put("meien", w -> Arrays.asList("meine", "mein", "meinen")); put("berüht", w -> Arrays.asList("berühmt", "berührt", "bemüht")); put("herlich", w -> Arrays.asList("ehrlich", "herrlich")); put("erzeiht", w -> Arrays.asList("erzieht", "verzeiht")); put("schalfen", w -> Arrays.asList("schlafen", "schaffen", "scharfen")); put("Anfage", w -> Arrays.asList("Anfrage", "Anlage")); put("Formulares", "Formulars"); put("Danl", "Dank"); put("umbennen", "umbenennen"); put("bevorzugs", "bevorzugst"); put("einhergend", "einhergehend"); put("dos", w -> Arrays.asList("das", "des", "DOS", "DoS")); put("mch", w -> Arrays.asList("mich", "ich", "ach")); put("Ihc", w -> Arrays.asList("Ich", "Ihr", "Ihm")); put("ihc", w -> Arrays.asList("ich", "ihr", "ihm")); put("ioch", "ich"); put("of", "oft"); put("mi", w -> Arrays.asList("im", "mit", "mir")); put("wier", w -> Arrays.asList("wie", "wir", "vier", "hier", "wer")); put("ander", w -> Arrays.asList("an der", "andere", "änder", "anders")); put("ech", w -> Arrays.asList("euch", "ich")); put("letzt", w -> Arrays.asList("letzte", "jetzt")); put("beu", w -> Arrays.asList("bei", "peu", "neu")); put("darn", w -> Arrays.asList("daran", "darin", "dann", "dar")); put("zwie", w -> Arrays.asList("zwei", "wie", "sie", "sowie")); put("gebten", w -> Arrays.asList("gebeten", "gaben", "geboten", "gelten")); put("dea", w -> Arrays.asList("der", "den", "des", "dem")); put("neune", w -> Arrays.asList("neuen", "neue", "Neune")); put("geren", w -> Arrays.asList("gegen", "gerne", "gären")); put("wuerden", w -> Arrays.asList("würden", "wurden")); put("wuerde", w -> Arrays.asList("würde", "wurde")); put("git", w -> Arrays.asList("gut", "gibt", "gilt", "mit")); put("voher", w -> Arrays.asList("vorher", "woher", "hoher")); put("hst", w -> Arrays.asList("hast", "ist", "hat")); put("Hst", w -> Arrays.asList("Hast", "Ist", "Hat")); put("herlichen", w -> Arrays.asList("herzlichen", "ehrlichen", "herrlichen")); put("Herlichen", w -> Arrays.asList("Herzlichen", "Ehrlichen", "Herrlichen")); put("herliche", w -> Arrays.asList("herzliche", "ehrliche", "herrliche")); put("Herliche", w -> Arrays.asList("Herzliche", "Ehrliche", "Herrliche")); put("it", w -> Arrays.asList("ist", "IT", "in", "im")); put("ads", w -> Arrays.asList("das", "ADS", "Ads", "als", "aus")); put("hats", w -> Arrays.asList("hat es", "hast", "hat")); put("Hats", w -> Arrays.asList("Hat es", "Hast", "Hat")); put("och", w -> Arrays.asList("ich", "noch", "doch")); put("bein", w -> Arrays.asList("Bein", "beim", "ein", "bei")); put("ser", w -> Arrays.asList("der", "sehr", "er", "sei")); put("Monatg", w -> Arrays.asList("Montag", "Monate", "Monats")); put("leiben", w -> Arrays.asList("lieben", "bleiben", "leben")); put("grad", w -> Arrays.asList("grade", "Grad", "gerade")); put("dnn", w -> Arrays.asList("dann", "denn", "den")); put("vn", w -> Arrays.asList("von", "an", "in")); put("sin", w -> Arrays.asList("ein", "sind", "sie", "in")); put("schein", w -> Arrays.asList("scheine", "Schein", "scheint", "schien")); put("wil", w -> Arrays.asList("will", "wie", "weil", "wir")); put("Ihen", w -> Arrays.asList("Ihren", "Ihnen", "Ihn", "Iren")); put("Iher", w -> Arrays.asList("Ihre", "Ihr")); put("neunen", w -> Arrays.asList("neuen", "neunten")); put("wiel", w -> Arrays.asList("weil", "wie", "viel")); put("brauchts", w -> Arrays.asList("braucht es", "brauchst", "braucht")); put("schöen", w -> Arrays.asList("schönen", "schön")); put("ihne", w -> Arrays.asList("ihn", "ihnen")); put("af", w -> Arrays.asList("auf", "an", "an", "als")); put("mächte", w -> Arrays.asList("möchte", "Mächte")); put("öffen", w -> Arrays.asList("öffnen", "offen")); put("fernsehgucken", w -> Arrays.asList("fernsehen", "Fernsehen gucken")); put("Mien", w -> Arrays.asList("Mein", "Wien", "Miene")); put("abgeharkt", w -> Arrays.asList("abgehakt", "abgehackt")); put("beiten", w -> Arrays.asList("beiden", "bieten")); put("ber", w -> Arrays.asList("über", "per", "der", "BER")); put("ehr", w -> Arrays.asList("eher", "mehr", "sehr", "er")); put("Meien", w -> Arrays.asList("Meine", "Meinen", "Mein", "Medien")); put("neus", w -> Arrays.asList("neues", "neue", "neu")); put("Sunden", w -> Arrays.asList("Sünden", "Stunden", "Kunden")); put("Bitt", w -> Arrays.asList("Bitte", "Bett", "Bist")); put("bst", w -> Arrays.asList("bist", "ist")); put("ds", w -> Arrays.asList("des", "das", "es")); put("mn", w -> Arrays.asList("man", "in", "an")); put("hilt", w -> Arrays.asList("gilt", "hilft", "hielt", "hält")); put("nei", w -> Arrays.asList("bei", "nie", "ein", "neu")); put("riesen", w -> Arrays.asList("riesigen", "diesen", "Riesen", "reisen")); put("Artal", "Ahrtal"); put("wuste", "wusste"); put("Kuden", "Kunden"); put("austehenden", "ausstehenden"); put("eingelogt", "eingeloggt"); put("kapput", "kaputt"); put("geeehrte", "geehrte"); put("geeehrter", "geehrter"); put("startup", "Start-up"); put("startups", "Start-ups"); put("Biite", "Bitte"); put("Gutn", "Guten"); put("gutn", "guten"); put("Ettiket", "Etikett"); put("iht", "ihr"); put("ligt", "liegt"); put("gester", "gestern"); put("veraten", "verraten"); put("dienem", "deinem"); put("Bite", "Bitte"); put("Serh", "Sehr"); put("serh", "sehr"); put("fargen", "fragen"); put("abrechen", "abbrechen"); put("aufzeichen", "aufzeichnen"); put("Geraet", "Gerät"); put("Geraets", "Geräts"); put("Geraete", "Geräte"); put("Geraeten", "Geräten"); put("Fals", "Falls"); put("soche", "solche"); put("verückt", "verrückt"); put("austellen", "ausstellen"); put("klapt", w -> Arrays.asList("klappt", "klagt")); put("denks", w -> Arrays.asList("denkst", "denkt", "denke", "denk")); put("geerhte", "geehrte"); put("geerte", "geehrte"); put("gehn", "gehen"); put("Spß", "Spaß"); put("kanst", "kannst"); put("fregen", "fragen"); put("Bingerloch", "Binger Loch"); put("[nN]or[dt]rh?einwest(f|ph)alen", "Nordrhein-Westfalen"); put("abzusolvieren", "zu absolvieren"); put("Schutzfließ", "Schutzvlies"); put("Simlock", "SIM-Lock"); put("fäschungen", "Fälschungen"); put("Weinverköstigung", "Weinverkostung"); put("vertag", "Vertrag"); put("geauessert", "geäußert"); put("gestriffen", "gestreift"); put("gefäh?ten", "Gefährten"); put("gefäh?te", "Gefährte"); put("immenoch", "immer noch"); put("sevice", "Service"); put("verhälst", "verhältst"); put("[sS]äusche", "Seuche"); put("Schalottenburg", "Charlottenburg"); put("senora", "Señora"); put("widerrum", "wiederum"); put("[dD]epp?risonen", "Depressionen"); put("Defribilator", "Defibrillator"); put("Defribilatoren", "Defibrillatoren"); put("SwatchGroup", "Swatch Group"); put("achtungslo[ßs]", "achtlos"); put("Boomerang", "Bumerang"); put("Boomerangs", "Bumerangs"); put("Lg", w -> Arrays.asList("LG", "Liebe Grüße")); put("gildet", "gilt"); put("gleitete", "glitt"); put("gleiteten", "glitten"); put("Standbay", "Stand-by"); put("[vV]ollkommnung", "Vervollkommnung"); put("femist", "vermisst"); put("stantepede", "stante pede"); put("[kK]ostarika", "Costa Rica"); put("[kK]ostarikas", "Costa Ricas"); put("[aA]uthenzität", "Authentizität"); put("anlässig", "anlässlich"); put("[sS]tieft", "Stift"); put("[Ii]nspruchnahme", "Inanspruchnahme"); put("höstwah?rsch[ea]inlich", "höchstwahrscheinlich"); put("[aA]lterschbeschränkung", "Altersbeschränkung"); put("[kK]unstoff", "Kunststoff"); put("[iI]nstergramm?", "Instagram"); put("fleicht", "vielleicht"); put("[eE]rartens", "Erachtens"); put("laufte", "lief"); put("lauften", "liefen"); put("malzeit", "Mahlzeit"); put("[wW]ahts?app", "WhatsApp"); put("[wW]elan", w -> Arrays.asList("WLAN", "W-LAN")); put("Pinn", w -> Arrays.asList("Pin", "PIN")); put("Geldmachung", w -> Arrays.asList("Geltendmachung", "Geldmacherei")); put("[uU]nstimm?ichkeiten", "Unstimmigkeiten"); put("Teilnehmung", "Teilnahme"); put("Teilnehmungen", "Teilnahmen"); put("waser", "Wasser"); put("Bekennung", "Bekenntnis"); put("[hH]irar?chie", "Hierarchie"); put("Chr", "Chr."); put("Tiefbaumt", "Tiefbauamt"); put("getäucht", "getäuscht"); put("[hH]ähme", "Häme"); put("Wochendruhezeiten", "Wochenendruhezeiten"); put("Studiumplatzt?", "Studienplatz"); put("Permanent-Make-Up", "Permanent-Make-up"); put("woltet", "wolltet"); put("Bäckei", "Bäckerei"); put("Bäckeien", "Bäckereien"); put("warmweis", "warmweiß"); put("kaltweis", "kaltweiß"); put("jez", "jetzt"); put("hendis", "Handys"); put("wie?derwarten", "wider Erwarten"); put("[eE]ntercott?e", "Entrecôte"); put("[eE]rwachtung", "Erwartung"); put("[aA]nung", "Ahnung"); put("[uU]nreimlichkeiten", "Ungereimtheiten"); put("[uU]nangeneh?mlichkeiten", "Unannehmlichkeiten"); put("Messy", "Messie"); put("Polover", "Pullover"); put("heilwegs", "halbwegs"); put("undsoweiter", "und so weiter"); put("Gladbeckerstrasse", "Gladbecker Straße"); put("Bonnerstra(ß|ss)e", "Bonner Straße"); put("[bB]range", "Branche"); put("Gewebtrauma", "Gewebetrauma"); put("aufgehangen", "aufgehängt"); put("Ehrenamtpauschale", "Ehrenamtspauschale"); put("Essenzubereitung", "Essenszubereitung"); put("[gG]eborgsamkeit", "Geborgenheit"); put("gekommt", "gekommen"); put("hinweißen", "hinweisen"); put("Importation", "Import"); put("lädest", "lädst"); put("Themabereich", "Themenbereich"); put("Werksresett", "Werksreset"); put("wiederfahren", "widerfahren"); put("wiederspiegelten", "widerspiegelten"); put("weicheinlich", "wahrscheinlich"); put("schnäpchen", "Schnäppchen"); put("Hinduist", "Hindu"); put("Hinduisten", "Hindus"); put("Konzeptierung", "Konzipierung"); put("Phyton", "Python"); put("nochnichtmals?", "noch nicht einmal"); put("Refelektion", "Reflexion"); put("Refelektionen", "Reflexionen"); put("[sS]chanse", "Chance"); put("nich", w -> Arrays.asList("nicht", "noch")); put("Nich", w -> Arrays.asList("Nicht", "Noch")); put("wat", "was"); put("[Ee][Ss]ports", "E-Sports"); put("gerelaunch(ed|t)", "relauncht"); put("Gerelaunch(ed|t)", "Relauncht"); put("Bowl", "Bowle"); put("Dark[Ww]eb", "Darknet"); put("Sachs?en-Anhal?t", "Sachsen-Anhalt"); put("[Ss]chalgen", "schlagen"); put("[Ss]chalge", "schlage"); put("[dD]eutsche?sprache", "deutsche Sprache"); put("eigl", "eigtl"); put("ma", "mal"); put("leidete", "litt"); put("leidetest", "littest"); put("leideten", "litten"); put("Hoody", "Hoodie"); put("Hoodys", "Hoodies"); put("Staatsexam", "Staatsexamen"); put("Staatsexams", "Staatsexamens"); put("Exam", "Examen"); put("Exams", "Examens"); put("[Rr]eviewing", "Review"); put("[Bb]aldmöglich", "baldmöglichst"); put("[Bb]rudi", "Bruder"); put("ih", w -> Arrays.asList("ich", "in", "im", "ah")); put("Ih", w -> Arrays.asList("Ich", "In", "Im", "Ah")); put("[qQ]uicky", "Quickie"); put("[qQ]uickys", "Quickies"); put("bissl", w -> Arrays.asList("bissel", "bisserl")); put("Keywort", w -> Arrays.asList("Keyword", "Stichwort")); put("Keyworts", w -> Arrays.asList("Keywords", "Stichworts")); put("Keywörter", w -> Arrays.asList("Keywords", "Stichwörter")); put("strang", w -> Arrays.asList("Strang", "strengte")); put("Gym", w -> Arrays.asList("Fitnessstudio", "Gymnasium")); put("Gyms", w -> Arrays.asList("Fitnessstudios", "Gymnasiums")); put("gäng", w -> Arrays.asList("ging", "gang")); put("di", w -> Arrays.asList("du", "die", "Di.", "der", "den")); put("Di", w -> Arrays.asList("Du", "Die", "Di.", "Der", "Den")); put("Aufn", w -> Arrays.asList("Auf den", "Auf einen", "Auf")); put("aufn", w -> Arrays.asList("auf den", "auf einen", "auf")); put("Aufm", w -> Arrays.asList("Auf dem", "Auf einem", "Auf")); put("aufm", w -> Arrays.asList("auf dem", "auf einem", "auf")); put("Ausm", w -> Arrays.asList("Aus dem", "Aus einem", "Aus")); put("ausm", w -> Arrays.asList("aus dem", "aus einem", "aus")); put("Bs", "Bis"); put("Biß", "Biss"); put("bs", "bis"); put("sehn", "sehen"); put("zutun", "zu tun"); put("Müllhalte", "Müllhalde"); put("Entäuschung", "Enttäuschung"); put("Entäuschungen", "Enttäuschungen"); put("kanns", w -> Arrays.asList("kann es", "kannst")); put("funktionierts", "funktioniert es"); put("hbat", "habt"); put("ichs", "ich es"); put("folgendermassen", "folgendermaßen"); put("Adon", "Add-on"); put("Adons", "Add-ons"); put("ud", "und"); put("vertaggt", w -> Arrays.asList("vertagt", "getaggt")); put("keinsten", w -> Arrays.asList("keinen", "kleinsten")); put("Angehensweise", "Vorgehensweise"); put("Angehensweisen", "Vorgehensweisen"); put("Neudefinierung", "Neudefinition"); put("Definierung", "Definition"); put("Definierungen", "Definitionen"); putRepl("[Üü]bergrifflich(e[mnrs]?)?", "lich", "ig"); put("löchen", w -> Arrays.asList("löschen", "löchern", "Köchen")); put("wergen", w -> Arrays.asList("werfen", "werben", "werten")); } private static void putRepl(String wordPattern, String pattern, String replacement) { ADDITIONAL_SUGGESTIONS.put(StringMatcher.regexp(wordPattern), w -> singletonList(w.replaceFirst(pattern, replacement))); } private static void put(String pattern, String replacement) { ADDITIONAL_SUGGESTIONS.put(StringMatcher.regexp(pattern), w -> singletonList(replacement)); } private static void put(String pattern, Function<String, List<String>> f) { ADDITIONAL_SUGGESTIONS.put(StringMatcher.regexp(pattern), f); } private static final GermanWordSplitter splitter = getSplitter(); private static GermanWordSplitter getSplitter() { try { return new GermanWordSplitter(false); } catch (IOException e) { throw new RuntimeException(e); } } private final LineExpander lineExpander = new LineExpander(); private final GermanCompoundTokenizer compoundTokenizer; private final Synthesizer synthesizer; private final Tagger tagger; public GermanSpellerRule(ResourceBundle messages, German language) { this(messages, language, null, null); } /** * @since 4.2 */ public GermanSpellerRule(ResourceBundle messages, German language, UserConfig userConfig, String languageVariantPlainTextDict) { this(messages, language, userConfig, languageVariantPlainTextDict, Collections.emptyList(), null); } /** * @since 4.3 */ public GermanSpellerRule(ResourceBundle messages, German language, UserConfig userConfig, String languageVariantPlainTextDict, List<Language> altLanguages, LanguageModel languageModel) { super(messages, language, language.getNonStrictCompoundSplitter(), getSpeller(language, userConfig, languageVariantPlainTextDict), userConfig, altLanguages, languageModel); addExamplePair(Example.wrong("LanguageTool kann mehr als eine <marker>nromale</marker> Rechtschreibprüfung."), Example.fixed("LanguageTool kann mehr als eine <marker>normale</marker> Rechtschreibprüfung.")); compoundTokenizer = language.getStrictCompoundTokenizer(); tagger = language.getTagger(); synthesizer = language.getSynthesizer(); } @Override protected synchronized void init() throws IOException { super.init(); super.ignoreWordsWithLength = 1; String pattern = "(" + nonWordPattern.pattern() + "|(?<=[\\d°])-|-(?=\\d+))"; nonWordPattern = Pattern.compile(pattern); } @Override public String getId() { return RULE_ID; } @Override protected boolean isIgnoredNoCase(String word) { return wordsToBeIgnored.contains(word) || // words from spelling.txt also accepted in uppercase (e.g. sentence start, bullet list items): (word.matches("[A-ZÖÄÜ][a-zöäüß-]+") && wordsToBeIgnored.contains(word.toLowerCase(language.getLocale()))) || (ignoreWordsWithLength > 0 && word.length() <= ignoreWordsWithLength); } @Override public List<String> getCandidates(String word) { List<List<String>> partList; try { partList = splitter.getAllSplits(word); } catch (InputTooLongException e) { partList = new ArrayList<>(); } List<String> candidates = new ArrayList<>(); for (List<String> parts : partList) { List<String> tmp = super.getCandidates(parts); tmp = tmp.stream().filter(k -> !k.matches("[A-ZÖÄÜ][a-zöäüß]+-[\\-\\s]?[a-zöäüß]+") && !k.matches("[a-zöäüß]+-[\\-\\s][A-ZÖÄÜa-zöäüß]+")).collect(Collectors.toList()); // avoid e.g. "Direkt-weg" tmp = tmp.stream().filter(k -> !k.contains("-s-")).collect(Collectors.toList()); // avoid e.g. "Geheimnis-s-voll" if (!word.endsWith("-")) { tmp = tmp.stream().filter(k -> !k.endsWith("-")).collect(Collectors.toList()); // avoid "xyz-" unless the input word ends in "-" } candidates.addAll(tmp); if (parts.size() == 2) { // e.g. "inneremedizin" -> "innere Medizin", "gleichgroß" -> "gleich groß" candidates.add(parts.get(0) + " " + parts.get(1)); if (isNounOrProperNoun(uppercaseFirstChar(parts.get(1)))) { candidates.add(parts.get(0) + " " + uppercaseFirstChar(parts.get(1))); } } if (parts.size() == 2 && !parts.get(0).endsWith("s")) { // so we get e.g. Einzahlungschein -> Einzahlungsschein candidates.add(parts.get(0) + "s" + parts.get(1)); } if (parts.size() == 2 && parts.get(1).startsWith("s")) { // so we get e.g. Ordnungshütter -> Ordnungshüter (Ordnungshütter is split as Ordnung + shütter) String firstPart = parts.get(0); String secondPart = parts.get(1); candidates.addAll(super.getCandidates(Arrays.asList(firstPart + "s", secondPart.substring(1)))); } } return candidates; } @Override protected boolean isProhibited(String word) { return super.isProhibited(word) || wordStartsToBeProhibited.stream().anyMatch(w -> word.startsWith(w)) || wordEndingsToBeProhibited.stream().anyMatch(w -> word.endsWith(w)); } @Override protected void addIgnoreWords(String origLine) { // hack: Swiss German doesn't use "ß" but always "ss" - replace this, otherwise // misspellings (from Swiss point-of-view) like "äußere" wouldn't be found: String line = language.getShortCodeWithCountryAndVariant().equals("de-CH") ? origLine.replace("ß", "ss") : origLine; if (origLine.endsWith("-*")) { // words whose line ends with "-*" are only allowed in hyphenated compounds wordsToBeIgnoredInCompounds.add(line.substring(0, line.length() - 2)); return; } List<String> words = expandLine(line); for (String word : words) { super.addIgnoreWords(word); } } @Override protected List<String> expandLine(String line) { return lineExpander.expandLine(line); } @Override protected RuleMatch createWrongSplitMatch(AnalyzedSentence sentence, List<RuleMatch> ruleMatchesSoFar, int pos, String coveredWord, String suggestion1, String suggestion2, int prevPos) { if (suggestion2.matches("[a-zöäü]-.+")) { // avoid confusing matches for e.g. "haben -sehr" (was: "habe n-sehr") return null; } return super.createWrongSplitMatch(sentence, ruleMatchesSoFar, pos, coveredWord, suggestion1, suggestion2, prevPos); } /* * @since 3.6 */ @Override public List<String> getSuggestions(String word) throws IOException { /* Do not just comment in because of https://github.com/languagetool-org/languagetool/issues/3757 if (word.length() < 18 && word.matches("[a-zA-Zöäüß-]+.?")) { for (String prefix : VerbPrefixes.get()) { if (word.startsWith(prefix)) { String lastPart = word.substring(prefix.length()); if (lastPart.length() > 3 && !isMisspelled(lastPart)) { // as these are only single words and both the first part and the last part are spelled correctly // (but the combination is not), it's okay to log the words from a privacy perspective: logger.info("UNKNOWN: {}", word); } } } }*/ List<String> suggestions = super.getSuggestions(word); suggestions = suggestions.stream().filter(this::acceptSuggestion).collect(Collectors.toList()); if (word.endsWith(".")) { // To avoid losing the "." of "word" if it is at the end of a sentence. suggestions.replaceAll(s -> s.endsWith(".") ? s : s + "."); } suggestions = suggestions.stream().filter(k -> !k.equals(word) && (!k.endsWith("-") || word.endsWith("-")) && // no "-" at end (#2450) !k.matches("\\p{L} \\p{L}+") // single chars like in "ü berstenden" (#2610) ).collect(Collectors.toList()); return suggestions; } @Override protected boolean acceptSuggestion(String s) { return !PREVENT_SUGGESTION.matcher(s).matches() && !s.matches(".+[*_:]in") // only suggested when using "..._in" in spelling.txt, so rather never offer this suggestion && !s.matches(".+[*_:]innen") && !s.contains("--") && !s.endsWith("roulett") && !s.matches(".+\\szigste[srnm]") // do not suggest "ein zigste" for "einzigste" && !s.matches("[\\wöäüÖÄÜß]+ [a-zöäüß]-[\\wöäüÖÄÜß]+") // e.g. "Mediation s-Background" && !s.matches("[\\wöäüÖÄÜß]+- [\\wöäüÖÄÜß]+") // e.g. "Pseudo- Rebellentum" && !s.matches("[A-ZÄÖÜ][a-zäöüß]+-[a-zäöüß]+-[a-zäöüß]+") // e.g. "Kapuze-over-teil" && !s.matches("[A-ZÄÖÜ][a-zäöüß]+- [a-zäöüßA-ZÄÖÜ\\-]+") // e.g. "Tuchs-N-Harmonie" && !s.matches("[\\wöäüÖÄÜß]+ -[\\wöäüÖÄÜß]+") // e.g. "ALT -TARIF" && !s.endsWith("-s") // https://github.com/languagetool-org/languagetool/issues/4042 && !s.endsWith(" de") // https://github.com/languagetool-org/languagetool/issues/4042 && !s.endsWith(" en") // https://github.com/languagetool-org/languagetool/issues/4042 && !s.matches("[A-ZÖÄÜa-zöäüß] .+") // z.B. nicht "I Tand" für "IT and Services" && !s.matches(".+ [a-zöäüßA-ZÖÄÜ]"); // z.B. nicht "rauchen e" für "rauche ne" vorschlagen } @NotNull protected static List<String> getSpellingFilePaths(String langCode) { List<String> paths = new ArrayList<>(CompoundAwareHunspellRule.getSpellingFilePaths(langCode)); paths.add( "/" + langCode + "/hunspell/spelling_recommendation.txt"); return paths; } @Nullable protected static MorfologikMultiSpeller getSpeller(Language language, UserConfig userConfig, String languageVariantPlainTextDict) { try { String langCode = language.getShortCode(); String morfoFile = "/" + langCode + "/hunspell/" + langCode + "_" + language.getCountries()[0] + JLanguageTool.DICTIONARY_FILENAME_EXTENSION; if (JLanguageTool.getDataBroker().resourceExists(morfoFile)) { // spell data will not exist in LibreOffice/OpenOffice context List<String> paths = new ArrayList<>(getSpellingFilePaths(langCode)); if (languageVariantPlainTextDict != null) { paths.add(languageVariantPlainTextDict); } List<InputStream> streams = getStreams(paths); try (BufferedReader br = new BufferedReader( new InputStreamReader(new SequenceInputStream(Collections.enumeration(streams)), UTF_8))) { BufferedReader variantReader = getVariantReader(languageVariantPlainTextDict); return new MorfologikMultiSpeller(morfoFile, new ExpandingReader(br), paths, variantReader, languageVariantPlainTextDict, userConfig, MAX_EDIT_DISTANCE); } } else { return null; } } catch (IOException e) { throw new RuntimeException("Could not set up morfologik spell checker", e); } } @Nullable private static BufferedReader getVariantReader(String languageVariantPlainTextDict) { BufferedReader variantReader = null; if (languageVariantPlainTextDict != null && !languageVariantPlainTextDict.isEmpty()) { InputStream variantStream = JLanguageTool.getDataBroker().getFromResourceDirAsStream(languageVariantPlainTextDict); variantReader = new ExpandingReader(new BufferedReader(new InputStreamReader(variantStream, UTF_8))); } return variantReader; } @Override protected void filterForLanguage(List<String> suggestions) { if (language.getShortCodeWithCountryAndVariant().equals("de-CH")) { for (int i = 0; i < suggestions.size(); i++) { String s = suggestions.get(i); suggestions.set(i, s.replace("ß", "ss")); } } // Remove suggestions like "Mafiosi s" and "Mafiosi s.": suggestions.removeIf(s -> Arrays.stream(s.split(" ")).anyMatch(k -> k.matches("\\w\\p{Punct}?"))); // This is not quite correct as it might remove valid suggestions that start with "-", // but without this we get too many strange suggestions that start with "-" for no apparent reason // (e.g. for "Gratifikationskrisem" -> "-Gratifikationskrisen"): suggestions.removeIf(s -> s.length() > 1 && s.startsWith("-")); } @Override protected List<String> sortSuggestionByQuality(String misspelling, List<String> suggestions) { List<String> result = new ArrayList<>(); List<String> topSuggestions = new ArrayList<>(); // candidates from suggestions that get boosted to the top for (String suggestion : suggestions) { if (misspelling.equalsIgnoreCase(suggestion)) { // this should be preferred - only case differs topSuggestions.add(suggestion); } else if (suggestion.contains(" ")) { // this should be preferred - prefer e.g. "vor allem": // suggestions at the sentence end include a period sometimes, clean up for ngram lookup String[] words = suggestion.replaceFirst("\\.$", "").split(" ", 2); if (languageModel != null && words.length == 2) { // language model available, test if split word occurs at all / more frequently than alternative Probability nonSplit = languageModel.getPseudoProbability(singletonList(words[0] + words[1])); Probability split = languageModel.getPseudoProbability(Arrays.asList(words)); //System.out.printf("Probability - %s vs %s: %.12f (%d) vs %.12f (%d)%n", // words[0] + words[1], suggestion, if (nonSplit.getProb() > split.getProb() || split.getProb() == 0) { result.add(suggestion); } else { topSuggestions.add(suggestion); } } else { topSuggestions.add(suggestion); } } else { result.add(suggestion); } } result.addAll(0, topSuggestions); return result; } @Override protected List<String> getFilteredSuggestions(List<String> wordsOrPhrases) { List<String> result = new ArrayList<>(); for (String wordOrPhrase : wordsOrPhrases) { String[] words = tokenizeText(wordOrPhrase); if (words.length >= 2 && isAdjOrNounOrUnknown(words[0]) && isNounOrUnknown(words[1]) && startsWithUppercase(words[0]) && startsWithUppercase(words[1])) { // ignore, seems to be in the form "Release Prozess" which is *probably* wrong } else { result.add(wordOrPhrase); } } return result; } private boolean isNounOrUnknown(String word) { try { List<AnalyzedTokenReadings> readings = tagger.tag(singletonList(word)); return readings.stream().anyMatch(reading -> reading.hasPosTagStartingWith("SUB") || reading.isPosTagUnknown()); } catch (IOException e) { throw new RuntimeException(e); } } private boolean isOnlyNoun(String word) { try { List<AnalyzedTokenReadings> readings = tagger.tag(singletonList(word)); for (AnalyzedTokenReadings reading : readings) { boolean accept = reading.getReadings().stream().allMatch(k -> k.getPOSTag() != null && k.getPOSTag().startsWith("SUB:")); if (!accept) { return false; } } return readings.stream().allMatch(reading -> reading.matchesPosTagRegex("SUB:.*")); } catch (IOException e) { throw new RuntimeException(e); } } private boolean isAdjOrNounOrUnknown(String word) { try { List<AnalyzedTokenReadings> readings = tagger.tag(singletonList(word)); return readings.stream().anyMatch(reading -> reading.hasPosTagStartingWith("SUB") || reading.hasPosTagStartingWith("ADJ") || reading.isPosTagUnknown()); } catch (IOException e) { throw new RuntimeException(e); } } private boolean isNounOrProperNoun(String word) { try { List<AnalyzedTokenReadings> readings = tagger.tag(singletonList(word)); return readings.stream().anyMatch(reading -> reading.hasPosTagStartingWith("SUB") || reading.hasPosTagStartingWith("EIG")); } catch (IOException e) { throw new RuntimeException(e); } } private boolean ignoreElative(String word) { if (StringUtils.startsWithAny(word, "bitter", "dunkel", "erz", "extra", "früh", "gemein", "hyper", "lau", "mega", "minder", "stock", "super", "tod", "ultra", "ur")) { String lastPart = RegExUtils.removePattern(word, "^(bitter|dunkel|erz|extra|früh|gemein|grund|hyper|lau|mega|minder|stock|super|tod|ultra|ur|voll)"); return lastPart.length() >= 3 && !isMisspelled(lastPart); } return false; } @Override public boolean isMisspelled(String word) { if (word.startsWith("Spielzug") && !word.matches("Spielzugs?|Spielzugangs?|Spielzuganges|Spielzugbuchs?|Spielzugbüchern?|Spielzuges|Spielzugverluste?|Spielzugverluste[ns]")) { return true; } if (word.startsWith("Standart") && !word.equals("Standarte") && !word.equals("Standarten") && !word.startsWith("Standartenträger") && !word.startsWith("Standartenführer")) { return true; } if (word.endsWith("schafte") && word.matches("[A-ZÖÄÜ][a-zöäß-]+schafte")) { return true; } return super.isMisspelled(word); } @Override protected boolean ignoreWord(List<String> words, int idx) throws IOException { String word = words.get(idx); if (word.length() > MAX_TOKEN_LENGTH) { return true; } boolean ignore = super.ignoreWord(words, idx); boolean ignoreUncapitalizedWord = !ignore && idx == 0 && super.ignoreWord(StringUtils.uncapitalize(words.get(0))); boolean ignoreByHyphen = false; boolean ignoreBulletPointCase = false; if (!ignoreUncapitalizedWord) { // happens e.g. with list items in Google Docs, which introduce \uFEFF, which here appears as // an empty token: ignoreBulletPointCase = !ignore && idx == 1 && words.get(0).isEmpty() && startsWithUppercase(word) && isMisspelled(word) && !isMisspelled(word.toLowerCase()); } boolean ignoreHyphenatedCompound = false; if (!ignore && !ignoreUncapitalizedWord) { if (word.contains("-")) { if (idx > 0 && "".equals(words.get(idx-1)) && StringUtils.startsWithAny(word, "stel-", "tel-") ) { // accept compounds such as '100stel-Millimeter' or '5tel-Gramm' return !isMisspelled(StringUtils.substringAfter(word, "-")); } else { ignoreByHyphen = word.endsWith("-") && ignoreByHangingHyphen(words, idx); } } ignoreHyphenatedCompound = !ignoreByHyphen && ignoreCompoundWithIgnoredWord(word); } if (CommonFileTypes.getSuffixPattern().matcher(word).matches()) { return true; } if (missingAdjPattern.matcher(word).matches()) { String firstPart = StringTools.uppercaseFirstChar(word.replaceFirst(adjSuffix + "(er|es|en|em|e)?", "")); // We append "test" to see if the word plus "test" is accepted as a compound. This way, we get the // infix 's" handled properly (e.g. "arbeitsartig" is okay, "arbeitartig" is not). It does not accept // all compounds, though, as hunspell's compound detection is limited ("Zwiebacktest"): // TODO: see isNeedingFugenS() // https://www.sekada.de/korrespondenz/rechtschreibung/artikel/grammatik-in-diesen-faellen-steht-das-fugen-s/ /*if (!isMisspelled(firstPart) && !isMisspelled(firstPart + "test")) { System.out.println("accept1: " + word + " [" + !isMisspelled(word) + "]"); //return true; } else if (firstPart.endsWith("s") && !isMisspelled(firstPart.replaceFirst("s$", "")) && !isMisspelled(firstPart + "test")) { // "handlungsartig" System.out.println("accept2: " + word + " [" + !isMisspelled(word) + "]"); //return true; }*/ if (isMisspelled(word)) { if (!isMisspelled(firstPart) && !firstPart.matches(".{3,25}(tum|ing|ling|heit|keit|schaft|ung|ion|tät|at|um)") && isOnlyNoun(firstPart) && !isMisspelled(firstPart + "test")) { // does hunspell accept this? takes infex-s into account automatically //System.out.println("will accept: " + word); return true; } else if (!isMisspelled(firstPart) && !firstPart.matches(".{3,25}(tum|ing|ling|heit|keit|schaft|ung|ion|tät|at|um)")) { //System.out.println("will not accept: " + word); } else if (firstPart.endsWith("s") && !isMisspelled(firstPart.replaceFirst("s$", "")) && firstPart.matches(".{3,25}(tum|ing|ling|heit|keit|schaft|ung|ion|tät|at|um)s") && // "handlungsartig" isOnlyNoun(firstPart.replaceFirst("s$", "")) && !isMisspelled(firstPart + "test")) { // does hunspell accept this? takes infex-s into account automatically //System.out.println("will accept: " + word); return true; } else if (firstPart.endsWith("s") && !isMisspelled(firstPart.replaceFirst("s$", "")) && firstPart.matches(".{3,25}(tum|ing|ling|heit|keit|schaft|ung|ion|tät|at|um)s")) { //System.out.println("will not accept: " + word); } } } if ((idx+1 < words.size() && (word.endsWith(".mp") || word.endsWith(".woff")) && words.get(idx+1).equals("")) || (idx > 0 && "".equals(words.get(idx-1)) && StringUtils.equalsAny(word, "sat", "stel", "tel", "stels", "tels") )) { // e.g. ".mp3", "3sat", "100stel", "5tel" - the check for the empty string is because digits were removed during // hunspell-style tokenization before return true; } return ignore || ignoreUncapitalizedWord || ignoreBulletPointCase || ignoreByHyphen || ignoreHyphenatedCompound || ignoreElative(word); } @Override protected List<SuggestedReplacement> getAdditionalTopSuggestions(List<SuggestedReplacement> suggestions, String word) throws IOException { List<String> suggestionsList = suggestions.stream() .map(SuggestedReplacement::getReplacement).collect(Collectors.toList()); return SuggestedReplacement.convert(getAdditionalTopSuggestionsString(suggestionsList, word)); } private List<String> getAdditionalTopSuggestionsString(List<String> suggestions, String word) throws IOException { String suggestion; if ("WIFI".equalsIgnoreCase(word)) { return singletonList("Wi-Fi"); } else if ("W-Lan".equalsIgnoreCase(word)) { return singletonList("WLAN"); } else if ("genomen".equals(word)) { return singletonList("genommen"); } else if ("Preis-Leistungsverhältnis".equals(word)) { return singletonList("Preis-Leistungs-Verhältnis"); } else if ("getz".equals(word)) { return Arrays.asList("jetzt", "geht's"); } else if ("Trons".equals(word)) { return singletonList("Trance"); } else if ("ei".equals(word)) { return singletonList("ein"); } else if ("jo".equals(word) || "jepp".equals(word) || "jopp".equals(word)) { return singletonList("ja"); } else if ("Jo".equals(word) || "Jepp".equals(word) || "Jopp".equals(word)) { return singletonList("Ja"); } else if ("Ne".equals(word)) { // "Ne einfach Frage!" // "Ne, das musst du machen!" return Arrays.asList("Nein", "Eine"); } else if ("is".equals(word)) { return singletonList("ist"); } else if ("Is".equals(word)) { return singletonList("Ist"); } else if ("un".equals(word)) { return singletonList("und"); } else if ("Un".equals(word)) { return singletonList("Und"); } else if ("Std".equals(word)) { return singletonList("Std."); } else if (word.matches(".*ibel[hk]eit$")) { suggestion = word.replaceFirst("el[hk]eit$", "ilität"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.endsWith("aquise")) { suggestion = word.replaceFirst("aquise$", "akquise"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.endsWith("standart")) { suggestion = word.replaceFirst("standart$", "standard"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.endsWith("standarts")) { suggestion = word.replaceFirst("standarts$", "standards"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.endsWith("tips")) { suggestion = word.replaceFirst("tips$", "tipps"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.endsWith("tip")) { suggestion = word + "p"; if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.endsWith("entfehlung")) { suggestion = word.replaceFirst("ent", "emp"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.endsWith("oullie")) { suggestion = word.replaceFirst("oullie$", "ouille"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.startsWith("[dD]urschnitt")) { suggestion = word.replaceFirst("^urschnitt", "urchschnitt"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.startsWith("Bundstift")) { suggestion = word.replaceFirst("^Bundstift", "Buntstift"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.matches("[aA]llmähll?i(g|ch)(e[mnrs]?)?")) { suggestion = word.replaceFirst("llmähll?i(g|ch)", "llmählich"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.matches(".*[mM]a[jy]onn?[äe]se.*")) { suggestion = word.replaceFirst("a[jy]onn?[äe]se", "ayonnaise"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.matches(".*[rR]es(a|er)[vw]i[he]?rung(en)?")) { suggestion = word.replaceFirst("es(a|er)[vw]i[he]?rung", "eservierung"); if (hunspell.spell(suggestion)) { // suggest e.g. 'Ticketreservierung', but not 'Blödsinnsquatschreservierung' return singletonList(suggestion); } } else if (word.matches("[rR]eschaschier.+")) { suggestion = word.replaceFirst("schaschier", "cherchier"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.matches(".*[lL]aborants$")) { suggestion = word.replaceFirst("ts$", "ten"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.matches("[pP]roff?ess?ion([äe])h?ll?(e[mnrs]?)?")) { suggestion = word.replaceFirst("roff?ess?ion([äe])h?l{1,2}", "rofessionell"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.matches("[vV]erstehendniss?(es?)?")) { suggestion = word.replaceFirst("[vV]erstehendnis", "Verständnis"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.startsWith("koregier")) { suggestion = word.replace("reg", "rrig"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.matches("diagno[sz]ier.*")) { suggestion = word.replaceAll("gno[sz]ier", "gnostizier"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.contains("eiss")) { suggestion = word.replace("eiss", "eiß"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.contains("uess")) { suggestion = word.replace("uess", "üß"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.equals("gin")) { return singletonList("ging"); } else if (word.equals("dh") || word.equals("dh.")) { return singletonList("d.\u202fh."); } else if (word.equals("ua") || word.equals("ua.")) { return singletonList("u.\u202fa."); } else if (word.matches("z[bB]") || word.matches("z[bB].")) { return singletonList("z.\u202fB."); } else if (word.equals("uvm") || word.equals("uvm.")) { return singletonList("u.\u202fv.\u202fm."); } else if (word.equals("udgl") || word.equals("udgl.")) { return singletonList("u.\u202fdgl."); } else if (word.equals("Ruhigkeit")) { return singletonList("Ruhe"); } else if (word.equals("angepreist")) { return singletonList("angepriesen"); } else if (word.equals("halo")) { return singletonList("hallo"); } else if (word.equalsIgnoreCase("zumindestens")) { return singletonList(word.replace("ens", "")); } else if (word.equals("ca")) { return singletonList("ca."); } else if (word.equals("Jezt")) { return singletonList("Jetzt"); } else if (word.equals("Wollst")) { return singletonList("Wolltest"); } else if (word.equals("wollst")) { return singletonList("wolltest"); } else if (word.equals("Rolladen")) { return singletonList("Rollladen"); } else if (word.equals("Maßname")) { return singletonList("Maßnahme"); } else if (word.equals("Maßnamen")) { return singletonList("Maßnahmen"); } else if (word.equals("nanten")) { return singletonList("nannten"); } else if (word.endsWith("ies")) { if (word.equals("Lobbies")) { return singletonList("Lobbys"); } else if (word.equals("Parties")) { return singletonList("Partys"); } else if (word.equals("Babies")) { return singletonList("Babys"); } else if (word.endsWith("derbies")) { suggestion = word.replaceFirst("derbies$", "derbys"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.endsWith("stories")) { suggestion = word.replaceFirst("stories$", "storys"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } else if (word.endsWith("parties")) { suggestion = word.replaceFirst("parties$", "partys"); if (hunspell.spell(suggestion)) { return singletonList(suggestion); } } } else if (word.equals("Hallochen")) { return Arrays.asList("Hallöchen", "hallöchen"); } else if (word.equals("hallochen")) { return singletonList("hallöchen"); } else if (word.equals("ok")) { return Arrays.asList("okay", "O.\u202fK."); // Duden-like suggestion with no-break space } else if (word.equals("gesuchen")) { return Arrays.asList("gesuchten", "gesucht"); } else if (word.equals("Germanistiker")) { return Arrays.asList("Germanist", "Germanisten"); } else if (word.equals("Abschlepper")) { return Arrays.asList("Abschleppdienst", "Abschleppwagen"); } else if (word.equals("par")) { return singletonList("paar"); } else if (word.equals("vllt")) { return singletonList("vielleicht"); } else if (word.equals("iwie")) { return singletonList("irgendwie"); } else if (word.equals("bzgl")) { return singletonList("bzgl."); } else if (word.equals("bau")) { return singletonList("baue"); } else if (word.equals("sry")) { return singletonList("sorry"); } else if (word.equals("Sry")) { return singletonList("Sorry"); } else if (word.equals("thx")) { return singletonList("danke"); } else if (word.equals("Thx")) { return singletonList("Danke"); } else if (word.equals("Zynik")) { return singletonList("Zynismus"); } else if (word.equalsIgnoreCase("email")) { return singletonList("E-Mail"); } else if (word.length() > 9 && word.startsWith("Email")) { String suffix = word.substring(5); if (!hunspell.spell(suffix)) { List<String> suffixSuggestions = hunspell.suggest(uppercaseFirstChar(suffix)); suffix = suffixSuggestions.isEmpty() ? suffix : suffixSuggestions.get(0); } return singletonList("E-Mail-"+Character.toUpperCase(suffix.charAt(0))+suffix.substring(1)); } else if (word.equals("wiederspiegeln")) { return singletonList("widerspiegeln"); } else if (word.equals("ch")) { return singletonList("ich"); } else { for (Map.Entry<StringMatcher, Function<String, List<String>>> entry : ADDITIONAL_SUGGESTIONS.entrySet()) { if (entry.getKey().matches(word)) { return entry.getValue().apply(word); } } } if (!startsWithUppercase(word)) { String ucWord = uppercaseFirstChar(word); if (!suggestions.contains(ucWord) && hunspell.spell(ucWord) && !ucWord.endsWith(".")) { // Hunspell doesn't always automatically offer the most obvious suggestion for compounds: return singletonList(ucWord); } } String verbSuggestion = getPastTenseVerbSuggestion(word); if (verbSuggestion != null) { return singletonList(verbSuggestion); } String participleSuggestion = getParticipleSuggestion(word); if (participleSuggestion != null) { return singletonList(participleSuggestion); } String abbreviationSuggestion = getAbbreviationSuggestion(word); if (abbreviationSuggestion != null) { return singletonList(abbreviationSuggestion); } // hyphenated compounds words (e.g., "Netflix-Flm") if (suggestions.isEmpty() && word.contains("-")) { String[] words = word.split("-"); if (words.length > 1) { List<List<String>> suggestionLists = new ArrayList<>(words.length); int startAt = 0; int stopAt = words.length; String partialWord = words[0] + "-" + words[1]; if (super.ignoreWord(partialWord) || wordsToBeIgnoredInCompounds.contains(partialWord)) { // "Au-pair-Agentr" startAt = 2; suggestionLists.add(singletonList(words[0] + "-" + words[1])); } partialWord = words[words.length-2] + "-" + words[words.length-1]; if (super.ignoreWord(partialWord) || wordsToBeIgnoredInCompounds.contains(partialWord)) { // "Seniren-Au-pair" stopAt = words.length-2; } for (int idx = startAt; idx < stopAt; idx++) { if (!hunspell.spell(words[idx])) { List<String> list = sortSuggestionByQuality(words[idx], super.getSuggestions(words[idx])); suggestionLists.add(list); } else { suggestionLists.add(singletonList(words[idx])); } } if (stopAt < words.length-1) { suggestionLists.add(singletonList(partialWord)); } if (suggestionLists.size() <= 3) { // avoid OutOfMemory on words like "free-and-open-source-and-cross-platform" List<String> additionalSuggestions = suggestionLists.get(0); for (int idx = 1; idx < suggestionLists.size(); idx++) { List<String> suggestionList = suggestionLists.get(idx); List<String> newList = new ArrayList<>(additionalSuggestions.size() * suggestionList.size()); for (String additionalSuggestion : additionalSuggestions) { for (String aSuggestionList : suggestionList) { newList.add(additionalSuggestion + "-" + aSuggestionList); } } additionalSuggestions = newList; } // avoid overly long lists of suggestions (we just take the first results, although we don't know whether they are better): return additionalSuggestions.subList(0, Math.min(5, additionalSuggestions.size())); } } } return Collections.emptyList(); } // Get a correct suggestion for invalid words like greifte, denkte, gehte: useful for // non-native speakers and cannot be found by just looking for similar words. @Nullable private String getPastTenseVerbSuggestion(String word) { if (word.endsWith("e")) { // strip trailing "e" String wordStem = word.substring(0, word.length()-1); try { String lemma = baseForThirdPersonSingularVerb(wordStem); if (lemma != null) { AnalyzedToken token = new AnalyzedToken(lemma, null, lemma); String[] forms = synthesizer.synthesize(token, "VER:3:SIN:PRT:.*", true); if (forms.length > 0) { return forms[0]; } } } catch (IOException e) { throw new RuntimeException(e); } } return null; } @Nullable private String baseForThirdPersonSingularVerb(String word) throws IOException { List<AnalyzedTokenReadings> readings = tagger.tag(singletonList(word)); for (AnalyzedTokenReadings reading : readings) { if (reading.hasPosTagStartingWith("VER:3:SIN")) { return reading.getReadings().get(0).getLemma(); } } return null; } // Get a correct suggestion for invalid words like geschwimmt, geruft: useful for // non-native speakers and cannot be found by just looking for similar words. @Nullable private String getParticipleSuggestion(String word) { if (word.startsWith("ge") && word.endsWith("t")) { // strip leading "ge" and replace trailing "t" with "en": String baseform = word.substring(2, word.length()-1) + "en"; try { String participle = getParticipleForBaseform(baseform); if (participle != null) { return participle; } } catch (IOException e) { throw new RuntimeException(e); } } return null; } @Nullable private String getParticipleForBaseform(String baseform) throws IOException { AnalyzedToken token = new AnalyzedToken(baseform, null, baseform); String[] forms = synthesizer.synthesize(token, "VER:PA2:.*", true); if (forms.length > 0 && hunspell.spell(forms[0])) { return forms[0]; } return null; } private String getAbbreviationSuggestion(String word) throws IOException { if (word.length() < 5) { List<AnalyzedTokenReadings> readings = tagger.tag(singletonList(word)); for (AnalyzedTokenReadings reading : readings) { if (reading.hasPosTagStartingWith("ABK")) { return word+"."; } } } return null; } private boolean ignoreByHangingHyphen(List<String> words, int idx) throws IOException { String word = words.get(idx); String nextWord = getWordAfterEnumerationOrNull(words, idx+1); nextWord = removeEnd(nextWord, "."); boolean isCompound = nextWord != null && (compoundTokenizer.tokenize(nextWord).size() > 1 || nextWord.indexOf('-') > 0 || nextWord.matches("[A-ZÖÄÜ][a-zöäüß]{2,}(ei|öl)$")); // compound tokenizer will only split compounds where each part is >= 3 characters... if (isCompound) { word = removeEnd(word, "-"); boolean isMisspelled = !hunspell.spell(word); // "Stil- und Grammatikprüfung" or "Stil-, Text- und Grammatikprüfung" if (isMisspelled && (super.ignoreWord(word) || wordsToBeIgnoredInCompounds.contains(word))) { isMisspelled = false; } else if (isMisspelled && word.endsWith("s") && isNeedingFugenS(removeEnd(word, "s"))) { // Vertuschungs- und Bespitzelungsmaßnahmen: remove trailing "s" before checking "Vertuschungs" so that the spell checker finds it isMisspelled = !hunspell.spell(removeEnd(word, "s")); } return !isMisspelled; } return false; } private boolean isNeedingFugenS(String word) { // according to http://www.spiegel.de/kultur/zwiebelfisch/zwiebelfisch-der-gebrauch-des-fugen-s-im-ueberblick-a-293195.html return StringUtils.endsWithAny(word, "tum", "ling", "ion", "tät", "keit", "schaft", "sicht", "ung", "en"); } // for "Stil- und Grammatikprüfung", get "Grammatikprüfung" when at position of "Stil-" @Nullable private String getWordAfterEnumerationOrNull(List<String> words, int idx) { for (int i = idx; i < words.size(); i++) { String word = words.get(i); if (!(word.endsWith("-") || StringUtils.equalsAny(word, ",", "und", "oder", "sowie") || word.trim().isEmpty())) { return word; } } return null; } // check whether a <code>word<code> is a valid compound (e.g., "Feynmandiagramm" or "Feynman-Diagramm") // that contains an ignored word from spelling.txt (e.g., "Feynman") private boolean ignoreCompoundWithIgnoredWord(String word) throws IOException { if (!startsWithUppercase(word) && !StringUtils.startsWithAny(word, "nord", "west", "ost", "süd")) { // otherwise stuff like "rumfangreichen" gets accepted return false; } String[] words = word.split("-"); if (words.length < 2) { // non-hyphenated compound (e.g., "Feynmandiagramm"): // only search for compounds that start(!) with a word from spelling.txt int end = super.startsWithIgnoredWord(word, true); if (end < 3) { // support for geographical adjectives - although "süd/ost/west/nord" are not in spelling.txt // to accept sentences such as // "Der westperuanische Ferienort, das ostargentinische Städtchen, das südukrainische Brauchtum, der nordägyptische Staudamm." if (word.startsWith("ost") || word.startsWith("süd")) { end = 3; } else if (word.startsWith("west") || word.startsWith("nord")) { end = 4; } else { return false; } } String ignoredWord = word.substring(0, end); String partialWord = word.substring(end); partialWord = partialWord.endsWith(".") ? partialWord.substring(0, partialWord.length()-1) : partialWord; boolean isCandidateForNonHyphenatedCompound = !StringUtils.isAllUpperCase(ignoredWord) && (StringUtils.isAllLowerCase(partialWord) || ignoredWord.endsWith("-")); boolean needFugenS = isNeedingFugenS(ignoredWord); if (isCandidateForNonHyphenatedCompound && !needFugenS && partialWord.length() > 2) { return hunspell.spell(partialWord) || hunspell.spell(StringUtils.capitalize(partialWord)); } else if (isCandidateForNonHyphenatedCompound && needFugenS && partialWord.length() > 2) { partialWord = partialWord.startsWith("s") ? partialWord.substring(1) : partialWord; return hunspell.spell(partialWord) || hunspell.spell(StringUtils.capitalize(partialWord)); } return false; } // hyphenated compound (e.g., "Feynman-Diagramm"): boolean hasIgnoredWord = false; List<String> toSpellCheck = new ArrayList<>(3); String stripFirst = word.substring(words[0].length()+1); // everything after the first "-" String stripLast = word.substring(0, word.length()-words[words.length-1].length()-1); // everything up to the last "-" if (super.ignoreWord(stripFirst) || wordsToBeIgnoredInCompounds.contains(stripFirst)) { // e.g., "Senioren-Au-pair" hasIgnoredWord = true; if (!super.ignoreWord(words[0])) { toSpellCheck.add(words[0]); } } else if (super.ignoreWord(stripLast) || wordsToBeIgnoredInCompounds.contains(stripLast)) { // e.g., "Au-pair-Agentur" hasIgnoredWord = true; if (!super.ignoreWord(words[words.length-1])){ toSpellCheck.add(words[words.length-1]); } } else { for (String word1 : words) { if (super.ignoreWord(word1) || wordsToBeIgnoredInCompounds.contains(word1)) { hasIgnoredWord = true; } else { toSpellCheck.add(word1); } } } if (hasIgnoredWord) { for (String w : toSpellCheck) { if (!hunspell.spell(w)) { return false; } } } return hasIgnoredWord; } static class ExpandingReader extends BufferedReader { private final List<String> buffer = new ArrayList<>(); private final LineExpander lineExpander = new LineExpander(); ExpandingReader(Reader in) { super(in); } @Override public String readLine() throws IOException { if (buffer.isEmpty()) { String line = super.readLine(); if (line == null) { return null; } buffer.addAll(lineExpander.expandLine(line)); } return buffer.remove(0); } } @Override protected boolean isQuotedCompound(AnalyzedSentence analyzedSentence, int idx, String token) { if (idx > 3 && token.startsWith("-")) { return StringUtils.equalsAny(analyzedSentence.getTokens()[idx-1].getToken(), "“", "\"") && StringUtils.equalsAny(analyzedSentence.getTokens()[idx-3].getToken(), "„", "\""); } return false; } /* (non-Javadoc) * @see org.languagetool.rules.spelling.SpellingCheckRule#addProhibitedWords(java.util.List) */ @Override protected void addProhibitedWords(List<String> words) { if (words.size() == 1 && words.get(0).endsWith(".*")) { wordStartsToBeProhibited.add(words.get(0).substring(0, words.get(0).length()-2)); } else if (words.get(0).startsWith(".*")) { words.stream().forEach(word -> wordEndingsToBeProhibited.add(word.substring(2))); } else { super.addProhibitedWords(words); } } @Override protected List<SuggestedReplacement> filterNoSuggestWords(List<SuggestedReplacement> l) { return l.stream() .filter(k -> !lcDoNotSuggestWords.contains(k.getReplacement().toLowerCase())) .filter(k -> !k.getReplacement().toLowerCase().matches("neger.*")) .filter(k -> !k.getReplacement().toLowerCase().matches(".+neger(s|n|in|innen)?")) .collect(Collectors.toList()); } @Override protected List<SuggestedReplacement> getOnlySuggestions(String word) { if (word.matches("[Aa]utentisch(e[nmsr]?|ste[nmsr]?|ere[nmsr]?)?")) { return topMatch(word.replaceFirst("utent", "uthent")); } if (word.matches("brilliant(e[nmsr]?|ere[nmsr]?|este[nmsr]?)?")) { return topMatch(word.replaceFirst("brilliant", "brillant")); } switch (word) { case "Reiszwecke": return topMatch("Reißzwecke", "kurzer Nagel mit flachem Kopf"); case "Reiszwecken": return topMatch("Reißzwecken", "kurzer Nagel mit flachem Kopf"); case "up-to-date": return topMatch("up to date"); case "falscherweise": return topMatch("fälschlicherweise"); case "daß": return topMatch("dass"); case "Daß": return topMatch("Dass"); case "mußt": return topMatch("musst"); case "Mußt": return topMatch("Musst"); case "müßt": return topMatch("müsst"); case "Müßt": return topMatch("Müsst"); case "mußten": return topMatch("mussten"); case "mußte": return topMatch("musste"); case "mußtest": return topMatch("musstest"); case "müßtest": return topMatch("müsstest"); case "müßen": return topMatch("müssen"); case "müßten": return topMatch("müssten"); case "müßte": return topMatch("müsste"); case "wüßte": return topMatch("wüsste"); case "wüßten": return topMatch("wüssten"); case "bescheid": return topMatch("Bescheid"); case "ausversehen": return topMatch("aus Versehen"); case "Stückweit": return topMatch("Stück weit"); case "Uranium": return topMatch("Uran"); case "Uraniums": return topMatch("Urans"); case "Luxenburg": return topMatch("Luxemburg"); case "Luxenburgs": return topMatch("Luxemburgs"); case "Lichtenstein": return topMatch("Liechtenstein"); case "Lichtensteins": return topMatch("Liechtensteins"); case "immernoch": return topMatch("immer noch"); case "Rechtshcreibfehler": return topMatch("Rechtschreibfehler"); // for demo text on home page case "markirt": return topMatch("markiert"); // for demo text on home page case "Johannesbeere": return topMatch("Johannisbeere"); case "Johannesbeeren": return topMatch("Johannisbeeren"); case "Endgeld": return topMatch("Entgeld"); case "Entäuschung": return topMatch("Enttäuschung"); case "Entäuschungen": return topMatch("Enttäuschungen"); case "Triologie": return topMatch("Trilogie", "Werk (z.B. Film), das aus drei Teilen besteht"); case "ausserdem": return topMatch("außerdem"); case "Ausserdem": return topMatch("Außerdem"); case "bischen": return topMatch("bisschen"); case "bißchen": return topMatch("bisschen"); case "meißt": return topMatch("meist"); case "meißten": return topMatch("meisten"); case "meißtens": return topMatch("meistens"); case "Babyphone": return topMatch("Babyfon"); case "Baby-Phone": return topMatch("Babyfon"); case "gescheint": return topMatch("geschienen"); case "staubgesaugt": return topMatch("gestaubsaugt"); case "gedownloadet": return topMatch("downgeloadet"); case "gedownloadete": return topMatch("downgeloadete"); case "gedownloadeter": return topMatch("downgeloadeter"); case "gedownloadetes": return topMatch("downgeloadetes"); case "gedownloadeten": return topMatch("downgeloadeten"); case "gedownloadetem": return topMatch("downgeloadetem"); case "geuploadet": return topMatch("upgeloadet"); case "geuploadete": return topMatch("upgeloadete"); case "geuploadeter": return topMatch("upgeloadeter"); case "geuploadetes": return topMatch("upgeloadetes"); case "geuploadeten": return topMatch("upgeloadeten"); case "geuploadetem": return topMatch("upgeloadetem"); case "Frauenhofer": return topMatch("Fraunhofer"); case "Mwst": return topMatch("MwSt"); case "MwSt": return topMatch("MwSt."); case "exkl": return topMatch("exkl."); case "inkl": return topMatch("inkl."); case "hälst": return topMatch("hältst"); case "Rythmus": return topMatch("Rhythmus"); case "Rhytmus": return topMatch("Rhythmus"); case "Rhytmen": return topMatch("Rhythmen"); case "Hobbies": return topMatch("Hobbys"); case "Stehgreif": return topMatch("Stegreif"); case "brilliant": return topMatch("brillant"); case "brilliante": return topMatch("brillante"); case "brilliantes": return topMatch("brillantes"); case "brillianter": return topMatch("brillanter"); case "brillianten": return topMatch("brillanten"); case "brilliantem": return topMatch("brillantem"); case "Billiard": return topMatch("Billard"); case "garnicht": return topMatch("gar nicht"); case "garnich": return topMatch("gar nicht"); case "garnichts": return topMatch("gar nichts"); case "assozial": return topMatch("asozial"); case "assoziale": return topMatch("asoziale"); case "assoziales": return topMatch("asoziales"); case "assozialer": return topMatch("asozialer"); case "assozialen": return topMatch("asozialen"); case "assozialem": return topMatch("asozialem"); case "Verwandschaft": return topMatch("Verwandtschaft"); case "vorraus": return topMatch("voraus"); case "Vorraus": return topMatch("Voraus"); case "Reperatur": return topMatch("Reparatur"); case "Reperaturen": return topMatch("Reparaturen"); case "Bzgl": return topMatch("Bzgl."); case "bzgl": return topMatch("bzgl."); case "Eigtl": return topMatch("Eigtl."); case "eigtl": return topMatch("eigtl."); case "Mo-Di": return topMatch("Mo.–Di."); case "Mo-Mi": return topMatch("Mo.–Mi."); case "Mo-Do": return topMatch("Mo.–Do."); case "Mo-Fr": return topMatch("Mo.–Fr."); case "Mo-Sa": return topMatch("Mo.–Sa."); case "Mo-So": return topMatch("Mo.–So."); case "Di-Mi": return topMatch("Di.–Mi."); case "Di-Do": return topMatch("Di.–Do."); case "Di-Fr": return topMatch("Di.–Fr."); case "Di-Sa": return topMatch("Di.–Sa."); case "Di-So": return topMatch("Di.–So."); case "Mi-Do": return topMatch("Mi.–Do."); case "Mi-Fr": return topMatch("Mi.–Fr."); case "Mi-Sa": return topMatch("Mi.–Sa."); case "Mi-So": return topMatch("Mi.–So."); case "Do-Fr": return topMatch("Do.–Fr."); case "Do-Sa": return topMatch("Do.–Sa."); case "Do-So": return topMatch("Do.–So."); case "Fr-Sa": return topMatch("Fr.–Sa."); case "Fr-So": return topMatch("Fr.–So."); case "Sa-So": return topMatch("Sa.–So."); case "Achso": return topMatch("Ach so"); case "achso": return topMatch("ach so"); case "Huskies": return topMatch("Huskys"); case "Jedesmal": return topMatch("Jedes Mal"); case "jedesmal": return topMatch("jedes Mal"); case "Lybien": return topMatch("Libyen"); case "Lybiens": return topMatch("Libyens"); case "Youtube": return topMatch("YouTube"); case "Youtuber": return topMatch("YouTuber"); case "Youtuberin": return topMatch("YouTuberin"); case "Youtuberinnen": return topMatch("YouTuberinnen"); case "Youtubers": return topMatch("YouTubers"); case "Reflektion": return topMatch("Reflexion"); case "Reflektionen": return topMatch("Reflexionen"); case "unrelevant": return topMatch("irrelevant"); case "inflagranti": return topMatch("in flagranti"); case "Storie": return topMatch("Story"); case "Stories": return topMatch("Storys"); case "Ladies": return topMatch("Ladys"); case "Parties": return topMatch("Partys"); case "Lobbies": return topMatch("Lobbys"); case "Nestle": return topMatch("Nestlé"); case "Nestles": return topMatch("Nestlés"); case "vollzeit": return topMatch("Vollzeit"); case "teilzeit": return topMatch("Teilzeit"); case "Dnake": return topMatch("Danke"); case "Muehe": return topMatch("Mühe"); case "Muehen": return topMatch("Mühen"); case "Torschusspanik": return topMatch("Torschlusspanik"); case "ggf": return topMatch("ggf."); case "Ggf": return topMatch("Ggf."); case "zzgl": return topMatch("zzgl."); case "Zzgl": return topMatch("Zzgl."); case "aufgehangen": return topMatch("aufgehängt"); case "Pieks": return topMatch("Piks"); case "Piekse": return topMatch("Pikse"); case "Piekses": return topMatch("Pikses"); case "Pieksen": return topMatch("Piksen"); case "Annektion": return topMatch("Annexion"); case "Annektionen": return topMatch("Annexionen"); case "unkonsistent": return topMatch("inkonsistent"); case "Weißheitszahn": return topMatch("Weisheitszahn"); case "Weissheitszahn": return topMatch("Weisheitszahn"); case "Weißheitszahns": return topMatch("Weisheitszahns"); case "Weissheitszahns": return topMatch("Weisheitszahns"); case "Weißheitszähne": return topMatch("Weisheitszähne"); case "Weissheitszähne": return topMatch("Weisheitszähne"); case "Weißheitszähnen": return topMatch("Weisheitszähnen"); case "Weissheitszähnen": return topMatch("Weisheitszähnen"); case "raufschauen": return topMatch("draufschauen"); case "raufzuschauen": return topMatch("draufzuschauen"); case "raufgeschaut": return topMatch("draufgeschaut"); case "raufschaue": return topMatch("draufschaue"); case "raufschaust": return topMatch("draufschaust"); case "raufschaut": return topMatch("draufschaut"); case "raufschaute": return topMatch("draufschaute"); case "raufschauten": return topMatch("draufschauten"); case "raufgucken": return topMatch("draufgucken"); case "raufzugucken": return topMatch("draufzugucken"); case "raufgeguckt": return topMatch("draufgeguckt"); case "raufgucke": return topMatch("draufgucke"); case "raufguckst": return topMatch("draufguckst"); case "raufguckt": return topMatch("draufguckt"); case "raufguckte": return topMatch("draufguckte"); case "raufguckten": return topMatch("draufguckten"); case "raufhauen": return topMatch("draufhauen"); case "raufzuhauen": return topMatch("draufzuhauen"); case "raufgehaut": return topMatch("draufgehaut"); case "raufhaue": return topMatch("draufhaue"); case "raufhaust": return topMatch("draufhaust"); case "raufhaut": return topMatch("draufhaut"); case "raufhaute": return topMatch("draufhaute"); case "raufhauten": return topMatch("draufhauten"); case "wohlmöglich": return topMatch("womöglich"); case "Click": return topMatch("Klick"); case "Clicks": return topMatch("Klicks"); case "jenachdem": return topMatch("je nachdem"); case "bsp": return topMatch("bspw"); case "vorallem": return topMatch("vor allem"); case "draussen": return topMatch("draußen"); case "ürbigens": return topMatch("übrigens"); case "Whatsapp": return topMatch("WhatsApp"); case "kucken": return topMatch("gucken"); case "kuckten": return topMatch("guckten"); case "kucke": return topMatch("gucke"); case "aelter": return topMatch("älter"); case "äussern": return topMatch("äußern"); case "äusserst": return topMatch("äußerst"); case "Dnk": return topMatch("Dank"); case "schleswig-holstein": return topMatch("Schleswig-Holstein"); case "Stahlkraft": return topMatch("Strahlkraft"); case "trümmern": return topMatch("Trümmern"); case "gradeaus": return topMatch("geradeaus"); case "Anschliessend": return topMatch("Anschließend"); case "anschliessend": return topMatch("anschließend"); case "Abschliessend": return topMatch("Abschließend"); case "abschliessend": return topMatch("abschließend"); case "Ruckmeldung": return topMatch("Rückmeldung"); case "Gepaeck": return topMatch("Gepäck"); case "Grüsse": return topMatch("Grüße"); case "Grüssen": return topMatch("Grüßen"); case "entgültig": return topMatch("endgültig"); case "entgültige": return topMatch("endgültige"); case "entgültiges": return topMatch("endgültiges"); case "entgültiger": return topMatch("endgültiger"); case "entgültigen": return topMatch("endgültigen"); case "desöfteren": return topMatch("des Öfteren"); case "desweiteren": return topMatch("des Weiteren"); case "weitesgehend": return topMatch("weitestgehend"); case "Tiktok": return topMatch("TikTok"); case "Tiktoks": return topMatch("TikToks"); case "sodaß": return topMatch("sodass"); case "regelmässig": return topMatch("regelmäßig"); case "Carplay": return topMatch("CarPlay"); case "Tiktoker": return topMatch("TikToker"); case "Tiktokerin": return topMatch("TikTokerin"); case "Tiktokerinnen": return topMatch("TikTokerinnen"); case "Tiktokers": return topMatch("TikTokers"); case "Tiktokern": return topMatch("TikTokern"); case "languagetool": return topMatch("LanguageTool"); case "languagetools": return topMatch("LanguageTools"); case "Languagetool": return topMatch("LanguageTool"); case "Languagetools": return topMatch("LanguageTools"); case "liket": return topMatch("likt"); } return Collections.emptyList(); } }
[de] avoid... unlikely suggestions (#6784)
languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/GermanSpellerRule.java
[de] avoid... unlikely suggestions (#6784)
<ide><path>anguagetool-language-modules/de/src/main/java/org/languagetool/rules/de/GermanSpellerRule.java <ide> // some exceptions for changes to the spelling in 2017 - just a workaround so we don't have to touch the binary dict: <ide> private static final Pattern PREVENT_SUGGESTION = Pattern.compile( <ide> ".*(Majonäse|Bravur|Anschovis|Belkanto|Campagne|Frotté|Grisli|Jockei|Joga|Kalvinismus|Kanossa|Kargo|Ketschup|" + <del> "Kollier|Kommunikee|Masurka|Negligee|Nessessär|Poulard|Varietee|Wandalismus|kalvinist).*"); <add> "Kollier|Kommunikee|Masurka|Negligee|Nessessär|Poulard|Varietee|Wandalismus|kalvinist|[Ff]ick).*"); <ide> <ide> private static final int MAX_TOKEN_LENGTH = 200; <ide>
Java
apache-2.0
fcf04f85357a43cd2ddd1468b5b7ed09e5e1e453
0
krismcqueen/gateway,mjolie/gateway,stanculescu/gateway,irina-mitrea-luxoft/gateway,krismcqueen/gateway,Anisotrop/gateway,a-zuckut/gateway,jfallows/gateway,michaelcretzman/gateway,adrian-galbenus/gateway,mjolie/gateway,irina-mitrea-luxoft/gateway,jitsni/gateway,danibusu/gateway,AdrianCozma/gateway,veschup/gateway,nemigaservices/gateway,michaelcretzman/gateway,cmebarrow/gateway,DoruM/gateway,danibusu/gateway,kaazing/gateway,DoruM/gateway,a-zuckut/gateway,chao-sun-kaazing/gateway,jfallows/gateway,veschup/gateway,mgherghe/gateway,vmaraloiu/gateway,kaazing/gateway,vmaraloiu/gateway,stanculescu/gateway,jitsni/gateway,michaelcretzman/gateway,michaelcretzman/gateway,sanjay-saxena/gateway,sanjay-saxena/gateway,EArdeleanu/gateway,nemigaservices/gateway,sanjay-saxena/gateway,DoruM/gateway,justinma246/gateway,irina-mitrea-luxoft/gateway,mjolie/gateway,sanjay-saxena/gateway,kaazing-build/gateway,EArdeleanu/gateway,adrian-galbenus/gateway,mjolie/gateway,Anisotrop/gateway,kaazing/gateway,mgherghe/gateway,mgherghe/gateway,veschup/gateway,biddyweb/gateway,biddyweb/gateway,stanculescu/gateway,danibusu/gateway,a-zuckut/gateway,DoruM/gateway,vmaraloiu/gateway,adrian-galbenus/gateway,a-zuckut/gateway,dpwspoon/gateway,nemigaservices/gateway,AdrianCozma/gateway,cmebarrow/gateway,dpwspoon/gateway,jitsni/gateway,chao-sun-kaazing/gateway,adrian-galbenus/gateway,jfallows/gateway,vmaraloiu/gateway,cmebarrow/gateway,justinma246/gateway,EArdeleanu/gateway,cmebarrow/gateway,justinma246/gateway,justinma246/gateway,stanculescu/gateway,krismcqueen/gateway,mgherghe/gateway,kaazing-build/gateway,jfallows/gateway,irina-mitrea-luxoft/gateway,jitsni/gateway,biddyweb/gateway,danibusu/gateway,dpwspoon/gateway,kaazing/gateway,chao-sun-kaazing/gateway,chao-sun-kaazing/gateway,AdrianCozma/gateway,Anisotrop/gateway,AdrianCozma/gateway,nemigaservices/gateway,veschup/gateway,kaazing-build/gateway,EArdeleanu/gateway,dpwspoon/gateway,biddyweb/gateway,Anisotrop/gateway,kaazing-build/gateway,krismcqueen/gateway
/** * Copyright (c) 2007-2014 Kaazing Corporation. All rights reserved. * * 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.kaazing.gateway.service.http.proxy; import org.apache.mina.core.future.CloseFuture; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.core.future.IoFutureListener; import org.apache.mina.core.session.IoSession; import org.apache.mina.core.session.IoSessionInitializer; import org.kaazing.gateway.resource.address.ResourceAddress; import org.kaazing.gateway.resource.address.http.HttpResourceAddress; import org.kaazing.gateway.service.proxy.AbstractProxyAcceptHandler; import org.kaazing.gateway.service.proxy.AbstractProxyHandler; import org.kaazing.gateway.transport.IoHandlerAdapter; import org.kaazing.gateway.transport.http.DefaultHttpSession; import org.kaazing.gateway.transport.http.HttpAcceptSession; import org.kaazing.gateway.transport.http.HttpConnectSession; import org.kaazing.gateway.transport.http.HttpSession; import org.kaazing.mina.core.session.IoSessionEx; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import static org.kaazing.gateway.transport.http.HttpHeaders.HEADER_CONNECTION; import static org.kaazing.gateway.transport.http.HttpHeaders.HEADER_UPGRADE; import static org.kaazing.gateway.transport.http.HttpHeaders.HEADER_VIA; import static org.kaazing.gateway.transport.http.HttpStatus.INFO_SWITCHING_PROTOCOLS; class HttpProxyServiceHandler extends AbstractProxyAcceptHandler { private static final Logger LOGGER = LoggerFactory.getLogger("http.proxy"); private static final String VIA_HEADER_VALUE = "1.1 kaazing"; private URI connectURI; @Override protected AbstractProxyHandler createConnectHandler() { return new ConnectHandler(); } public void initServiceConnectManager() { connectURI = getConnectURIs().iterator().next(); } @Override public void sessionOpened(IoSession session) { if (!session.isClosing()) { final DefaultHttpSession acceptSession = (DefaultHttpSession) session; //final Subject subject = ((IoSessionEx) acceptSession).getSubject(); ConnectSessionInitializer sessionInitializer = new ConnectSessionInitializer(acceptSession); ConnectFuture future = getServiceContext().connect(connectURI, getConnectHandler(), sessionInitializer); future.addListener(new ConnectListener(acceptSession)); super.sessionOpened(acceptSession); } } /* * Initializer for connect session. It adds the processed accept session headers * on the connect session */ private static class ConnectSessionInitializer implements IoSessionInitializer<ConnectFuture> { private final DefaultHttpSession acceptSession; ConnectSessionInitializer(DefaultHttpSession acceptSession) { this.acceptSession = acceptSession; } @Override public void initializeSession(IoSession session, ConnectFuture future) { HttpConnectSession connectSession = (HttpConnectSession) session; connectSession.setVersion(acceptSession.getVersion()); connectSession.setMethod(acceptSession.getMethod()); connectSession.setRequestURI(acceptSession.getRequestURI()); processRequestHeaders(acceptSession, connectSession); } } private class ConnectListener implements IoFutureListener<ConnectFuture> { private final DefaultHttpSession acceptSession; ConnectListener(DefaultHttpSession acceptSession) { this.acceptSession = acceptSession; } @Override public void operationComplete(ConnectFuture future) { if (future.isConnected()) { DefaultHttpSession connectSession = (DefaultHttpSession)future.getSession(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Connected to " + getConnectURIs().iterator().next() + " ["+acceptSession+"->"+connectSession+"]"); } if (acceptSession == null || acceptSession.isClosing()) { connectSession.close(true); } else { AttachedSessionManager attachedSessionManager = attachSessions(acceptSession, connectSession); connectSession.getCloseFuture().addListener(new Upgrader(connectSession, acceptSession)); acceptSession.getCloseFuture().addListener(new Upgrader(acceptSession, connectSession)); flushQueuedMessages(acceptSession, attachedSessionManager); } } else { LOGGER.warn("Connection to " + getConnectURIs().iterator().next() + " failed ["+acceptSession+"->]"); acceptSession.close(true); } } } private static class ConnectHandler extends AbstractProxyHandler { @Override public void messageReceived(IoSession session, Object message) { processResponseHeaders(session); super.messageReceived(session, message); } @Override public void sessionClosed(IoSession session) { processResponseHeaders(session); super.sessionClosed(session); } private void processResponseHeaders(IoSession session) { HttpConnectSession connectSession = (HttpConnectSession) session; AttachedSessionManager attachedSessionManager = getAttachedSessionManager(session); if (attachedSessionManager != null) { HttpAcceptSession acceptSession = (HttpAcceptSession) attachedSessionManager.getAttachedSession(); if (acceptSession.getWrittenBytes() == 0L && !acceptSession.isCommitting() && !acceptSession.isClosing()) { acceptSession.setStatus(connectSession.getStatus()); acceptSession.setReason(connectSession.getReason()); acceptSession.setVersion(connectSession.getVersion()); boolean upgrade = processHopByHopHeaders(connectSession, acceptSession); // Add Connection: upgrade to acceptSession if (upgrade) { acceptSession.setWriteHeader(HEADER_CONNECTION, HEADER_UPGRADE); } } } } } /* * Write all (except hop-by-hop) headers from source session to destination * session. * * If the header is an upgrade one, let the Upgrade header go through as this * service supports upgrade */ private static boolean processHopByHopHeaders(HttpSession src, HttpSession dest) { Set<String> hopByHopHeaders = getHopByHopHeaders(src); boolean upgrade = src.getReadHeader(HEADER_UPGRADE) != null; if (upgrade) { hopByHopHeaders.remove(HEADER_UPGRADE); } // Add source session headers to destination session for(Map.Entry<String, List<String>> e : src.getReadHeaders().entrySet()) { String name = e.getKey(); for(String value : e.getValue()) { if (!hopByHopHeaders.contains(name)) { dest.addWriteHeader(name, value); } } } return upgrade; } /* * Write all (except hop-by-hop) request headers from accept session to connect session. * If the request is an upgrade one, let the Upgrade header go through as this * service supports upgrade */ private static void processRequestHeaders(HttpAcceptSession acceptSession, HttpConnectSession connectSession) { boolean upgrade = processHopByHopHeaders(acceptSession, connectSession); // Add Connection: upgrade or Connection: close header if (upgrade) { connectSession.setWriteHeader(HEADER_CONNECTION, HEADER_UPGRADE); } else { ResourceAddress address = connectSession.getRemoteAddress(); // If keep-alive is disabled, add Connection: close header if (!address.getOption(HttpResourceAddress.KEEP_ALIVE)) { connectSession.setWriteHeader(HEADER_CONNECTION, "close"); } } // Add Via: 1.1 kaazing header connectSession.addWriteHeader(HEADER_VIA, VIA_HEADER_VALUE); } /* * Get all hop-by-hop headers from Connection header value. * Also add Connection header itself to the set */ private static Set<String> getHopByHopHeaders(HttpSession session) { List<String> connectionHeaders = session.getReadHeaders(HEADER_CONNECTION); if (connectionHeaders == null) { connectionHeaders = Collections.emptyList(); } Set<String> hopByHopHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); for(String conHeader : connectionHeaders) { hopByHopHeaders.add(conHeader); } hopByHopHeaders.add(HEADER_CONNECTION); return hopByHopHeaders; } /* * An upgrade handler that connects transport sessions of http accept and connect * sessions. */ private static class ProxyUpgradeHandler extends IoHandlerAdapter<IoSessionEx> { final IoSession attachedSession; ProxyUpgradeHandler(IoSession attachedSession) { this.attachedSession = attachedSession; } @Override protected void doSessionOpened(final IoSessionEx session) throws Exception { session.resumeRead(); } @Override protected void doMessageReceived(IoSessionEx session, Object message) throws Exception { attachedSession.write(message); } @Override protected void doExceptionCaught(IoSessionEx session, Throwable cause) throws Exception { attachedSession.close(false); } @Override protected void doSessionClosed(IoSessionEx session) throws Exception { attachedSession.close(false); } } /* * A close listener that upgrades underlying transport connection * at the end of http session close. */ private static class Upgrader implements IoFutureListener<CloseFuture> { private final DefaultHttpSession session; private final DefaultHttpSession attachedSession; Upgrader(DefaultHttpSession session, DefaultHttpSession attachedSession) { this.session = session; this.attachedSession = attachedSession; } @Override public void operationComplete(CloseFuture future) { if (session.getStatus() == INFO_SWITCHING_PROTOCOLS) { ProxyUpgradeHandler handler = new ProxyUpgradeHandler(attachedSession.getParent()); session.suspendRead(); if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("http.proxy service is upgrading session %s", session)); } session.upgrade(handler); } } } }
service/http.proxy/src/main/java/org/kaazing/gateway/service/http/proxy/HttpProxyServiceHandler.java
/** * Copyright (c) 2007-2014 Kaazing Corporation. All rights reserved. * * 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.kaazing.gateway.service.http.proxy; import org.apache.mina.core.future.CloseFuture; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.core.future.IoFutureListener; import org.apache.mina.core.session.IoSession; import org.apache.mina.core.session.IoSessionInitializer; import org.kaazing.gateway.resource.address.ResourceAddress; import org.kaazing.gateway.resource.address.http.HttpResourceAddress; import org.kaazing.gateway.service.proxy.AbstractProxyAcceptHandler; import org.kaazing.gateway.service.proxy.AbstractProxyHandler; import org.kaazing.gateway.transport.IoHandlerAdapter; import org.kaazing.gateway.transport.http.DefaultHttpSession; import org.kaazing.gateway.transport.http.HttpAcceptSession; import org.kaazing.gateway.transport.http.HttpConnectSession; import org.kaazing.gateway.transport.http.HttpSession; import org.kaazing.mina.core.session.IoSessionEx; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import static org.kaazing.gateway.transport.http.HttpHeaders.HEADER_CONNECTION; import static org.kaazing.gateway.transport.http.HttpHeaders.HEADER_UPGRADE; import static org.kaazing.gateway.transport.http.HttpHeaders.HEADER_VIA; import static org.kaazing.gateway.transport.http.HttpStatus.INFO_SWITCHING_PROTOCOLS; class HttpProxyServiceHandler extends AbstractProxyAcceptHandler { private static final Logger LOGGER = LoggerFactory.getLogger("http.proxy"); private static final String VIA_HEADER_VALUE = "1.1 kaazing"; private URI connectURI; @Override protected AbstractProxyHandler createConnectHandler() { return new ConnectHandler(); } public void initServiceConnectManager() { connectURI = getConnectURIs().iterator().next(); } @Override public void sessionOpened(IoSession session) { if (!session.isClosing()) { final DefaultHttpSession acceptSession = (DefaultHttpSession) session; //final Subject subject = ((IoSessionEx) acceptSession).getSubject(); ConnectSessionInitializer sessionInitializer = new ConnectSessionInitializer(acceptSession); ConnectFuture future = getServiceContext().connect(connectURI, getConnectHandler(), sessionInitializer); future.addListener(new ConnectListener(acceptSession)); super.sessionOpened(acceptSession); } } /* * Initializer for connect session. It adds the processed accept session headers * on the connect session */ private static class ConnectSessionInitializer implements IoSessionInitializer<ConnectFuture> { private final DefaultHttpSession acceptSession; ConnectSessionInitializer(DefaultHttpSession acceptSession) { this.acceptSession = acceptSession; } @Override public void initializeSession(IoSession session, ConnectFuture future) { HttpConnectSession connectSession = (HttpConnectSession) session; connectSession.setVersion(acceptSession.getVersion()); connectSession.setMethod(acceptSession.getMethod()); connectSession.setRequestURI(acceptSession.getRequestURI()); processRequestHeaders(acceptSession, connectSession); } } private class ConnectListener implements IoFutureListener<ConnectFuture> { private final DefaultHttpSession acceptSession; ConnectListener(DefaultHttpSession acceptSession) { this.acceptSession = acceptSession; } @Override public void operationComplete(ConnectFuture future) { if (future.isConnected()) { DefaultHttpSession connectSession = (DefaultHttpSession)future.getSession(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Connected to " + getConnectURIs().iterator().next() + " ["+acceptSession+"->"+connectSession+"]"); } if (acceptSession == null || acceptSession.isClosing()) { connectSession.close(true); } else { AttachedSessionManager attachedSessionManager = attachSessions(acceptSession, connectSession); connectSession.getCloseFuture().addListener(new Upgrader(connectSession, acceptSession)); acceptSession.getCloseFuture().addListener(new Upgrader(acceptSession, connectSession)); flushQueuedMessages(acceptSession, attachedSessionManager); } } else { LOGGER.warn("Connection to " + getConnectURIs().iterator().next() + " failed ["+acceptSession+"->]"); acceptSession.close(true); } } } private static class ConnectHandler extends AbstractProxyHandler { @Override public void messageReceived(IoSession session, Object message) { processResponseHeaders(session); super.messageReceived(session, message); } @Override public void sessionClosed(IoSession session) { processResponseHeaders(session); super.sessionClosed(session); } private void processResponseHeaders(IoSession session) { HttpConnectSession connectSession = (HttpConnectSession) session; AttachedSessionManager attachedSessionManager = getAttachedSessionManager(session); if (attachedSessionManager != null) { HttpAcceptSession acceptSession = (HttpAcceptSession) attachedSessionManager.getAttachedSession(); if (acceptSession.getWrittenBytes() == 0L && !acceptSession.isCommitting() && !acceptSession.isClosing()) { acceptSession.setStatus(connectSession.getStatus()); acceptSession.setReason(connectSession.getReason()); acceptSession.setVersion(connectSession.getVersion()); boolean upgrade = processHopByHopHeaders(connectSession, acceptSession); // Add Connection: upgrade if (upgrade) { acceptSession.setWriteHeader(HEADER_CONNECTION, HEADER_UPGRADE); } } } } } /* * Write all (except hop-by-hop) request headers from source session to destination * session. * * If the request is an upgrade one, let the Upgrade header go through as this * service supports upgrade */ private static boolean processHopByHopHeaders(HttpSession src, HttpSession dest) { Set<String> hopByHopHeaders = getHopByHopHeaders(src); boolean upgrade = src.getReadHeader(HEADER_UPGRADE) != null; if (upgrade) { hopByHopHeaders.remove(HEADER_UPGRADE); } // Add accept session headers to connect session for(Map.Entry<String, List<String>> e : src.getReadHeaders().entrySet()) { String name = e.getKey(); for(String value : e.getValue()) { if (!hopByHopHeaders.contains(name)) { dest.addWriteHeader(name, value); } } } return upgrade; } /* * Write all (except hop-by-hop) request headers from accept session to connect session. * If the request is an upgrade one, let the Upgrade header go through as this * service supports upgrade */ private static void processRequestHeaders(HttpAcceptSession acceptSession, HttpConnectSession connectSession) { boolean upgrade = processHopByHopHeaders(acceptSession, connectSession); // Add Connection: upgrade or Connection: close header if (upgrade) { connectSession.setWriteHeader(HEADER_CONNECTION, HEADER_UPGRADE); } else { ResourceAddress address = connectSession.getRemoteAddress(); // If keep-alive is disabled, add Connection: close header if (!address.getOption(HttpResourceAddress.KEEP_ALIVE)) { connectSession.setWriteHeader(HEADER_CONNECTION, "close"); } } // Add Via: 1.1 kaazing header connectSession.addWriteHeader(HEADER_VIA, VIA_HEADER_VALUE); } /* * Get all hop-by-hop headers from Connection header value. * Also add Connection header itself to the set */ private static Set<String> getHopByHopHeaders(HttpSession session) { List<String> connectionHeaders = session.getReadHeaders(HEADER_CONNECTION); if (connectionHeaders == null) { connectionHeaders = Collections.emptyList(); } Set<String> hopByHopHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); for(String conHeader : connectionHeaders) { hopByHopHeaders.add(conHeader); } hopByHopHeaders.add(HEADER_CONNECTION); return hopByHopHeaders; } /* * An upgrade handler that connects transport sessions of http accept and connect * sessions. */ private static class ProxyUpgradeHandler extends IoHandlerAdapter<IoSessionEx> { final IoSession attachedSession; ProxyUpgradeHandler(IoSession attachedSession) { this.attachedSession = attachedSession; } @Override protected void doSessionOpened(final IoSessionEx session) throws Exception { session.resumeRead(); } @Override protected void doMessageReceived(IoSessionEx session, Object message) throws Exception { attachedSession.write(message); } @Override protected void doExceptionCaught(IoSessionEx session, Throwable cause) throws Exception { attachedSession.close(false); } @Override protected void doSessionClosed(IoSessionEx session) throws Exception { attachedSession.close(false); } } /* * A close listener that upgrades underlying transport connection * at the end of http session close. */ private static class Upgrader implements IoFutureListener<CloseFuture> { private final DefaultHttpSession session; private final DefaultHttpSession attachedSession; Upgrader(DefaultHttpSession session, DefaultHttpSession attachedSession) { this.session = session; this.attachedSession = attachedSession; } @Override public void operationComplete(CloseFuture future) { if (session.getStatus() == INFO_SWITCHING_PROTOCOLS) { ProxyUpgradeHandler handler = new ProxyUpgradeHandler(attachedSession.getParent()); session.suspendRead(); if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("http.proxy service is upgrading session %s", session)); } session.upgrade(handler); } } } }
Some comments are fixed
service/http.proxy/src/main/java/org/kaazing/gateway/service/http/proxy/HttpProxyServiceHandler.java
Some comments are fixed
<ide><path>ervice/http.proxy/src/main/java/org/kaazing/gateway/service/http/proxy/HttpProxyServiceHandler.java <ide> acceptSession.setVersion(connectSession.getVersion()); <ide> <ide> boolean upgrade = processHopByHopHeaders(connectSession, acceptSession); <del> // Add Connection: upgrade <add> // Add Connection: upgrade to acceptSession <ide> if (upgrade) { <ide> acceptSession.setWriteHeader(HEADER_CONNECTION, HEADER_UPGRADE); <ide> } <ide> <ide> <ide> /* <del> * Write all (except hop-by-hop) request headers from source session to destination <add> * Write all (except hop-by-hop) headers from source session to destination <ide> * session. <ide> * <del> * If the request is an upgrade one, let the Upgrade header go through as this <add> * If the header is an upgrade one, let the Upgrade header go through as this <ide> * service supports upgrade <ide> */ <ide> private static boolean processHopByHopHeaders(HttpSession src, HttpSession dest) { <ide> hopByHopHeaders.remove(HEADER_UPGRADE); <ide> } <ide> <del> // Add accept session headers to connect session <add> // Add source session headers to destination session <ide> for(Map.Entry<String, List<String>> e : src.getReadHeaders().entrySet()) { <ide> String name = e.getKey(); <ide> for(String value : e.getValue()) {
Java
apache-2.0
67f3dc669a33c1c549c133123bfa2fb9282dcf6c
0
realityforge/replicant,realityforge/replicant
package org.realityforge.replicant.client.runtime; import arez.annotations.Action; import arez.annotations.Observable; import arez.component.RepositoryUtil; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nonnull; import org.realityforge.replicant.client.transport.DataLoaderListenerAdapter; import org.realityforge.replicant.client.transport.DataLoaderService; public abstract class ReplicantClientSystem { public enum State { /// The service is not yet connected or has been disconnected DISCONNECTED, /// The service has started connecting but connection has not completed. CONNECTING, /// The service is connected. CONNECTED, /// The service has started disconnecting but disconnection has not completed. DISCONNECTING, /// The service is in error state. This error may occur during connection, disconnection or in normal operation. ERROR } protected static final int CONVERGE_DELAY_IN_MS = 2000; private static final Logger LOG = Logger.getLogger( ReplicantClientSystem.class.getName() ); private final Listener _dataLoaderListener = new Listener(); private DataLoaderEntry[] _dataLoaders; private State _state = State.DISCONNECTED; /** * If true then the desired state is CONNECTED while if false then the desired state is DISCONNECTED. */ private boolean _active; public ReplicantClientSystem( final DataLoaderEntry[] dataLoaders ) { _dataLoaders = Objects.requireNonNull( dataLoaders ); addListener(); } /** * Release resources associated with the system. */ protected void release() { removeListener(); } /** * Returns true if the system is expected to be active and connected to all data sources. * This is a desired state rather than an actual state that is represented by {@link #getState()} */ public boolean isActive() { return _active; } /** * Return the actual state of the system. */ @Observable public State getState() { return _state; } protected void setState( @Nonnull final State state ) { _state = Objects.requireNonNull( state ); } /** * Mark the client system as active and start to converge to being CONNECTED. */ public void activate() { setActive( true ); } /** * Mark the client system as inactive and start to converge to being DISCONNECTED. */ public void deactivate() { setActive( false ); } /** * Attempt to converge the state of the system towards the desired state. * This should be invoked periodically. */ public void converge() { updateStatus(); reflectActiveState(); } @Nonnull public List<DataLoaderEntry> getDataLoaders() { return RepositoryUtil.toResults( Arrays.asList( _dataLoaders ) ); } /** * Retrieve the dataloader service associated with the channelType. */ @Nonnull public DataLoaderService getDataLoaderService( @Nonnull final Enum channelType ) throws IllegalArgumentException { for ( final DataLoaderEntry dataLoader : _dataLoaders ) { if ( dataLoader.getService().getSystemType().equals( channelType.getClass() ) ) { return dataLoader.getService(); } } throw new IllegalArgumentException(); } private void setActive( final boolean active ) { _active = active; reflectActiveState(); } private void reflectActiveState() { if ( isActive() ) { doActivate(); } else if ( !isActive() ) { doDeactivate(); } } private void doActivate() { for ( final DataLoaderEntry dataLoader : _dataLoaders ) { final DataLoaderService service = dataLoader.getService(); final DataLoaderService.State state = service.getState(); if ( !isTransitionState( state ) && DataLoaderService.State.CONNECTED != state ) { dataLoader.attemptAction( this::doConnectDataLoaderService ); } } } private void doConnectDataLoaderService( @Nonnull final DataLoaderService service ) { LOG.info( "Connecting " + service + ". Initial state: " + service.getState() ); service.connect(); } private boolean isTransitionState( @Nonnull final DataLoaderService.State state ) { return DataLoaderService.State.DISCONNECTING == state || DataLoaderService.State.CONNECTING == state; } private void doDeactivate() { for ( final DataLoaderEntry dataLoader : _dataLoaders ) { final DataLoaderService service = dataLoader.getService(); final DataLoaderService.State state = service.getState(); if ( !isTransitionState( state ) && DataLoaderService.State.DISCONNECTED != state && DataLoaderService.State.ERROR != state ) { dataLoader.attemptAction( this::doDisconnectDataLoaderService ); } } } private void doDisconnectDataLoaderService( final DataLoaderService service ) { final String message = "Disconnecting " + service + ". Initial state: " + service.getState(); LOG.info( message ); service.disconnect(); } @Action protected void updateStatus() { // Are any required connecting? boolean connecting = false; // Are any required disconnecting? boolean disconnecting = false; // Are any required disconnecting? boolean disconnected = false; // Are any required in error? boolean error = false; for ( final DataLoaderEntry entry : _dataLoaders ) { if ( entry.isRequired() ) { final DataLoaderService.State state = entry.getService().getState(); if ( DataLoaderService.State.DISCONNECTED == state ) { disconnected = true; } else if ( DataLoaderService.State.DISCONNECTING == state ) { disconnecting = true; } else if ( DataLoaderService.State.CONNECTING == state ) { connecting = true; } else if ( DataLoaderService.State.ERROR == state ) { error = true; } } } if ( error ) { setState( State.ERROR ); } else if ( disconnected ) { setState( State.DISCONNECTED ); } else if ( disconnecting ) { setState( State.DISCONNECTING ); } else if ( connecting ) { setState( State.CONNECTING ); } else { setState( State.CONNECTED ); } reflectActiveState(); } private void disconnectIfPossible( @Nonnull final DataLoaderService service, @Nonnull final Throwable cause ) { LOG.log( Level.INFO, "Attempting to disconnect " + service + " and restart.", cause ); if ( !isTransitionState( service.getState() ) ) { service.disconnect(); } updateStatus(); } @Nonnull private Listener getDataLoaderListener() { return _dataLoaderListener; } private void addListener() { for ( final DataLoaderEntry dataLoader : _dataLoaders ) { dataLoader.getService().addDataLoaderListener( getDataLoaderListener() ); } } private void removeListener() { if ( null != _dataLoaders ) { for ( final DataLoaderEntry dataLoader : _dataLoaders ) { dataLoader.getService().removeDataLoaderListener( getDataLoaderListener() ); } } } final class Listener extends DataLoaderListenerAdapter { @Override public void onDisconnect( @Nonnull final DataLoaderService service ) { updateStatus(); } @Override public void onInvalidDisconnect( @Nonnull final DataLoaderService service, @Nonnull final Throwable throwable ) { updateStatus(); } @Override public void onConnect( @Nonnull final DataLoaderService service ) { updateStatus(); } @Override public void onInvalidConnect( @Nonnull final DataLoaderService service, @Nonnull final Throwable throwable ) { LOG.log( Level.INFO, "InvalidConnect: Error connecting " + service + ": " + throwable.toString() ); updateStatus(); } @Override public void onDataLoadFailure( @Nonnull final DataLoaderService service, @Nonnull final Throwable throwable ) { disconnectIfPossible( service, throwable ); } @Override public void onPollFailure( @Nonnull final DataLoaderService service, @Nonnull final Throwable throwable ) { disconnectIfPossible( service, throwable ); } } }
client/src/main/java/org/realityforge/replicant/client/runtime/ReplicantClientSystem.java
package org.realityforge.replicant.client.runtime; import arez.annotations.Action; import arez.annotations.Observable; import arez.component.RepositoryUtil; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nonnull; import org.realityforge.replicant.client.transport.DataLoaderListenerAdapter; import org.realityforge.replicant.client.transport.DataLoaderService; public abstract class ReplicantClientSystem { public enum State { /// The service is not yet connected or has been disconnected DISCONNECTED, /// The service has started connecting but connection has not completed. CONNECTING, /// The service is connected. CONNECTED, /// The service has started disconnecting but disconnection has not completed. DISCONNECTING, /// The service is in error state. This error may occur during connection, disconnection or in normal operation. ERROR } protected static final int CONVERGE_DELAY_IN_MS = 2000; private static final Logger LOG = Logger.getLogger( ReplicantClientSystem.class.getName() ); private final Listener _dataLoaderListener = new Listener(); private DataLoaderEntry[] _dataLoaders; private State _state = State.DISCONNECTED; /** * If true then the desired state is CONNECTED while if false then the desired state is DISCONNECTED. */ private boolean _active; public ReplicantClientSystem( final DataLoaderEntry[] dataLoaders ) { _dataLoaders = Objects.requireNonNull( dataLoaders ); addListener(); } /** * Release resources associated with the system. */ protected void release() { removeListener(); } /** * Returns true if the system is expected to be active and connected to all data sources. * This is a desired state rather than an actual state that is represented by {@link #getState()} */ public boolean isActive() { return _active; } /** * Return the actual state of the system. */ @Observable public State getState() { return _state; } protected void setState( @Nonnull final State state ) { _state = Objects.requireNonNull( state ); } /** * Mark the client system as active and start to converge to being CONNECTED. */ public void activate() { setActive( true ); } /** * Mark the client system as inactive and start to converge to being DISCONNECTED. */ public void deactivate() { setActive( false ); } /** * Attempt to converge the state of the system towards the desired state. * This should be invoked periodically. */ public void converge() { updateStatus(); reflectActiveState(); } @Nonnull public List<DataLoaderEntry> getDataLoaders() { return RepositoryUtil.toResults( Arrays.asList( _dataLoaders ) ); } /** * Retrieve the dataloader service associated with the channelType. */ @Nonnull public DataLoaderService getDataLoaderService( @Nonnull final Enum channelType ) throws IllegalArgumentException { for ( final DataLoaderEntry dataLoader : _dataLoaders ) { if ( dataLoader.getService().getSystemType().equals( channelType.getClass() ) ) { return dataLoader.getService(); } } throw new IllegalArgumentException(); } private void setActive( final boolean active ) { _active = active; reflectActiveState(); } private void reflectActiveState() { if ( isActive() ) { doActivate(); } else if ( !isActive() ) { doDeactivate(); } } private void doActivate() { for ( final DataLoaderEntry dataLoader : _dataLoaders ) { final DataLoaderService service = dataLoader.getService(); final DataLoaderService.State state = service.getState(); if ( !isTransitionState( state ) && DataLoaderService.State.CONNECTED != state ) { dataLoader.attemptAction( this::doConnectDataLoaderService ); } } } private void doConnectDataLoaderService( @Nonnull final DataLoaderService service ) { LOG.info( "Connecting " + service + ". Initial state: " + service.getState() ); service.connect(); } private boolean isTransitionState( @Nonnull final DataLoaderService.State state ) { return DataLoaderService.State.DISCONNECTING == state || DataLoaderService.State.CONNECTING == state; } private void doDeactivate() { for ( final DataLoaderEntry dataLoader : _dataLoaders ) { final DataLoaderService service = dataLoader.getService(); final DataLoaderService.State state = service.getState(); if ( !isTransitionState( state ) && DataLoaderService.State.DISCONNECTED != state && DataLoaderService.State.ERROR != state ) { dataLoader.attemptAction( this::doDisconnectDataLoaderService ); } } } private void doDisconnectDataLoaderService( final DataLoaderService service ) { final String message = "Disconnecting " + service + ". Initial state: " + service.getState(); LOG.info( message ); service.disconnect(); } @Action protected void updateStatus() { // Are any required connecting? boolean connecting = false; // Are any required disconnecting? boolean disconnecting = false; // Are any required disconnecting? boolean disconnected = false; // Are any required in error? boolean error = false; for ( final DataLoaderEntry entry : _dataLoaders ) { if ( entry.isRequired() ) { final DataLoaderService.State state = entry.getService().getState(); if ( DataLoaderService.State.DISCONNECTED == state ) { disconnected = true; } else if ( DataLoaderService.State.DISCONNECTING == state ) { disconnecting = true; } else if ( DataLoaderService.State.CONNECTING == state ) { connecting = true; } else if ( DataLoaderService.State.ERROR == state ) { error = true; } } } if ( error ) { setState( State.ERROR ); } else if ( disconnected ) { setState( State.DISCONNECTED ); } else if ( disconnecting ) { setState( State.DISCONNECTING ); } else if ( connecting ) { setState( State.CONNECTING ); } else { setState( State.CONNECTED ); } reflectActiveState(); } private void disconnectIfPossible( @Nonnull final DataLoaderService service ) { if ( !isTransitionState( service.getState() ) ) { service.disconnect(); } updateStatus(); } @Nonnull private Listener getDataLoaderListener() { return _dataLoaderListener; } private void addListener() { for ( final DataLoaderEntry dataLoader : _dataLoaders ) { dataLoader.getService().addDataLoaderListener( getDataLoaderListener() ); } } private void removeListener() { if ( null != _dataLoaders ) { for ( final DataLoaderEntry dataLoader : _dataLoaders ) { dataLoader.getService().removeDataLoaderListener( getDataLoaderListener() ); } } } final class Listener extends DataLoaderListenerAdapter { @Override public void onDisconnect( @Nonnull final DataLoaderService service ) { updateStatus(); } @Override public void onInvalidDisconnect( @Nonnull final DataLoaderService service, @Nonnull final Throwable throwable ) { updateStatus(); } @Override public void onConnect( @Nonnull final DataLoaderService service ) { updateStatus(); } @Override public void onInvalidConnect( @Nonnull final DataLoaderService service, @Nonnull final Throwable throwable ) { LOG.log( Level.INFO, "InvalidConnect: Error connecting " + service + ": " + throwable.toString() ); updateStatus(); } @Override public void onDataLoadFailure( @Nonnull final DataLoaderService service, @Nonnull final Throwable throwable ) { LOG.log( Level.INFO, "DataLoadFailure: Attempting to disconnect " + service + " and restart.", throwable ); disconnectIfPossible( service ); } @Override public void onPollFailure( @Nonnull final DataLoaderService service, @Nonnull final Throwable throwable ) { LOG.log( Level.INFO, "PollFailure: Attempting to disconnect " + service + " and restart.", throwable ); disconnectIfPossible( service ); } } }
Move logging into disconnectIfPossible
client/src/main/java/org/realityforge/replicant/client/runtime/ReplicantClientSystem.java
Move logging into disconnectIfPossible
<ide><path>lient/src/main/java/org/realityforge/replicant/client/runtime/ReplicantClientSystem.java <ide> reflectActiveState(); <ide> } <ide> <del> private void disconnectIfPossible( @Nonnull final DataLoaderService service ) <del> { <add> private void disconnectIfPossible( @Nonnull final DataLoaderService service, @Nonnull final Throwable cause ) <add> { <add> LOG.log( Level.INFO, "Attempting to disconnect " + service + " and restart.", cause ); <ide> if ( !isTransitionState( service.getState() ) ) <ide> { <ide> service.disconnect(); <ide> @Override <ide> public void onDataLoadFailure( @Nonnull final DataLoaderService service, @Nonnull final Throwable throwable ) <ide> { <del> LOG.log( Level.INFO, <del> "DataLoadFailure: Attempting to disconnect " + service + " and restart.", <del> throwable ); <del> disconnectIfPossible( service ); <add> disconnectIfPossible( service, throwable ); <ide> } <ide> <ide> @Override <ide> public void onPollFailure( @Nonnull final DataLoaderService service, @Nonnull final Throwable throwable ) <ide> { <del> LOG.log( Level.INFO, <del> "PollFailure: Attempting to disconnect " + service + " and restart.", <del> throwable ); <del> disconnectIfPossible( service ); <add> disconnectIfPossible( service, throwable ); <ide> } <ide> } <ide> }
JavaScript
mit
b564866f2a05e3e4d8a334d73863c3d6389db701
0
datadesk/web-map-maker,datadesk/web-map-maker
// var fs = require('fs'); // var jsdom = require('jsdom'); // var d3 = require('d3'); // var XMLHttpRequest = require('xhr2') window.addEventListener('unhandledrejection', event => { // Prevent error output on the console: event.preventDefault(); console.log('Reason: ' + event.reason); }); window.addEventListener('rejectionhandled', event => { console.log('REJECTIONHANDLED'); }); // set up land use groups for LAT var landusePark = ['national_park', 'battlefield', 'protected_area', 'nature_reserve', 'park', 'golf_course', 'recreation_ground', 'camp_site', 'garden', 'allotments', 'pitch', 'meadow', 'village_green', 'farmland', 'playground', 'attraction', 'artwork', 'wilderness_hut', 'hanami'], landuseForest = ['forest', 'wood', 'natural_wood', 'natural_forest'], landuseAirport = ['aerodrome'], landuseMilitary = ['military'], landuseUniversity = ['university', 'college'], landuseSchool = ['school'], landuseCemetery = ['cemetery', 'place_of_worship'], landuseHospital = ['hospital'], landuseStadium = ['stadium'], landuseResort = ['theme_park', 'resort', 'aquarium', 'winery', 'maze'], landuseBeach = ['beach']; function setupJson(mapObject) { console.info('setupJson()') console.log(mapObject); var formattedJson = {}; var dataKind = mapObject.dKinds.join(','); // ocean if (mapObject.options.layers_visible.indexOf('water_visible_ocean') != -1) { formattedJson['ocean'] = { oceanwater: { features: [] } } } // earth formattedJson['earth'] = { earthland: { features: [] } } // landuse if (mapObject.options.layers_visible.indexOf('landuse_visible') != -1) { formattedJson['landuse'] = {} if (mapObject.options.layers_visible.indexOf('landuse_visible_airports') != -1) { formattedJson['landuse']['airport'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_beach') != -1) { formattedJson['landuse']['beach'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_cemetery') != -1) { formattedJson['landuse']['cemetery'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_college') != -1) { formattedJson['landuse']['university'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_forest') != -1) { formattedJson['landuse']['forest'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_hospital') != -1) { formattedJson['landuse']['hospital'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_military') != -1) { formattedJson['landuse']['military'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_park') != -1) { formattedJson['landuse']['park'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_resort') != -1) { formattedJson['landuse']['resort'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_school') != -1) { formattedJson['landuse']['school'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_stadium') != -1) { formattedJson['landuse']['stadium'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_prison') != -1) { formattedJson['landuse']['prison'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_wetland') != -1) { formattedJson['landuse']['wetland'] = { features: [] } } formattedJson['landuse']['pier'] = { features: [] } } // landuse // borders if (mapObject.options.layers_visible.indexOf('borders_visible') != -1) { formattedJson['boundaries'] = {} if (mapObject.options.layers_visible.indexOf('borders_visible_countries') != -1) { formattedJson['boundaries']['country'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('borders_visible_disputed') != -1) { formattedJson['boundaries']['disputed'] = { features: [] } formattedJson['boundaries']['indefinite'] = { features: [] } formattedJson['boundaries']['interminate'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('borders_visible_states') != -1) { formattedJson['boundaries']['region'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('borders_visible_counties') != -1) { formattedJson['boundaries']['county'] = { features: [] } } } // water if (mapObject.options.layers_visible.indexOf('water_visible') != -1) { formattedJson['water'] = {} if (mapObject.options.layers_visible.indexOf('water_visible_inland_water') != -1) { formattedJson['water']['bay'] = { features: [] } formattedJson['water']['lake'] = { features: [] } formattedJson['water']['river'] = { features: [] } formattedJson['water']['riverbank'] = { features: [] } formattedJson['water']['stream'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('water_visible_swimming_pools') != -1) { formattedJson['water']['swimming_pool'] = { features: [] } } // need etc to grab other water formattedJson['water']['wateretc'] = { features: [] } } // buildings if (mapObject.options.layers_visible.indexOf('buildings_visible') != -1) { formattedJson['buildings'] = { building: { features: [] } } } // transit if (mapObject.options.layers_visible.indexOf('transit_visible') != -1 || mapObject.options.layers_visible.indexOf('rail_visible') != -1) { formattedJson['transit'] = {} if (mapObject.options.layers_visible.indexOf('transit_visible') != -1) { formattedJson['transit']['light_rail'] = { features: [] } formattedJson['transit']['subway'] = { features: [] } formattedJson['transit']['station'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('rail_visible') != -1) { formattedJson['transit']['rail'] = { features: [] } } } // roads if (mapObject.options.layers_visible.indexOf('roads_visible') != -1) { formattedJson['roads'] = {} if (mapObject.options.layers_visible.indexOf('roads_visible_ferry_route') != -1) { formattedJson['roads']['ferry'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('roads_visible_taxi_and_runways') != -1) { formattedJson['roads']['taxiway'] = { features: [] } formattedJson['roads']['runway'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('roads_visible_service') != -1) { formattedJson['roads']['service'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('roads_visible_minor') != -1) { formattedJson['roads']['minor_road'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('roads_visible_major') != -1) { formattedJson['roads']['major_road'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('roads_visible_highway_ramps') != -1) { formattedJson['roads']['highway_link'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('roads_visible_highways') != -1) { formattedJson['roads']['highway'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('roads_visible_paths') != -1) { formattedJson['roads']['path'] = { features: [] } formattedJson['roads']['track'] = { features: [] } } formattedJson['roads']['pier'] = { features: [] } } // roads // check for uploaded features // put into one parent of jsonupload if (mapObject.options['polygonFeatures'].length > 0 || mapObject.options['lineFeatures'].length > 0 || mapObject.options['pointFeatures'].length > 0) { formattedJson['jsonupload'] = {}; } if (mapObject.options['polygonFeatures'].length > 0) { formattedJson['jsonupload']['polygonFeatures'] = { features: mapObject.options['polygonFeatures'] } } if (mapObject.options['lineFeatures'].length > 0) { formattedJson['jsonupload']['lineFeatures'] = { features: mapObject.options['lineFeatures'] } } if (mapObject.options['pointFeatures'].length > 0) { formattedJson['jsonupload']['pointFeatures'] = { features: mapObject.options['pointFeatures'] } } // clipping path with view of map formattedJson['clippingpath'] = { clippingpath: { features: [ { "type": "Feature", "properties": {"name":"clippingpath"}, "geometry": { "type": "Polygon", "coordinates": [ [ [mapObject.options.endLon, mapObject.options.endLat], // southwest [mapObject.options.endLon, mapObject.options.startLat], // northwest [mapObject.options.startLon, mapObject.options.startLat], // northeast [mapObject.options.startLon, mapObject.options.endLat], // southeast [mapObject.options.endLon, mapObject.options.endLat] // southwest ] ] } } ] } } return formattedJson; } // setupJson() function getTilesToFetch(startLat, endLat, startLon, endLon) { const tilesToFetch = []; // for(let i = startLon; i <= endLon; i++) lonArr.push(i); for(let j = startLat; j <= endLat; j++) { const coords = []; for(let i = startLon; i <= endLon; i++) { coords.push({ lat: j, lon: i }); } tilesToFetch.push(coords); } return tilesToFetch; } // function to fire up tile maker based on json options function parseJSON(req) { return new Promise((resolve, reject) => { console.info('parseJSON()'); var newMap = {}; newMap.options = JSON.parse(req); newMap.zoom = parseInt(newMap.options.zoomLevel); newMap.lat1 = lat2tile(parseFloat(newMap.options.startLat), newMap.zoom) newMap.lat2 = lat2tile(parseFloat(newMap.options.endLat), newMap.zoom) newMap.lon1 = long2tile(parseFloat(newMap.options.startLon), newMap.zoom) newMap.lon2 = long2tile(parseFloat(newMap.options.endLon), newMap.zoom) if(newMap.lat1 > newMap.lat2) { newMap.startLat = newMap.lat2; newMap.endLat = newMap.lat1; } else { newMap.startLat = newMap.lat1; newMap.endLat = newMap.lat2; } if(newMap.lon1 > newMap.lon2) { newMap.startLon = newMap.lon2; newMap.endLon = newMap.lon1; } else { newMap.startLon = newMap.lon1; newMap.endLon = newMap.lon2; } newMap.tileWidth = 100; // set up list of layers newMap.dKinds = []; // push parent layers into array if (newMap.options.layers_visible.indexOf('water_visible_ocean') != -1) newMap.dKinds.push('ocean'); newMap.dKinds.push('earth'); if (newMap.options.layers_visible.indexOf('borders_visible') != -1) newMap.dKinds.push('boundaries'); if (newMap.options.layers_visible.indexOf('landuse_visible') != -1) newMap.dKinds.push('landuse'); if (newMap.options.layers_visible.indexOf('water_visible') != -1) newMap.dKinds.push('water'); if (newMap.options.layers_visible.indexOf('transit_visible') != -1 || newMap.options.layers_visible.indexOf('rail_visible') != -1 ) newMap.dKinds.push('transit'); if (newMap.options.layers_visible.indexOf('roads_visible') != -1) newMap.dKinds.push('roads'); if (newMap.options.layers_visible.indexOf('buildings_visible') != -1) newMap.dKinds.push('buildings'); newMap.dKinds.push('clipping'); newMap.tilesToFetch = getTilesToFetch(newMap.startLat, newMap.endLat, newMap.startLon, newMap.endLon); newMap.key = newMap.options.apikey; if(typeof(newMap.key) === 'undefined'){ reject(new Error('No Mapzen API key :(')); } newMap.delayTime = 100; newMap.outputLocation = 'svgmap'+ newMap.tilesToFetch[0][0].lon +'-'+newMap.tilesToFetch[0][0].lat +'-'+newMap.zoom +'.svg'; newMap.data; newMap.xCount = newMap.tilesToFetch.length-1;//latArr.length - 1; newMap.yCount = newMap.tilesToFetch[0].length-1;//lonArr.length - 1; newMap.originalYCount = newMap.yCount; newMap.jsonArray = []; // console.log(newMap) resolve(newMap); }); } function makeSVGCall(newMap) { console.info("makeSVGCall()") return new Promise((resolve, reject) => { var tilesLoaded = false; var tiles = []; var tileURLs = []; // create list of tile URLs for (var i = 0; i < newMap.tilesToFetch.length; i++) { for (var j = 0; j < newMap.tilesToFetch[i].length; j++) { var tileURL = "https://tile.mapzen.com/mapzen/vector/v1/all/"+newMap.zoom+"/"+newMap.tilesToFetch[i][j].lon + "/" + newMap.tilesToFetch[i][j].lat + ".json?api_key="+newMap.key; tileURLs.push(tileURL); } } console.log('tileURLs.length: ' + tileURLs.length); // get the tiles! var i = 0; // start value function tileLoop() { setTimeout(function() { var tileData; console.log(tileURLs[i]); $.get(tileURLs[i], function(data) { tileData = data; }) .done(function() { tiles.push(tileData); // check if done or not if (i < tileURLs.length-1) { i++; tileLoop(); } else { console.log('tiles are done!'); console.log('tiles.length: ' + tiles.length); console.log(tiles); return Promise.all(tiles) .then(values => { console.log(values) for(var x = 0; x < values.length; x++){ newMap.jsonArray.push(values[x]); } resolve(newMap) }) } }); }, newMap.delayTime); } tileLoop(); }); } // makeSVGCall() function bakeJson(mapObject) { return new Promise((resolve,reject) => { var resultArray = mapObject.jsonArray var dKinds = mapObject.dKinds; console.log(resultArray) var ids = []; console.info('bakeJson()'); var geojsonToReform = setupJson(mapObject); console.log(geojsonToReform); // console.log(geojsonToReform); // response geojson array for (let result of resultArray) { // inside of one object for (let response in result) { // console.log(response) // if the property is one of dataKinds that user selected if (dKinds.indexOf(response) > -1) { let responseResult = result[response]; for (let feature of responseResult.features) { // console.log(feature.properties); // skip if a water tunnel or water intermittent if (feature.properties.kind == 'stream' || feature.properties.kind == 'river') { if (feature.properties.intermittent == true || feature.properties.is_tunnel == true) { break; } } if (feature.properties.kind == "train") { console.log(feature.properties); } // segment off motorway_link if (feature.properties.kind_detail == "motorway_link") { var dataKindTitle = 'highway_link'; } else if (feature.properties.kind_detail == "service") { // segment off service roads var dataKindTitle = 'service'; } else if (feature.properties.kind == "train") { var dataKindTitle = 'rail'; } else if (feature.properties.kind_detail == "runway") { // aeroway roads var dataKindTitle = 'runway'; } else if (feature.properties.kind_detail == "taxiway") { var dataKindTitle = 'taxiway'; } else if (landusePark.indexOf(feature.properties.kind) !== -1 ) { // land uses var dataKindTitle = 'park'; } else if (landuseForest.indexOf(feature.properties.kind) !== -1 ) { var dataKindTitle = 'forest'; } else if (landuseAirport.indexOf(feature.properties.kind) !== -1 ) { var dataKindTitle = 'airport'; } else if (landuseMilitary.indexOf(feature.properties.kind) !== -1 ) { var dataKindTitle = 'military'; } else if (landuseUniversity.indexOf(feature.properties.kind) !== -1 ) { var dataKindTitle = 'university'; } else if (landuseSchool.indexOf(feature.properties.kind) !== -1 ) { var dataKindTitle = 'school'; } else if (landuseCemetery.indexOf(feature.properties.kind) !== -1 ) { var dataKindTitle = 'cemetery'; } else if (landuseHospital.indexOf(feature.properties.kind) !== -1 ) { var dataKindTitle = 'hospital'; } else if (landuseStadium.indexOf(feature.properties.kind) !== -1 ) { var dataKindTitle = 'stadium'; } else if (landuseResort.indexOf(feature.properties.kind) !== -1 ) { var dataKindTitle = 'resort'; } else if (landuseBeach.indexOf(feature.properties.kind) !== -1 ) { var dataKindTitle = 'beach'; } else if (feature.properties.kind_detail === "pier") { var dataKindTitle = 'pier'; } else if (feature.properties.kind_detail === "track") { var dataKindTitle = 'track'; } else { var dataKindTitle = feature.properties.kind; } if (geojsonToReform[response].hasOwnProperty(dataKindTitle)) { geojsonToReform[response][dataKindTitle].features.push(feature); } else if (feature.properties.kind == 'ocean') { geojsonToReform['ocean']['oceanwater'].features.push(feature); } else if (geojsonToReform[response].hasOwnProperty('etc') && response == 'water') { geojsonToReform['water']['wateretc'].features.push(feature); } else if (response == 'water') { geojsonToReform['water']['wateretc'].features.push(feature); } else if (response == 'earth') { geojsonToReform['earth']['earthland'].features.push(feature); } // else { // geojsonToReform[response]['etc'].features.push(feature) // } } } } } mapObject.reformedJson = geojsonToReform; resolve(mapObject); }); } function writeSVGFile(mapObject) { return new Promise((resolve, reject) => { console.info('writeSVGFile()'); var reformedJson = mapObject.reformedJson; console.log(reformedJson) // remove any old svgs d3.select("#export-container").remove(); var svg = d3.select('body') .append('div').attr('id','export-container') //make a container div to ease the saving process .append('svg') .attr({ xmlns: 'http://www.w3.org/2000/svg', width: mapObject.tileWidth * mapObject.tilesToFetch[0].length, height: mapObject.tileWidth* mapObject.tilesToFetch.length }); var previewProjection = d3.geo.mercator() .center([tile2Lon(mapObject.startLon, mapObject.zoom), tile2Lat(mapObject.startLat, mapObject.zoom)]) //this are carved based on zoom 16, fit into 100px * 100px rect .scale(600000* mapObject.tileWidth/57.5 * Math.pow(2,(mapObject.zoom-16))) .precision(.0) .translate([0, 0]) var previewPath = d3.geo.path().projection(previewProjection); for (var dataK in reformedJson) { console.log('adding ' + dataK) let oneDataKind = reformedJson[dataK]; let g = svg.append('g') g.attr('id',dataK) for(let subKinds in oneDataKind) { let tempSubK = oneDataKind[subKinds] let subG = g.append('g') subG.attr('id',subKinds.replace('_','')) for(let f in tempSubK.features) { let geoFeature = tempSubK.features[f] // check if point upload if (dataK === 'jsonupload' && geoFeature.geometry.type === "Point" ) { subG.append("circle") .attr("r",5) .attr("transform",function(d){ return "translate(" + previewProjection([ geoFeature.geometry.coordinates[0], geoFeature.geometry.coordinates[1] ]) + ")"; }); } else { // otherwise if path let previewFeature = previewPath(geoFeature); if(previewFeature && previewFeature.indexOf('a') > 0) ; else { // pull stroke if subway or light rail var strokeColor = "#000000"; if (geoFeature.properties.kind === "light_rail" || geoFeature.properties.kind === "subway") { strokeColor = geoFeature.properties.colour; } subG.append('path') .attr('d', previewFeature) .attr('fill','none') .attr('stroke',strokeColor); } } } } } // remove all non-closing riverbank tiles $("#riverbank path").each(function(){ var pathD = $(this).attr("d"); if (pathD.substr(pathD.length - 1) != 'Z') { $(this).remove(); } }); // remove all non-closing wateretc tiles $("#wateretc path").each(function(){ var pathD = $(this).attr("d"); if (pathD.substr(pathD.length - 1) != 'Z') { $(this).remove(); } }); // remove all non-closing ocean tiles $("#oceanwater path").each(function(){ var pathD = $(this).attr("d"); if (pathD.substr(pathD.length - 1) != 'Z') { $(this).remove(); } }); // clip based on view var viewClip = d3.select("#clippingpath path").attr("d"); // figure out widths and viewport based on clipping path var svgX = parseFloat(viewClip.split(',')[0].substring(1,20)).toFixed(3); var svgY = parseFloat(viewClip.split(',')[2].split('L')[0]).toFixed(3); var svgWidth = parseFloat(viewClip.split(',')[2].split('L')[1] - svgX).toFixed(3); var svgHeight = parseFloat(viewClip.split(',')[1].split('L')[0] - svgY).toFixed(3); // these are pulled from the mapmaker pixels if not a column selected from dropdown var fileWidth = mapObject.options.width; var fileHeight = mapObject.options.height; var origSVGWidth = svgWidth, origSVGHeight = svgHeight; // update size if columb based if (mapObject.options.sizeDesc.indexOf('col') === 0) { // figure out many columns var columnCount = mapObject.options.sizeDesc[mapObject.options.sizeDesc.length -1]; // be sure to set a "columnWidth" and "gutterWidth" in your config.js file // set new width based on those columns (Los Angeles Times column sizes for six-column page) var svgWidth = (configOptions.columnWidth * columnCount) + ((columnCount-1) * configOptions.gutterWidth); // set new sizes svgHeight = parseFloat((svgWidth / origSVGWidth)*svgHeight).toFixed(3); svg.attr('viewBox',svgX+ ' ' + svgY + ' '+origSVGWidth+' '+origSVGHeight); fileWidth = svgWidth; fileHeight = svgHeight; } // set 'em // svg.attr('width',svgWidth+'px'); svg.attr('width',fileWidth+'px'); // svg.attr('height',svgHeight+'px'); svg.attr('height',fileHeight+'px'); svg.attr('xml:space','preserve'); svg.attr('x','0px'); svg.attr('y','0px'); svg.attr('version','1.1'); svg.attr('viewBox',svgX+ ' ' + svgY + ' '+origSVGWidth+' '+origSVGHeight); // remove the clipping path d3.select("#clippingpath").remove(); svg.append('defs') .append('clipPath').attr('id','view-clip') .append('path').attr('d',viewClip); // make a copy and put them in a new clipping group svg.append('g') .attr('id','layergroup') .attr('style','fill: none; clip-path: url(#view-clip);'); // .attr('transform','translate(' + -svgX*(origSVGWidth/svgWidth) + ' ' + -svgY*(origSVGWidth/svgWidth) + ')'); // translate over by x and y // move parent layers into clip group $('#layergroup').append($("svg g#ocean")); $('#layergroup').append($("svg g#earth")); $('#layergroup').append($("svg g#boundaries")); $('#layergroup').append($("svg g#landuse")); $('#layergroup').append($("svg g#water")); $('#layergroup').append($("svg g#transit")); $('#layergroup').append($("svg g#roads")); $('#layergroup').append($("svg g#buildings")); $('#layergroup').append($("svg g#jsonupload")); /* restyle anything in groups */ // roads d3.selectAll('#highway path') .attr('stroke','#A6A6A6') .attr('stroke-width','2px'); d3.selectAll('#highwaylink path') .attr('stroke','#BCBEC0') .attr('stroke-width','1px'); d3.selectAll('#majorroad path') .attr('stroke','#BCBEC0') .attr('stroke-width','1px'); d3.selectAll('#minorroad path') .attr('stroke','#CDCFD0') .attr('stroke-width','0.65px'); d3.selectAll('#service path') .attr('stroke','#CDCFD0') .attr('stroke-width','0.65px'); d3.selectAll('#path path') .attr('stroke','#CDCFD0') .attr('stroke-width','0.65px') .attr('stroke-dasharray','1,1'); d3.selectAll('#rail path') .attr('stroke','#CDCFD0') .attr('stroke-width','0.65px'); d3.selectAll('#aerialway path') .attr('stroke','#CDCFD0') .attr('stroke-width','0.65px'); d3.selectAll('#ferry path') .attr('stroke','#8AB1CD') .attr('stroke-width','0.5px') .attr('stroke-dasharray','1,1'); d3.selectAll('#etc path') .attr('stroke','#CDCFD0') .attr('stroke-width','0.65px'); d3.selectAll('#runway path') .attr('stroke','#CDCFD0') .attr('stroke-width','2px'); d3.selectAll('#taxiway path') .attr('stroke','#CDCFD0') .attr('stroke-width','0.65px'); d3.selectAll('#roads #pier path') .attr('stroke','#fff') .attr('stroke-width','1px'); // landuse styles d3.selectAll('#university path') .attr('fill','#F2F0E7') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#stadium path') .attr('fill','#F9F3D6') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#school path') .attr('fill','#F2F0E7') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#resort path') .attr('fill','#F9F3D6') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#park path') .attr('fill','#E7F1CA') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#wetland path') .attr('fill','#e1e9db') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#military path') .attr('fill','#eff0ef') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#prison path') .attr('fill','#eff0ef') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#hospital path') .attr('fill','#E2EDEF') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#forest path') .attr('fill','#E7F1CA') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#cemetery path') .attr('fill','#E4E4D5') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#beach path') .attr('fill','#F8F4E1') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#airport path') .attr('fill','#eff0ef') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#landuse #pier path') .attr('fill','#fff') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#etc path') .attr('fill','none') .attr('stroke','#fff') .attr('stroke-width','0px'); // water console.log('collecting #water path') d3.selectAll('#water path') .attr('fill','#A9D7F4') .attr('stroke','#fff') .attr('stroke-width','0px'); console.log('collecting #ocean path') d3.selectAll('#ocean path') .attr('fill','#A9D7F4') .attr('stroke','#fff') .attr('stroke-width','0px'); console.log('collecting #riverbank path') d3.selectAll('#riverbank path') .attr('fill','#A9D7F4') .attr('stroke','#fff') .attr('stroke-width','0px'); console.log('collecting #river path') d3.selectAll('#river path') .attr('fill','none') .attr('stroke','#A9D7F4') .attr('stroke-width','0.5px'); console.log('collecting #stream path') d3.selectAll('#stream path') .attr('fill','none') .attr('stroke','#A9D7F4') .attr('stroke-width','0.35px'); // earth console.log('collecting #earth #earthland path') d3.selectAll('#earth #earthland path') .attr('fill','#fff') .attr('stroke','#fff') .attr('stroke-width','0px'); // buildings console.log('collecting #buildings #building path') d3.selectAll('#buildings #building path') .attr('fill','#f7f9fc') .attr('stroke','none'); // uploaded geojson polygons window.d3.selectAll('#polygonFeatures path') .attr('fill','none') .attr('stroke','#cd7139') .attr('stroke-width','1px'); // uploaded geojson polylines window.d3.selectAll('#lineFeatures path') .attr('fill','none') .attr('stroke','#cd7139') .attr('stroke-width','1px'); // uploaded geojson points window.d3.selectAll('#pointFeatures circle') .attr('fill','#cd7139') .attr('stroke','#ffffff') .attr('stroke-width','1px'); // boundaries window.d3.selectAll("#boundaries path") .attr('fill','none') .attr('stroke','#827676') .attr('stroke-width','0.5px'); // mask landuse with another earth // svg.append('defs').append('clipPath').attr('id','earth-clip'); // d3.select('#earth-clip').append('path').attr('d',earthTiles); // d3.select('#landuse').attr('clip-path','url(#earth-clip)'); // /tmp // fs.writeFile(outputLocation, d3.select('.container').html(),(err)=> { // if(err) throw err; // console.log('yess svg is there') // }) resolve(d3.select('#export-container').html()); // //jsdom done function done // } // }) }) } // writeSVG() var saveData = (function () { var a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; return function (data, fileName) { var blob = new Blob([data], {type: "octet/stream"}), url = window.URL.createObjectURL(blob); a.href = url; a.download = fileName; a.click(); window.URL.revokeObjectURL(url); }; }()); function createVector(options){ console.log("NEW"); console.log(options); return new Promise((resolve, reject) => { parseJSON(options) .then(makeSVGCall) .then(bakeJson) .then(writeSVGFile) .then((svgString) => { saveData(svgString, 'map-' + getDatetime() + '.svg'); $("#download_vector").html('Download vector'); $("#download_vector").removeClass("gray"); }); }); } // here all maps spells are! // convert lat/lon to mercator style number or reverse. function long2tile(lon,zoom) { return (Math.floor((lon+180)/360*Math.pow(2,zoom))); } function lat2tile(lat,zoom) { return (Math.floor((1-Math.log(Math.tan(lat*Math.PI/180) + 1/Math.cos(lat*Math.PI/180))/Math.PI)/2 *Math.pow(2,zoom))); } function tile2Lon(tileLon, zoom) { return (tileLon*360/Math.pow(2,zoom)-180).toFixed(10); } function tile2Lat(tileLat, zoom) { return ((360/Math.PI) * Math.atan(Math.pow( Math.E, (Math.PI - 2*Math.PI*tileLat/(Math.pow(2,zoom)))))-90).toFixed(10); } function slugify(str) { return str.replace(/[\s]|[,\s]+/g, '-').replace(/[^a-zA-Z-]/g, '').toLowerCase(); }
js/svg-export.js
// var fs = require('fs'); // var jsdom = require('jsdom'); // var d3 = require('d3'); // var XMLHttpRequest = require('xhr2') window.addEventListener('unhandledrejection', event => { // Prevent error output on the console: event.preventDefault(); console.log('Reason: ' + event.reason); }); window.addEventListener('rejectionhandled', event => { console.log('REJECTIONHANDLED'); }); // set up land use groups for LAT var landusePark = ['national_park', 'battlefield', 'protected_area', 'nature_reserve', 'park', 'golf_course', 'recreation_ground', 'camp_site', 'garden', 'allotments', 'pitch', 'meadow', 'village_green', 'farmland', 'playground', 'attraction', 'artwork', 'wilderness_hut', 'hanami'], landuseForest = ['forest', 'wood', 'natural_wood', 'natural_forest'], landuseAirport = ['aerodrome'], landuseMilitary = ['military'], landuseUniversity = ['university', 'college'], landuseSchool = ['school'], landuseCemetery = ['cemetery', 'place_of_worship'], landuseHospital = ['hospital'], landuseStadium = ['stadium'], landuseResort = ['theme_park', 'resort', 'aquarium', 'winery', 'maze'], landuseBeach = ['beach']; function setupJson(mapObject) { console.info('setupJson()') console.log(mapObject); var formattedJson = {}; var dataKind = mapObject.dKinds.join(','); // ocean if (mapObject.options.layers_visible.indexOf('water_visible_ocean') != -1) { formattedJson['ocean'] = { oceanwater: { features: [] } } } // earth formattedJson['earth'] = { earthland: { features: [] } } // landuse if (mapObject.options.layers_visible.indexOf('landuse_visible') != -1) { formattedJson['landuse'] = {} if (mapObject.options.layers_visible.indexOf('landuse_visible_airports') != -1) { formattedJson['landuse']['airport'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_beach') != -1) { formattedJson['landuse']['beach'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_cemetery') != -1) { formattedJson['landuse']['cemetery'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_college') != -1) { formattedJson['landuse']['university'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_forest') != -1) { formattedJson['landuse']['forest'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_hospital') != -1) { formattedJson['landuse']['hospital'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_military') != -1) { formattedJson['landuse']['military'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_park') != -1) { formattedJson['landuse']['park'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_resort') != -1) { formattedJson['landuse']['resort'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_school') != -1) { formattedJson['landuse']['school'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_stadium') != -1) { formattedJson['landuse']['stadium'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_prison') != -1) { formattedJson['landuse']['prison'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('landuse_visible_wetland') != -1) { formattedJson['landuse']['wetland'] = { features: [] } } formattedJson['landuse']['pier'] = { features: [] } } // landuse // borders if (mapObject.options.layers_visible.indexOf('borders_visible') != -1) { formattedJson['boundaries'] = {} if (mapObject.options.layers_visible.indexOf('borders_visible_countries') != -1) { formattedJson['boundaries']['country'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('borders_visible_disputed') != -1) { formattedJson['boundaries']['disputed'] = { features: [] } formattedJson['boundaries']['indefinite'] = { features: [] } formattedJson['boundaries']['interminate'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('borders_visible_states') != -1) { formattedJson['boundaries']['region'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('borders_visible_counties') != -1) { formattedJson['boundaries']['county'] = { features: [] } } } // water if (mapObject.options.layers_visible.indexOf('water_visible') != -1) { formattedJson['water'] = {} if (mapObject.options.layers_visible.indexOf('water_visible_inland_water') != -1) { formattedJson['water']['bay'] = { features: [] } formattedJson['water']['lake'] = { features: [] } formattedJson['water']['river'] = { features: [] } formattedJson['water']['riverbank'] = { features: [] } formattedJson['water']['stream'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('water_visible_swimming_pools') != -1) { formattedJson['water']['swimming_pool'] = { features: [] } } // need etc to grab other water formattedJson['water']['wateretc'] = { features: [] } } // buildings if (mapObject.options.layers_visible.indexOf('buildings_visible') != -1) { formattedJson['buildings'] = { building: { features: [] } } } // roads if (mapObject.options.layers_visible.indexOf('roads_visible') != -1) { formattedJson['roads'] = {} if (mapObject.options.layers_visible.indexOf('roads_visible_ferry_route') != -1) { formattedJson['roads']['ferry'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('roads_visible_taxi_and_runways') != -1) { formattedJson['roads']['taxiway'] = { features: [] } formattedJson['roads']['runway'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('roads_visible_service') != -1) { formattedJson['roads']['service'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('roads_visible_minor') != -1) { formattedJson['roads']['minor_road'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('roads_visible_major') != -1) { formattedJson['roads']['major_road'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('roads_visible_highway_ramps') != -1) { formattedJson['roads']['highway_link'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('roads_visible_highways') != -1) { formattedJson['roads']['highway'] = { features: [] } } if (mapObject.options.layers_visible.indexOf('roads_visible_paths') != -1) { formattedJson['roads']['path'] = { features: [] } formattedJson['roads']['track'] = { features: [] } } formattedJson['roads']['pier'] = { features: [] } } // roads // check for uploaded features // put into one parent of jsonupload if (mapObject.options['polygonFeatures'].length > 0 || mapObject.options['lineFeatures'].length > 0 || mapObject.options['pointFeatures'].length > 0) { formattedJson['jsonupload'] = {}; } if (mapObject.options['polygonFeatures'].length > 0) { formattedJson['jsonupload']['polygonFeatures'] = { features: mapObject.options['polygonFeatures'] } } if (mapObject.options['lineFeatures'].length > 0) { formattedJson['jsonupload']['lineFeatures'] = { features: mapObject.options['lineFeatures'] } } if (mapObject.options['pointFeatures'].length > 0) { formattedJson['jsonupload']['pointFeatures'] = { features: mapObject.options['pointFeatures'] } } // clipping path with view of map formattedJson['clippingpath'] = { clippingpath: { features: [ { "type": "Feature", "properties": {"name":"clippingpath"}, "geometry": { "type": "Polygon", "coordinates": [ [ [mapObject.options.endLon, mapObject.options.endLat], // southwest [mapObject.options.endLon, mapObject.options.startLat], // northwest [mapObject.options.startLon, mapObject.options.startLat], // northeast [mapObject.options.startLon, mapObject.options.endLat], // southeast [mapObject.options.endLon, mapObject.options.endLat] // southwest ] ] } } ] } } return formattedJson; } // setupJson() function getTilesToFetch(startLat, endLat, startLon, endLon) { const tilesToFetch = []; // for(let i = startLon; i <= endLon; i++) lonArr.push(i); for(let j = startLat; j <= endLat; j++) { const coords = []; for(let i = startLon; i <= endLon; i++) { coords.push({ lat: j, lon: i }); } tilesToFetch.push(coords); } return tilesToFetch; } // function to fire up tile maker based on json options function parseJSON(req) { return new Promise((resolve, reject) => { console.info('parseJSON()'); var newMap = {}; newMap.options = JSON.parse(req); newMap.zoom = parseInt(newMap.options.zoomLevel); newMap.lat1 = lat2tile(parseFloat(newMap.options.startLat), newMap.zoom) newMap.lat2 = lat2tile(parseFloat(newMap.options.endLat), newMap.zoom) newMap.lon1 = long2tile(parseFloat(newMap.options.startLon), newMap.zoom) newMap.lon2 = long2tile(parseFloat(newMap.options.endLon), newMap.zoom) if(newMap.lat1 > newMap.lat2) { newMap.startLat = newMap.lat2; newMap.endLat = newMap.lat1; } else { newMap.startLat = newMap.lat1; newMap.endLat = newMap.lat2; } if(newMap.lon1 > newMap.lon2) { newMap.startLon = newMap.lon2; newMap.endLon = newMap.lon1; } else { newMap.startLon = newMap.lon1; newMap.endLon = newMap.lon2; } newMap.tileWidth = 100; // set up list of layers newMap.dKinds = []; // push parent layers into array if (newMap.options.layers_visible.indexOf('water_visible_ocean') != -1) newMap.dKinds.push('ocean'); newMap.dKinds.push('earth'); if (newMap.options.layers_visible.indexOf('borders_visible') != -1) newMap.dKinds.push('boundaries'); if (newMap.options.layers_visible.indexOf('landuse_visible') != -1) newMap.dKinds.push('landuse'); if (newMap.options.layers_visible.indexOf('water_visible') != -1) newMap.dKinds.push('water'); if (newMap.options.layers_visible.indexOf('roads_visible') != -1) newMap.dKinds.push('roads'); if (newMap.options.layers_visible.indexOf('buildings_visible') != -1) newMap.dKinds.push('buildings'); newMap.dKinds.push('clipping'); newMap.tilesToFetch = getTilesToFetch(newMap.startLat, newMap.endLat, newMap.startLon, newMap.endLon); newMap.key = newMap.options.apikey; if(typeof(newMap.key) === 'undefined'){ reject(new Error('No Mapzen API key :(')); } newMap.delayTime = 100; newMap.outputLocation = 'svgmap'+ newMap.tilesToFetch[0][0].lon +'-'+newMap.tilesToFetch[0][0].lat +'-'+newMap.zoom +'.svg'; newMap.data; newMap.xCount = newMap.tilesToFetch.length-1;//latArr.length - 1; newMap.yCount = newMap.tilesToFetch[0].length-1;//lonArr.length - 1; newMap.originalYCount = newMap.yCount; newMap.jsonArray = []; // console.log(newMap) resolve(newMap); }); } function makeSVGCall(newMap) { console.info("makeSVGCall()") return new Promise((resolve, reject) => { var tilesLoaded = false; var tiles = []; var tileURLs = []; // create list of tile URLs for (var i = 0; i < newMap.tilesToFetch.length; i++) { for (var j = 0; j < newMap.tilesToFetch[i].length; j++) { var tileURL = "https://tile.mapzen.com/mapzen/vector/v1/all/"+newMap.zoom+"/"+newMap.tilesToFetch[i][j].lon + "/" + newMap.tilesToFetch[i][j].lat + ".json?api_key="+newMap.key; tileURLs.push(tileURL); } } console.log('tileURLs.length: ' + tileURLs.length); // get the tiles! var i = 0; // start value function tileLoop() { setTimeout(function() { var tileData; console.log(tileURLs[i]); $.get(tileURLs[i], function(data) { tileData = data; }) .done(function() { tiles.push(tileData); // check if done or not if (i < tileURLs.length-1) { i++; tileLoop(); } else { console.log('tiles are done!'); console.log('tiles.length: ' + tiles.length); console.log(tiles); return Promise.all(tiles) .then(values => { console.log(values) for(var x = 0; x < values.length; x++){ newMap.jsonArray.push(values[x]); } resolve(newMap) }) } }); }, newMap.delayTime); } tileLoop(); }); } // makeSVGCall() function bakeJson(mapObject) { return new Promise((resolve,reject) => { var resultArray = mapObject.jsonArray var dKinds = mapObject.dKinds; console.log(resultArray) var ids = []; console.info('bakeJson()'); var geojsonToReform = setupJson(mapObject); console.log(geojsonToReform); // console.log(geojsonToReform); // response geojson array for (let result of resultArray) { // inside of one object for (let response in result) { // console.log(response) // if the property is one of dataKinds that user selected if (dKinds.indexOf(response) > -1) { let responseResult = result[response]; for (let feature of responseResult.features) { // console.log(feature.properties); // skip if a water tunnel or water intermittent if (feature.properties.kind == 'stream' || feature.properties.kind == 'river') { if (feature.properties.intermittent == true || feature.properties.is_tunnel == true) { break; } } // segment off motorway_link if (feature.properties.kind_detail == "motorway_link") { var dataKindTitle = 'highway_link'; } else if (feature.properties.kind_detail == "service") { // segment off service roads var dataKindTitle = 'service'; } else if (feature.properties.kind_detail == "runway") { // aeroway roads var dataKindTitle = 'runway'; } else if (feature.properties.kind_detail == "taxiway") { var dataKindTitle = 'taxiway'; } else if (landusePark.indexOf(feature.properties.kind) !== -1 ) { // land uses var dataKindTitle = 'park'; } else if (landuseForest.indexOf(feature.properties.kind) !== -1 ) { var dataKindTitle = 'forest'; } else if (landuseAirport.indexOf(feature.properties.kind) !== -1 ) { var dataKindTitle = 'airport'; } else if (landuseMilitary.indexOf(feature.properties.kind) !== -1 ) { var dataKindTitle = 'military'; } else if (landuseUniversity.indexOf(feature.properties.kind) !== -1 ) { var dataKindTitle = 'university'; } else if (landuseSchool.indexOf(feature.properties.kind) !== -1 ) { var dataKindTitle = 'school'; } else if (landuseCemetery.indexOf(feature.properties.kind) !== -1 ) { var dataKindTitle = 'cemetery'; } else if (landuseHospital.indexOf(feature.properties.kind) !== -1 ) { var dataKindTitle = 'hospital'; } else if (landuseStadium.indexOf(feature.properties.kind) !== -1 ) { var dataKindTitle = 'stadium'; } else if (landuseResort.indexOf(feature.properties.kind) !== -1 ) { var dataKindTitle = 'resort'; } else if (landuseBeach.indexOf(feature.properties.kind) !== -1 ) { var dataKindTitle = 'beach'; } else if (feature.properties.kind_detail === "pier") { var dataKindTitle = 'pier'; } else if (feature.properties.kind_detail === "track") { var dataKindTitle = 'track'; } else { var dataKindTitle = feature.properties.kind; } if (geojsonToReform[response].hasOwnProperty(dataKindTitle)) { geojsonToReform[response][dataKindTitle].features.push(feature); } else if (feature.properties.kind == 'ocean') { geojsonToReform['ocean']['oceanwater'].features.push(feature); } else if (geojsonToReform[response].hasOwnProperty('etc') && response == 'water') { geojsonToReform['water']['wateretc'].features.push(feature); } else if (response == 'water') { geojsonToReform['water']['wateretc'].features.push(feature); } else if (response == 'earth') { geojsonToReform['earth']['earthland'].features.push(feature); } // else { // geojsonToReform[response]['etc'].features.push(feature) // } } } } } mapObject.reformedJson = geojsonToReform; resolve(mapObject); }); } function writeSVGFile(mapObject) { return new Promise((resolve, reject) => { console.info('writeSVGFile()'); var reformedJson = mapObject.reformedJson; console.log(reformedJson) // remove any old svgs d3.select("#export-container").remove(); // window.d3 = d3.select(window.document); var svg = d3.select('body') .append('div').attr('id','export-container') //make a container div to ease the saving process .append('svg') .attr({ xmlns: 'http://www.w3.org/2000/svg', width: mapObject.tileWidth * mapObject.tilesToFetch[0].length, height: mapObject.tileWidth* mapObject.tilesToFetch.length }); var previewProjection = d3.geo.mercator() .center([tile2Lon(mapObject.startLon, mapObject.zoom), tile2Lat(mapObject.startLat, mapObject.zoom)]) //this are carved based on zoom 16, fit into 100px * 100px rect .scale(600000* mapObject.tileWidth/57.5 * Math.pow(2,(mapObject.zoom-16))) .precision(.0) .translate([0, 0]) var previewPath = d3.geo.path().projection(previewProjection); for (var dataK in reformedJson) { console.log('adding ' + dataK) let oneDataKind = reformedJson[dataK]; let g = svg.append('g') g.attr('id',dataK) for(let subKinds in oneDataKind) { let tempSubK = oneDataKind[subKinds] let subG = g.append('g') subG.attr('id',subKinds.replace('_','')) for(let f in tempSubK.features) { let geoFeature = tempSubK.features[f] // check if point upload if (dataK === 'jsonupload' && geoFeature.geometry.type === "Point" ) { subG.append("circle") .attr("r",5) .attr("transform",function(d){ return "translate(" + previewProjection([ geoFeature.geometry.coordinates[0], geoFeature.geometry.coordinates[1] ]) + ")"; }); } else { // otherwise if path let previewFeature = previewPath(geoFeature); if(previewFeature && previewFeature.indexOf('a') > 0) ; else { subG.append('path') .attr('d', previewFeature) .attr('fill','none') .attr('stroke','black') } } } } } // // combine all earth tiles // var earthTiles = ""; // d3.selectAll("#earth path").each(function(){ // earthTiles += d3.select(this).attr("d"); // }); // d3.selectAll("#earth").append("path").attr("d",earthTiles); // remove all non-closing riverbank tiles $("#riverbank path").each(function(){ var pathD = $(this).attr("d"); if (pathD.substr(pathD.length - 1) != 'Z') { $(this).remove(); } }); // remove all non-closing wateretc tiles $("#wateretc path").each(function(){ var pathD = $(this).attr("d"); if (pathD.substr(pathD.length - 1) != 'Z') { $(this).remove(); } }); // remove all non-closing ocean tiles $("#oceanwater path").each(function(){ var pathD = $(this).attr("d"); if (pathD.substr(pathD.length - 1) != 'Z') { $(this).remove(); } }); // // combine all riverbank tiles // var riverbankPaths = ""; // d3.selectAll("#riverbank path").each(function(){ // riverbankPaths += d3.select(this).attr("d"); // d3.select(this).remove(); // }); // d3.selectAll("#riverbank").append("path").attr("d",riverbankPaths); // clip based on view var viewClip = d3.select("#clippingpath path").attr("d"); // figure out widths and viewport based on clipping path var svgX = parseFloat(viewClip.split(',')[0].substring(1,20)).toFixed(3); var svgY = parseFloat(viewClip.split(',')[2].split('L')[0]).toFixed(3); var svgWidth = parseFloat(viewClip.split(',')[2].split('L')[1] - svgX).toFixed(3); var svgHeight = parseFloat(viewClip.split(',')[1].split('L')[0] - svgY).toFixed(3); // these are pulled from the mapmaker pixels if not a column selected from dropdown var fileWidth = mapObject.options.width; var fileHeight = mapObject.options.height; var origSVGWidth = svgWidth, origSVGHeight = svgHeight; // update size if columb based if (mapObject.options.sizeDesc.indexOf('col') === 0) { // figure out many columns var columnCount = mapObject.options.sizeDesc[mapObject.options.sizeDesc.length -1]; // be sure to set a "columnWidth" and "gutterWidth" in your config.js file // set new width based on those columns (Los Angeles Times column sizes for six-column page) var svgWidth = (configOptions.columnWidth * columnCount) + ((columnCount-1) * configOptions.gutterWidth); // set new sizes svgHeight = parseFloat((svgWidth / origSVGWidth)*svgHeight).toFixed(3); svg.attr('viewBox',svgX+ ' ' + svgY + ' '+origSVGWidth+' '+origSVGHeight); fileWidth = svgWidth; fileHeight = svgHeight; } // set 'em // svg.attr('width',svgWidth+'px'); svg.attr('width',fileWidth+'px'); // svg.attr('height',svgHeight+'px'); svg.attr('height',fileHeight+'px'); svg.attr('xml:space','preserve'); svg.attr('x','0px'); svg.attr('y','0px'); svg.attr('version','1.1'); svg.attr('viewBox',svgX+ ' ' + svgY + ' '+origSVGWidth+' '+origSVGHeight); // remove the clipping path d3.select("#clippingpath").remove(); svg.append('defs') .append('clipPath').attr('id','view-clip') .append('path').attr('d',viewClip); // make a copy and put them in a new clipping group svg.append('g') .attr('id','layergroup') .attr('style','fill: none; clip-path: url(#view-clip);'); // .attr('transform','translate(' + -svgX*(origSVGWidth/svgWidth) + ' ' + -svgY*(origSVGWidth/svgWidth) + ')'); // translate over by x and y // move parent layers into clip group $('#layergroup').append($("svg g#ocean")); $('#layergroup').append($("svg g#earth")); $('#layergroup').append($("svg g#boundaries")); $('#layergroup').append($("svg g#landuse")); $('#layergroup').append($("svg g#water")); $('#layergroup').append($("svg g#roads")); $('#layergroup').append($("svg g#buildings")); $('#layergroup').append($("svg g#jsonupload")); /* restyle anything in groups */ // roads d3.selectAll('#highway path') .attr('stroke','#A6A6A6') .attr('stroke-width','2px'); d3.selectAll('#highwaylink path') .attr('stroke','#BCBEC0') .attr('stroke-width','1px'); d3.selectAll('#majorroad path') .attr('stroke','#BCBEC0') .attr('stroke-width','1px'); d3.selectAll('#minorroad path') .attr('stroke','#CDCFD0') .attr('stroke-width','0.65px'); d3.selectAll('#service path') .attr('stroke','#CDCFD0') .attr('stroke-width','0.65px'); d3.selectAll('#path path') .attr('stroke','#CDCFD0') .attr('stroke-width','0.65px') .attr('stroke-dasharray','1,1'); d3.selectAll('#rail path') .attr('stroke','#CDCFD0') .attr('stroke-width','0.65px'); d3.selectAll('#aerialway path') .attr('stroke','#CDCFD0') .attr('stroke-width','0.65px'); d3.selectAll('#ferry path') .attr('stroke','#8AB1CD') .attr('stroke-width','0.5px') .attr('stroke-dasharray','1,1'); d3.selectAll('#etc path') .attr('stroke','#CDCFD0') .attr('stroke-width','0.65px'); d3.selectAll('#runway path') .attr('stroke','#CDCFD0') .attr('stroke-width','2px'); d3.selectAll('#taxiway path') .attr('stroke','#CDCFD0') .attr('stroke-width','0.65px'); d3.selectAll('#roads #pier path') .attr('stroke','#fff') .attr('stroke-width','1px'); // landuse styles d3.selectAll('#university path') .attr('fill','#F2F0E7') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#stadium path') .attr('fill','#F9F3D6') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#school path') .attr('fill','#F2F0E7') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#resort path') .attr('fill','#F9F3D6') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#park path') .attr('fill','#E7F1CA') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#wetland path') .attr('fill','#e1e9db') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#military path') .attr('fill','#eff0ef') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#prison path') .attr('fill','#eff0ef') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#hospital path') .attr('fill','#E2EDEF') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#forest path') .attr('fill','#E7F1CA') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#cemetery path') .attr('fill','#E4E4D5') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#beach path') .attr('fill','#F8F4E1') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#airport path') .attr('fill','#eff0ef') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#landuse #pier path') .attr('fill','#fff') .attr('stroke','#fff') .attr('stroke-width','0px'); d3.selectAll('#etc path') .attr('fill','none') .attr('stroke','#fff') .attr('stroke-width','0px'); // water console.log('collecting #water path') d3.selectAll('#water path') .attr('fill','#A9D7F4') .attr('stroke','#fff') .attr('stroke-width','0px'); console.log('collecting #ocean path') d3.selectAll('#ocean path') .attr('fill','#A9D7F4') .attr('stroke','#fff') .attr('stroke-width','0px'); console.log('collecting #riverbank path') d3.selectAll('#riverbank path') .attr('fill','#A9D7F4') .attr('stroke','#fff') .attr('stroke-width','0px'); console.log('collecting #river path') d3.selectAll('#river path') .attr('fill','none') .attr('stroke','#A9D7F4') .attr('stroke-width','0.5px'); console.log('collecting #stream path') d3.selectAll('#stream path') .attr('fill','none') .attr('stroke','#A9D7F4') .attr('stroke-width','0.35px'); // earth console.log('collecting #earth #earthland path') d3.selectAll('#earth #earthland path') .attr('fill','#fff') .attr('stroke','#fff') .attr('stroke-width','0px'); // buildings console.log('collecting #buildings #building path') d3.selectAll('#buildings #building path') .attr('fill','#f7f9fc') .attr('stroke','none'); // uploaded geojson polygons window.d3.selectAll('#polygonFeatures path') .attr('fill','none') .attr('stroke','#cd7139') .attr('stroke-width','1px'); // uploaded geojson polylines window.d3.selectAll('#lineFeatures path') .attr('fill','none') .attr('stroke','#cd7139') .attr('stroke-width','1px'); // uploaded geojson points window.d3.selectAll('#pointFeatures circle') .attr('fill','#cd7139') .attr('stroke','#ffffff') .attr('stroke-width','1px'); // boundaries window.d3.selectAll("#boundaries path") .attr('fill','none') .attr('stroke','#827676') .attr('stroke-width','0.5px'); // mask landuse with another earth // svg.append('defs').append('clipPath').attr('id','earth-clip'); // d3.select('#earth-clip').append('path').attr('d',earthTiles); // d3.select('#landuse').attr('clip-path','url(#earth-clip)'); // /tmp // fs.writeFile(outputLocation, d3.select('.container').html(),(err)=> { // if(err) throw err; // console.log('yess svg is there') // }) resolve(d3.select('#export-container').html()); // //jsdom done function done // } // }) }) } // writeSVG() var saveData = (function () { var a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; return function (data, fileName) { var blob = new Blob([data], {type: "octet/stream"}), url = window.URL.createObjectURL(blob); a.href = url; a.download = fileName; a.click(); window.URL.revokeObjectURL(url); }; }()); function createVector(options){ console.log("NEW"); console.log(options); return new Promise((resolve, reject) => { parseJSON(options) .then(makeSVGCall) .then(bakeJson) .then(writeSVGFile) .then((svgString) => { saveData(svgString, 'map-' + getDatetime() + '.svg'); $("#download_vector").html('Download vector'); $("#download_vector").removeClass("gray"); }); }); } // here all maps spells are! // convert lat/lon to mercator style number or reverse. function long2tile(lon,zoom) { return (Math.floor((lon+180)/360*Math.pow(2,zoom))); } function lat2tile(lat,zoom) { return (Math.floor((1-Math.log(Math.tan(lat*Math.PI/180) + 1/Math.cos(lat*Math.PI/180))/Math.PI)/2 *Math.pow(2,zoom))); } function tile2Lon(tileLon, zoom) { return (tileLon*360/Math.pow(2,zoom)-180).toFixed(10); } function tile2Lat(tileLat, zoom) { return ((360/Math.PI) * Math.atan(Math.pow( Math.E, (Math.PI - 2*Math.PI*tileLat/(Math.pow(2,zoom)))))-90).toFixed(10); } function slugify(str) { return str.replace(/[\s]|[,\s]+/g, '-').replace(/[^a-zA-Z-]/g, '').toLowerCase(); }
some transit rail vector export happening
js/svg-export.js
some transit rail vector export happening
<ide><path>s/svg-export.js <ide> building: { <ide> features: [] <ide> } <add> } <add> } <add> <add> // transit <add> if (mapObject.options.layers_visible.indexOf('transit_visible') != -1 || <add> mapObject.options.layers_visible.indexOf('rail_visible') != -1) { <add> formattedJson['transit'] = {} <add> <add> if (mapObject.options.layers_visible.indexOf('transit_visible') != -1) { <add> formattedJson['transit']['light_rail'] = { features: [] } <add> formattedJson['transit']['subway'] = { features: [] } <add> formattedJson['transit']['station'] = { features: [] } <add> } <add> if (mapObject.options.layers_visible.indexOf('rail_visible') != -1) { <add> formattedJson['transit']['rail'] = { features: [] } <ide> } <ide> } <ide> <ide> if (newMap.options.layers_visible.indexOf('borders_visible') != -1) newMap.dKinds.push('boundaries'); <ide> if (newMap.options.layers_visible.indexOf('landuse_visible') != -1) newMap.dKinds.push('landuse'); <ide> if (newMap.options.layers_visible.indexOf('water_visible') != -1) newMap.dKinds.push('water'); <add> if (newMap.options.layers_visible.indexOf('transit_visible') != -1 || newMap.options.layers_visible.indexOf('rail_visible') != -1 ) newMap.dKinds.push('transit'); <ide> if (newMap.options.layers_visible.indexOf('roads_visible') != -1) newMap.dKinds.push('roads'); <ide> if (newMap.options.layers_visible.indexOf('buildings_visible') != -1) newMap.dKinds.push('buildings'); <ide> newMap.dKinds.push('clipping'); <ide> } <ide> } <ide> <add> if (feature.properties.kind == "train") { <add> console.log(feature.properties); <add> } <add> <ide> // segment off motorway_link <ide> if (feature.properties.kind_detail == "motorway_link") { <ide> var dataKindTitle = 'highway_link'; <ide> } else if (feature.properties.kind_detail == "service") { <ide> // segment off service roads <ide> var dataKindTitle = 'service'; <add> } else if (feature.properties.kind == "train") { <add> var dataKindTitle = 'rail'; <ide> } else if (feature.properties.kind_detail == "runway") { <ide> // aeroway roads <ide> var dataKindTitle = 'runway'; <ide> <ide> // remove any old svgs <ide> d3.select("#export-container").remove(); <del> // window.d3 = d3.select(window.document); <del> <ide> var svg = d3.select('body') <ide> .append('div').attr('id','export-container') //make a container div to ease the saving process <ide> .append('svg') <ide> <ide> if(previewFeature && previewFeature.indexOf('a') > 0) ; <ide> else { <add> // pull stroke if subway or light rail <add> var strokeColor = "#000000"; <add> if (geoFeature.properties.kind === "light_rail" || geoFeature.properties.kind === "subway") { <add> strokeColor = geoFeature.properties.colour; <add> } <ide> subG.append('path') <ide> .attr('d', previewFeature) <ide> .attr('fill','none') <del> .attr('stroke','black') <add> .attr('stroke',strokeColor); <ide> } <ide> } <ide> } <ide> } <ide> } <del> <del> // // combine all earth tiles <del> // var earthTiles = ""; <del> // d3.selectAll("#earth path").each(function(){ <del> // earthTiles += d3.select(this).attr("d"); <del> // }); <del> // d3.selectAll("#earth").append("path").attr("d",earthTiles); <ide> <ide> // remove all non-closing riverbank tiles <ide> $("#riverbank path").each(function(){ <ide> $(this).remove(); <ide> } <ide> }); <del> <del> // // combine all riverbank tiles <del> // var riverbankPaths = ""; <del> // d3.selectAll("#riverbank path").each(function(){ <del> // riverbankPaths += d3.select(this).attr("d"); <del> // d3.select(this).remove(); <del> // }); <del> // d3.selectAll("#riverbank").append("path").attr("d",riverbankPaths); <del> <del> <del> <ide> <ide> // clip based on view <ide> var viewClip = d3.select("#clippingpath path").attr("d"); <ide> $('#layergroup').append($("svg g#boundaries")); <ide> $('#layergroup').append($("svg g#landuse")); <ide> $('#layergroup').append($("svg g#water")); <add> $('#layergroup').append($("svg g#transit")); <ide> $('#layergroup').append($("svg g#roads")); <ide> $('#layergroup').append($("svg g#buildings")); <ide> $('#layergroup').append($("svg g#jsonupload"));
Java
mit
7d5717aa7050b78f73985e6ffff9287b31b2760e
0
hagbeck/ApiPaiaService,cdkoltermann/ApiPaiaService,cdkoltermann/ApiPaiaService,hagbeck/ApiPaiaService
/* The MIT License (MIT) Copyright (c) 2015-2016, Hans-Georg Becker, http://orcid.org/0000-0003-0432-294X 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 de.tu_dortmund.ub.api.paia.core; import com.fasterxml.jackson.databind.ObjectMapper; import com.opencsv.CSVReader; import com.opencsv.CSVWriter; import de.tu_dortmund.ub.api.paia.core.model.*; import de.tu_dortmund.ub.api.paia.interfaces.AuthorizationException; import de.tu_dortmund.ub.api.paia.interfaces.AuthorizationInterface; import de.tu_dortmund.ub.api.paia.auth.model.LoginResponse; import de.tu_dortmund.ub.api.paia.interfaces.LibraryManagementSystemException; import de.tu_dortmund.ub.api.paia.interfaces.LibraryManagementSystem; import de.tu_dortmund.ub.api.paia.model.RequestError; import de.tu_dortmund.ub.util.impl.Lookup; import de.tu_dortmund.ub.util.output.ObjectToHtmlTransformation; import de.tu_dortmund.ub.util.output.TransformationException; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import redis.clients.jedis.Jedis; import redis.clients.jedis.ScanResult; import javax.json.JsonObject; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import java.io.*; import java.net.URLDecoder; import java.net.URLEncoder; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.*; /** * This class represents the PAIA Core component. * * @author Hans-Georg Becker * @version 2015-05-06 */ public class PaiaCoreEndpoint extends HttpServlet { // Configuration private String conffile = ""; private Properties config = new Properties(); private Logger logger = Logger.getLogger(PaiaCoreEndpoint.class.getName()); /** * * @throws IOException */ public PaiaCoreEndpoint() throws IOException { this("conf/paia.properties"); } /** * * @param conffile * @throws IOException */ public PaiaCoreEndpoint(String conffile) throws IOException { this.conffile = conffile; // Init properties try { InputStream inputStream = new FileInputStream(conffile); try { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); try { this.config.load(reader); } finally { reader.close(); } } finally { inputStream.close(); } } catch (IOException e) { System.out.println("FATAL ERROR: Die Datei '" + conffile + "' konnte nicht geöffnet werden!"); } // init logger PropertyConfigurator.configure(this.config.getProperty("service.log4j-conf")); this.logger.info("Starting 'PAIA Core Endpoint' ..."); this.logger.info("conf-file = " + conffile); this.logger.info("log4j-conf-file = " + this.config.getProperty("service.log4j-conf")); } /** * * @param httpServletRequest * @param httpServletResponse * @throws ServletException * @throws IOException */ protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { this.doPost(httpServletRequest, httpServletResponse); } /** * * @param httpServletRequest * @param httpServletResponse */ protected void doDelete(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException { this.logger.debug("PathInfo = " + httpServletRequest.getPathInfo()); this.logger.debug("QueryString = " + httpServletRequest.getQueryString()); String patronid = ""; String service = ""; String application = ""; String listName = ""; String favoriteId = ""; ObjectMapper mapper = new ObjectMapper(); // Einlesen der Konkordanz, die einer Application einen Redis-DB-Index zuordnet Map<String, Object> concordance = mapper.readValue(new File("conf/concordance.json"), Map.class); Jedis jedis = new Jedis(this.config.getProperty("redis-favorites-server"), Integer.parseInt(this.config.getProperty("redis-favorites-server-port"))); String path = httpServletRequest.getPathInfo(); if (!path.equals(null)) { String[] params = path.substring(1,path.length()).split("/"); switch (params.length) { // ganze Liste löschen: case 4: patronid = params[0]; service = params[1]; application = params[2]; listName = params[3]; if (service.equals("favlist") && concordance.containsKey(application)) { int appIndexList = Integer.parseInt(String.valueOf(concordance.get(application))); jedis.select(appIndexList); if (jedis.hexists(patronid, listName)) { jedis.hdel(patronid, listName); httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); } } else { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } break; // einzelnen Favoriten löschen: case 5: patronid = params[0]; service = params[1]; application = params[2]; listName = params[3]; favoriteId = params[4]; if (service.equals("favorite") && concordance.containsKey(application)) { int appIndexSingleFavorite = Integer.parseInt(String.valueOf(concordance.get(application))); jedis.select(appIndexSingleFavorite); if (jedis.hexists(patronid, listName)) { String listContent = jedis.hget(patronid, listName); FavoriteList favoriteList = mapper.readValue(listContent, FavoriteList.class); String[] recordids = new String[favoriteList.getFavorites().size()]; for (int i = 0; i < favoriteList.getFavorites().size(); i++) { recordids[i] = favoriteList.getFavorites().get(i).getRecordid(); } if (Arrays.asList(recordids).contains(favoriteId)) { ArrayList<Favorite> arrayList = favoriteList.getFavorites(); for (int i = 0; i < arrayList.size(); i++) { if (favoriteList.getFavorites().get(i).getRecordid().equals(favoriteId)) { arrayList.remove(i); httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT); } } favoriteList.setFavorites(arrayList); listContent = mapper.writeValueAsString(favoriteList); jedis.hset(patronid, listName, listContent); } else { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); // Favoriten nicht gefunden } } else { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); // Liste nicht gefunden } } else { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } break; } } else { // TODO } /* alte Version: this.logger.debug("PathInfo = " + httpServletRequest.getPathInfo()); this.logger.debug("QueryString = " + httpServletRequest.getQueryString()); String patronid = ""; String service = ""; String listName = ""; String path = httpServletRequest.getPathInfo(); if (path != null) { String[] params = path.substring(1,path.length()).split("/"); if (params.length == 3) { patronid = params[0]; service = params[1]; listName = params[2]; // Jedis-Objekt zur Kommunikation mit Redis Jedis jedis = new Jedis(this.config.getProperty("redis-favorites-server"), Integer.parseInt(this.config.getProperty("redis-favorites-server-port"))); if (service.equals("deletefavlist")) { if (jedis.hexists(patronid, listName)) { jedis.hdel(patronid, listName); httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); } } } else { httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } */ } /** * * @param httpServletRequest * @param httpServletResponse * @throws ServletException * @throws IOException */ protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { ObjectMapper mapper = new ObjectMapper(); String format; String language; String redirect_url; this.logger.debug("PathInfo = " + httpServletRequest.getPathInfo()); this.logger.debug("QueryString = " + httpServletRequest.getQueryString()); String patronid = ""; String service = ""; String accept = ""; String authorization = ""; String application = ""; String listName = ""; FavoriteList favoriteRequest = new FavoriteList(); String path = httpServletRequest.getPathInfo(); if (path != null) { String[] params = path.substring(1,path.length()).split("/"); if (params.length == 1) { patronid = params[0]; service = "patron"; } else if (params.length == 2) { if (params[0].equals("backup")) { switch (params[1]) { case "favorites" : patronid = "ubdo"; service = "backup/favorites"; break; // hier ggf. weitere cases für andere Backups ergänzen } } else { patronid = params[0]; service = params[1]; } } else if (params[1].equals("items") && params.length > 2) { patronid = params[0]; for (int i = 1; i < params.length; i++) { service += params[i]; if (i < params.length-1) { service += "/"; } } } else if ((params[1].equals("favorite") || params[1].equals("favlist")) && params.length > 2) { patronid = params[0]; service = params[1]; application = params[2]; if (params.length > 3) { listName = params[3]; } } /* alt: else if (params[1].equals("favorites") && params.length > 2) { patronid = params[0]; service = params[1]; listName = params[2]; } */ } if (patronid.equals("patronid")) { patronid = ""; } this.logger.debug("Service: " + service); this.logger.debug("Patron: " + patronid); format = "html"; if (httpServletRequest.getParameter("format") != null && !httpServletRequest.getParameter("format").equals("")) { format = httpServletRequest.getParameter("format"); } else { Enumeration<String> headerNames = httpServletRequest.getHeaderNames(); while ( headerNames.hasMoreElements() ) { String headerNameKey = headerNames.nextElement(); if (headerNameKey.equals("Accept")) { this.logger.debug("headerNameKey = " + httpServletRequest.getHeader( headerNameKey )); if (httpServletRequest.getHeader( headerNameKey ).contains("text/html")) { format = "html"; } else if (httpServletRequest.getHeader( headerNameKey ).contains("application/xml")) { format = "xml"; } else if (httpServletRequest.getHeader( headerNameKey ).contains("application/json")) { format = "json"; } } } } this.logger.info("format = " + format); if (format.equals("html") && Lookup.lookupAll(ObjectToHtmlTransformation.class).size() == 0) { this.logger.error(HttpServletResponse.SC_BAD_REQUEST + ": " + "html not implemented!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST))); requestError.setCode(HttpServletResponse.SC_BAD_REQUEST); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, "", ""); } else { // read requestBody StringBuffer jb = new StringBuffer(); String line = null; try { BufferedReader reader = httpServletRequest.getReader(); while ((line = reader.readLine()) != null) jb.append(line); } catch (Exception e) { /*report an error*/ } String requestBody = jb.toString(); if (service.equals("favorite")) { favoriteRequest = mapper.readValue(requestBody, FavoriteList.class); // listName = favoriteRequest.getList(); } // read document list DocumentList documentList = null; try { // read DocumentList documentList = mapper.readValue(requestBody, DocumentList.class); } catch (Exception e) { if (!requestBody.equals("")) { String[] params = requestBody.split("&"); if (params.length > 1) { documentList = new DocumentList(); documentList.setDoc(new ArrayList<Document>()); for (String param : params) { if (param.startsWith("document_id")) { Document document = new Document(); document.setEdition(param.split("=")[1]); documentList.getDoc().add(document); } } } } else if (httpServletRequest.getParameter("document_id") != null && !httpServletRequest.getParameter("document_id").equals("")) { Document document = new Document(); document.setEdition(httpServletRequest.getParameter("document_id")); if (httpServletRequest.getParameter("storage_id") != null && !httpServletRequest.getParameter("storage_id").equals("")) { document.setStorage_id(httpServletRequest.getParameter("storage_id")); } documentList = new DocumentList(); documentList.setDoc(new ArrayList<Document>()); documentList.getDoc().add(document); } else { // if exists cookie with name "PaiaServiceDocumentList": read it Cookie[] cookies = httpServletRequest.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("PaiaServiceDocumentList")) { if (cookie.getValue() != null && !cookie.getValue().equals("") && !cookie.getValue().equals("null")) { String value = URLDecoder.decode(cookie.getValue(), "UTF-8"); this.logger.info(value); documentList = mapper.readValue(value, DocumentList.class); } break; } } } } } if (patronid.equals("")) { // Authorization this.authorize(httpServletRequest, httpServletResponse, format, documentList); } else { redirect_url = ""; if (httpServletRequest.getParameter("redirect_url") != null && !httpServletRequest.getParameter("redirect_url").equals("")) { redirect_url = httpServletRequest.getParameter("redirect_url"); } this.logger.info("redirect_url = " + redirect_url); language = ""; // PAIA core - function if ((httpServletRequest.getMethod().equals("GET") && (service.equals("patron") || service.equals("fullpatron") || service.equals("items") || service.startsWith("items/ordered") || service.startsWith("items/reserved") || service.startsWith("items/borrowed") || service.startsWith("items/borrowed/ill") || service.startsWith("items/borrowed/renewed") || service.startsWith("items/borrowed/recalled") || service.equals("fees") || service.equals("request") || service.equals("favorites") || service.equals("favlist") || service.equals("backup/favorites"))) || (httpServletRequest.getMethod().equals("POST") && (service.equals("request") || service.equals("renew") || service.equals("cancel") || service.equals("favorite")))) { // get 'Accept' and 'Authorization' from Header Enumeration<String> headerNames = httpServletRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerNameKey = (String) headerNames.nextElement(); this.logger.debug("headerNameKey = " + headerNameKey + " / headerNameValue = " + httpServletRequest.getHeader(headerNameKey)); if (headerNameKey.equals("Accept-Language")) { language = httpServletRequest.getHeader(headerNameKey); this.logger.debug("Accept-Language: " + language); } if (headerNameKey.equals("Accept")) { accept = httpServletRequest.getHeader(headerNameKey); this.logger.debug("Accept: " + accept); } if (headerNameKey.equals("Authorization")) { authorization = httpServletRequest.getHeader(headerNameKey); } } // language if (language.startsWith("de")) { language = "de"; } else if (language.startsWith("en")) { language = "en"; } else if (httpServletRequest.getParameter("l") != null) { language = httpServletRequest.getParameter("l"); } else { language = "de"; } // if not exists token: read request parameter if ((authorization == null || authorization.equals("")) && httpServletRequest.getParameter("access_token") != null && !httpServletRequest.getParameter("access_token").equals("")) { authorization = httpServletRequest.getParameter("access_token"); } // if not exists token if (authorization == null || authorization.equals("")) { // if exists PaiaService-Cookie: read content Cookie[] cookies = httpServletRequest.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("PaiaService")) { String value = URLDecoder.decode(cookie.getValue(), "UTF-8"); this.logger.info(value); LoginResponse loginResponse = mapper.readValue(value, LoginResponse.class); // A C H T U N G: ggf. andere patronID im Cookie als in Request (UniAccount vs. BibAccount) if (loginResponse.getPatron().equals(patronid)) { authorization = loginResponse.getAccess_token(); } break; } } // if not exists token - search for Shibboleth-Token if (authorization == null || authorization.equals("")) { if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) { AuthorizationInterface authorizationInterface = Lookup.lookup(AuthorizationInterface.class); // init Authorization Service authorizationInterface.init(this.config); try { authorization = authorizationInterface.getAuthCookies(cookies); } catch (AuthorizationException e) { // TODO correct error handling this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!"); } this.logger.debug("Authorization: " + authorization); } } } } httpServletResponse.setHeader("Access-Control-Allow-Origin", this.config.getProperty("Access-Control-Allow-Origin")); httpServletResponse.setHeader("Cache-Control", this.config.getProperty("Cache-Control")); // check token ... boolean isAuthorized = false; if (authorization != null && !authorization.equals("")) { if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) { AuthorizationInterface authorizationInterface = Lookup.lookup(AuthorizationInterface.class); // init Authorization Service authorizationInterface.init(this.config); try { isAuthorized = authorizationInterface.isTokenValid(httpServletResponse, service, patronid, authorization); } catch (AuthorizationException e) { // TODO correct error handling this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!"); } } else { // TODO correct error handling this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": " + "Authorization Interface not implemented!"); } } this.logger.debug("Authorization: " + authorization + " - " + isAuthorized); if (isAuthorized) { // execute query this.provideService(httpServletRequest, httpServletResponse, patronid, service, format, language, redirect_url, documentList, application, listName, favoriteRequest); } else { // Authorization this.authorize(httpServletRequest, httpServletResponse, format, documentList); } } else { this.logger.error(HttpServletResponse.SC_METHOD_NOT_ALLOWED + ": " + httpServletRequest.getMethod() + " for '" + service + "' not allowed!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED))); requestError.setCode(HttpServletResponse.SC_METHOD_NOT_ALLOWED); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } } } protected void doOptions(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { httpServletResponse.setHeader("Access-Control-Allow-Methods", this.config.getProperty("Access-Control-Allow-Methods")); httpServletResponse.addHeader("Access-Control-Allow-Headers", this.config.getProperty("Access-Control-Allow-Headers")); httpServletResponse.setHeader("Accept", this.config.getProperty("Accept")); httpServletResponse.setHeader("Access-Control-Allow-Origin", this.config.getProperty("Access-Control-Allow-Origin")); httpServletResponse.setHeader("Cache-Control", this.config.getProperty("Cache-Control")); httpServletResponse.getWriter().println(); } /** * * @param httpServletRequest * @param httpServletResponse * @throws IOException */ private void authorize(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String format, DocumentList documents) throws IOException { httpServletResponse.setHeader("Access-Control-Allow-Origin", this.config.getProperty("Access-Control-Allow-Origin")); httpServletResponse.setHeader("Cache-Control", this.config.getProperty("Cache-Control")); ObjectMapper mapper = new ObjectMapper(); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED))); requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri")); // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(RequestError.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(requestError, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), requestError); } // html > redirect zu "PAIA auth - login" mit redirect_url = "PAIA core - service" if (format.equals("html")) { httpServletResponse.setContentType("text/html;charset=UTF-8"); if (documents != null) { // set Cookie with urlencoded DocumentList-JSON StringWriter stringWriter = new StringWriter(); mapper.writeValue(stringWriter, documents); Cookie cookie = new Cookie("PaiaServiceDocumentList", URLEncoder.encode(stringWriter.toString(), "UTF-8")); if (this.config.getProperty("service.cookie.domain") != null && !this.config.getProperty("service.cookie.domain").equals("")) { cookie.setDomain(this.config.getProperty("service.cookie.domain")); } cookie.setMaxAge(-1); cookie.setPath("/"); httpServletResponse.addCookie(cookie); } //String redirect_url = "http://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort() + this.config.getProperty("service.endpoint.core") + httpServletRequest.getPathInfo(); String redirect_url = this.config.getProperty("service.base_url") + this.config.getProperty("service.endpoint.core") + httpServletRequest.getPathInfo(); if (httpServletRequest.getQueryString() != null && !httpServletRequest.getQueryString().equals("")) { redirect_url += "?" + httpServletRequest.getQueryString(); } this.logger.info("redirect_url = " + redirect_url); //String login_url = "http://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort() + this.config.getProperty("service.endpoint.auth") + "/login?redirect_url=" + redirect_url; String login_url = this.config.getProperty("service.base_url") + this.config.getProperty("service.endpoint.auth") + "/login?redirect_url=" + redirect_url; this.logger.info("login_url = " + login_url); httpServletResponse.sendRedirect(login_url); } } /** * PAIA core services: Prüfe jeweils die scopes und liefere die Daten */ private void provideService(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String patronid, String service, String format, String language, String redirect_url, DocumentList documents, String application, String listName, FavoriteList favoriteRequest) throws IOException { httpServletResponse.setHeader("Access-Control-Allow-Origin", this.config.getProperty("Access-Control-Allow-Origin")); httpServletResponse.setHeader("Cache-Control", this.config.getProperty("Cache-Control")); ObjectMapper mapper = new ObjectMapper(); if (Lookup.lookupAll(LibraryManagementSystem.class).size() > 0) { try { LibraryManagementSystem libraryManagementSystem = Lookup.lookup(LibraryManagementSystem.class); // init ILS libraryManagementSystem.init(this.config); switch (service) { case "patron": { Patron patron = libraryManagementSystem.patron(patronid, false); if (patron != null) { StringWriter json = new StringWriter(); mapper = new ObjectMapper(); mapper.writeValue(json, patron); this.logger.debug(json); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_patron"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(patron, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(Patron.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(patron, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), patron); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "fullpatron": { Patron patron = libraryManagementSystem.patron(patronid, true); if (patron != null) { StringWriter json = new StringWriter(); mapper = new ObjectMapper(); mapper.writeValue(json, patron); this.logger.debug(json); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "write_patron"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(patron, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(Patron.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(patron, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), patron); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "items": { DocumentList documentList = libraryManagementSystem.items(patronid, "all"); if (documentList != null) { StringWriter json = new StringWriter(); mapper = new ObjectMapper(); mapper.writeValue(json, documentList); this.logger.debug(json); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(documentList, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(DocumentList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(documentList, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), documentList); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "items/borrowed": { DocumentList documentList = libraryManagementSystem.items(patronid, "borrowed"); if (documentList != null) { StringWriter json = new StringWriter(); mapper = new ObjectMapper(); mapper.writeValue(json, documentList); this.logger.debug(json); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(documentList, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(DocumentList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(documentList, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), documentList); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "items/borrowed/ill": { DocumentList documentList = libraryManagementSystem.items(patronid, "borrowed", "ill"); if (documentList != null) { StringWriter json = new StringWriter(); mapper = new ObjectMapper(); mapper.writeValue(json, documentList); this.logger.debug(json); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(documentList, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(DocumentList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(documentList, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), documentList); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "items/borrowed/renewed": { DocumentList documentList = libraryManagementSystem.items(patronid, "borrowed", "renewed"); if (documentList != null) { StringWriter json = new StringWriter(); mapper = new ObjectMapper(); mapper.writeValue(json, documentList); this.logger.debug(json); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(documentList, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(DocumentList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(documentList, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), documentList); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "items/borrowed/recalled": { DocumentList documentList = libraryManagementSystem.items(patronid, "borrowed", "recalled"); if (documentList != null) { StringWriter json = new StringWriter(); mapper = new ObjectMapper(); mapper.writeValue(json, documentList); this.logger.debug(json); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(documentList, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(DocumentList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(documentList, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), documentList); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "items/ordered": { DocumentList documentList = libraryManagementSystem.items(patronid, "ordered"); if (documentList != null) { StringWriter json = new StringWriter(); mapper = new ObjectMapper(); mapper.writeValue(json, documentList); this.logger.debug(json); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(documentList, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(DocumentList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(documentList, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), documentList); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "items/reserved": { DocumentList documentList = libraryManagementSystem.items(patronid, "reserved"); if (documentList != null) { StringWriter json = new StringWriter(); mapper = new ObjectMapper(); mapper.writeValue(json, documentList); this.logger.debug(json); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(documentList, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(DocumentList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(documentList, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), documentList); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "request": { DocumentList documentList = libraryManagementSystem.request(patronid, documents); if (documentList != null) { StringWriter json = new StringWriter(); mapper.writeValue(json, documentList); this.logger.debug(json); // set Cookie with new value for urlencoded DocumentList-JSON StringWriter stringWriter = new StringWriter(); mapper.writeValue(stringWriter, documents); Cookie cookie = new Cookie("PaiaServiceDocumentList", URLEncoder.encode(stringWriter.toString(), "UTF-8")); if (this.config.getProperty("service.cookie.domain") != null && !this.config.getProperty("service.cookie.domain").equals("")) { cookie.setDomain(this.config.getProperty("service.cookie.domain")); } cookie.setMaxAge(-1); cookie.setPath("/"); httpServletResponse.addCookie(cookie); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "write_items"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { this.logger.info("redirect_url = " + redirect_url); if (!redirect_url.equals("")) { httpServletResponse.sendRedirect(redirect_url); } else { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(documentList, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } } else{ this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(DocumentList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(documentList, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), documentList); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "renew": { DocumentList documentList = libraryManagementSystem.renew(patronid, documents); if (documentList != null) { StringWriter json = new StringWriter(); mapper.writeValue(json, documentList); this.logger.debug(json); // delete DocumentList cookie Cookie cookie = new Cookie("PaiaServiceDocumentList", null); if (this.config.getProperty("service.cookie.domain") != null && !this.config.getProperty("service.cookie.domain").equals("")) { cookie.setDomain(this.config.getProperty("service.cookie.domain")); } cookie.setMaxAge(0); httpServletResponse.addCookie(cookie); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "write_items"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(documentList, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(DocumentList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(documentList, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), documentList); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "cancel": { DocumentList documentList = libraryManagementSystem.cancel(patronid, documents); if (documentList != null) { StringWriter json = new StringWriter(); mapper.writeValue(json, documentList); this.logger.debug(json); // delete DocumentList cookie Cookie cookie = new Cookie("PaiaServiceDocumentList", null); if (this.config.getProperty("service.cookie.domain") != null && !this.config.getProperty("service.cookie.domain").equals("")) { cookie.setDomain(this.config.getProperty("service.cookie.domain")); } cookie.setMaxAge(0); httpServletResponse.addCookie(cookie); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "write_items"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(documentList, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(DocumentList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(documentList, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), documentList); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "fees": { FeeList feeList = libraryManagementSystem.fees(patronid); if (feeList != null) { StringWriter json = new StringWriter(); mapper = new ObjectMapper(); mapper.writeValue(json, feeList); this.logger.debug(json); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_fees"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(feeList, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(FeeList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(feeList, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), feeList); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "favorite": { if (listName.equals("") || listName.equals(null)) { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else { Jedis jedis = new Jedis(this.config.getProperty("redis-favorites-server"), Integer.parseInt(this.config.getProperty("redis-favorites-server-port"))); // Einlesen der Konkordanz, die einer Application einen Redis-DB-Index zuordnet Map<String, Object> concordance = mapper.readValue(new File("conf/concordance.json"), Map.class); if (concordance.containsKey(application)) { int appIndex = Integer.parseInt(String.valueOf(concordance.get(application))); jedis.select(appIndex); String listContent; if (jedis.hexists(patronid, listName)) { listContent = jedis.hget(patronid, listName); FavoriteList favoriteList = mapper.readValue(listContent, FavoriteList.class); ArrayList<Favorite> arrayList = favoriteList.getFavorites(); String[] recordids = new String[arrayList.size()]; String[] openUrls = new String[arrayList.size()]; for (int i = 0; i < arrayList.size(); i++) { recordids[i] = arrayList.get(i).getRecordid(); } for (int i = 0; i < arrayList.size(); i++) { openUrls[i] = arrayList.get(i).getOpenUrl(); } for (int i = 0; i < favoriteRequest.getFavorites().size(); i++) { Favorite favoriteToAdd = favoriteRequest.getFavorites().get(i); if (!Arrays.asList(recordids).contains(favoriteToAdd.getRecordid()) || !Arrays.asList(openUrls).contains(favoriteToAdd.getOpenUrl())) { arrayList.add(favoriteToAdd); } } favoriteList.setFavorites(arrayList); listContent = mapper.writeValueAsString(favoriteList); jedis.hset(patronid, listName, listContent); } else { FavoriteList favoriteList = new FavoriteList(); ArrayList<Favorite> arrayList =new ArrayList<>(); for (int i = 0; i < favoriteRequest.getFavorites().size(); i++) { Favorite favoriteToAdd = favoriteRequest.getFavorites().get(i); arrayList.add(favoriteToAdd); } favoriteList.setFavorites(arrayList); listContent = mapper.writeValueAsString(favoriteList); jedis.hset(patronid, listName, listContent); } httpServletResponse.setStatus(HttpServletResponse.SC_CREATED); } else { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } /* erste Version: if (listName.equals("") || listName.equals(null)) { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else { // Einlesen der Konkordanz, die einer Application einen Redis-DB-Index zuordnet Map<String, Object> concordance = mapper.readValue(new File("conf/concordance.json"), Map.class); int appIndex = Integer.parseInt(String.valueOf(concordance.get(application))); Jedis jedis = new Jedis(this.config.getProperty("redis-favorites-server"), Integer.parseInt(this.config.getProperty("redis-favorites-server-port"))); jedis.select(appIndex); String listContent; // Fallunterscheidung danach, ob eine Liste mit dem angegebenen Namen bereits existiert if (jedis.hexists(patronid, listName)) { // Holen der Liste und Ablegen in ein POJO listContent = jedis.hget(patronid, listName); FavoriteList favoriteList = mapper.readValue(listContent, FavoriteList.class); // Hinzufügen des Favoriten, wenn er noch nicht in der Liste enthalten ist, mit Hilfe einer ArrayList ArrayList<Favorite> al = favoriteList.getFavorites(); String[] recordIds = new String[al.size()]; for (int i = 0; i < al.size(); i++) { recordIds[i] = al.get(i).getRecordid(); } for (int i = 0; i < favoriteRequest.getFavorites().size(); i++) { Favorite favoriteToAdd = favoriteRequest.getFavorites().get(i); if (!Arrays.asList(recordIds).contains(favoriteToAdd.getRecordid())) { al.add(favoriteToAdd); } } favoriteList.setFavorites(al); // Schreiben in Redis: listContent = mapper.writeValueAsString(favoriteList); jedis.hset(patronid, listName, listContent); } else { // Anlegen einer neuen Merkliste als Objekt, mit dem Namen aus dem FavoriteRequest: FavoriteList favoriteList = new FavoriteList(); favoriteList.setList(favoriteRequest.getList()); favoriteList.setApplication(favoriteRequest.getApplication()); // ArrayList zum Hinzufügen: ArrayList<Favorite> arrayList = new ArrayList<>(); for (int i = 0; i < favoriteRequest.getFavorites().size(); i++) { Favorite favorite = favoriteRequest.getFavorites().get(i); arrayList.add(favorite); } // Bearbeitete ArrayList in das Objekt: favoriteList.setFavorites(arrayList); // Schreiben in Redis listContent = mapper.writeValueAsString(favoriteList); jedis.hset(patronid, listName, listContent); } httpServletResponse.setStatus(HttpServletResponse.SC_CREATED); } */ break; } case "favlist": { // Einlesen der Konkordanz, die einer Application einen Redis-DB-Index zuordnet Map<String, Object> concordance = mapper.readValue(new File("conf/concordance.json"), Map.class); if (concordance.containsKey(application)) { int appIndex = Integer.parseInt(String.valueOf(concordance.get(application))); Jedis jedis = new Jedis(this.config.getProperty("redis-favorites-server"), Integer.parseInt(this.config.getProperty("redis-favorites-server-port"))); jedis.select(appIndex); if (listName.equals("")) { Set<String> fieldNames = jedis.hkeys(patronid); if (fieldNames.isEmpty()) { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { FavoriteListList favoriteListList = new FavoriteListList(); favoriteListList.setFavoriteLists(fieldNames); String lists = mapper.writeValueAsString(favoriteListList); // XML-Ausgabe mit JAXB // TODO // JSON-Ausgabe if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); httpServletResponse.getWriter().write(lists); } } } else { if (jedis.hexists(patronid, listName)) { String listContent = jedis.hget(patronid, listName); httpServletResponse.setStatus(HttpServletResponse.SC_OK); // XML-Ausgabe mit JAXB // TODO // JSON-Ausgabe if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); httpServletResponse.getWriter().write(listContent); } } else { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); } } } else { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } break; } /* alte 'cases' favor, unfavor, favorites auskommentiert case "favor": { if ((favoriteRequest.getApplication().equals("") || favoriteRequest.getApplication().equals(null)) || (listName.equals("") || listName.equals(null))) { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else { // Jedis-Objekt zur Kommunikation mit Redis Jedis jedis = new Jedis(this.config.getProperty("redis-favorites-server"), Integer.parseInt(this.config.getProperty("redis-favorites-server-port"))); String listContent; if (jedis.hexists(patronid, listName)) { // Holen der Merkliste, wenn diese bereits existiert, aus Redis: listContent = jedis.hget(patronid, listName); // Von der String-Variable zum Objekt: FavoriteList favoriteList = mapper.readValue(listContent, FavoriteList.class); // ArrayList zum Hinzufügen: ArrayList<Favorite> arrayList = favoriteList.getFavorites(); // Array mit nur den Recordids aus der ArrayList: String[] recordids = new String[arrayList.size()]; for (int i = 0; i < arrayList.size(); i++) { recordids[i] = arrayList.get(i).getRecordid(); } // Einfügen von Favoriten, wenn recordid nicht in dem Array enthalten: for (int i = 0; i < favoriteRequest.getFavorites().size(); i++) { Favorite favoriteToAdd = favoriteRequest.getFavorites().get(i); if (!Arrays.asList(recordids).contains(favoriteToAdd.getRecordid())) { arrayList.add(favoriteToAdd); } } // Bearbeitete ArrayList in das Objekt: favoriteList.setFavorites(arrayList); // Schreiben in Redis: listContent = mapper.writeValueAsString(favoriteList); jedis.hset(patronid, listName, listContent); } else { // Anlegen einer neuen Merkliste als Objekt, mit dem Namen aus dem FavoriteRequest: FavoriteList favoriteList = new FavoriteList(); favoriteList.setList(favoriteRequest.getList()); favoriteList.setApplication(favoriteRequest.getApplication()); // ArrayList zum Hinzufügen: ArrayList<Favorite> arrayList = new ArrayList<>(); for (int i = 0; i < favoriteRequest.getFavorites().size(); i++) { Favorite favorite = favoriteRequest.getFavorites().get(i); arrayList.add(favorite); } // Bearbeitete ArrayList in das Objekt: favoriteList.setFavorites(arrayList); // Schreiben in Redis listContent = mapper.writeValueAsString(favoriteList); jedis.hset(patronid, listName, listContent); } httpServletResponse.setStatus(HttpServletResponse.SC_CREATED); } break; } case "unfavor": { // Jedis-Objekt zur Kommunikation mit Redis Jedis jedis = new Jedis(this.config.getProperty("redis-favorites-server"), Integer.parseInt(this.config.getProperty("redis-favorites-server-port"))); if (jedis.hexists(patronid, listName)) { // Holen der Merkliste, wenn diese bereits existiert, aus Redis: String listContent = jedis.hget(patronid, listName); // Von der String-Variable zum Objekt: FavoriteList favoriteList = mapper.readValue(listContent, FavoriteList.class); // ArrayList zum Arbeiten: ArrayList<Favorite> arrayList = favoriteList.getFavorites(); // Einen oder mehrere Favoriten aus der ArrayList entfernen: for (int i = 0; i < favoriteRequest.getFavorites().size(); i++) { Favorite favoriteToRemove = favoriteRequest.getFavorites().get(i); for (int j = 0; j < arrayList.size(); j++) { if (favoriteToRemove.getRecordid().equals(arrayList.get(j).getRecordid())) { arrayList.remove(j); } } } // Bearbeitete ArrayList in das Objekt: favoriteList.setFavorites(arrayList); // Schreiben in Redis: listContent = mapper.writeValueAsString(favoriteList); jedis.hset(patronid, listName, listContent); httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } break; } case "favorites": { // Jedis-Objekt zur Kommunikation mit Redis Jedis jedis = new Jedis(this.config.getProperty("redis-favorites-server"), Integer.parseInt(this.config.getProperty("redis-favorites-server-port"))); // Wenn kein Listenname angegeben ist, Ausgabe aller Listen, die der patron angelegt hat if (listName.equals("")){ Set<String> listsOfPatron = jedis.hkeys(patronid); if (listsOfPatron.isEmpty()) { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { // Aufbau eines Objekts, nämlich einer Liste von Merklisten eines Nutzers FavoriteListList favoriteListList = new FavoriteListList(); favoriteListList.setPatron(patronid); favoriteListList.setFavoriteLists(new ArrayList<FavoriteList>()); for (String list : listsOfPatron) { String listContent = jedis.hget(patronid, list); FavoriteList favoriteList = mapper.readValue(listContent, FavoriteList.class); favoriteListList.getFavoriteLists().add(favoriteList); } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), favoriteListList); } } } // sonst, Ausgabe der angegebenen Merkliste // (evtl. überflüssig, wenn, um Requests zu sparen, nur der if-Zweig genutzt wird) else { if (jedis.hexists(patronid, listName)) { String listContent = jedis.hget(patronid, listName); httpServletResponse.setStatus(HttpServletResponse.SC_OK); // XML-Ausgabe mit JAXB // TODO // JSON-Ausgabe if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); httpServletResponse.getWriter().write(listContent); } } else { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); } } break; } */ case "backup/favorites" : { // Jedis-Objekt zur Kommunikation mit Redis Jedis jedis = new Jedis(this.config.getProperty("redis-favorites-server"), Integer.parseInt(this.config.getProperty("redis-favorites-server-port"))); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.setContentType("application/csv;charset=UTF-8"); // Variablen zur Aufnahme des Ergebnisses einer SCAN-Anfrage an Redis String cursor = "0"; List<String> resultList; // Schleife, bis cursor wieder bei "0" ist, um alle keys abzufragen do { // SCAN-Anfrage ScanResult<String> scanResult = jedis.scan(cursor); resultList = scanResult.getResult(); // Schleife über alle keys for (int i = 0; i < resultList.size(); i++) { String key = resultList.get(i); // Überprüfung, ob unter dem key ein hash gespeichert ist if (jedis.type(key).equals("hash")) { Set<String> fields = jedis.hkeys(key); // Schleife über alle fields eines key for (String field : fields) { String value = jedis.hget(key, field); httpServletResponse.getWriter().println(key + ";" + field + ";" + value); } } } // Neu Setzen des Cursors cursor = scanResult.getStringCursor(); } while (!cursor.equals("0")); jedis.close(); break; } // hier ggf. weitere cases für andere Backup-Szenarien } } catch (LibraryManagementSystemException e) { StringWriter json = new StringWriter(); // TODO Frage nach "570-unknown patron" ist nicht gut! Lösung: Welche Typen von ILSExceptions treten auf? Erzeuge für jeden Typ eine eigene Exception! if (e.getMessage().contains("570-unknown patron")) { this.logger.error(HttpServletResponse.SC_NOT_FOUND + ": '" + patronid + "'"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_NOT_FOUND))); requestError.setCode(HttpServletResponse.SC_NOT_FOUND); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_NOT_FOUND) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_NOT_FOUND) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } else { this.logger.error(HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } catch (Exception e) { e.printStackTrace(); } } else { this.logger.error(HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": Config Error!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } private void sendRequestError(HttpServletResponse httpServletResponse, RequestError requestError, String format, String language, String redirect_url) { httpServletResponse.setHeader("Access-Control-Allow-Origin", config.getProperty("Access-Control-Allow-Origin")); httpServletResponse.setHeader("Cache-Control", config.getProperty("Cache-Control")); ObjectMapper mapper = new ObjectMapper(); httpServletResponse.setHeader("WWW-Authentificate", "Bearer"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAIA core\""); httpServletResponse.setContentType("application/json"); try { // html if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("redirect_uri_params", URLDecoder.decode(redirect_url, "UTF-8")); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(requestError, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(RequestError.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(requestError, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), requestError); } } catch (Exception e) { e.printStackTrace(); } } }
src/main/java/de/tu_dortmund/ub/api/paia/core/PaiaCoreEndpoint.java
/* The MIT License (MIT) Copyright (c) 2015-2016, Hans-Georg Becker, http://orcid.org/0000-0003-0432-294X 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 de.tu_dortmund.ub.api.paia.core; import com.fasterxml.jackson.databind.ObjectMapper; import com.opencsv.CSVReader; import com.opencsv.CSVWriter; import de.tu_dortmund.ub.api.paia.core.model.*; import de.tu_dortmund.ub.api.paia.interfaces.AuthorizationException; import de.tu_dortmund.ub.api.paia.interfaces.AuthorizationInterface; import de.tu_dortmund.ub.api.paia.auth.model.LoginResponse; import de.tu_dortmund.ub.api.paia.interfaces.LibraryManagementSystemException; import de.tu_dortmund.ub.api.paia.interfaces.LibraryManagementSystem; import de.tu_dortmund.ub.api.paia.model.RequestError; import de.tu_dortmund.ub.util.impl.Lookup; import de.tu_dortmund.ub.util.output.ObjectToHtmlTransformation; import de.tu_dortmund.ub.util.output.TransformationException; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import redis.clients.jedis.Jedis; import redis.clients.jedis.ScanResult; import javax.json.JsonObject; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import java.io.*; import java.net.URLDecoder; import java.net.URLEncoder; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.*; /** * This class represents the PAIA Core component. * * @author Hans-Georg Becker * @version 2015-05-06 */ public class PaiaCoreEndpoint extends HttpServlet { // Configuration private String conffile = ""; private Properties config = new Properties(); private Logger logger = Logger.getLogger(PaiaCoreEndpoint.class.getName()); /** * * @throws IOException */ public PaiaCoreEndpoint() throws IOException { this("conf/paia.properties"); } /** * * @param conffile * @throws IOException */ public PaiaCoreEndpoint(String conffile) throws IOException { this.conffile = conffile; // Init properties try { InputStream inputStream = new FileInputStream(conffile); try { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); try { this.config.load(reader); } finally { reader.close(); } } finally { inputStream.close(); } } catch (IOException e) { System.out.println("FATAL ERROR: Die Datei '" + conffile + "' konnte nicht geöffnet werden!"); } // init logger PropertyConfigurator.configure(this.config.getProperty("service.log4j-conf")); this.logger.info("Starting 'PAIA Core Endpoint' ..."); this.logger.info("conf-file = " + conffile); this.logger.info("log4j-conf-file = " + this.config.getProperty("service.log4j-conf")); } /** * * @param httpServletRequest * @param httpServletResponse * @throws ServletException * @throws IOException */ protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { this.doPost(httpServletRequest, httpServletResponse); } /** * * @param httpServletRequest * @param httpServletResponse */ protected void doDelete(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException { this.logger.debug("PathInfo = " + httpServletRequest.getPathInfo()); this.logger.debug("QueryString = " + httpServletRequest.getQueryString()); String patronid = ""; String service = ""; String application = ""; String listName = ""; String favoriteId = ""; ObjectMapper mapper = new ObjectMapper(); // Einlesen der Konkordanz, die einer Application einen Redis-DB-Index zuordnet Map<String, Object> concordance = mapper.readValue(new File("conf/concordance.json"), Map.class); Jedis jedis = new Jedis(this.config.getProperty("redis-favorites-server"), Integer.parseInt(this.config.getProperty("redis-favorites-server-port"))); String path = httpServletRequest.getPathInfo(); if (!path.equals(null)) { String[] params = path.substring(1,path.length()).split("/"); switch (params.length) { // ganze Liste löschen: case 4: patronid = params[0]; service = params[1]; application = params[2]; listName = params[3]; if (service.equals("favlist")) { int appIndexList = Integer.parseInt(String.valueOf(concordance.get(application))); jedis.select(appIndexList); if (jedis.hexists(patronid, listName)) { jedis.hdel(patronid, listName); httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); } } break; // einzelnen Favoriten löschen: case 5: patronid = params[0]; service = params[1]; application = params[2]; listName = params[3]; favoriteId = params[4]; if (service.equals("favorite")) { int appIndexSingleFavorite = Integer.parseInt(String.valueOf(concordance.get(application))); jedis.select(appIndexSingleFavorite); if (jedis.hexists(patronid, listName)) { String listContent = jedis.hget(patronid, listName); FavoriteList favoriteList = mapper.readValue(listContent, FavoriteList.class); String[] recordids = new String[favoriteList.getFavorites().size()]; for (int i = 0; i < favoriteList.getFavorites().size(); i++) { recordids[i] = favoriteList.getFavorites().get(i).getRecordid(); } if (Arrays.asList(recordids).contains(favoriteId)) { ArrayList<Favorite> arrayList = favoriteList.getFavorites(); for (int i = 0; i < arrayList.size(); i++) { if (favoriteList.getFavorites().get(i).getRecordid().equals(favoriteId)) { arrayList.remove(i); httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT); } } favoriteList.setFavorites(arrayList); listContent = mapper.writeValueAsString(favoriteList); jedis.hset(patronid, listName, listContent); } else { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); // Favoriten nicht gefunden } } else { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); // Liste nicht gefunden } } break; } } else { // TODO } /* alte Version: this.logger.debug("PathInfo = " + httpServletRequest.getPathInfo()); this.logger.debug("QueryString = " + httpServletRequest.getQueryString()); String patronid = ""; String service = ""; String listName = ""; String path = httpServletRequest.getPathInfo(); if (path != null) { String[] params = path.substring(1,path.length()).split("/"); if (params.length == 3) { patronid = params[0]; service = params[1]; listName = params[2]; // Jedis-Objekt zur Kommunikation mit Redis Jedis jedis = new Jedis(this.config.getProperty("redis-favorites-server"), Integer.parseInt(this.config.getProperty("redis-favorites-server-port"))); if (service.equals("deletefavlist")) { if (jedis.hexists(patronid, listName)) { jedis.hdel(patronid, listName); httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); } } } else { httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } */ } /** * * @param httpServletRequest * @param httpServletResponse * @throws ServletException * @throws IOException */ protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { ObjectMapper mapper = new ObjectMapper(); String format; String language; String redirect_url; this.logger.debug("PathInfo = " + httpServletRequest.getPathInfo()); this.logger.debug("QueryString = " + httpServletRequest.getQueryString()); String patronid = ""; String service = ""; String accept = ""; String authorization = ""; String application = ""; String listName = ""; FavoriteList favoriteRequest = new FavoriteList(); String path = httpServletRequest.getPathInfo(); if (path != null) { String[] params = path.substring(1,path.length()).split("/"); if (params.length == 1) { patronid = params[0]; service = "patron"; } else if (params.length == 2) { if (params[0].equals("backup")) { switch (params[1]) { case "favorites" : patronid = "ubdo"; service = "backup/favorites"; break; // hier ggf. weitere cases für andere Backups ergänzen } } else { patronid = params[0]; service = params[1]; } } else if (params[1].equals("items") && params.length > 2) { patronid = params[0]; for (int i = 1; i < params.length; i++) { service += params[i]; if (i < params.length-1) { service += "/"; } } } else if ((params[1].equals("favorite") || params[1].equals("favlist")) && params.length > 2) { patronid = params[0]; service = params[1]; application = params[2]; if (params.length > 3) { listName = params[3]; } } /* alt: else if (params[1].equals("favorites") && params.length > 2) { patronid = params[0]; service = params[1]; listName = params[2]; } */ } if (patronid.equals("patronid")) { patronid = ""; } this.logger.debug("Service: " + service); this.logger.debug("Patron: " + patronid); format = "html"; if (httpServletRequest.getParameter("format") != null && !httpServletRequest.getParameter("format").equals("")) { format = httpServletRequest.getParameter("format"); } else { Enumeration<String> headerNames = httpServletRequest.getHeaderNames(); while ( headerNames.hasMoreElements() ) { String headerNameKey = headerNames.nextElement(); if (headerNameKey.equals("Accept")) { this.logger.debug("headerNameKey = " + httpServletRequest.getHeader( headerNameKey )); if (httpServletRequest.getHeader( headerNameKey ).contains("text/html")) { format = "html"; } else if (httpServletRequest.getHeader( headerNameKey ).contains("application/xml")) { format = "xml"; } else if (httpServletRequest.getHeader( headerNameKey ).contains("application/json")) { format = "json"; } } } } this.logger.info("format = " + format); if (format.equals("html") && Lookup.lookupAll(ObjectToHtmlTransformation.class).size() == 0) { this.logger.error(HttpServletResponse.SC_BAD_REQUEST + ": " + "html not implemented!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST))); requestError.setCode(HttpServletResponse.SC_BAD_REQUEST); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, "", ""); } else { // read requestBody StringBuffer jb = new StringBuffer(); String line = null; try { BufferedReader reader = httpServletRequest.getReader(); while ((line = reader.readLine()) != null) jb.append(line); } catch (Exception e) { /*report an error*/ } String requestBody = jb.toString(); if (service.equals("favorite")) { favoriteRequest = mapper.readValue(requestBody, FavoriteList.class); // listName = favoriteRequest.getList(); } // read document list DocumentList documentList = null; try { // read DocumentList documentList = mapper.readValue(requestBody, DocumentList.class); } catch (Exception e) { if (!requestBody.equals("")) { String[] params = requestBody.split("&"); if (params.length > 1) { documentList = new DocumentList(); documentList.setDoc(new ArrayList<Document>()); for (String param : params) { if (param.startsWith("document_id")) { Document document = new Document(); document.setEdition(param.split("=")[1]); documentList.getDoc().add(document); } } } } else if (httpServletRequest.getParameter("document_id") != null && !httpServletRequest.getParameter("document_id").equals("")) { Document document = new Document(); document.setEdition(httpServletRequest.getParameter("document_id")); if (httpServletRequest.getParameter("storage_id") != null && !httpServletRequest.getParameter("storage_id").equals("")) { document.setStorage_id(httpServletRequest.getParameter("storage_id")); } documentList = new DocumentList(); documentList.setDoc(new ArrayList<Document>()); documentList.getDoc().add(document); } else { // if exists cookie with name "PaiaServiceDocumentList": read it Cookie[] cookies = httpServletRequest.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("PaiaServiceDocumentList")) { if (cookie.getValue() != null && !cookie.getValue().equals("") && !cookie.getValue().equals("null")) { String value = URLDecoder.decode(cookie.getValue(), "UTF-8"); this.logger.info(value); documentList = mapper.readValue(value, DocumentList.class); } break; } } } } } if (patronid.equals("")) { // Authorization this.authorize(httpServletRequest, httpServletResponse, format, documentList); } else { redirect_url = ""; if (httpServletRequest.getParameter("redirect_url") != null && !httpServletRequest.getParameter("redirect_url").equals("")) { redirect_url = httpServletRequest.getParameter("redirect_url"); } this.logger.info("redirect_url = " + redirect_url); language = ""; // PAIA core - function if ((httpServletRequest.getMethod().equals("GET") && (service.equals("patron") || service.equals("fullpatron") || service.equals("items") || service.startsWith("items/ordered") || service.startsWith("items/reserved") || service.startsWith("items/borrowed") || service.startsWith("items/borrowed/ill") || service.startsWith("items/borrowed/renewed") || service.startsWith("items/borrowed/recalled") || service.equals("fees") || service.equals("request") || service.equals("favorites") || service.equals("favlist") || service.equals("backup/favorites"))) || (httpServletRequest.getMethod().equals("POST") && (service.equals("request") || service.equals("renew") || service.equals("cancel") || service.equals("favorite")))) { // get 'Accept' and 'Authorization' from Header Enumeration<String> headerNames = httpServletRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerNameKey = (String) headerNames.nextElement(); this.logger.debug("headerNameKey = " + headerNameKey + " / headerNameValue = " + httpServletRequest.getHeader(headerNameKey)); if (headerNameKey.equals("Accept-Language")) { language = httpServletRequest.getHeader(headerNameKey); this.logger.debug("Accept-Language: " + language); } if (headerNameKey.equals("Accept")) { accept = httpServletRequest.getHeader(headerNameKey); this.logger.debug("Accept: " + accept); } if (headerNameKey.equals("Authorization")) { authorization = httpServletRequest.getHeader(headerNameKey); } } // language if (language.startsWith("de")) { language = "de"; } else if (language.startsWith("en")) { language = "en"; } else if (httpServletRequest.getParameter("l") != null) { language = httpServletRequest.getParameter("l"); } else { language = "de"; } // if not exists token: read request parameter if ((authorization == null || authorization.equals("")) && httpServletRequest.getParameter("access_token") != null && !httpServletRequest.getParameter("access_token").equals("")) { authorization = httpServletRequest.getParameter("access_token"); } // if not exists token if (authorization == null || authorization.equals("")) { // if exists PaiaService-Cookie: read content Cookie[] cookies = httpServletRequest.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("PaiaService")) { String value = URLDecoder.decode(cookie.getValue(), "UTF-8"); this.logger.info(value); LoginResponse loginResponse = mapper.readValue(value, LoginResponse.class); // A C H T U N G: ggf. andere patronID im Cookie als in Request (UniAccount vs. BibAccount) if (loginResponse.getPatron().equals(patronid)) { authorization = loginResponse.getAccess_token(); } break; } } // if not exists token - search for Shibboleth-Token if (authorization == null || authorization.equals("")) { if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) { AuthorizationInterface authorizationInterface = Lookup.lookup(AuthorizationInterface.class); // init Authorization Service authorizationInterface.init(this.config); try { authorization = authorizationInterface.getAuthCookies(cookies); } catch (AuthorizationException e) { // TODO correct error handling this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!"); } this.logger.debug("Authorization: " + authorization); } } } } httpServletResponse.setHeader("Access-Control-Allow-Origin", this.config.getProperty("Access-Control-Allow-Origin")); httpServletResponse.setHeader("Cache-Control", this.config.getProperty("Cache-Control")); // check token ... boolean isAuthorized = false; if (authorization != null && !authorization.equals("")) { if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) { AuthorizationInterface authorizationInterface = Lookup.lookup(AuthorizationInterface.class); // init Authorization Service authorizationInterface.init(this.config); try { isAuthorized = authorizationInterface.isTokenValid(httpServletResponse, service, patronid, authorization); } catch (AuthorizationException e) { // TODO correct error handling this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!"); } } else { // TODO correct error handling this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": " + "Authorization Interface not implemented!"); } } this.logger.debug("Authorization: " + authorization + " - " + isAuthorized); if (isAuthorized) { // execute query this.provideService(httpServletRequest, httpServletResponse, patronid, service, format, language, redirect_url, documentList, application, listName, favoriteRequest); } else { // Authorization this.authorize(httpServletRequest, httpServletResponse, format, documentList); } } else { this.logger.error(HttpServletResponse.SC_METHOD_NOT_ALLOWED + ": " + httpServletRequest.getMethod() + " for '" + service + "' not allowed!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED))); requestError.setCode(HttpServletResponse.SC_METHOD_NOT_ALLOWED); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } } } protected void doOptions(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { httpServletResponse.setHeader("Access-Control-Allow-Methods", this.config.getProperty("Access-Control-Allow-Methods")); httpServletResponse.addHeader("Access-Control-Allow-Headers", this.config.getProperty("Access-Control-Allow-Headers")); httpServletResponse.setHeader("Accept", this.config.getProperty("Accept")); httpServletResponse.setHeader("Access-Control-Allow-Origin", this.config.getProperty("Access-Control-Allow-Origin")); httpServletResponse.setHeader("Cache-Control", this.config.getProperty("Cache-Control")); httpServletResponse.getWriter().println(); } /** * * @param httpServletRequest * @param httpServletResponse * @throws IOException */ private void authorize(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String format, DocumentList documents) throws IOException { httpServletResponse.setHeader("Access-Control-Allow-Origin", this.config.getProperty("Access-Control-Allow-Origin")); httpServletResponse.setHeader("Cache-Control", this.config.getProperty("Cache-Control")); ObjectMapper mapper = new ObjectMapper(); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED))); requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri")); // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(RequestError.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(requestError, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), requestError); } // html > redirect zu "PAIA auth - login" mit redirect_url = "PAIA core - service" if (format.equals("html")) { httpServletResponse.setContentType("text/html;charset=UTF-8"); if (documents != null) { // set Cookie with urlencoded DocumentList-JSON StringWriter stringWriter = new StringWriter(); mapper.writeValue(stringWriter, documents); Cookie cookie = new Cookie("PaiaServiceDocumentList", URLEncoder.encode(stringWriter.toString(), "UTF-8")); if (this.config.getProperty("service.cookie.domain") != null && !this.config.getProperty("service.cookie.domain").equals("")) { cookie.setDomain(this.config.getProperty("service.cookie.domain")); } cookie.setMaxAge(-1); cookie.setPath("/"); httpServletResponse.addCookie(cookie); } //String redirect_url = "http://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort() + this.config.getProperty("service.endpoint.core") + httpServletRequest.getPathInfo(); String redirect_url = this.config.getProperty("service.base_url") + this.config.getProperty("service.endpoint.core") + httpServletRequest.getPathInfo(); if (httpServletRequest.getQueryString() != null && !httpServletRequest.getQueryString().equals("")) { redirect_url += "?" + httpServletRequest.getQueryString(); } this.logger.info("redirect_url = " + redirect_url); //String login_url = "http://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort() + this.config.getProperty("service.endpoint.auth") + "/login?redirect_url=" + redirect_url; String login_url = this.config.getProperty("service.base_url") + this.config.getProperty("service.endpoint.auth") + "/login?redirect_url=" + redirect_url; this.logger.info("login_url = " + login_url); httpServletResponse.sendRedirect(login_url); } } /** * PAIA core services: Prüfe jeweils die scopes und liefere die Daten */ private void provideService(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String patronid, String service, String format, String language, String redirect_url, DocumentList documents, String application, String listName, FavoriteList favoriteRequest) throws IOException { httpServletResponse.setHeader("Access-Control-Allow-Origin", this.config.getProperty("Access-Control-Allow-Origin")); httpServletResponse.setHeader("Cache-Control", this.config.getProperty("Cache-Control")); ObjectMapper mapper = new ObjectMapper(); if (Lookup.lookupAll(LibraryManagementSystem.class).size() > 0) { try { LibraryManagementSystem libraryManagementSystem = Lookup.lookup(LibraryManagementSystem.class); // init ILS libraryManagementSystem.init(this.config); switch (service) { case "patron": { Patron patron = libraryManagementSystem.patron(patronid, false); if (patron != null) { StringWriter json = new StringWriter(); mapper = new ObjectMapper(); mapper.writeValue(json, patron); this.logger.debug(json); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_patron"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(patron, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(Patron.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(patron, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), patron); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "fullpatron": { Patron patron = libraryManagementSystem.patron(patronid, true); if (patron != null) { StringWriter json = new StringWriter(); mapper = new ObjectMapper(); mapper.writeValue(json, patron); this.logger.debug(json); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "write_patron"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(patron, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(Patron.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(patron, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), patron); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "items": { DocumentList documentList = libraryManagementSystem.items(patronid, "all"); if (documentList != null) { StringWriter json = new StringWriter(); mapper = new ObjectMapper(); mapper.writeValue(json, documentList); this.logger.debug(json); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(documentList, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(DocumentList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(documentList, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), documentList); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "items/borrowed": { DocumentList documentList = libraryManagementSystem.items(patronid, "borrowed"); if (documentList != null) { StringWriter json = new StringWriter(); mapper = new ObjectMapper(); mapper.writeValue(json, documentList); this.logger.debug(json); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(documentList, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(DocumentList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(documentList, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), documentList); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "items/borrowed/ill": { DocumentList documentList = libraryManagementSystem.items(patronid, "borrowed", "ill"); if (documentList != null) { StringWriter json = new StringWriter(); mapper = new ObjectMapper(); mapper.writeValue(json, documentList); this.logger.debug(json); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(documentList, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(DocumentList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(documentList, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), documentList); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "items/borrowed/renewed": { DocumentList documentList = libraryManagementSystem.items(patronid, "borrowed", "renewed"); if (documentList != null) { StringWriter json = new StringWriter(); mapper = new ObjectMapper(); mapper.writeValue(json, documentList); this.logger.debug(json); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(documentList, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(DocumentList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(documentList, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), documentList); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "items/borrowed/recalled": { DocumentList documentList = libraryManagementSystem.items(patronid, "borrowed", "recalled"); if (documentList != null) { StringWriter json = new StringWriter(); mapper = new ObjectMapper(); mapper.writeValue(json, documentList); this.logger.debug(json); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(documentList, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(DocumentList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(documentList, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), documentList); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "items/ordered": { DocumentList documentList = libraryManagementSystem.items(patronid, "ordered"); if (documentList != null) { StringWriter json = new StringWriter(); mapper = new ObjectMapper(); mapper.writeValue(json, documentList); this.logger.debug(json); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(documentList, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(DocumentList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(documentList, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), documentList); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "items/reserved": { DocumentList documentList = libraryManagementSystem.items(patronid, "reserved"); if (documentList != null) { StringWriter json = new StringWriter(); mapper = new ObjectMapper(); mapper.writeValue(json, documentList); this.logger.debug(json); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(documentList, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(DocumentList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(documentList, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), documentList); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "request": { DocumentList documentList = libraryManagementSystem.request(patronid, documents); if (documentList != null) { StringWriter json = new StringWriter(); mapper.writeValue(json, documentList); this.logger.debug(json); // set Cookie with new value for urlencoded DocumentList-JSON StringWriter stringWriter = new StringWriter(); mapper.writeValue(stringWriter, documents); Cookie cookie = new Cookie("PaiaServiceDocumentList", URLEncoder.encode(stringWriter.toString(), "UTF-8")); if (this.config.getProperty("service.cookie.domain") != null && !this.config.getProperty("service.cookie.domain").equals("")) { cookie.setDomain(this.config.getProperty("service.cookie.domain")); } cookie.setMaxAge(-1); cookie.setPath("/"); httpServletResponse.addCookie(cookie); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "write_items"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { this.logger.info("redirect_url = " + redirect_url); if (!redirect_url.equals("")) { httpServletResponse.sendRedirect(redirect_url); } else { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(documentList, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } } else{ this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(DocumentList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(documentList, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), documentList); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "renew": { DocumentList documentList = libraryManagementSystem.renew(patronid, documents); if (documentList != null) { StringWriter json = new StringWriter(); mapper.writeValue(json, documentList); this.logger.debug(json); // delete DocumentList cookie Cookie cookie = new Cookie("PaiaServiceDocumentList", null); if (this.config.getProperty("service.cookie.domain") != null && !this.config.getProperty("service.cookie.domain").equals("")) { cookie.setDomain(this.config.getProperty("service.cookie.domain")); } cookie.setMaxAge(0); httpServletResponse.addCookie(cookie); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "write_items"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(documentList, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(DocumentList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(documentList, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), documentList); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "cancel": { DocumentList documentList = libraryManagementSystem.cancel(patronid, documents); if (documentList != null) { StringWriter json = new StringWriter(); mapper.writeValue(json, documentList); this.logger.debug(json); // delete DocumentList cookie Cookie cookie = new Cookie("PaiaServiceDocumentList", null); if (this.config.getProperty("service.cookie.domain") != null && !this.config.getProperty("service.cookie.domain").equals("")) { cookie.setDomain(this.config.getProperty("service.cookie.domain")); } cookie.setMaxAge(0); httpServletResponse.addCookie(cookie); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "write_items"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(documentList, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(DocumentList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(documentList, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), documentList); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "fees": { FeeList feeList = libraryManagementSystem.fees(patronid); if (feeList != null) { StringWriter json = new StringWriter(); mapper = new ObjectMapper(); mapper.writeValue(json, feeList); this.logger.debug(json); httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_fees"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("service", service); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(feeList, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(FeeList.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(feeList, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), feeList); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "favorite": { if (listName.equals("") || listName.equals(null)) { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else { Jedis jedis = new Jedis(this.config.getProperty("redis-favorites-server"), Integer.parseInt(this.config.getProperty("redis-favorites-server-port"))); // Einlesen der Konkordanz, die einer Application einen Redis-DB-Index zuordnet Map<String, Object> concordance = mapper.readValue(new File("conf/concordance.json"), Map.class); int appIndex = Integer.parseInt(String.valueOf(concordance.get(application))); jedis.select(appIndex); String listContent; if (jedis.hexists(patronid, listName)) { listContent = jedis.hget(patronid, listName); FavoriteList favoriteList = mapper.readValue(listContent, FavoriteList.class); ArrayList<Favorite> arrayList = favoriteList.getFavorites(); String[] recordids = new String[arrayList.size()]; String[] openUrls = new String[arrayList.size()]; for (int i = 0; i < arrayList.size(); i++) { recordids[i] = arrayList.get(i).getRecordid(); } for (int i = 0; i < arrayList.size(); i++) { openUrls[i] = arrayList.get(i).getOpenUrl(); } for (int i = 0; i < favoriteRequest.getFavorites().size(); i++) { Favorite favoriteToAdd = favoriteRequest.getFavorites().get(i); if (!Arrays.asList(recordids).contains(favoriteToAdd.getRecordid()) || !Arrays.asList(openUrls).contains(favoriteToAdd.getOpenUrl())) { arrayList.add(favoriteToAdd); } } favoriteList.setFavorites(arrayList); listContent = mapper.writeValueAsString(favoriteList); jedis.hset(patronid, listName, listContent); } else { FavoriteList favoriteList = new FavoriteList(); ArrayList<Favorite> arrayList =new ArrayList<>(); for (int i = 0; i < favoriteRequest.getFavorites().size(); i++) { Favorite favoriteToAdd = favoriteRequest.getFavorites().get(i); arrayList.add(favoriteToAdd); } favoriteList.setFavorites(arrayList); listContent = mapper.writeValueAsString(favoriteList); jedis.hset(patronid, listName, listContent); } httpServletResponse.setStatus(HttpServletResponse.SC_CREATED); } /* erste Version: if (listName.equals("") || listName.equals(null)) { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else { // Einlesen der Konkordanz, die einer Application einen Redis-DB-Index zuordnet Map<String, Object> concordance = mapper.readValue(new File("conf/concordance.json"), Map.class); int appIndex = Integer.parseInt(String.valueOf(concordance.get(application))); Jedis jedis = new Jedis(this.config.getProperty("redis-favorites-server"), Integer.parseInt(this.config.getProperty("redis-favorites-server-port"))); jedis.select(appIndex); String listContent; // Fallunterscheidung danach, ob eine Liste mit dem angegebenen Namen bereits existiert if (jedis.hexists(patronid, listName)) { // Holen der Liste und Ablegen in ein POJO listContent = jedis.hget(patronid, listName); FavoriteList favoriteList = mapper.readValue(listContent, FavoriteList.class); // Hinzufügen des Favoriten, wenn er noch nicht in der Liste enthalten ist, mit Hilfe einer ArrayList ArrayList<Favorite> al = favoriteList.getFavorites(); String[] recordIds = new String[al.size()]; for (int i = 0; i < al.size(); i++) { recordIds[i] = al.get(i).getRecordid(); } for (int i = 0; i < favoriteRequest.getFavorites().size(); i++) { Favorite favoriteToAdd = favoriteRequest.getFavorites().get(i); if (!Arrays.asList(recordIds).contains(favoriteToAdd.getRecordid())) { al.add(favoriteToAdd); } } favoriteList.setFavorites(al); // Schreiben in Redis: listContent = mapper.writeValueAsString(favoriteList); jedis.hset(patronid, listName, listContent); } else { // Anlegen einer neuen Merkliste als Objekt, mit dem Namen aus dem FavoriteRequest: FavoriteList favoriteList = new FavoriteList(); favoriteList.setList(favoriteRequest.getList()); favoriteList.setApplication(favoriteRequest.getApplication()); // ArrayList zum Hinzufügen: ArrayList<Favorite> arrayList = new ArrayList<>(); for (int i = 0; i < favoriteRequest.getFavorites().size(); i++) { Favorite favorite = favoriteRequest.getFavorites().get(i); arrayList.add(favorite); } // Bearbeitete ArrayList in das Objekt: favoriteList.setFavorites(arrayList); // Schreiben in Redis listContent = mapper.writeValueAsString(favoriteList); jedis.hset(patronid, listName, listContent); } httpServletResponse.setStatus(HttpServletResponse.SC_CREATED); } */ break; } case "favlist": { // Einlesen der Konkordanz, die einer Application einen Redis-DB-Index zuordnet Map<String, Object> concordance = mapper.readValue(new File("conf/concordance.json"), Map.class); int appIndex = Integer.parseInt(String.valueOf(concordance.get(application))); Jedis jedis = new Jedis(this.config.getProperty("redis-favorites-server"), Integer.parseInt(this.config.getProperty("redis-favorites-server-port"))); jedis.select(appIndex); if (listName.equals("")) { Set<String> fieldNames = jedis.hkeys(patronid); if (fieldNames.isEmpty()) { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { FavoriteListList favoriteListList = new FavoriteListList(); favoriteListList.setFavoriteLists(fieldNames); String lists = mapper.writeValueAsString(favoriteListList); // XML-Ausgabe mit JAXB // TODO // JSON-Ausgabe if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); httpServletResponse.getWriter().write(lists); } } } else { if (jedis.hexists(patronid, listName)) { String listContent = jedis.hget(patronid, listName); httpServletResponse.setStatus(HttpServletResponse.SC_OK); // XML-Ausgabe mit JAXB // TODO // JSON-Ausgabe if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); httpServletResponse.getWriter().write(listContent); } } else { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); } } break; } /* alte 'cases' favor, unfavor, favorites auskommentiert case "favor": { if ((favoriteRequest.getApplication().equals("") || favoriteRequest.getApplication().equals(null)) || (listName.equals("") || listName.equals(null))) { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else { // Jedis-Objekt zur Kommunikation mit Redis Jedis jedis = new Jedis(this.config.getProperty("redis-favorites-server"), Integer.parseInt(this.config.getProperty("redis-favorites-server-port"))); String listContent; if (jedis.hexists(patronid, listName)) { // Holen der Merkliste, wenn diese bereits existiert, aus Redis: listContent = jedis.hget(patronid, listName); // Von der String-Variable zum Objekt: FavoriteList favoriteList = mapper.readValue(listContent, FavoriteList.class); // ArrayList zum Hinzufügen: ArrayList<Favorite> arrayList = favoriteList.getFavorites(); // Array mit nur den Recordids aus der ArrayList: String[] recordids = new String[arrayList.size()]; for (int i = 0; i < arrayList.size(); i++) { recordids[i] = arrayList.get(i).getRecordid(); } // Einfügen von Favoriten, wenn recordid nicht in dem Array enthalten: for (int i = 0; i < favoriteRequest.getFavorites().size(); i++) { Favorite favoriteToAdd = favoriteRequest.getFavorites().get(i); if (!Arrays.asList(recordids).contains(favoriteToAdd.getRecordid())) { arrayList.add(favoriteToAdd); } } // Bearbeitete ArrayList in das Objekt: favoriteList.setFavorites(arrayList); // Schreiben in Redis: listContent = mapper.writeValueAsString(favoriteList); jedis.hset(patronid, listName, listContent); } else { // Anlegen einer neuen Merkliste als Objekt, mit dem Namen aus dem FavoriteRequest: FavoriteList favoriteList = new FavoriteList(); favoriteList.setList(favoriteRequest.getList()); favoriteList.setApplication(favoriteRequest.getApplication()); // ArrayList zum Hinzufügen: ArrayList<Favorite> arrayList = new ArrayList<>(); for (int i = 0; i < favoriteRequest.getFavorites().size(); i++) { Favorite favorite = favoriteRequest.getFavorites().get(i); arrayList.add(favorite); } // Bearbeitete ArrayList in das Objekt: favoriteList.setFavorites(arrayList); // Schreiben in Redis listContent = mapper.writeValueAsString(favoriteList); jedis.hset(patronid, listName, listContent); } httpServletResponse.setStatus(HttpServletResponse.SC_CREATED); } break; } case "unfavor": { // Jedis-Objekt zur Kommunikation mit Redis Jedis jedis = new Jedis(this.config.getProperty("redis-favorites-server"), Integer.parseInt(this.config.getProperty("redis-favorites-server-port"))); if (jedis.hexists(patronid, listName)) { // Holen der Merkliste, wenn diese bereits existiert, aus Redis: String listContent = jedis.hget(patronid, listName); // Von der String-Variable zum Objekt: FavoriteList favoriteList = mapper.readValue(listContent, FavoriteList.class); // ArrayList zum Arbeiten: ArrayList<Favorite> arrayList = favoriteList.getFavorites(); // Einen oder mehrere Favoriten aus der ArrayList entfernen: for (int i = 0; i < favoriteRequest.getFavorites().size(); i++) { Favorite favoriteToRemove = favoriteRequest.getFavorites().get(i); for (int j = 0; j < arrayList.size(); j++) { if (favoriteToRemove.getRecordid().equals(arrayList.get(j).getRecordid())) { arrayList.remove(j); } } } // Bearbeitete ArrayList in das Objekt: favoriteList.setFavorites(arrayList); // Schreiben in Redis: listContent = mapper.writeValueAsString(favoriteList); jedis.hset(patronid, listName, listContent); httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } break; } case "favorites": { // Jedis-Objekt zur Kommunikation mit Redis Jedis jedis = new Jedis(this.config.getProperty("redis-favorites-server"), Integer.parseInt(this.config.getProperty("redis-favorites-server-port"))); // Wenn kein Listenname angegeben ist, Ausgabe aller Listen, die der patron angelegt hat if (listName.equals("")){ Set<String> listsOfPatron = jedis.hkeys(patronid); if (listsOfPatron.isEmpty()) { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { // Aufbau eines Objekts, nämlich einer Liste von Merklisten eines Nutzers FavoriteListList favoriteListList = new FavoriteListList(); favoriteListList.setPatron(patronid); favoriteListList.setFavoriteLists(new ArrayList<FavoriteList>()); for (String list : listsOfPatron) { String listContent = jedis.hget(patronid, list); FavoriteList favoriteList = mapper.readValue(listContent, FavoriteList.class); favoriteListList.getFavoriteLists().add(favoriteList); } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), favoriteListList); } } } // sonst, Ausgabe der angegebenen Merkliste // (evtl. überflüssig, wenn, um Requests zu sparen, nur der if-Zweig genutzt wird) else { if (jedis.hexists(patronid, listName)) { String listContent = jedis.hget(patronid, listName); httpServletResponse.setStatus(HttpServletResponse.SC_OK); // XML-Ausgabe mit JAXB // TODO // JSON-Ausgabe if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); httpServletResponse.getWriter().write(listContent); } } else { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); } } break; } */ case "backup/favorites" : { // Jedis-Objekt zur Kommunikation mit Redis Jedis jedis = new Jedis(this.config.getProperty("redis-favorites-server"), Integer.parseInt(this.config.getProperty("redis-favorites-server-port"))); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.setContentType("application/csv;charset=UTF-8"); // Variablen zur Aufnahme des Ergebnisses einer SCAN-Anfrage an Redis String cursor = "0"; List<String> resultList; // Schleife, bis cursor wieder bei "0" ist, um alle keys abzufragen do { // SCAN-Anfrage ScanResult<String> scanResult = jedis.scan(cursor); resultList = scanResult.getResult(); // Schleife über alle keys for (int i = 0; i < resultList.size(); i++) { String key = resultList.get(i); // Überprüfung, ob unter dem key ein hash gespeichert ist if (jedis.type(key).equals("hash")) { Set<String> fields = jedis.hkeys(key); // Schleife über alle fields eines key for (String field : fields) { String value = jedis.hget(key, field); httpServletResponse.getWriter().println(key + ";" + field + ";" + value); } } } // Neu Setzen des Cursors cursor = scanResult.getStringCursor(); } while (!cursor.equals("0")); jedis.close(); break; } // hier ggf. weitere cases für andere Backup-Szenarien } } catch (LibraryManagementSystemException e) { StringWriter json = new StringWriter(); // TODO Frage nach "570-unknown patron" ist nicht gut! Lösung: Welche Typen von ILSExceptions treten auf? Erzeuge für jeden Typ eine eigene Exception! if (e.getMessage().contains("570-unknown patron")) { this.logger.error(HttpServletResponse.SC_NOT_FOUND + ": '" + patronid + "'"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_NOT_FOUND))); requestError.setCode(HttpServletResponse.SC_NOT_FOUND); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_NOT_FOUND) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_NOT_FOUND) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } else { this.logger.error(HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } catch (Exception e) { e.printStackTrace(); } } else { this.logger.error(HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": Config Error!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json für Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } private void sendRequestError(HttpServletResponse httpServletResponse, RequestError requestError, String format, String language, String redirect_url) { httpServletResponse.setHeader("Access-Control-Allow-Origin", config.getProperty("Access-Control-Allow-Origin")); httpServletResponse.setHeader("Cache-Control", config.getProperty("Cache-Control")); ObjectMapper mapper = new ObjectMapper(); httpServletResponse.setHeader("WWW-Authentificate", "Bearer"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAIA core\""); httpServletResponse.setContentType("application/json"); try { // html if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup.lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("redirect_uri_params", URLDecoder.decode(redirect_url, "UTF-8")); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(htmlTransformation.transform(requestError, parameters)); } catch (TransformationException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(RequestError.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(requestError, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), requestError); } } catch (Exception e) { e.printStackTrace(); } } }
added 'concordance.containsKey(application)' if-statements
src/main/java/de/tu_dortmund/ub/api/paia/core/PaiaCoreEndpoint.java
added 'concordance.containsKey(application)' if-statements
<ide><path>rc/main/java/de/tu_dortmund/ub/api/paia/core/PaiaCoreEndpoint.java <ide> application = params[2]; <ide> listName = params[3]; <ide> <del> if (service.equals("favlist")) { <add> if (service.equals("favlist") && concordance.containsKey(application)) { <ide> int appIndexList = Integer.parseInt(String.valueOf(concordance.get(application))); <ide> <ide> jedis.select(appIndexList); <ide> else { <ide> httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); <ide> } <add> } <add> else { <add> httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); <ide> } <ide> break; <ide> <ide> listName = params[3]; <ide> favoriteId = params[4]; <ide> <del> if (service.equals("favorite")) { <add> if (service.equals("favorite") && concordance.containsKey(application)) { <ide> int appIndexSingleFavorite = Integer.parseInt(String.valueOf(concordance.get(application))); <ide> <ide> jedis.select(appIndexSingleFavorite); <ide> else { <ide> httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); // Liste nicht gefunden <ide> } <add> } <add> else { <add> httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); <ide> } <ide> break; <ide> } <ide> <ide> // Einlesen der Konkordanz, die einer Application einen Redis-DB-Index zuordnet <ide> Map<String, Object> concordance = mapper.readValue(new File("conf/concordance.json"), Map.class); <del> int appIndex = Integer.parseInt(String.valueOf(concordance.get(application))); <del> <del> jedis.select(appIndex); <del> <del> String listContent; <del> <del> if (jedis.hexists(patronid, listName)) { <del> listContent = jedis.hget(patronid, listName); <del> FavoriteList favoriteList = mapper.readValue(listContent, FavoriteList.class); <del> <del> ArrayList<Favorite> arrayList = favoriteList.getFavorites(); <del> String[] recordids = new String[arrayList.size()]; <del> String[] openUrls = new String[arrayList.size()]; <del> <del> for (int i = 0; i < arrayList.size(); i++) { <del> recordids[i] = arrayList.get(i).getRecordid(); <del> } <del> for (int i = 0; i < arrayList.size(); i++) { <del> openUrls[i] = arrayList.get(i).getOpenUrl(); <del> } <del> <del> for (int i = 0; i < favoriteRequest.getFavorites().size(); i++) { <del> Favorite favoriteToAdd = favoriteRequest.getFavorites().get(i); <del> if (!Arrays.asList(recordids).contains(favoriteToAdd.getRecordid()) || <del> !Arrays.asList(openUrls).contains(favoriteToAdd.getOpenUrl())) { <add> <add> if (concordance.containsKey(application)) { <add> int appIndex = Integer.parseInt(String.valueOf(concordance.get(application))); <add> <add> jedis.select(appIndex); <add> <add> String listContent; <add> <add> if (jedis.hexists(patronid, listName)) { <add> listContent = jedis.hget(patronid, listName); <add> FavoriteList favoriteList = mapper.readValue(listContent, FavoriteList.class); <add> <add> ArrayList<Favorite> arrayList = favoriteList.getFavorites(); <add> String[] recordids = new String[arrayList.size()]; <add> String[] openUrls = new String[arrayList.size()]; <add> <add> for (int i = 0; i < arrayList.size(); i++) { <add> recordids[i] = arrayList.get(i).getRecordid(); <add> } <add> for (int i = 0; i < arrayList.size(); i++) { <add> openUrls[i] = arrayList.get(i).getOpenUrl(); <add> } <add> <add> for (int i = 0; i < favoriteRequest.getFavorites().size(); i++) { <add> Favorite favoriteToAdd = favoriteRequest.getFavorites().get(i); <add> if (!Arrays.asList(recordids).contains(favoriteToAdd.getRecordid()) || <add> !Arrays.asList(openUrls).contains(favoriteToAdd.getOpenUrl())) { <add> arrayList.add(favoriteToAdd); <add> } <add> } <add> <add> favoriteList.setFavorites(arrayList); <add> <add> listContent = mapper.writeValueAsString(favoriteList); <add> jedis.hset(patronid, listName, listContent); <add> } <add> <add> else { <add> FavoriteList favoriteList = new FavoriteList(); <add> <add> ArrayList<Favorite> arrayList =new ArrayList<>(); <add> for (int i = 0; i < favoriteRequest.getFavorites().size(); i++) { <add> Favorite favoriteToAdd = favoriteRequest.getFavorites().get(i); <ide> arrayList.add(favoriteToAdd); <ide> } <del> } <del> <del> favoriteList.setFavorites(arrayList); <del> <del> listContent = mapper.writeValueAsString(favoriteList); <del> jedis.hset(patronid, listName, listContent); <del> } <del> <add> <add> favoriteList.setFavorites(arrayList); <add> listContent = mapper.writeValueAsString(favoriteList); <add> jedis.hset(patronid, listName, listContent); <add> } <add> <add> httpServletResponse.setStatus(HttpServletResponse.SC_CREATED); <add> } <ide> else { <del> FavoriteList favoriteList = new FavoriteList(); <del> <del> ArrayList<Favorite> arrayList =new ArrayList<>(); <del> for (int i = 0; i < favoriteRequest.getFavorites().size(); i++) { <del> Favorite favoriteToAdd = favoriteRequest.getFavorites().get(i); <del> arrayList.add(favoriteToAdd); <del> } <del> <del> favoriteList.setFavorites(arrayList); <del> listContent = mapper.writeValueAsString(favoriteList); <del> jedis.hset(patronid, listName, listContent); <del> } <del> <del> httpServletResponse.setStatus(HttpServletResponse.SC_CREATED); <add> httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); <add> } <add> <ide> } <ide> <ide> /* erste Version: <ide> case "favlist": { <ide> // Einlesen der Konkordanz, die einer Application einen Redis-DB-Index zuordnet <ide> Map<String, Object> concordance = mapper.readValue(new File("conf/concordance.json"), Map.class); <del> int appIndex = Integer.parseInt(String.valueOf(concordance.get(application))); <del> <del> Jedis jedis = new Jedis(this.config.getProperty("redis-favorites-server"), Integer.parseInt(this.config.getProperty("redis-favorites-server-port"))); <del> jedis.select(appIndex); <del> <del> if (listName.equals("")) { <del> Set<String> fieldNames = jedis.hkeys(patronid); <del> <del> if (fieldNames.isEmpty()) { <del> httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); <add> <add> if (concordance.containsKey(application)) { <add> int appIndex = Integer.parseInt(String.valueOf(concordance.get(application))); <add> <add> Jedis jedis = new Jedis(this.config.getProperty("redis-favorites-server"), Integer.parseInt(this.config.getProperty("redis-favorites-server-port"))); <add> jedis.select(appIndex); <add> <add> if (listName.equals("")) { <add> Set<String> fieldNames = jedis.hkeys(patronid); <add> <add> if (fieldNames.isEmpty()) { <add> httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); <add> } <add> else { <add> FavoriteListList favoriteListList = new FavoriteListList(); <add> favoriteListList.setFavoriteLists(fieldNames); <add> <add> String lists = mapper.writeValueAsString(favoriteListList); <add> <add> // XML-Ausgabe mit JAXB <add> // TODO <add> <add> // JSON-Ausgabe <add> if (format.equals("json")) { <add> httpServletResponse.setContentType("application/json;charset=UTF-8"); <add> httpServletResponse.getWriter().write(lists); <add> } <add> } <ide> } <ide> else { <del> FavoriteListList favoriteListList = new FavoriteListList(); <del> favoriteListList.setFavoriteLists(fieldNames); <del> <del> String lists = mapper.writeValueAsString(favoriteListList); <del> <del> // XML-Ausgabe mit JAXB <del> // TODO <del> <del> // JSON-Ausgabe <del> if (format.equals("json")) { <del> httpServletResponse.setContentType("application/json;charset=UTF-8"); <del> httpServletResponse.getWriter().write(lists); <add> if (jedis.hexists(patronid, listName)) { <add> String listContent = jedis.hget(patronid, listName); <add> <add> httpServletResponse.setStatus(HttpServletResponse.SC_OK); <add> <add> // XML-Ausgabe mit JAXB <add> // TODO <add> <add> // JSON-Ausgabe <add> if (format.equals("json")) { <add> httpServletResponse.setContentType("application/json;charset=UTF-8"); <add> httpServletResponse.getWriter().write(listContent); <add> } <add> } <add> else { <add> httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); <ide> } <ide> } <ide> } <ide> else { <del> if (jedis.hexists(patronid, listName)) { <del> String listContent = jedis.hget(patronid, listName); <del> <del> httpServletResponse.setStatus(HttpServletResponse.SC_OK); <del> <del> // XML-Ausgabe mit JAXB <del> // TODO <del> <del> // JSON-Ausgabe <del> if (format.equals("json")) { <del> httpServletResponse.setContentType("application/json;charset=UTF-8"); <del> httpServletResponse.getWriter().write(listContent); <del> } <del> } <del> else { <del> httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); <del> } <del> } <add> httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); <add> } <add> <ide> <ide> break; <ide> }
Java
bsd-3-clause
544f2e094883c51f883f5f0c441f3337c5382e81
0
ZenHarbinger/RSTALanguageSupport,bobbylight/RSTALanguageSupport,bobbylight/RSTALanguageSupport,ZenHarbinger/RSTALanguageSupport,bobbylight/RSTALanguageSupport
/* * 03/21/2010 * * Copyright (C) 2010 Robert Futrell * robert_futrell at users.sourceforge.net * http://fifesoft.com/rsyntaxtextarea * * This library is distributed under a modified BSD license. See the included * RSTALanguageSupport.License.txt file for details. */ package org.fife.rsta.ac.java; import java.awt.Cursor; import java.awt.Point; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import javax.swing.text.BadLocationException; import javax.swing.text.JTextComponent; import org.fife.rsta.ac.ShorthandCompletionCache; import org.fife.rsta.ac.java.buildpath.LibraryInfo; import org.fife.rsta.ac.java.buildpath.SourceLocation; import org.fife.rsta.ac.java.classreader.ClassFile; import org.fife.rsta.ac.java.classreader.FieldInfo; import org.fife.rsta.ac.java.classreader.MemberInfo; import org.fife.rsta.ac.java.classreader.MethodInfo; import org.fife.rsta.ac.java.rjc.ast.CodeBlock; import org.fife.rsta.ac.java.rjc.ast.CompilationUnit; import org.fife.rsta.ac.java.rjc.ast.Field; import org.fife.rsta.ac.java.rjc.ast.FormalParameter; import org.fife.rsta.ac.java.rjc.ast.ImportDeclaration; import org.fife.rsta.ac.java.rjc.ast.LocalVariable; import org.fife.rsta.ac.java.rjc.ast.Member; import org.fife.rsta.ac.java.rjc.ast.Method; import org.fife.rsta.ac.java.rjc.ast.NormalClassDeclaration; import org.fife.rsta.ac.java.rjc.ast.TypeDeclaration; import org.fife.rsta.ac.java.rjc.lang.Type; import org.fife.rsta.ac.java.rjc.lang.TypeArgument; import org.fife.rsta.ac.java.rjc.lang.TypeParameter; import org.fife.ui.autocomplete.Completion; import org.fife.ui.autocomplete.DefaultCompletionProvider; import org.fife.ui.rsyntaxtextarea.RSyntaxDocument; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.RSyntaxUtilities; import org.fife.ui.rsyntaxtextarea.Token; /** * Parses a Java AST for code completions. It currently scans the following: * * <ul> * <li>Import statements * <li>Method names * <li>Field names * </ul> * * Also, if the caret is inside a method, local variables up to the caret * position are also returned. * * @author Robert Futrell * @version 1.0 */ class SourceCompletionProvider extends DefaultCompletionProvider { /** * The parent completion provider. */ private JavaCompletionProvider javaProvider; /** * Used to get information about what classes match imports. */ private JarManager jarManager; private static final String JAVA_LANG_PACKAGE = "java.lang.*"; private static final String THIS = "this"; //Shorthand completions (templates and comments) private ShorthandCompletionCache shorthandCache; /** * Constructor. */ public SourceCompletionProvider() { this(null); } /** * Constructor. * * @param jarManager The jar manager for this provider. */ public SourceCompletionProvider(JarManager jarManager) { if (jarManager==null) { jarManager = new JarManager(); } this.jarManager = jarManager; setParameterizedCompletionParams('(', ", ", ')'); setAutoActivationRules(false, "."); // Default - only activate after '.' setParameterChoicesProvider(new SourceParamChoicesProvider()); } private void addCompletionsForStaticMembers(Set<Completion> set, CompilationUnit cu, ClassFile cf, String pkg) { // Check us first, so if we override anything, we get the "newest" // version. int methodCount = cf.getMethodCount(); for (int i=0; i<methodCount; i++) { MethodInfo info = cf.getMethodInfo(i); if (isAccessible(info, pkg) && info.isStatic()) { MethodCompletion mc = new MethodCompletion(this, info); set.add(mc); } } int fieldCount = cf.getFieldCount(); for (int i=0; i<fieldCount; i++) { FieldInfo info = cf.getFieldInfo(i); if (isAccessible(info, pkg) && info.isStatic()) { FieldCompletion fc = new FieldCompletion(this, info); set.add(fc); } } ClassFile superClass = getClassFileFor(cu, cf.getSuperClassName(true)); if (superClass!=null) { addCompletionsForStaticMembers(set, cu, superClass, pkg); } } /** * Adds completions for accessible methods and fields of super classes. * This is only called when the caret is inside of a class. * TODO: Handle accessibility correctly! * * @param set * @param cu The compilation unit. * @param cf A class in the chain of classes that a type being parsed * inherits from. * @param pkg The package of the source being parsed. * @param typeParamMap A mapping of type parameters to type arguments * for the object whose fields/methods/etc. are currently being * code-completed. */ private void addCompletionsForExtendedClass(Set<Completion> set, CompilationUnit cu, ClassFile cf, String pkg, Map<String, String> typeParamMap) { // Reset this class's type-arguments-to-type-parameters map, so that // when methods and fields need to know type arguments, they can query // for them. cf.setTypeParamsToTypeArgs(typeParamMap); // Check us first, so if we override anything, we get the "newest" // version. int methodCount = cf.getMethodCount(); for (int i=0; i<methodCount; i++) { MethodInfo info = cf.getMethodInfo(i); // Don't show constructors if (isAccessible(info, pkg) && !info.isConstructor()) { MethodCompletion mc = new MethodCompletion(this, info); set.add(mc); } } int fieldCount = cf.getFieldCount(); for (int i=0; i<fieldCount; i++) { FieldInfo info = cf.getFieldInfo(i); if (isAccessible(info, pkg)) { FieldCompletion fc = new FieldCompletion(this, info); set.add(fc); } } // Add completions for any non-overridden super-class methods. ClassFile superClass = getClassFileFor(cu, cf.getSuperClassName(true)); if (superClass!=null) { addCompletionsForExtendedClass(set, cu, superClass, pkg, typeParamMap); } // Add completions for any interface methods, in case this class is // abstract and hasn't implemented some of them yet. // TODO: Do this only if "top-level" class is declared abstract for (int i=0; i<cf.getImplementedInterfaceCount(); i++) { String inter = cf.getImplementedInterfaceName(i, true); cf = getClassFileFor(cu, inter); addCompletionsForExtendedClass(set, cu, cf, pkg, typeParamMap); } } /** * Adds completions for all methods and public fields of a local variable. * This will add nothing if the local variable is a primitive type. * * @param cu The compilation unit being parsed. * @param var The local variable. * @param retVal The set to add completions to. */ private void addCompletionsForLocalVarsMethods(CompilationUnit cu, LocalVariable var, Set<Completion> retVal) { Type type = var.getType(); String pkg = cu.getPackageName(); if (type.isArray()) { ClassFile cf = getClassFileFor(cu, "java.lang.Object"); addCompletionsForExtendedClass(retVal, cu, cf, pkg, null); FieldCompletion fc = FieldCompletion. createLengthCompletion(this, type); retVal.add(fc); } else if (!type.isBasicType()) { String typeStr = type.getName(true, false); ClassFile cf = getClassFileFor(cu, typeStr); if (cf!=null) { Map<String, String> typeParamMap = createTypeParamMap(type, cf); addCompletionsForExtendedClass(retVal, cu, cf, pkg, typeParamMap); } } } /** * Adds simple shorthand completions relevant to Java. * * @param set The set to add to. */ private void addShorthandCompletions(Set<Completion> set) { if(shorthandCache != null) { set.addAll(shorthandCache.getShorthandCompletions()); } } /** * Set template completion cache for source completion provider * @param templateCache */ public void setShorthandCache(ShorthandCompletionCache shorthandCache) { this.shorthandCache = shorthandCache; } /** * Gets the {@link ClassFile} for a class. * * @param cu The compilation unit being parsed. * @param className The name of the class (fully qualified or not). * @return The {@link ClassFile} for the class, or <code>null</code> if * <code>cf</code> represents <code>java.lang.Object</code> (or * if the super class could not be determined). */ private ClassFile getClassFileFor(CompilationUnit cu, String className) { //System.err.println(">>> Getting class file for: " + className); if (className==null) { return null; } ClassFile superClass = null; // Determine the fully qualified class to grab if (!Util.isFullyQualified(className)) { // Check in this source file's package first String pkg = cu.getPackageName(); if (pkg!=null) { String temp = pkg + "." + className; superClass = jarManager.getClassEntry(temp); } // Next, go through the imports (order is important) if (superClass==null) { Iterator<ImportDeclaration> i = cu.getImportIterator(); while (i.hasNext()) { ImportDeclaration id = i.next(); String imported = id.getName(); if (imported.endsWith(".*")) { String temp = imported.substring( 0, imported.length()-1) + className; superClass = jarManager.getClassEntry(temp); if (superClass!=null) { break; } } else if (imported.endsWith("." + className)) { superClass = jarManager.getClassEntry(imported); break; } } } // Finally, try java.lang if (superClass==null) { String temp = "java.lang." + className; superClass = jarManager.getClassEntry(temp); } } else { superClass = jarManager.getClassEntry(className); } return superClass; } /** * Adds completions for local variables in a method. * * @param set * @param method * @param offs The caret's offset into the source. This should be inside * of <code>method</code>. */ private void addLocalVarCompletions(Set<Completion> set, Method method, int offs) { for (int i=0; i<method.getParameterCount(); i++) { FormalParameter param = method.getParameter(i); set.add(new LocalVariableCompletion(this, param)); } CodeBlock body = method.getBody(); if (body!=null) { addLocalVarCompletions(set, body, offs); } } /** * Adds completions for local variables in a code block inside of a method. * * @param set * @param block The code block. * @param offs The caret's offset into the source. This should be inside * of <code>block</code>. */ private void addLocalVarCompletions(Set<Completion> set, CodeBlock block, int offs) { for (int i=0; i<block.getLocalVarCount(); i++) { LocalVariable var = block.getLocalVar(i); if (var.getNameEndOffset()<=offs) { set.add(new LocalVariableCompletion(this, var)); } else { // This and all following declared after offs break; } } for (int i=0; i<block.getChildBlockCount(); i++) { CodeBlock child = block.getChildBlock(i); if (child.containsOffset(offs)) { addLocalVarCompletions(set, child, offs); break; // All other blocks are past this one } // If we've reached a block that's past the offset we're // searching for... else if (child.getNameStartOffset()>offs) { break; } } } /** * Adds a jar to read from. * * @param info The jar to add. If this is <code>null</code>, then * the current JVM's main JRE jar (rt.jar, or classes.jar on OS X) * will be added. If this jar has already been added, adding it * again will do nothing (except possibly update its attached source * location). * @throws IOException If an IO error occurs. * @see #getJars() * @see #removeJar(File) */ public void addJar(LibraryInfo info) throws IOException { jarManager.addClassFileSource(info); } /** * Checks whether the user is typing a completion for a String member after * a String literal. * * @param comp The text component. * @param alreadyEntered The text already entered. * @param cu The compilation unit being parsed. * @param set The set to add possible completions to. * @return Whether the user is indeed typing a completion for a String * literal member. */ private boolean checkStringLiteralMember(JTextComponent comp, String alreadyEntered, CompilationUnit cu, Set<Completion> set) { boolean stringLiteralMember = false; int offs = comp.getCaretPosition() - alreadyEntered.length() - 1; if (offs>1) { RSyntaxTextArea textArea = (RSyntaxTextArea)comp; RSyntaxDocument doc = (RSyntaxDocument)textArea.getDocument(); try { //System.out.println(doc.charAt(offs) + ", " + doc.charAt(offs+1)); if (doc.charAt(offs)=='"' && doc.charAt(offs+1)=='.') { int curLine = textArea.getLineOfOffset(offs); Token list = textArea.getTokenListForLine(curLine); Token prevToken = RSyntaxUtilities.getTokenAtOffset(list, offs); if (prevToken!=null && prevToken.getType()==Token.LITERAL_STRING_DOUBLE_QUOTE) { ClassFile cf = getClassFileFor(cu, "java.lang.String"); addCompletionsForExtendedClass(set, cu, cf, cu.getPackageName(), null); stringLiteralMember = true; } else { System.out.println(prevToken); } } } catch (BadLocationException ble) { // Never happens ble.printStackTrace(); } } return stringLiteralMember; } /** * Removes all jars from the "build path." * * @see #removeJar(File) * @see #addClassFileSource(JarInfo) * @see #getJars() */ public void clearJars() { jarManager.clearClassFileSources(); // The memory used by the completions can be quite large, so go ahead // and clear out the completions list so no-longer-needed ones are // eligible for GC. clear(); } /** * Creates and returns a mapping of type parameters to type arguments. * * @param type The type of a variable/field/etc. whose fields/methods/etc. * are being code completed, as declared in the source. This * includes type arguments. * @param cf The <code>ClassFile</code> representing the actual type of * the variable/field/etc. being code completed * @return A mapping of type parameter names to type arguments (both * Strings). */ private Map<String, String> createTypeParamMap(Type type, ClassFile cf) { Map<String, String> typeParamMap = null; List<TypeArgument> typeArgs = type.getTypeArguments(type.getIdentifierCount()-1); if (typeArgs!=null) { typeParamMap = new HashMap<String, String>(); List<String> paramTypes = cf.getParamTypes(); // Should be the same size! Otherwise, the source code has // too many/too few type arguments listed for this type. int min = Math.min(paramTypes==null ? 0 : paramTypes.size(), typeArgs.size()); for (int i=0; i<min; i++) { TypeArgument typeArg = typeArgs.get(i); typeParamMap.put(paramTypes.get(i), typeArg.toString()); } } return typeParamMap; } /** * {@inheritDoc} */ @Override public List<Completion> getCompletionsAt(JTextComponent tc, Point p) { getCompletionsImpl(tc); // Force loading of completions return super.getCompletionsAt(tc, p); } /** * {@inheritDoc} */ @Override protected List<Completion> getCompletionsImpl(JTextComponent comp) { comp.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try { completions = new ArrayList<Completion>();//completions.clear(); CompilationUnit cu = javaProvider.getCompilationUnit(); if (cu==null) { return completions; // empty } Set<Completion> set = new TreeSet<Completion>(); // Cut down the list to just those matching what we've typed. // Note: getAlreadyEnteredText() never returns null String text = getAlreadyEnteredText(comp); // Special case - end of a String literal boolean stringLiteralMember = checkStringLiteralMember(comp, text, cu, set); // Not after a String literal - regular code completion if (!stringLiteralMember) { // Don't add shorthand completions if they're typing something // qualified if (text.indexOf('.')==-1) { addShorthandCompletions(set); } loadImportCompletions(set, text, cu); // Add completions for fully-qualified stuff (e.g. "com.sun.jav") //long startTime = System.currentTimeMillis(); jarManager.addCompletions(this, text, set); //long time = System.currentTimeMillis() - startTime; //System.out.println("jar completions loaded in: " + time); // Loop through all types declared in this source, and provide // completions depending on in what type/method/etc. the caret's in. loadCompletionsForCaretPosition(cu, comp, text, set); } // Do a final sort of all of our completions and we're good to go! completions = new ArrayList<Completion>(set); Collections.sort(completions); // Only match based on stuff after the final '.', since that's what is // displayed for all of our completions. text = text.substring(text.lastIndexOf('.')+1); @SuppressWarnings("unchecked") int start = Collections.binarySearch(completions, text, comparator); if (start<0) { start = -(start+1); } else { // There might be multiple entries with the same input text. while (start>0 && comparator.compare(completions.get(start-1), text)==0) { start--; } } @SuppressWarnings("unchecked") int end = Collections.binarySearch(completions, text+'{', comparator); end = -(end+1); return completions.subList(start, end); } finally { comp.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)); } } /** * Returns the jars on the "build path." * * @return A list of {@link LibraryInfo}s. Modifying a * <code>LibraryInfo</code> in this list will have no effect on * this completion provider; in order to do that, you must re-add * the jar via {@link #addJar(LibraryInfo)}. If there are * no jars on the "build path," this will be an empty list. * @see #addJar(LibraryInfo) */ public List<LibraryInfo> getJars() { return jarManager.getClassFileSources(); } public SourceLocation getSourceLocForClass(String className) { return jarManager.getSourceLocForClass(className); } /** * Returns whether a method defined by a super class is accessible to * this class. * * @param info Information about the member. * @param pkg The package of the source currently being parsed. * @return Whether or not the method is accessible. */ private boolean isAccessible(MemberInfo info, String pkg) { boolean accessible = false; int access = info.getAccessFlags(); if (org.fife.rsta.ac.java.classreader.Util.isPublic(access) || org.fife.rsta.ac.java.classreader.Util.isProtected(access)) { accessible = true; } else if (org.fife.rsta.ac.java.classreader.Util.isDefault(access)) { String pkg2 = info.getClassFile().getPackageName(); accessible = (pkg==null && pkg2==null) || (pkg!=null && pkg.equals(pkg2)); } return accessible; } /** * {@inheritDoc} */ @Override protected boolean isValidChar(char ch) { return Character.isJavaIdentifierPart(ch) || ch=='.'; } /** * Loads completions based on the current caret location in the source. In * other words: * * <ul> * <li>If the caret is anywhere in a class, the names of all methods and * fields in the class are loaded. Methods and fields in super * classes are also loaded. TODO: Get super methods/fields added * correctly by access! * <li>If the caret is in a field, local variables currently accessible * are loaded. * </ul> * * @param cu * @param comp * @param alreadyEntered * @param retVal */ private void loadCompletionsForCaretPosition(CompilationUnit cu, JTextComponent comp, String alreadyEntered, Set<Completion> retVal) { // Get completions for all fields and methods of all type declarations. //long startTime = System.currentTimeMillis(); int caret = comp.getCaretPosition(); //List temp = new ArrayList(); int start, end; int lastDot = alreadyEntered.lastIndexOf('.'); boolean qualified = lastDot>-1; String prefix = qualified ? alreadyEntered.substring(0, lastDot) : null; Iterator<TypeDeclaration> i = cu.getTypeDeclarationIterator(); while (i.hasNext()) { TypeDeclaration td = i.next(); start = td.getBodyStartOffset(); end = td.getBodyEndOffset(); if (caret>start && caret<=end) { loadCompletionsForCaretPosition(cu, comp, alreadyEntered, retVal, td, prefix, caret); } else if (caret<start) { break; // We've passed any type declarations we could be in } } //long time = System.currentTimeMillis() - startTime; //System.out.println("methods/fields/localvars loaded in: " + time); } /** * Loads completions based on the current caret location in the source. * This method is called when the caret is found to be in a specific type * declaration. This method checks if the caret is in a child type * declaration first, then adds completions for itself next. * * <ul> * <li>If the caret is anywhere in a class, the names of all methods and * fields in the class are loaded. Methods and fields in super * classes are also loaded. TODO: Get super methods/fields added * correctly by access! * <li>If the caret is in a field, local variables currently accessible * are loaded. * </ul> * * @param cu * @param comp * @param alreadyEntered * @param retVal */ private void loadCompletionsForCaretPosition(CompilationUnit cu, JTextComponent comp, String alreadyEntered, Set<Completion> retVal, TypeDeclaration td, String prefix, int caret) { // Do any child types first, so if any vars, etc. have duplicate names, // we pick up the one "closest" to us first. for (int i=0; i<td.getChildTypeCount(); i++) { TypeDeclaration childType = td.getChildType(i); loadCompletionsForCaretPosition(cu, comp, alreadyEntered, retVal, childType, prefix, caret); } Method currentMethod = null; Map<String, String> typeParamMap = new HashMap<String, String>(); if (td instanceof NormalClassDeclaration) { NormalClassDeclaration ncd = (NormalClassDeclaration)td; List<TypeParameter> typeParams = ncd.getTypeParameters(); if (typeParams!=null) { for (TypeParameter typeParam : typeParams) { String typeVar = typeParam.getName(); // For non-qualified completions, use type var name. typeParamMap.put(typeVar, typeVar); } } } // Get completions for this class's methods, fields and local // vars. Do this before checking super classes so that, if // we overrode anything, we get the "newest" version. String pkg = cu.getPackageName(); Iterator<Member> j = td.getMemberIterator(); while (j.hasNext()) { Member m = j.next(); if (m instanceof Method) { Method method = (Method)m; if (prefix==null || THIS.equals(prefix)) { retVal.add(new MethodCompletion(this, method)); } if (caret>=method.getBodyStartOffset() && caret<method.getBodyEndOffset()) { currentMethod = method; // Don't add completions for local vars if there is // a prefix, even "this". if (prefix==null) { addLocalVarCompletions(retVal, method, caret); } } } else if (m instanceof Field) { if (prefix==null || THIS.equals(prefix)) { Field field = (Field)m; retVal.add(new FieldCompletion(this, field)); } } } // Completions for superclass methods. // TODO: Implement me better if (prefix==null || THIS.equals(prefix)) { if (td instanceof NormalClassDeclaration) { NormalClassDeclaration ncd = (NormalClassDeclaration)td; Type extended = ncd.getExtendedType(); if (extended!=null) { // e.g., not java.lang.Object String superClassName = extended.toString(); ClassFile cf = getClassFileFor(cu, superClassName); if (cf!=null) { addCompletionsForExtendedClass(retVal, cu, cf, pkg, null); } else { System.out.println("[DEBUG]: Couldn't find ClassFile for: " + superClassName); } } } } // Completions for methods of fields, return values of methods, // static fields/methods, etc. if (prefix!=null && !THIS.equals(prefix)) { loadCompletionsForCaretPositionQualified(cu, alreadyEntered, retVal, td, currentMethod, prefix, caret); } } /** * Loads completions for the text at the current caret position, if there * is a "prefix" of chars and at least one '.' character in the text up to * the caret. This is currently very limited and needs to be improved. * * @param cu * @param alreadyEntered * @param retVal * @param td The type declaration the caret is in. * @param currentMethod The method the caret is in, or <code>null</code> if * none. * @param prefix The text up to the current caret position. This is * guaranteed to be non-<code>null</code> not equal to * "<tt>this</tt>". * @param offs The offset of the caret in the document. */ private void loadCompletionsForCaretPositionQualified(CompilationUnit cu, String alreadyEntered, Set<Completion> retVal, TypeDeclaration td, Method currentMethod, String prefix, int offs) { // TODO: Remove this restriction. int dot = prefix.indexOf('.'); if (dot>-1) { System.out.println("[DEBUG]: Qualified non-this completions currently only go 1 level deep"); return; } // TODO: Remove this restriction. else if (!prefix.matches("[A-Za-z_][A-Za-z0-9_\\$]*")) { System.out.println("[DEBUG]: Only identifier non-this completions are currently supported"); return; } String pkg = cu.getPackageName(); boolean matched = false; for (Iterator<Member> j=td.getMemberIterator(); j.hasNext(); ) { Member m = j.next(); // The prefix might be a field in the local class. if (m instanceof Field) { Field field = (Field)m; if (field.getName().equals(prefix)) { //System.out.println("FOUND: " + prefix + " (" + pkg + ")"); Type type = field.getType(); if (type.isArray()) { ClassFile cf = getClassFileFor(cu, "java.lang.Object"); addCompletionsForExtendedClass(retVal, cu, cf, pkg, null); FieldCompletion fc = FieldCompletion. createLengthCompletion(this, type); retVal.add(fc); } else if (!type.isBasicType()) { String typeStr = type.getName(true, false); ClassFile cf = getClassFileFor(cu, typeStr); // Add completions for extended class type chain if (cf!=null) { Map<String, String> typeParamMap = createTypeParamMap(type, cf); addCompletionsForExtendedClass(retVal, cu, cf, pkg, typeParamMap); // Add completions for all implemented interfaces // TODO: Only do this if type is abstract! for (int i=0; i<cf.getImplementedInterfaceCount(); i++) { String inter = cf.getImplementedInterfaceName(i, true); cf = getClassFileFor(cu, inter); System.out.println(cf); } } } matched = true; break; } } } // The prefix might be for a local variable in the current method. if (currentMethod!=null) { boolean found = false; // Check parameters to the current method for (int i=0; i<currentMethod.getParameterCount(); i++) { FormalParameter param = currentMethod.getParameter(i); String name = param.getName(); // Assuming prefix is "one level deep" and contains no '.'... if (prefix.equals(name)) { addCompletionsForLocalVarsMethods(cu, param, retVal); found = true; break; } } // If a formal param wasn't matched, check local variables. if (!found) { CodeBlock body = currentMethod.getBody(); if (body!=null) { loadCompletionsForCaretPositionQualifiedCodeBlock(cu, retVal, td, body, prefix, offs); } } matched |= found; } // Could be a class name, in which case we'll need to add completions // for static fields and methods. if (!matched) { List<ImportDeclaration> imports = cu.getImports(); List<ClassFile> matches = jarManager.getClassesWithUnqualifiedName( prefix, imports); if (matches!=null) { for (int i=0; i<matches.size(); i++) { ClassFile cf = matches.get(i); addCompletionsForStaticMembers(retVal, cu, cf, pkg); } } } } private void loadCompletionsForCaretPositionQualifiedCodeBlock( CompilationUnit cu, Set<Completion> retVal, TypeDeclaration td, CodeBlock block, String prefix, int offs) { boolean found = false; for (int i=0; i<block.getLocalVarCount(); i++) { LocalVariable var = block.getLocalVar(i); if (var.getNameEndOffset()<=offs) { // TODO: This assumes prefix is "1 level deep" if (prefix.equals(var.getName())) { addCompletionsForLocalVarsMethods(cu, var, retVal); found = true; break; } } else { // This and all following declared after offs break; } } if (found) { return; } for (int i=0; i<block.getChildBlockCount(); i++) { CodeBlock child = block.getChildBlock(i); if (child.containsOffset(offs)) { loadCompletionsForCaretPositionQualifiedCodeBlock(cu, retVal, td, child, prefix, offs); break; // All other blocks are past this one } // If we've reached a block that's past the offset we're // searching for... else if (child.getNameStartOffset()>offs) { break; } } } /** * Loads completions for a single import statement. * * @param importStr The import statement. * @param pkgName The package of the source currently being parsed. */ private void loadCompletionsForImport(Set<Completion> set, String importStr, String pkgName) { if (importStr.endsWith(".*")) { String pkg = importStr.substring(0, importStr.length()-2); boolean inPkg = pkg.equals(pkgName); List<ClassFile> classes= jarManager.getClassesInPackage(pkg, inPkg); for (ClassFile cf : classes) { set.add(new ClassCompletion(this, cf)); } } else { ClassFile cf = jarManager.getClassEntry(importStr); if (cf!=null) { set.add(new ClassCompletion(this, cf)); } } } /** * Loads completions for all import statements. * * @param cu The compilation unit being parsed. */ private void loadImportCompletions(Set<Completion> set, String text, CompilationUnit cu) { // Fully-qualified completions are handled elsewhere, so no need to // duplicate the work here if (text.indexOf('.')>-1) { return; } //long startTime = System.currentTimeMillis(); String pkgName = cu.getPackageName(); loadCompletionsForImport(set, JAVA_LANG_PACKAGE, pkgName); for (Iterator<ImportDeclaration> i=cu.getImportIterator(); i.hasNext(); ) { ImportDeclaration id = i.next(); String name = id.getName(); if (!JAVA_LANG_PACKAGE.equals(name)) { loadCompletionsForImport(set, name, pkgName); } } // Collections.sort(completions); //long time = System.currentTimeMillis() - startTime; //System.out.println("imports loaded in: " + time); } /** * Removes a jar from the "build path." * * @param jar The jar to remove. * @return Whether the jar was removed. This will be <code>false</code> * if the jar was not on the build path. * @see #addClassFileSource(JarInfo) * @see #getJars() * @see #clearJars() */ public boolean removeJar(File jar) { boolean removed = jarManager.removeClassFileSource(jar); // The memory used by the completions can be quite large, so go ahead // and clear out the completions list so no-longer-needed ones are // eligible for GC. if (removed) { clear(); } return removed; } /** * Sets the parent Java provider. * * @param javaProvider The parent completion provider. */ void setJavaProvider(JavaCompletionProvider javaProvider) { this.javaProvider = javaProvider; } }
src/org/fife/rsta/ac/java/SourceCompletionProvider.java
/* * 03/21/2010 * * Copyright (C) 2010 Robert Futrell * robert_futrell at users.sourceforge.net * http://fifesoft.com/rsyntaxtextarea * * This library is distributed under a modified BSD license. See the included * RSTALanguageSupport.License.txt file for details. */ package org.fife.rsta.ac.java; import java.awt.Cursor; import java.awt.Point; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import javax.swing.text.BadLocationException; import javax.swing.text.JTextComponent; import org.fife.rsta.ac.ShorthandCompletionCache; import org.fife.rsta.ac.java.buildpath.LibraryInfo; import org.fife.rsta.ac.java.buildpath.SourceLocation; import org.fife.rsta.ac.java.classreader.ClassFile; import org.fife.rsta.ac.java.classreader.FieldInfo; import org.fife.rsta.ac.java.classreader.MemberInfo; import org.fife.rsta.ac.java.classreader.MethodInfo; import org.fife.rsta.ac.java.rjc.ast.CodeBlock; import org.fife.rsta.ac.java.rjc.ast.CompilationUnit; import org.fife.rsta.ac.java.rjc.ast.Field; import org.fife.rsta.ac.java.rjc.ast.FormalParameter; import org.fife.rsta.ac.java.rjc.ast.ImportDeclaration; import org.fife.rsta.ac.java.rjc.ast.LocalVariable; import org.fife.rsta.ac.java.rjc.ast.Member; import org.fife.rsta.ac.java.rjc.ast.Method; import org.fife.rsta.ac.java.rjc.ast.NormalClassDeclaration; import org.fife.rsta.ac.java.rjc.ast.TypeDeclaration; import org.fife.rsta.ac.java.rjc.lang.Type; import org.fife.rsta.ac.java.rjc.lang.TypeArgument; import org.fife.rsta.ac.java.rjc.lang.TypeParameter; import org.fife.ui.autocomplete.Completion; import org.fife.ui.autocomplete.DefaultCompletionProvider; import org.fife.ui.rsyntaxtextarea.RSyntaxDocument; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.RSyntaxUtilities; import org.fife.ui.rsyntaxtextarea.Token; /** * Parses a Java AST for code completions. It currently scans the following: * * <ul> * <li>Import statements * <li>Method names * <li>Field names * </ul> * * Also, if the caret is inside a method, local variables up to the caret * position are also returned. * * @author Robert Futrell * @version 1.0 */ class SourceCompletionProvider extends DefaultCompletionProvider { /** * The parent completion provider. */ private JavaCompletionProvider javaProvider; /** * Used to get information about what classes match imports. */ private JarManager jarManager; private static final String JAVA_LANG_PACKAGE = "java.lang.*"; private static final String THIS = "this"; //Shorthand completions (templates and comments) private ShorthandCompletionCache shorthandCache; /** * Constructor. */ public SourceCompletionProvider() { this(null); } /** * Constructor. * * @param jarManager The jar manager for this provider. */ public SourceCompletionProvider(JarManager jarManager) { if (jarManager==null) { jarManager = new JarManager(); } this.jarManager = jarManager; setParameterizedCompletionParams('(', ", ", ')'); setAutoActivationRules(false, "."); // Default - only activate after '.' setParameterChoicesProvider(new SourceParamChoicesProvider()); } private void addCompletionsForStaticMembers(Set<Completion> set, CompilationUnit cu, ClassFile cf, String pkg) { // Check us first, so if we override anything, we get the "newest" // version. int methodCount = cf.getMethodCount(); for (int i=0; i<methodCount; i++) { MethodInfo info = cf.getMethodInfo(i); if (isAccessible(info, pkg) && info.isStatic()) { MethodCompletion mc = new MethodCompletion(this, info); set.add(mc); } } int fieldCount = cf.getFieldCount(); for (int i=0; i<fieldCount; i++) { FieldInfo info = cf.getFieldInfo(i); if (isAccessible(info, pkg) && info.isStatic()) { FieldCompletion fc = new FieldCompletion(this, info); set.add(fc); } } ClassFile superClass = getClassFileFor(cu, cf.getSuperClassName(true)); if (superClass!=null) { addCompletionsForStaticMembers(set, cu, superClass, pkg); } } /** * Adds completions for accessible methods and fields of super classes. * This is only called when the caret is inside of a class. * TODO: Handle accessibility correctly! * * @param set * @param cu The compilation unit. * @param cf A class in the chain of classes that a type being parsed * inherits from. * @param pkg The package of the source being parsed. * @param typeParamMap A mapping of type parameters to type arguments * for the object whose fields/methods/etc. are currently being * code-completed. */ private void addCompletionsForExtendedClass(Set<Completion> set, CompilationUnit cu, ClassFile cf, String pkg, Map<String, String> typeParamMap) { // Reset this class's type-arguments-to-type-parameters map, so that // when methods and fields need to know type arguments, they can query // for them. cf.setTypeParamsToTypeArgs(typeParamMap); // Check us first, so if we override anything, we get the "newest" // version. int methodCount = cf.getMethodCount(); for (int i=0; i<methodCount; i++) { MethodInfo info = cf.getMethodInfo(i); // Don't show constructors if (isAccessible(info, pkg) && !info.isConstructor()) { MethodCompletion mc = new MethodCompletion(this, info); set.add(mc); } } int fieldCount = cf.getFieldCount(); for (int i=0; i<fieldCount; i++) { FieldInfo info = cf.getFieldInfo(i); if (isAccessible(info, pkg)) { FieldCompletion fc = new FieldCompletion(this, info); set.add(fc); } } // Add completions for any non-overridden super-class methods. ClassFile superClass = getClassFileFor(cu, cf.getSuperClassName(true)); if (superClass!=null) { addCompletionsForExtendedClass(set, cu, superClass, pkg, typeParamMap); } // Add completions for any interface methods, in case this class is // abstract and hasn't implemented some of them yet. // TODO: Do this only if "top-level" class is declared abstract for (int i=0; i<cf.getImplementedInterfaceCount(); i++) { String inter = cf.getImplementedInterfaceName(i, true); cf = getClassFileFor(cu, inter); addCompletionsForExtendedClass(set, cu, cf, pkg, typeParamMap); } } /** * Adds completions for all methods and public fields of a local variable. * This will add nothing if the local variable is a primitive type. * * @param cu The compilation unit being parsed. * @param var The local variable. * @param retVal The set to add completions to. */ private void addCompletionsForLocalVarsMethods(CompilationUnit cu, LocalVariable var, Set<Completion> retVal) { Type type = var.getType(); String pkg = cu.getPackageName(); if (type.isArray()) { ClassFile cf = getClassFileFor(cu, "java.lang.Object"); addCompletionsForExtendedClass(retVal, cu, cf, pkg, null); FieldCompletion fc = FieldCompletion. createLengthCompletion(this, type); retVal.add(fc); } else if (!type.isBasicType()) { String typeStr = type.getName(true, false); ClassFile cf = getClassFileFor(cu, typeStr); if (cf!=null) { Map<String, String> typeParamMap = createTypeParamMap(type, cf); addCompletionsForExtendedClass(retVal, cu, cf, pkg, typeParamMap); } } } /** * Adds simple shorthand completions relevant to Java. * * @param set The set to add to. */ private void addShorthandCompletions(Set<Completion> set) { if(shorthandCache != null) { set.addAll(shorthandCache.getShorthandCompletions()); } } /** * Set template completion cache for source completion provider * @param templateCache */ public void setShorthandCache(ShorthandCompletionCache shorthandCache) { this.shorthandCache = shorthandCache; } /** * Gets the {@link ClassFile} for a class. * * @param cu The compilation unit being parsed. * @param className The name of the class (fully qualified or not). * @return The {@link ClassFile} for the class, or <code>null</code> if * <code>cf</code> represents <code>java.lang.Object</code> (or * if the super class could not be determined). */ private ClassFile getClassFileFor(CompilationUnit cu, String className) { //System.err.println(">>> Getting class file for: " + className); if (className==null) { return null; } ClassFile superClass = null; // Determine the fully qualified class to grab if (!Util.isFullyQualified(className)) { // Check in this source file's package first String pkg = cu.getPackageName(); if (pkg!=null) { String temp = pkg + "." + className; superClass = jarManager.getClassEntry(temp); } // Next, go through the imports (order is important) if (superClass==null) { Iterator<ImportDeclaration> i = cu.getImportIterator(); while (i.hasNext()) { ImportDeclaration id = i.next(); String imported = id.getName(); if (imported.endsWith(".*")) { String temp = imported.substring( 0, imported.length()-1) + className; superClass = jarManager.getClassEntry(temp); if (superClass!=null) { break; } } else if (imported.endsWith("." + className)) { superClass = jarManager.getClassEntry(imported); break; } } } // Finally, try java.lang if (superClass==null) { String temp = "java.lang." + className; superClass = jarManager.getClassEntry(temp); } } else { superClass = jarManager.getClassEntry(className); } return superClass; } /** * Adds completions for local variables in a method. * * @param set * @param method * @param offs The caret's offset into the source. This should be inside * of <code>method</code>. */ private void addLocalVarCompletions(Set<Completion> set, Method method, int offs) { for (int i=0; i<method.getParameterCount(); i++) { FormalParameter param = method.getParameter(i); set.add(new LocalVariableCompletion(this, param)); } CodeBlock body = method.getBody(); if (body!=null) { addLocalVarCompletions(set, body, offs); } } /** * Adds completions for local variables in a code block inside of a method. * * @param set * @param block The code block. * @param offs The caret's offset into the source. This should be inside * of <code>block</code>. */ private void addLocalVarCompletions(Set<Completion> set, CodeBlock block, int offs) { for (int i=0; i<block.getLocalVarCount(); i++) { LocalVariable var = block.getLocalVar(i); if (var.getNameEndOffset()<=offs) { set.add(new LocalVariableCompletion(this, var)); } else { // This and all following declared after offs break; } } for (int i=0; i<block.getChildBlockCount(); i++) { CodeBlock child = block.getChildBlock(i); if (child.containsOffset(offs)) { addLocalVarCompletions(set, child, offs); break; // All other blocks are past this one } // If we've reached a block that's past the offset we're // searching for... else if (child.getNameStartOffset()>offs) { break; } } } /** * Adds a jar to read from. * * @param info The jar to add. If this is <code>null</code>, then * the current JVM's main JRE jar (rt.jar, or classes.jar on OS X) * will be added. If this jar has already been added, adding it * again will do nothing (except possibly update its attached source * location). * @throws IOException If an IO error occurs. * @see #getJars() * @see #removeJar(File) */ public void addJar(LibraryInfo info) throws IOException { jarManager.addClassFileSource(info); } /** * Checks whether the user is typing a completion for a String member after * a String literal. * * @param comp The text component. * @param alreadyEntered The text already entered. * @param cu The compilation unit being parsed. * @param set The set to add possible completions to. * @return Whether the user is indeed typing a completion for a String * literal member. */ private boolean checkStringLiteralMember(JTextComponent comp, String alreadyEntered, CompilationUnit cu, Set<Completion> set) { boolean stringLiteralMember = false; int offs = comp.getCaretPosition() - alreadyEntered.length() - 1; if (offs>1) { RSyntaxTextArea textArea = (RSyntaxTextArea)comp; RSyntaxDocument doc = (RSyntaxDocument)textArea.getDocument(); try { //System.out.println(doc.charAt(offs) + ", " + doc.charAt(offs+1)); if (doc.charAt(offs)=='"' && doc.charAt(offs+1)=='.') { int curLine = textArea.getLineOfOffset(offs); Token list = textArea.getTokenListForLine(curLine); Token prevToken = RSyntaxUtilities.getTokenAtOffset(list, offs); if (prevToken!=null && prevToken.getType()==Token.LITERAL_STRING_DOUBLE_QUOTE) { ClassFile cf = getClassFileFor(cu, "java.lang.String"); addCompletionsForExtendedClass(set, cu, cf, cu.getPackageName(), null); stringLiteralMember = true; } else { System.out.println(prevToken); } } } catch (BadLocationException ble) { // Never happens ble.printStackTrace(); } } return stringLiteralMember; } /** * Removes all jars from the "build path." * * @see #removeJar(File) * @see #addClassFileSource(JarInfo) * @see #getJars() */ public void clearJars() { jarManager.clearClassFileSources(); // The memory used by the completions can be quite large, so go ahead // and clear out the completions list so no-longer-needed ones are // eligible for GC. clear(); } /** * Creates and returns a mapping of type parameters to type arguments. * * @param type The type of a variable/field/etc. whose fields/methods/etc. * are being code completed, as declared in the source. This * includes type arguments. * @param cf The <code>ClassFile</code> representing the actual type of * the variable/field/etc. being code completed * @return A mapping of type parameter names to type arguments (both * Strings). */ private Map<String, String> createTypeParamMap(Type type, ClassFile cf) { Map<String, String> typeParamMap = null; List<TypeArgument> typeArgs = type.getTypeArguments(type.getIdentifierCount()-1); if (typeArgs!=null) { typeParamMap = new HashMap<String, String>(); List<String> paramTypes = cf.getParamTypes(); // Should be the same size! Otherwise, the source code has // too many/too few type arguments listed for this type. int min = Math.min(paramTypes==null ? 0 : paramTypes.size(), typeArgs.size()); for (int i=0; i<min; i++) { TypeArgument typeArg = typeArgs.get(i); typeParamMap.put(paramTypes.get(i), typeArg.toString()); } } return typeParamMap; } /** * {@inheritDoc} */ @Override public List<Completion> getCompletionsAt(JTextComponent tc, Point p) { getCompletionsImpl(tc); // Force loading of completions return super.getCompletionsAt(tc, p); } /** * {@inheritDoc} */ @Override protected List<Completion> getCompletionsImpl(JTextComponent comp) { comp.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try { completions.clear(); CompilationUnit cu = javaProvider.getCompilationUnit(); if (cu==null) { return completions; // empty } Set<Completion> set = new TreeSet<Completion>(); // Cut down the list to just those matching what we've typed. // Note: getAlreadyEnteredText() never returns null String text = getAlreadyEnteredText(comp); // Special case - end of a String literal boolean stringLiteralMember = checkStringLiteralMember(comp, text, cu, set); // Not after a String literal - regular code completion if (!stringLiteralMember) { // Don't add shorthand completions if they're typing something // qualified if (text.indexOf('.')==-1) { addShorthandCompletions(set); } loadImportCompletions(set, text, cu); // Add completions for fully-qualified stuff (e.g. "com.sun.jav") //long startTime = System.currentTimeMillis(); jarManager.addCompletions(this, text, set); //long time = System.currentTimeMillis() - startTime; //System.out.println("jar completions loaded in: " + time); // Loop through all types declared in this source, and provide // completions depending on in what type/method/etc. the caret's in. loadCompletionsForCaretPosition(cu, comp, text, set); } // Do a final sort of all of our completions and we're good to go! completions = new ArrayList<Completion>(set); Collections.sort(completions); // Only match based on stuff after the final '.', since that's what is // displayed for all of our completions. text = text.substring(text.lastIndexOf('.')+1); @SuppressWarnings("unchecked") int start = Collections.binarySearch(completions, text, comparator); if (start<0) { start = -(start+1); } else { // There might be multiple entries with the same input text. while (start>0 && comparator.compare(completions.get(start-1), text)==0) { start--; } } @SuppressWarnings("unchecked") int end = Collections.binarySearch(completions, text+'{', comparator); end = -(end+1); return completions.subList(start, end); } finally { comp.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)); } } /** * Returns the jars on the "build path." * * @return A list of {@link LibraryInfo}s. Modifying a * <code>LibraryInfo</code> in this list will have no effect on * this completion provider; in order to do that, you must re-add * the jar via {@link #addJar(LibraryInfo)}. If there are * no jars on the "build path," this will be an empty list. * @see #addJar(LibraryInfo) */ public List<LibraryInfo> getJars() { return jarManager.getClassFileSources(); } public SourceLocation getSourceLocForClass(String className) { return jarManager.getSourceLocForClass(className); } /** * Returns whether a method defined by a super class is accessible to * this class. * * @param info Information about the member. * @param pkg The package of the source currently being parsed. * @return Whether or not the method is accessible. */ private boolean isAccessible(MemberInfo info, String pkg) { boolean accessible = false; int access = info.getAccessFlags(); if (org.fife.rsta.ac.java.classreader.Util.isPublic(access) || org.fife.rsta.ac.java.classreader.Util.isProtected(access)) { accessible = true; } else if (org.fife.rsta.ac.java.classreader.Util.isDefault(access)) { String pkg2 = info.getClassFile().getPackageName(); accessible = (pkg==null && pkg2==null) || (pkg!=null && pkg.equals(pkg2)); } return accessible; } /** * {@inheritDoc} */ @Override protected boolean isValidChar(char ch) { return Character.isJavaIdentifierPart(ch) || ch=='.'; } /** * Loads completions based on the current caret location in the source. In * other words: * * <ul> * <li>If the caret is anywhere in a class, the names of all methods and * fields in the class are loaded. Methods and fields in super * classes are also loaded. TODO: Get super methods/fields added * correctly by access! * <li>If the caret is in a field, local variables currently accessible * are loaded. * </ul> * * @param cu * @param comp * @param alreadyEntered * @param retVal */ private void loadCompletionsForCaretPosition(CompilationUnit cu, JTextComponent comp, String alreadyEntered, Set<Completion> retVal) { // Get completions for all fields and methods of all type declarations. //long startTime = System.currentTimeMillis(); int caret = comp.getCaretPosition(); //List temp = new ArrayList(); int start, end; int lastDot = alreadyEntered.lastIndexOf('.'); boolean qualified = lastDot>-1; String prefix = qualified ? alreadyEntered.substring(0, lastDot) : null; Iterator<TypeDeclaration> i = cu.getTypeDeclarationIterator(); while (i.hasNext()) { TypeDeclaration td = i.next(); start = td.getBodyStartOffset(); end = td.getBodyEndOffset(); if (caret>start && caret<=end) { loadCompletionsForCaretPosition(cu, comp, alreadyEntered, retVal, td, prefix, caret); } else if (caret<start) { break; // We've passed any type declarations we could be in } } //long time = System.currentTimeMillis() - startTime; //System.out.println("methods/fields/localvars loaded in: " + time); } /** * Loads completions based on the current caret location in the source. * This method is called when the caret is found to be in a specific type * declaration. This method checks if the caret is in a child type * declaration first, then adds completions for itself next. * * <ul> * <li>If the caret is anywhere in a class, the names of all methods and * fields in the class are loaded. Methods and fields in super * classes are also loaded. TODO: Get super methods/fields added * correctly by access! * <li>If the caret is in a field, local variables currently accessible * are loaded. * </ul> * * @param cu * @param comp * @param alreadyEntered * @param retVal */ private void loadCompletionsForCaretPosition(CompilationUnit cu, JTextComponent comp, String alreadyEntered, Set<Completion> retVal, TypeDeclaration td, String prefix, int caret) { // Do any child types first, so if any vars, etc. have duplicate names, // we pick up the one "closest" to us first. for (int i=0; i<td.getChildTypeCount(); i++) { TypeDeclaration childType = td.getChildType(i); loadCompletionsForCaretPosition(cu, comp, alreadyEntered, retVal, childType, prefix, caret); } Method currentMethod = null; Map<String, String> typeParamMap = new HashMap<String, String>(); if (td instanceof NormalClassDeclaration) { NormalClassDeclaration ncd = (NormalClassDeclaration)td; List<TypeParameter> typeParams = ncd.getTypeParameters(); if (typeParams!=null) { for (TypeParameter typeParam : typeParams) { String typeVar = typeParam.getName(); // For non-qualified completions, use type var name. typeParamMap.put(typeVar, typeVar); } } } // Get completions for this class's methods, fields and local // vars. Do this before checking super classes so that, if // we overrode anything, we get the "newest" version. String pkg = cu.getPackageName(); Iterator<Member> j = td.getMemberIterator(); while (j.hasNext()) { Member m = j.next(); if (m instanceof Method) { Method method = (Method)m; if (prefix==null || THIS.equals(prefix)) { retVal.add(new MethodCompletion(this, method)); } if (caret>=method.getBodyStartOffset() && caret<method.getBodyEndOffset()) { currentMethod = method; // Don't add completions for local vars if there is // a prefix, even "this". if (prefix==null) { addLocalVarCompletions(retVal, method, caret); } } } else if (m instanceof Field) { if (prefix==null || THIS.equals(prefix)) { Field field = (Field)m; retVal.add(new FieldCompletion(this, field)); } } } // Completions for superclass methods. // TODO: Implement me better if (prefix==null || THIS.equals(prefix)) { if (td instanceof NormalClassDeclaration) { NormalClassDeclaration ncd = (NormalClassDeclaration)td; Type extended = ncd.getExtendedType(); if (extended!=null) { // e.g., not java.lang.Object String superClassName = extended.toString(); ClassFile cf = getClassFileFor(cu, superClassName); if (cf!=null) { addCompletionsForExtendedClass(retVal, cu, cf, pkg, null); } else { System.out.println("[DEBUG]: Couldn't find ClassFile for: " + superClassName); } } } } // Completions for methods of fields, return values of methods, // static fields/methods, etc. if (prefix!=null && !THIS.equals(prefix)) { loadCompletionsForCaretPositionQualified(cu, alreadyEntered, retVal, td, currentMethod, prefix, caret); } } /** * Loads completions for the text at the current caret position, if there * is a "prefix" of chars and at least one '.' character in the text up to * the caret. This is currently very limited and needs to be improved. * * @param cu * @param alreadyEntered * @param retVal * @param td The type declaration the caret is in. * @param currentMethod The method the caret is in, or <code>null</code> if * none. * @param prefix The text up to the current caret position. This is * guaranteed to be non-<code>null</code> not equal to * "<tt>this</tt>". * @param offs The offset of the caret in the document. */ private void loadCompletionsForCaretPositionQualified(CompilationUnit cu, String alreadyEntered, Set<Completion> retVal, TypeDeclaration td, Method currentMethod, String prefix, int offs) { // TODO: Remove this restriction. int dot = prefix.indexOf('.'); if (dot>-1) { System.out.println("[DEBUG]: Qualified non-this completions currently only go 1 level deep"); return; } // TODO: Remove this restriction. else if (!prefix.matches("[A-Za-z_][A-Za-z0-9_\\$]*")) { System.out.println("[DEBUG]: Only identifier non-this completions are currently supported"); return; } String pkg = cu.getPackageName(); boolean matched = false; for (Iterator<Member> j=td.getMemberIterator(); j.hasNext(); ) { Member m = j.next(); // The prefix might be a field in the local class. if (m instanceof Field) { Field field = (Field)m; if (field.getName().equals(prefix)) { //System.out.println("FOUND: " + prefix + " (" + pkg + ")"); Type type = field.getType(); if (type.isArray()) { ClassFile cf = getClassFileFor(cu, "java.lang.Object"); addCompletionsForExtendedClass(retVal, cu, cf, pkg, null); FieldCompletion fc = FieldCompletion. createLengthCompletion(this, type); retVal.add(fc); } else if (!type.isBasicType()) { String typeStr = type.getName(true, false); ClassFile cf = getClassFileFor(cu, typeStr); // Add completions for extended class type chain if (cf!=null) { Map<String, String> typeParamMap = createTypeParamMap(type, cf); addCompletionsForExtendedClass(retVal, cu, cf, pkg, typeParamMap); // Add completions for all implemented interfaces // TODO: Only do this if type is abstract! for (int i=0; i<cf.getImplementedInterfaceCount(); i++) { String inter = cf.getImplementedInterfaceName(i, true); cf = getClassFileFor(cu, inter); System.out.println(cf); } } } matched = true; break; } } } // The prefix might be for a local variable in the current method. if (currentMethod!=null) { boolean found = false; // Check parameters to the current method for (int i=0; i<currentMethod.getParameterCount(); i++) { FormalParameter param = currentMethod.getParameter(i); String name = param.getName(); // Assuming prefix is "one level deep" and contains no '.'... if (prefix.equals(name)) { addCompletionsForLocalVarsMethods(cu, param, retVal); found = true; break; } } // If a formal param wasn't matched, check local variables. if (!found) { CodeBlock body = currentMethod.getBody(); if (body!=null) { loadCompletionsForCaretPositionQualifiedCodeBlock(cu, retVal, td, body, prefix, offs); } } matched |= found; } // Could be a class name, in which case we'll need to add completions // for static fields and methods. if (!matched) { List<ImportDeclaration> imports = cu.getImports(); List<ClassFile> matches = jarManager.getClassesWithUnqualifiedName( prefix, imports); if (matches!=null) { for (int i=0; i<matches.size(); i++) { ClassFile cf = matches.get(i); addCompletionsForStaticMembers(retVal, cu, cf, pkg); } } } } private void loadCompletionsForCaretPositionQualifiedCodeBlock( CompilationUnit cu, Set<Completion> retVal, TypeDeclaration td, CodeBlock block, String prefix, int offs) { boolean found = false; for (int i=0; i<block.getLocalVarCount(); i++) { LocalVariable var = block.getLocalVar(i); if (var.getNameEndOffset()<=offs) { // TODO: This assumes prefix is "1 level deep" if (prefix.equals(var.getName())) { addCompletionsForLocalVarsMethods(cu, var, retVal); found = true; break; } } else { // This and all following declared after offs break; } } if (found) { return; } for (int i=0; i<block.getChildBlockCount(); i++) { CodeBlock child = block.getChildBlock(i); if (child.containsOffset(offs)) { loadCompletionsForCaretPositionQualifiedCodeBlock(cu, retVal, td, child, prefix, offs); break; // All other blocks are past this one } // If we've reached a block that's past the offset we're // searching for... else if (child.getNameStartOffset()>offs) { break; } } } /** * Loads completions for a single import statement. * * @param importStr The import statement. * @param pkgName The package of the source currently being parsed. */ private void loadCompletionsForImport(Set<Completion> set, String importStr, String pkgName) { if (importStr.endsWith(".*")) { String pkg = importStr.substring(0, importStr.length()-2); boolean inPkg = pkg.equals(pkgName); List<ClassFile> classes= jarManager.getClassesInPackage(pkg, inPkg); for (ClassFile cf : classes) { set.add(new ClassCompletion(this, cf)); } } else { ClassFile cf = jarManager.getClassEntry(importStr); if (cf!=null) { set.add(new ClassCompletion(this, cf)); } } } /** * Loads completions for all import statements. * * @param cu The compilation unit being parsed. */ private void loadImportCompletions(Set<Completion> set, String text, CompilationUnit cu) { // Fully-qualified completions are handled elsewhere, so no need to // duplicate the work here if (text.indexOf('.')>-1) { return; } //long startTime = System.currentTimeMillis(); String pkgName = cu.getPackageName(); loadCompletionsForImport(set, JAVA_LANG_PACKAGE, pkgName); for (Iterator<ImportDeclaration> i=cu.getImportIterator(); i.hasNext(); ) { ImportDeclaration id = i.next(); String name = id.getName(); if (!JAVA_LANG_PACKAGE.equals(name)) { loadCompletionsForImport(set, name, pkgName); } } // Collections.sort(completions); //long time = System.currentTimeMillis() - startTime; //System.out.println("imports loaded in: " + time); } /** * Removes a jar from the "build path." * * @param jar The jar to remove. * @return Whether the jar was removed. This will be <code>false</code> * if the jar was not on the build path. * @see #addClassFileSource(JarInfo) * @see #getJars() * @see #clearJars() */ public boolean removeJar(File jar) { boolean removed = jarManager.removeClassFileSource(jar); // The memory used by the completions can be quite large, so go ahead // and clear out the completions list so no-longer-needed ones are // eligible for GC. if (removed) { clear(); } return removed; } /** * Sets the parent Java provider. * * @param javaProvider The parent completion provider. */ void setJavaProvider(JavaCompletionProvider javaProvider) { this.javaProvider = javaProvider; } }
Fixing ConcurrentModificationException in some instances in Java language support
src/org/fife/rsta/ac/java/SourceCompletionProvider.java
Fixing ConcurrentModificationException in some instances in Java language support
<ide><path>rc/org/fife/rsta/ac/java/SourceCompletionProvider.java <ide> <ide> try { <ide> <del> completions.clear(); <add> completions = new ArrayList<Completion>();//completions.clear(); <ide> <ide> CompilationUnit cu = javaProvider.getCompilationUnit(); <ide> if (cu==null) {
JavaScript
mit
c19ba472ddd0d10d704d1403ab91ab98403ff2ce
0
Samnsparky/ljswitchboard,Samnsparky/ljswitchboard,Samnsparky/ljswitchboard,Samnsparky/ljswitchboard,Samnsparky/ljswitchboard
/** * Logic for the register matrix LabJack Switchboard module. * * Logic for a matrix with information about registers that also allows users * to read and write the current value of those registers via raw values. * * @author A. Samuel Pottinger (LabJack Corp, 2013) **/ var async = require('async'); var handlebars = require('handlebars'); var simplesets = require('simplesets'); var q = require('q'); var ljmmm = require('./ljmmm'); var REGISTERS_DATA_SRC = 'register_matrix/ljm_constants.json'; var REGISTERS_TABLE_TEMPLATE_SRC = 'register_matrix/matrix.html'; var REGISTER_WATCH_LIST_TEMPLATE_SRC = 'register_matrix/watchlist.html'; var REGISTER_MATRIX_SELECTOR = '#register-matrix'; var REGISTER_WATCHLIST_SELECTOR = '#register-watchlist' var DESCRIPTION_DISPLAY_TEMPLATE_SELECTOR_STR = '#{{address}}-description-display'; var ADD_TO_LIST_DESCRIPTOR_TEMPLATE_STR = '#{{address}}-add-to-list-button'; var WATCH_ROW_SELECTOR_TEMPLATE_STR = '#{{address}}-watch-row'; var DESCRIPTION_DISPLAY_SELECTOR_TEMPLATE = handlebars.compile( DESCRIPTION_DISPLAY_TEMPLATE_SELECTOR_STR); var ADD_TO_LIST_DESCRIPTOR_TEMPLATE = handlebars.compile( ADD_TO_LIST_DESCRIPTOR_TEMPLATE_STR); var WATCH_ROW_SELECTOR_TEMPLATE = handlebars.compile( WATCH_ROW_SELECTOR_TEMPLATE_STR); var registerWatchList = []; /** * Interpret the name fields of entries as LJMMM fields. * * Interpret the name fields of entries as LJMMM fields, creating the * appropriate register information Objects during enumeration during that * LJMMM interpretation. * * @param {Array} entries An Array of Object with information about registers * whose name field should be interpreted as LJMMM fields. * @return {q.deferred.promise} A Q promise that resolves to an Array of Array * of Objects with information about registers. Each sub-array is the * result of interpreting a register entry's name field as LJMMM and * enumerating as appropriate. **/ function expandLJMMMEntries(entries) { var deferred = q.defer(); async.map( entries, function(entry, callback){ ljmmm.expandLJMMMEntry(entry, function(newEntries){ callback(null, newEntries); }); }, function(error, newEntries){ deferred.resolve(newEntries); } ); return deferred.promise; } /** * Load information about registers for all devices. * * @return {q.defer.promise} A Q promise that will resolve to an Array of Object * where each object contains information about a register or set of * registers. The later will have a name field that can be interpreted as * LJMMM. **/ function getRegisterInfo() { var deferred = q.defer(); var registerInfoSrc = fs_facade.getExternalURI(REGISTERS_DATA_SRC); fs_facade.getJSON(registerInfoSrc, genericErrorHandler, function(info){ deferred.resolve(info['registers']); }); return deferred.promise; } /** * Filter out register entries that are not available on the given device type. * * @param {Array} registers An Array of Object with information about a * register or a set of registers. Each Object must have a device field * with the type of Array of Object, each element having a name field. * @param {String} deviceName The device type to look for. All register entries * that do not have this device type will be filtered out. * @return {q.defer.promise} A Q promise that will resolve to an Array of Object * where each Object contains information about an register or class of * registers. This Array will contain all of the registers originally * passed in that have the given device type listed in their devices * field. All others will be excluded. **/ function filterDeviceRegisters(registers, deviceName) { var deferred = q.defer(); async.filter( registers, function(register, callback){ var names = register.devices.map(function(e){ if(e.name === undefined) return e; else return e.name }); callback(names.indexOf(deviceName) != -1); }, function(registers){ deferred.resolve(registers); } ); return deferred.promise; } /** * Create a function as a closure over a device type for filterDeviceRegisters. * * Create a closure around device that calls filterDeviceRegisters with the * provided device type. * * @param {String} device The device type that is being filtered for. * @return {function} Closure with device type info. See filterDeviceRegisters. **/ function createDeviceFilter(device) { return function(registers){ return filterDeviceRegisters(registers, device); } } /** * Add a new field to the given register information objects with firmware info. * * Add a new field to the given register information objects with the minimum * firmware at which the cooresponding register became available for the given * device type. * * @param {Array} registers An Array of Object with information about registers * to decorate. * @param {String} device The name of the device type to find the minimum * firmware version for. * @return {q.defer.promise} A Q promise that resovles to an Array of Object * with information about a register or class of registers. These modified * Objects will have an added relevantFwmin field. **/ function fwminSelector(registers, device) { var deferred = q.defer(); async.map( registers, function(register, callback){ var newRegister = $.extend({}, register); var device = register.devices[device]; var relevantFwmin; if(device === undefined || device.fwmin === undefined) relevantFwmin = 0; else relevantFwmin = device.fwmin; newRegister.relevantFwmin = relevantFwmin; callback(null, newRegister); }, function(error, registers){ if(error !== null) genericErrorHandler(error); deferred.resolve(registers); } ); return deferred.promise; } /** * Create a closure around device type information for fwminSelector. * * Create a closure around device type information to call fwminSelector for * that device type. * * @param {String} device The device type to create the closure with. * @return {function} Closure around fwminSelector for the given device type. * See fwminSelector. **/ function createFwminSelector(device) { return function(registers){ return fwminSelector(registers, device); } } /** * jQuery event listener to show / hide documentation for a register entry. * * @param {Event} event Standard jQuery event information. **/ function toggleRegisterInfo(event) { var toggleButtonID = event.target.id; var jqueryToggleButtonID = '#' + toggleButtonID; var address = toggleButtonID.replace('-toggle-button', ''); var expand = event.target.className.indexOf('expand') != -1; var descriptionSelector = DESCRIPTION_DISPLAY_SELECTOR_TEMPLATE( {address: address}); if(expand) { $(descriptionSelector).fadeIn(); $(jqueryToggleButtonID).addClass('collapse').removeClass('expand'); $(jqueryToggleButtonID).addClass('icon-minus').removeClass( 'icon-plus'); } else { $(descriptionSelector).fadeOut(); $(jqueryToggleButtonID).addClass('expand').removeClass('collapse'); $(jqueryToggleButtonID).addClass('icon-plus').removeClass( 'icon-minus'); } } /** * Convert an Array of two Arrays to an Object. * * Convert an Array of Arrays with two elements to a dict such that each * Array's first element acts as a key to the second. * * @param {Array} data An Array of two Arrays to zip together into a dict. * @return {Object} Object created by combining the two arrays. * @throws Error thrown if one of data's Arrays does not contain exactly two * elements. **/ function zip(data) { var retVal = {}; for(var i in data) { if(data[i].length != 2) { throw new Error( 'The collection to be zipped must have two elements.' ); } retVal[data[i][0]] = data[i][1]; } return retVal; } /** * Index a collection of registers by their addresses. * * Create an Object with address numbers for attributes and Objects describing * the corresponding register as values. * * @param {Array} registers An Array of Object with register information. * @return {Object} An Object acting as an index or mapping between address and * register info Object. **/ function organizeRegistersByAddress(registers) { var pairs = registers.map(function(e){ return [e.address, e]; }); return zip(pairs); } /** * Get a list of unique tags represented across all of the provided registers. * * @param {Array} entries Array of Object with register information. * @return {Array} An Array of String, each element a unique tag found in the * provided corpus of registers. This represents the set of all unique tags * across all of the provided entries. **/ function getTagSet(entries) { var tagsHierarchical = entries.map(function(e) {return e.tags;}); var tags = []; for(var i in tagsHierarchical) { tags.push.apply(tags, tagsHierarchical[i]); } var tagSet = new simplesets.Set(tags); return tagSet.array(); } /** * Render a table with information about registers. * * Render the UI widgets to view / manipulate information about device * registers. * * @param {Array} entries An Array of Object with information about registers. * @return {q.defer.promise} A Q promise that resolves to null. **/ function renderRegistersTable(entries, tags, filteredEntries, currentTag, currentSearchTerm) { var deferred = q.defer(); var location = fs_facade.getExternalURI(REGISTERS_TABLE_TEMPLATE_SRC); var entriesByAddress = organizeRegistersByAddress(entries); if(tags == undefined) tags = getTagSet(entries); if(currentTag === undefined) currentTag = 'all'; if(currentSearchTerm === undefined) currentSearchTerm = ''; if(filteredEntries === undefined) filteredEntries = entries; var templateVals = { 'registers': filteredEntries, 'tags': tags, 'currentTag': currentTag, 'currentSearchTerm': currentSearchTerm }; fs_facade.renderTemplate( location, templateVals, genericErrorHandler, function(renderedHTML) { $(REGISTER_MATRIX_SELECTOR).html(renderedHTML); $('.toggle-info-button').click(toggleRegisterInfo); $('.add-to-list-button').click(function(event){ addToWatchList(event, entriesByAddress); }); $('.tag-selection-link').click(function(event){ var tag = event.target.id.replace('-tag-selector', ''); searchRegisters(entries, tags, tag, currentSearchTerm); }); $('#search-button').click(function(event){ var term = $('#search-box').val(); searchRegisters(entries, tags, currentTag, term); }); $('#search-box').keypress(function (e) { if (e.which != 13) return; var term = $('#search-box').val(); searchRegisters(entries, tags, currentTag, term); }); // Redraw bug document.body.style.display='none'; document.body.offsetHeight; // no need to store this anywhere, the reference is enough document.body.style.display='block'; deferred.resolve(); } ); return deferred.promise; } // TODO: By LJMMM, 'all' is a valid tag. /** * Filter / search registers by tag and search term. * * Filter / search registers by tag and search term, rendering a registers table * with the listing after filtering. * * @param {Array} entires An Array of Object with information about the corpus * of registers to search through. * @param {Array} allTags An Array of String with the names of all tags in the * provided corpus of registers. * @param {String} tag The tag to filter by. Can be 'all' to avoid filtering. * @param {String} searchTerm The term to search the description, name, and * tags for. If the term cannot be found, the register will be filered out. **/ function searchRegisters(entries, allTags, tag, searchTerm) { var filteredEntries = entries; if(tag !== 'all') { filteredEntries = filteredEntries.filter(function(e){ return e.tags.indexOf(tag) != -1; }); } var termLow = searchTerm.toLowerCase(); if(termLow !== '') { filteredEntries = filteredEntries.filter(function(e){ var inName = e.name.toLowerCase().indexOf(termLow) != -1; var inTag = e.flatTagStr.toLowerCase().indexOf(termLow) != -1; var inDesc = e.description.toLowerCase().indexOf(termLow) != -1; return inName || inTag || inDesc; }); } renderRegistersTable(entries, allTags, filteredEntries, tag, searchTerm); } /** * Turn a hierarchical Array of register information into a linear one. * * Convert an Array with Array elements containing Objects with register * information to an Array of the same Objects. * * @param {Array} entries The Array of Arrays to convert. * @return {q.defer.promise} A Q promise that resolves to the "flattened" or * converted Array of Object. **/ function flattenEntries(entries) { var deferred = q.defer(); var retList = []; async.each( entries, function(itemSet, callback){ for(i in itemSet) retList.push(itemSet[i]); callback(); }, function(error){ deferred.resolve(retList); } ); return deferred.promise; } /** * Convert the tags attribute of Objects with register info to a String. * * Convert the tags attribute of Objects with register info from an Array of * String tags to a String containing the same list of tags joined by a comma. * The list will be saved as a new attribute called flatTagStr on the same * objects. * * @param {Array} registers An Array of Objects with register information to * create flattened tag strings for. * @return {q.defer.promise} A Q promise that resolves to the new Array of * Object with flattened tag strings. **/ function flattenTags(registers) { var deferred = q.defer(); async.map( registers, function(register, callback){ var newRegister = $.extend({}, register); newRegister.flatTagStr = register.tags.join(','); callback(null, newRegister); }, function(error, registers){ if(error !== null) genericErrorHandler(error); deferred.resolve(registers); } ); return deferred.promise; } /** * Add information to register info Objects about register access restrictions. * * Parse the readwrite field of register information Objects, adding the Boolean * fields of readAccess and writeAccess indicating if the register can be read * and written to respectively. * * @param {Array} registers An Array of Object with register inforamtion to * decorate. * @return {q.promise} A promise that resovles to the decorated / updated * register information objects. **/ function addRWInfo(registers) { var deferred = q.defer(); async.map( registers, function(register, callback){ var newRegister = $.extend({}, register); newRegister.readAccess = newRegister.readwrite.indexOf('R') != -1 newRegister.writeAccess = newRegister.readwrite.indexOf('W') != -1 callback(null, newRegister); }, function(error, registers){ if(error !== null) genericErrorHandler(error); deferred.resolve(registers); } ); return deferred.promise; } /** * Refresh / re-render the list of registers being watchted by this module. **/ function refreshWatchList() { var location = fs_facade.getExternalURI(REGISTER_WATCH_LIST_TEMPLATE_SRC); registerWatchList.sort(function(a, b){ return a.address - b.address; }); if(registerWatchList.length > 0) { fs_facade.renderTemplate( location, {'registers': registerWatchList}, genericErrorHandler, function(renderedHTML) { $(REGISTER_WATCHLIST_SELECTOR).html(renderedHTML); $(REGISTER_WATCHLIST_SELECTOR).show(); var showRegiserEditControls = function(event){ var address = event.target.id.replace('edit-reg-', ''); var rowSelector = WATCH_ROW_SELECTOR_TEMPLATE({ 'address': address }); $(rowSelector).find('.value-display').slideUp(); $(rowSelector).find('.value-edit-controls').slideDown(); }; var hideRegisterEditControls = function(event){ var address = event.target.id; address = address.replace('close-edit-reg-', ''); address = address.replace('icon-', ''); var rowSelector = WATCH_ROW_SELECTOR_TEMPLATE({ 'address': address }); $(rowSelector).find('.value-edit-controls').slideUp(); $(rowSelector).find('.value-display').slideDown(); }; var writeRegister = function(event){ var address = event.target.id; address = address.replace('write-reg-', ''); address = address.replace('icon-', ''); var rowSelector = WATCH_ROW_SELECTOR_TEMPLATE({ 'address': address }); $(rowSelector).find('.write-confirm-msg').slideDown( function(){ window.setTimeout(function(){ $(rowSelector).find( '.write-confirm-msg' ).slideUp(); }, 250); } ); }; $('.remove-from-list-button').click(removeFromWatchList); $('.edit-register-button').click(showRegiserEditControls); $('.close-value-editor-button').click(hideRegisterEditControls); $('.write-value-editor-button').click(writeRegister); } ); } else { $(REGISTER_WATCHLIST_SELECTOR).hide(); } } /** * Event listener to add a new register to the watch list for this module. * * Event listener that will add a new register entry to the watch list for this * module, refresing the watch list in the process. * * @param {Event} event jQuery event information. * @param {Object} registerInfoByAddress Object acting as an address indexed * access layer for register information. Attributes should be addresses * of registers and values should be Objects with information about the * corresponding register. **/ function addToWatchList(event, registerInfoByAddress) { var buttonID = event.target.id; var address = Number(buttonID.replace('-add-to-list-button', '')); var descriptor = ADD_TO_LIST_DESCRIPTOR_TEMPLATE({address: address}); $(descriptor).hide(); var targetRegister = registerInfoByAddress[address]; registerWatchList.push(targetRegister); refreshWatchList(); } /** * Event listener to remove a register from the watch list for this module. * * @param {Event} event jQuery event information. **/ function removeFromWatchList(event) { var buttonID = event.target.id; var address = buttonID.replace('-remove-from-list-button', ''); console.log(registerWatchList); var registersToRemove = registerWatchList.filter( function(e){ return e.address == address; } ); registerWatchList = registerWatchList.filter( function(e){ return e.address != address; } ); refreshWatchList(); for(var i in registersToRemove) { var registerToRemove = registersToRemove[i]; var descriptor = ADD_TO_LIST_DESCRIPTOR_TEMPLATE( {address: registerToRemove.address} ); $(descriptor).show(); } } // TODO: Need to select device filter based on selected device $('#register-matrix-holder').ready(function(){ var filterByDevice = createDeviceFilter('T7'); var selectFwmin = createFwminSelector('T7'); $('.device-selection-radio').first().prop('checked', true); $('.device-selection-radio').change(function(){ $('#device-selector').hide(); $('#device-selector').fadeIn(); }); getRegisterInfo() .then(filterByDevice) .then(selectFwmin) .then(flattenTags) .then(addRWInfo) .then(expandLJMMMEntries) .then(flattenEntries) .then(renderRegistersTable) .done(); });
switchboard_modules/register_matrix/controller.js
/** * Logic for the register matrix LabJack Switchboard module. * * Logic for a matrix with information about registers that also allows users * to read and write the current value of those registers via raw values. * * @author A. Samuel Pottinger (LabJack Corp, 2013) **/ var async = require('async'); var handlebars = require('handlebars'); var simplesets = require('simplesets'); var q = require('q'); var ljmmm = require('./ljmmm'); var REGISTERS_DATA_SRC = 'register_matrix/ljm_constants.json'; var REGISTERS_TABLE_TEMPLATE_SRC = 'register_matrix/matrix.html'; var REGISTER_WATCH_LIST_TEMPLATE_SRC = 'register_matrix/watchlist.html'; var REGISTER_MATRIX_SELECTOR = '#register-matrix'; var REGISTER_WATCHLIST_SELECTOR = '#register-watchlist' var DESCRIPTION_DISPLAY_TEMPLATE_SELECTOR_STR = '#{{address}}-description-display'; var ADD_TO_LIST_DESCRIPTOR_TEMPLATE_STR = '#{{address}}-add-to-list-button'; var WATCH_ROW_SELECTOR_TEMPLATE_STR = '#{{address}}-watch-row'; var DESCRIPTION_DISPLAY_SELECTOR_TEMPLATE = handlebars.compile( DESCRIPTION_DISPLAY_TEMPLATE_SELECTOR_STR); var ADD_TO_LIST_DESCRIPTOR_TEMPLATE = handlebars.compile( ADD_TO_LIST_DESCRIPTOR_TEMPLATE_STR); var WATCH_ROW_SELECTOR_TEMPLATE = handlebars.compile( WATCH_ROW_SELECTOR_TEMPLATE_STR); var registerWatchList = []; /** * Interpret the name fields of entries as LJMMM fields. * * Interpret the name fields of entries as LJMMM fields, creating the * appropriate register information Objects during enumeration during that * LJMMM interpretation. * * @param {Array} entries An Array of Object with information about registers * whose name field should be interpreted as LJMMM fields. * @return {q.deferred.promise} A Q promise that resolves to an Array of Array * of Objects with information about registers. Each sub-array is the * result of interpreting a register entry's name field as LJMMM and * enumerating as appropriate. **/ function expandLJMMMEntries(entries) { var deferred = q.defer(); async.map( entries, function(entry, callback){ ljmmm.expandLJMMMEntry(entry, function(newEntries){ callback(null, newEntries); }); }, function(error, newEntries){ deferred.resolve(newEntries); } ); return deferred.promise; } /** * Load information about registers for all devices. * * @return {q.defer.promise} A Q promise that will resolve to an Array of Object * where each object contains information about a register or set of * registers. The later will have a name field that can be interpreted as * LJMMM. **/ function getRegisterInfo() { var deferred = q.defer(); var registerInfoSrc = fs_facade.getExternalURI(REGISTERS_DATA_SRC); fs_facade.getJSON(registerInfoSrc, genericErrorHandler, function(info){ deferred.resolve(info['registers']); }); return deferred.promise; } /** * Filter out register entries that are not available on the given device type. * * @param {Array} registers An Array of Object with information about a * register or a set of registers. Each Object must have a device field * with the type of Array of Object, each element having a name field. * @param {String} deviceName The device type to look for. All register entries * that do not have this device type will be filtered out. * @return {q.defer.promise} A Q promise that will resolve to an Array of Object * where each Object contains information about an register or class of * registers. This Array will contain all of the registers originally * passed in that have the given device type listed in their devices * field. All others will be excluded. **/ function filterDeviceRegisters(registers, deviceName) { var deferred = q.defer(); async.filter( registers, function(register, callback){ var names = register.devices.map(function(e){ if(e.name === undefined) return e; else return e.name }); callback(names.indexOf(deviceName) != -1); }, function(registers){ deferred.resolve(registers); } ); return deferred.promise; } /** * Create a function as a closure over a device type for filterDeviceRegisters. * * Create a closure around device that calls filterDeviceRegisters with the * provided device type. * * @param {String} device The device type that is being filtered for. * @return {function} Closure with device type info. See filterDeviceRegisters. **/ function createDeviceFilter(device) { return function(registers){ return filterDeviceRegisters(registers, device); } } /** * Add a new field to the given register information objects with firmware info. * * Add a new field to the given register information objects with the minimum * firmware at which the cooresponding register became available for the given * device type. * * @param {Array} registers An Array of Object with information about registers * to decorate. * @param {String} device The name of the device type to find the minimum * firmware version for. * @return {q.defer.promise} A Q promise that resovles to an Array of Object * with information about a register or class of registers. These modified * Objects will have an added relevantFwmin field. **/ function fwminSelector(registers, device) { var deferred = q.defer(); async.map( registers, function(register, callback){ var newRegister = $.extend({}, register); var device = register.devices[device]; var relevantFwmin; if(device === undefined || device.fwmin === undefined) relevantFwmin = 0; else relevantFwmin = device.fwmin; newRegister.relevantFwmin = relevantFwmin; callback(null, newRegister); }, function(error, registers){ if(error !== null) genericErrorHandler(error); deferred.resolve(registers); } ); return deferred.promise; } /** * Create a closure around device type information for fwminSelector. * * Create a closure around device type information to call fwminSelector for * that device type. * * @param {String} device The device type to create the closure with. * @return {function} Closure around fwminSelector for the given device type. * See fwminSelector. **/ function createFwminSelector(device) { return function(registers){ return fwminSelector(registers, device); } } /** * jQuery event listener to show / hide documentation for a register entry. * * @param {Event} event Standard jQuery event information. **/ function toggleRegisterInfo(event) { var toggleButtonID = event.target.id; var jqueryToggleButtonID = '#' + toggleButtonID; var address = toggleButtonID.replace('-toggle-button', ''); var expand = event.target.className.indexOf('expand') != -1; var descriptionSelector = DESCRIPTION_DISPLAY_SELECTOR_TEMPLATE( {address: address}); if(expand) { $(descriptionSelector).fadeIn(); $(jqueryToggleButtonID).addClass('collapse').removeClass('expand'); $(jqueryToggleButtonID).addClass('icon-minus').removeClass( 'icon-plus'); } else { $(descriptionSelector).fadeOut(); $(jqueryToggleButtonID).addClass('expand').removeClass('collapse'); $(jqueryToggleButtonID).addClass('icon-plus').removeClass( 'icon-minus'); } } function zip(data) { var retVal = {}; for(var i in data) { retVal[data[i][0]] = data[i][1]; } return retVal; } function organizeRegistersByAddress(registers) { var pairs = registers.map(function(e){ return [e.address, e]; }); return zip(pairs); } function getTagSet(entries) { var tagsHierarchical = entries.map(function(e) {return e.tags;}); var tags = []; for(var i in tagsHierarchical) { tags.push.apply(tags, tagsHierarchical[i]); } var tagSet = new simplesets.Set(tags); return tagSet.array(); } /** * Render a table with information about registers. * * Render the UI widgets to view / manipulate information about device * registers. * * @param {Array} entries An Array of Object with information about registers. * @return {q.defer.promise} A Q promise that resolves to null. **/ function renderRegistersTable(entries, tags, filteredEntries, currentTag, currentSearchTerm) { var deferred = q.defer(); var location = fs_facade.getExternalURI(REGISTERS_TABLE_TEMPLATE_SRC); var entriesByAddress = organizeRegistersByAddress(entries); if(tags == undefined) tags = getTagSet(entries); if(currentTag === undefined) currentTag = 'all'; if(currentSearchTerm === undefined) currentSearchTerm = ''; if(filteredEntries === undefined) filteredEntries = entries; var templateVals = { 'registers': filteredEntries, 'tags': tags, 'currentTag': currentTag, 'currentSearchTerm': currentSearchTerm }; fs_facade.renderTemplate( location, templateVals, genericErrorHandler, function(renderedHTML) { $(REGISTER_MATRIX_SELECTOR).html(renderedHTML); $('.toggle-info-button').click(toggleRegisterInfo); $('.add-to-list-button').click(function(event){ addToWatchList(event, entriesByAddress); }); $('.tag-selection-link').click(function(event){ var tag = event.target.id.replace('-tag-selector', ''); searchRegisters(entries, tags, tag, currentSearchTerm); }); $('#search-button').click(function(event){ var term = $('#search-box').val(); searchRegisters(entries, tags, currentTag, term); }); $('#search-box').keypress(function (e) { if (e.which != 13) return; var term = $('#search-box').val(); searchRegisters(entries, tags, currentTag, term); }); // Redraw bug document.body.style.display='none'; document.body.offsetHeight; // no need to store this anywhere, the reference is enough document.body.style.display='block'; deferred.resolve(); } ); return deferred.promise; } function searchRegisters(entries, allTags, tag, searchTerm) { var filteredEntries = entries; if(tag !== 'all') { filteredEntries = filteredEntries.filter(function(e){ return e.tags.indexOf(tag) != -1; }); } var termLow = searchTerm.toLowerCase(); if(termLow !== '') { filteredEntries = filteredEntries.filter(function(e){ var inName = e.name.toLowerCase().indexOf(termLow) != -1; var inTag = e.flatTagStr.toLowerCase().indexOf(termLow) != -1; var inDesc = e.description.toLowerCase().indexOf(termLow) != -1; return inName || inTag || inDesc; }); } renderRegistersTable(entries, allTags, filteredEntries, tag, searchTerm); } /** * Turn a hierarchical Array of register information into a linear one. * * Convert an Array with Array elements containing Objects with register * information to an Array of the same Objects. * * @param {Array} entries The Array of Arrays to convert. * @return {q.defer.promise} A Q promise that resolves to the "flattened" or * converted Array of Object. **/ function flattenEntries(entries) { var deferred = q.defer(); var retList = []; async.each( entries, function(itemSet, callback){ for(i in itemSet) retList.push(itemSet[i]); callback(); }, function(error){ deferred.resolve(retList); } ); return deferred.promise; } /** * Convert the tags attribute of Objects with register info to a String. * * Convert the tags attribute of Objects with register info from an Array of * String tags to a String containing the same list of tags joined by a comma. * The list will be saved as a new attribute called flatTagStr on the same * objects. * * @param {Array} registers An Array of Objects with register information to * create flattened tag strings for. * @return {q.defer.promise} A Q promise that resolves to the new Array of * Object with flattened tag strings. **/ function flattenTags(registers) { var deferred = q.defer(); async.map( registers, function(register, callback){ var newRegister = $.extend({}, register); newRegister.flatTagStr = register.tags.join(','); callback(null, newRegister); }, function(error, registers){ if(error !== null) genericErrorHandler(error); deferred.resolve(registers); } ); return deferred.promise; } function addRWInfo(registers) { var deferred = q.defer(); async.map( registers, function(register, callback){ var newRegister = $.extend({}, register); newRegister.readAccess = newRegister.readwrite.indexOf('R') != -1 newRegister.writeAccess = newRegister.readwrite.indexOf('W') != -1 callback(null, newRegister); }, function(error, registers){ if(error !== null) genericErrorHandler(error); deferred.resolve(registers); } ); return deferred.promise; } function refreshWatchList() { var location = fs_facade.getExternalURI(REGISTER_WATCH_LIST_TEMPLATE_SRC); registerWatchList.sort(function(a, b){ return a.address - b.address; }); if(registerWatchList.length > 0) { fs_facade.renderTemplate( location, {'registers': registerWatchList}, genericErrorHandler, function(renderedHTML) { $(REGISTER_WATCHLIST_SELECTOR).html(renderedHTML); $(REGISTER_WATCHLIST_SELECTOR).show(); var showRegiserEditControls = function(event){ var address = event.target.id.replace('edit-reg-', ''); var rowSelector = WATCH_ROW_SELECTOR_TEMPLATE({ 'address': address }); $(rowSelector).find('.value-display').slideUp(); $(rowSelector).find('.value-edit-controls').slideDown(); }; var hideRegisterEditControls = function(event){ var address = event.target.id; address = address.replace('close-edit-reg-', ''); address = address.replace('icon-', ''); var rowSelector = WATCH_ROW_SELECTOR_TEMPLATE({ 'address': address }); $(rowSelector).find('.value-edit-controls').slideUp(); $(rowSelector).find('.value-display').slideDown(); }; var writeRegister = function(event){ var address = event.target.id; address = address.replace('write-reg-', ''); address = address.replace('icon-', ''); var rowSelector = WATCH_ROW_SELECTOR_TEMPLATE({ 'address': address }); $(rowSelector).find('.write-confirm-msg').slideDown( function(){ window.setTimeout(function(){ $(rowSelector).find( '.write-confirm-msg' ).slideUp(); }, 250); } ); }; $('.remove-from-list-button').click(removeFromWatchList); $('.edit-register-button').click(showRegiserEditControls); $('.close-value-editor-button').click(hideRegisterEditControls); $('.write-value-editor-button').click(writeRegister); } ); } else { $(REGISTER_WATCHLIST_SELECTOR).hide(); } } function addToWatchList(event, registerInfoByAddress) { var buttonID = event.target.id; var address = Number(buttonID.replace('-add-to-list-button', '')); var descriptor = ADD_TO_LIST_DESCRIPTOR_TEMPLATE({address: address}); $(descriptor).hide(); var targetRegister = registerInfoByAddress[address]; registerWatchList.push(targetRegister); refreshWatchList(); } function removeFromWatchList(event) { var buttonID = event.target.id; var address = buttonID.replace('-remove-from-list-button', ''); console.log(registerWatchList); var registersToRemove = registerWatchList.filter( function(e){ return e.address == address; } ); registerWatchList = registerWatchList.filter( function(e){ return e.address != address; } ); refreshWatchList(); for(var i in registersToRemove) { var registerToRemove = registersToRemove[i]; var descriptor = ADD_TO_LIST_DESCRIPTOR_TEMPLATE( {address: registerToRemove.address} ); $(descriptor).show(); } } // TODO: Need to select device filter based on selected device $('#register-matrix-holder').ready(function(){ var filterByDevice = createDeviceFilter('T7'); var selectFwmin = createFwminSelector('T7'); $('.device-selection-radio').first().prop('checked', true); $('.device-selection-radio').change(function(){ $('#device-selector').hide(); $('#device-selector').fadeIn(); }); getRegisterInfo() .then(filterByDevice) .then(selectFwmin) .then(flattenTags) .then(addRWInfo) .then(expandLJMMMEntries) .then(flattenEntries) .then(renderRegistersTable) .done(); });
Added jsDoc for register matrix logic.
switchboard_modules/register_matrix/controller.js
Added jsDoc for register matrix logic.
<ide><path>witchboard_modules/register_matrix/controller.js <ide> } <ide> <ide> <add>/** <add> * Convert an Array of two Arrays to an Object. <add> * <add> * Convert an Array of Arrays with two elements to a dict such that each <add> * Array's first element acts as a key to the second. <add> * <add> * @param {Array} data An Array of two Arrays to zip together into a dict. <add> * @return {Object} Object created by combining the two arrays. <add> * @throws Error thrown if one of data's Arrays does not contain exactly two <add> * elements. <add>**/ <ide> function zip(data) <ide> { <add> <ide> var retVal = {}; <ide> <ide> for(var i in data) <ide> { <add> if(data[i].length != 2) <add> { <add> throw new Error( <add> 'The collection to be zipped must have two elements.' <add> ); <add> } <ide> retVal[data[i][0]] = data[i][1]; <ide> } <ide> <ide> } <ide> <ide> <add>/** <add> * Index a collection of registers by their addresses. <add> * <add> * Create an Object with address numbers for attributes and Objects describing <add> * the corresponding register as values. <add> * <add> * @param {Array} registers An Array of Object with register information. <add> * @return {Object} An Object acting as an index or mapping between address and <add> * register info Object. <add>**/ <ide> function organizeRegistersByAddress(registers) <ide> { <ide> var pairs = registers.map(function(e){ <ide> } <ide> <ide> <add>/** <add> * Get a list of unique tags represented across all of the provided registers. <add> * <add> * @param {Array} entries Array of Object with register information. <add> * @return {Array} An Array of String, each element a unique tag found in the <add> * provided corpus of registers. This represents the set of all unique tags <add> * across all of the provided entries. <add>**/ <ide> function getTagSet(entries) <ide> { <ide> var tagsHierarchical = entries.map(function(e) {return e.tags;}); <ide> } <ide> <ide> <add>// TODO: By LJMMM, 'all' is a valid tag. <add>/** <add> * Filter / search registers by tag and search term. <add> * <add> * Filter / search registers by tag and search term, rendering a registers table <add> * with the listing after filtering. <add> * <add> * @param {Array} entires An Array of Object with information about the corpus <add> * of registers to search through. <add> * @param {Array} allTags An Array of String with the names of all tags in the <add> * provided corpus of registers. <add> * @param {String} tag The tag to filter by. Can be 'all' to avoid filtering. <add> * @param {String} searchTerm The term to search the description, name, and <add> * tags for. If the term cannot be found, the register will be filered out. <add>**/ <ide> function searchRegisters(entries, allTags, tag, searchTerm) <ide> { <ide> var filteredEntries = entries; <ide> } <ide> <ide> <add>/** <add> * Add information to register info Objects about register access restrictions. <add> * <add> * Parse the readwrite field of register information Objects, adding the Boolean <add> * fields of readAccess and writeAccess indicating if the register can be read <add> * and written to respectively. <add> * <add> * @param {Array} registers An Array of Object with register inforamtion to <add> * decorate. <add> * @return {q.promise} A promise that resovles to the decorated / updated <add> * register information objects. <add>**/ <ide> function addRWInfo(registers) <ide> { <ide> var deferred = q.defer(); <ide> } <ide> <ide> <add>/** <add> * Refresh / re-render the list of registers being watchted by this module. <add>**/ <ide> function refreshWatchList() <ide> { <ide> var location = fs_facade.getExternalURI(REGISTER_WATCH_LIST_TEMPLATE_SRC); <ide> } <ide> <ide> <add>/** <add> * Event listener to add a new register to the watch list for this module. <add> * <add> * Event listener that will add a new register entry to the watch list for this <add> * module, refresing the watch list in the process. <add> * <add> * @param {Event} event jQuery event information. <add> * @param {Object} registerInfoByAddress Object acting as an address indexed <add> * access layer for register information. Attributes should be addresses <add> * of registers and values should be Objects with information about the <add> * corresponding register. <add>**/ <ide> function addToWatchList(event, registerInfoByAddress) <ide> { <ide> var buttonID = event.target.id; <ide> } <ide> <ide> <add>/** <add> * Event listener to remove a register from the watch list for this module. <add> * <add> * @param {Event} event jQuery event information. <add>**/ <ide> function removeFromWatchList(event) <ide> { <ide> var buttonID = event.target.id;
Java
apache-2.0
88429ac8b2c1c9965cb20ea0debb16e580886846
0
eyal-lezmy/Android-DataLib
package fr.eyal.datalib.sample.netflix.data.model.movieimage; import java.lang.ref.SoftReference; import android.content.Context; import android.content.OperationApplicationException; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Parcel; import android.os.Parcelable; import android.os.RemoteException; import fr.eyal.lib.data.model.ResponseBusinessObject; import fr.eyal.lib.data.service.model.ComplexOptions; import fr.eyal.lib.data.service.model.DataLibRequest; import fr.eyal.lib.util.FileManager; public class MovieImageBase implements ResponseBusinessObject { @SuppressWarnings("unused") private static final String TAG = MovieImageBase.class.getSimpleName(); protected static String CACHE_DIRECTORY = "movieimage"; /** * A soft reference to the Bitmap */ public SoftReference<Bitmap> image; /** * The last {@link BitmapFactory.Options} used to load the bitmap */ public BitmapFactory.Options lastOptions; /** * The image file path */ public String imagePath; protected FileManager mFileManager = null; public MovieImageBase() { super(); } /** * Constructor to build the image * * @param fingerprint */ public MovieImageBase(String fingerprint, ComplexOptions complexOptions) { super(); loadFromCache(fingerprint, complexOptions); } /** * PARCELABLE MANAGMENT */ public static final Parcelable.Creator<MovieImageBase> CREATOR = new Parcelable.Creator<MovieImageBase>() { @Override public MovieImageBase createFromParcel(final Parcel in) { return new MovieImageBase(in); } @Override public MovieImageBase[] newArray(final int size) { return new MovieImageBase[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(final Parcel dest, final int flags) { if(image != null) dest.writeParcelable(image.get(), flags); else dest.writeParcelable(null, flags); } public MovieImageBase(final Parcel in) { image = new SoftReference<Bitmap>((Bitmap) in.readParcelable(Bitmap.class.getClassLoader())); } @Override public void save(final DataLibRequest request) throws RemoteException, OperationApplicationException { if((mFileManager = FileManager.getInstance()) == null) return; String extension = FileManager.getFileExtension(request.url); String name = request.getFingerprint(); imagePath = mFileManager.saveInInternalCache(CACHE_DIRECTORY, name, extension, image.get(), 100); } /** * Load the associated cached file thanks to its request's fingerprint * * @param fingerprint */ protected void loadFromCache(String fingerprint, ComplexOptions complexOptions){ if((mFileManager = FileManager.getInstance()) == null) return; //we get the bitmap options BitmapFactory.Options options; if(complexOptions != null) options = (BitmapFactory.Options) complexOptions.getBitmapOptions(); else options = new BitmapFactory.Options(); //we get the bitmap from a cache file Bitmap bmp = mFileManager.getPictureFromInternalCache(CACHE_DIRECTORY, fingerprint, options); if(bmp != null) image = new SoftReference<Bitmap>(bmp); else image = null; //we store the options after treatment lastOptions = options; //we store the image path file for futur use imagePath = mFileManager.getPathFromInternalCache(CACHE_DIRECTORY, fingerprint); } }
Android-DataLib-Sample-Netflix/src/fr/eyal/datalib/sample/netflix/data/model/movieimage/MovieImageBase.java
package fr.eyal.datalib.sample.netflix.data.model.movieimage; import java.lang.ref.SoftReference; import android.content.Context; import android.content.OperationApplicationException; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Parcel; import android.os.Parcelable; import android.os.RemoteException; import fr.eyal.lib.data.model.ResponseBusinessObject; import fr.eyal.lib.data.service.model.ComplexOptions; import fr.eyal.lib.data.service.model.DataLibRequest; import fr.eyal.lib.util.FileManager; public class MovieImageBase implements ResponseBusinessObject { @SuppressWarnings("unused") private static final String TAG = MovieImageBase.class.getSimpleName(); protected static String CACHE_DIRECTORY = "movieimage"; /** * A soft reference to the Bitmap */ public SoftReference<Bitmap> image; /** * The last {@link BitmapFactory.Options} used to load the bitmap */ public BitmapFactory.Options lastOptions; /** * The image file path */ public String imagePath; protected FileManager mFileManager = null; public MovieImageBase() { super(); } /** * Constructor to build the image * * @param fingerprint */ public MovieImageBase(String fingerprint, ComplexOptions complexOptions) { super(); loadFromCache(fingerprint, complexOptions); } /** * PARCELABLE MANAGMENT */ public static final Parcelable.Creator<MovieImageBase> CREATOR = new Parcelable.Creator<MovieImageBase>() { @Override public MovieImageBase createFromParcel(final Parcel in) { return new MovieImageBase(in); } @Override public MovieImageBase[] newArray(final int size) { return new MovieImageBase[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(final Parcel dest, final int flags) { dest.writeParcelable(image.get(), flags); } public MovieImageBase(final Parcel in) { image = new SoftReference<Bitmap>((Bitmap) in.readParcelable(Bitmap.class.getClassLoader())); } @Override public void save(final DataLibRequest request) throws RemoteException, OperationApplicationException { if((mFileManager = FileManager.getInstance()) == null) return; String extension = FileManager.getFileExtension(request.url); String name = request.getFingerprint(); imagePath = mFileManager.saveInInternalCache(CACHE_DIRECTORY, name, extension, image.get(), 100); } /** * Load the associated cached file thanks to its request's fingerprint * * @param fingerprint */ protected void loadFromCache(String fingerprint, ComplexOptions complexOptions){ if((mFileManager = FileManager.getInstance()) == null) return; //we get the bitmap options BitmapFactory.Options options; if(complexOptions != null) options = (BitmapFactory.Options) complexOptions.getBitmapOptions(); else options = new BitmapFactory.Options(); //we get the bitmap from a cache file Bitmap bmp = mFileManager.getPictureFromInternalCache(CACHE_DIRECTORY, fingerprint, options); if(bmp != null) image = new SoftReference<Bitmap>(bmp); else image = null; //we store the options after treatment lastOptions = options; //we store the image path file for futur use imagePath = mFileManager.getPathFromInternalCache(CACHE_DIRECTORY, fingerprint); } }
NPE fix
Android-DataLib-Sample-Netflix/src/fr/eyal/datalib/sample/netflix/data/model/movieimage/MovieImageBase.java
NPE fix
<ide><path>ndroid-DataLib-Sample-Netflix/src/fr/eyal/datalib/sample/netflix/data/model/movieimage/MovieImageBase.java <ide> <ide> @Override <ide> public void writeToParcel(final Parcel dest, final int flags) { <del> dest.writeParcelable(image.get(), flags); <add> if(image != null) <add> dest.writeParcelable(image.get(), flags); <add> else <add> dest.writeParcelable(null, flags); <ide> } <ide> <ide> public MovieImageBase(final Parcel in) {
Java
mit
5ddc32e05d2e5a853ec1e76dc11cf7b6f0f3a210
0
CS2103JAN2017-W14-B4/main,CS2103JAN2017-W14-B4/main
package seedu.ezdo.storage; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlElement; import seedu.ezdo.commons.exceptions.IllegalValueException; import seedu.ezdo.model.tag.Tag; import seedu.ezdo.model.tag.UniqueTagList; import seedu.ezdo.model.todo.StartDate; import seedu.ezdo.model.todo.Email; import seedu.ezdo.model.todo.Name; import seedu.ezdo.model.todo.Task; import seedu.ezdo.model.todo.Priority; import seedu.ezdo.model.todo.ReadOnlyTask; import seedu.ezdo.model.todo.*; /** * JAXB-friendly version of the Task. */ public class XmlAdaptedTask { @XmlElement(required = true) private String name; @XmlElement(required = true) private int priority; @XmlElement(required = true) private String email; @XmlElement(required = true) private String startDate; @XmlElement private List<XmlAdaptedTag> tagged = new ArrayList<>(); /** * Constructs an XmlAdaptedTask. * This is the no-arg constructor that is required by JAXB. */ public XmlAdaptedTask() {} /** * Converts a given Task into this class for JAXB use. * * @param source future changes to this will not affect the created XmlAdaptedTask */ public XmlAdaptedTask(ReadOnlyTask source) { name = source.getName().fullName; priority = source.getPriority().value; email = source.getEmail().value; startDate = source.getStartDate().value; tagged = new ArrayList<>(); for (Tag tag : source.getTags()) { tagged.add(new XmlAdaptedTag(tag)); } } /** * Converts this jaxb-friendly adapted task object into the model's Task object. * * @throws IllegalValueException if there were any data constraints violated in the adapted task */ public Task toModelType() throws IllegalValueException { final List<Tag> taskTags = new ArrayList<>(); for (XmlAdaptedTag tag : tagged) { taskTags.add(tag.toModelType()); } final Name name = new Name(this.name); final Priority priority = new Priority(this.priority); final Email email = new Email(this.email); final StartDate startDate = new StartDate(this.startDate); final UniqueTagList tags = new UniqueTagList(taskTags); return new Task(name, priority, email, startDate, tags); } }
src/main/java/seedu/ezdo/storage/XmlAdaptedTask.java
package seedu.ezdo.storage; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlElement; import seedu.ezdo.commons.exceptions.IllegalValueException; import seedu.ezdo.model.tag.Tag; import seedu.ezdo.model.tag.UniqueTagList; <<<<<<< HEAD:src/main/java/seedu/ezdo/storage/XmlAdaptedPerson.java import seedu.ezdo.model.todo.Address; import seedu.ezdo.model.todo.Email; import seedu.ezdo.model.todo.Name; import seedu.ezdo.model.todo.Person; import seedu.ezdo.model.todo.Priority; import seedu.ezdo.model.todo.ReadOnlyPerson; ======= import seedu.ezdo.model.todo.*; >>>>>>> 6228ae6b03115b0e64fed2b189d86d8b94d2fa7e:src/main/java/seedu/ezdo/storage/XmlAdaptedTask.java /** * JAXB-friendly version of the Task. */ public class XmlAdaptedTask { @XmlElement(required = true) private String name; @XmlElement(required = true) private int priority; @XmlElement(required = true) private String email; @XmlElement(required = true) private String startDate; @XmlElement private List<XmlAdaptedTag> tagged = new ArrayList<>(); /** * Constructs an XmlAdaptedTask. * This is the no-arg constructor that is required by JAXB. */ public XmlAdaptedTask() {} /** * Converts a given Task into this class for JAXB use. * * @param source future changes to this will not affect the created XmlAdaptedTask */ public XmlAdaptedTask(ReadOnlyTask source) { name = source.getName().fullName; priority = source.getPriority().value; email = source.getEmail().value; startDate = source.getStartDate().value; tagged = new ArrayList<>(); for (Tag tag : source.getTags()) { tagged.add(new XmlAdaptedTag(tag)); } } /** * Converts this jaxb-friendly adapted task object into the model's Task object. * * @throws IllegalValueException if there were any data constraints violated in the adapted task */ public Task toModelType() throws IllegalValueException { final List<Tag> taskTags = new ArrayList<>(); for (XmlAdaptedTag tag : tagged) { taskTags.add(tag.toModelType()); } final Name name = new Name(this.name); final Priority priority = new Priority(this.priority); final Email email = new Email(this.email); <<<<<<< HEAD:src/main/java/seedu/ezdo/storage/XmlAdaptedPerson.java final Address address = new Address(this.address); final UniqueTagList tags = new UniqueTagList(personTags); return new Person(name, priority, email, address, tags); ======= final StartDate startDate = new StartDate(this.startDate); final UniqueTagList tags = new UniqueTagList(taskTags); return new Task(name, phone, email, startDate, tags); >>>>>>> 6228ae6b03115b0e64fed2b189d86d8b94d2fa7e:src/main/java/seedu/ezdo/storage/XmlAdaptedTask.java } }
Resolve some merge conflict arrows and more instances of Phone
src/main/java/seedu/ezdo/storage/XmlAdaptedTask.java
Resolve some merge conflict arrows and more instances of Phone
<ide><path>rc/main/java/seedu/ezdo/storage/XmlAdaptedTask.java <ide> import seedu.ezdo.commons.exceptions.IllegalValueException; <ide> import seedu.ezdo.model.tag.Tag; <ide> import seedu.ezdo.model.tag.UniqueTagList; <del><<<<<<< HEAD:src/main/java/seedu/ezdo/storage/XmlAdaptedPerson.java <del>import seedu.ezdo.model.todo.Address; <add>import seedu.ezdo.model.todo.StartDate; <ide> import seedu.ezdo.model.todo.Email; <ide> import seedu.ezdo.model.todo.Name; <del>import seedu.ezdo.model.todo.Person; <add>import seedu.ezdo.model.todo.Task; <ide> import seedu.ezdo.model.todo.Priority; <del>import seedu.ezdo.model.todo.ReadOnlyPerson; <del>======= <add>import seedu.ezdo.model.todo.ReadOnlyTask; <ide> import seedu.ezdo.model.todo.*; <del>>>>>>>> 6228ae6b03115b0e64fed2b189d86d8b94d2fa7e:src/main/java/seedu/ezdo/storage/XmlAdaptedTask.java <ide> <ide> /** <ide> * JAXB-friendly version of the Task. <ide> final Name name = new Name(this.name); <ide> final Priority priority = new Priority(this.priority); <ide> final Email email = new Email(this.email); <del><<<<<<< HEAD:src/main/java/seedu/ezdo/storage/XmlAdaptedPerson.java <del> final Address address = new Address(this.address); <del> final UniqueTagList tags = new UniqueTagList(personTags); <del> return new Person(name, priority, email, address, tags); <del>======= <ide> final StartDate startDate = new StartDate(this.startDate); <ide> final UniqueTagList tags = new UniqueTagList(taskTags); <del> return new Task(name, phone, email, startDate, tags); <del>>>>>>>> 6228ae6b03115b0e64fed2b189d86d8b94d2fa7e:src/main/java/seedu/ezdo/storage/XmlAdaptedTask.java <add> return new Task(name, priority, email, startDate, tags); <ide> } <ide> }
Java
mit
c3380ef53d726f491367f7496119a479ce4513d7
0
sandy-8925/3MatchGame
package com.provinggrounds.match3things.activity; import java.util.Collection; import java.util.HashSet; import com.proving.grounds.match3things.R; import com.provinggrounds.match3things.game.Grid; import com.provinggrounds.match3things.game.MatchingSet; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.ArrayAdapter; import android.widget.GridView; public class GameActivity extends Activity { private static final int defaultNumBlockTypes = 6; private static final int defaultGridWidth = 4; private static final int defaultGridHeight = 4; Grid currentGameGrid; GridView gameGridView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game); // Show the Up button in the action bar. setupActionBar(); Intent callingIntent = getIntent(); int gridHeight = callingIntent.getIntExtra(IntentExtraReferences.HEIGHT, defaultGridHeight); int gridWidth = callingIntent.getIntExtra(IntentExtraReferences.WIDTH, defaultGridWidth); int gridNumBlockTypes = callingIntent.getIntExtra(IntentExtraReferences.NUMBLOCKTYPES, defaultNumBlockTypes); currentGameGrid = Grid.createGrid(gridWidth, gridHeight, gridNumBlockTypes); setGridViewProperties(currentGameGrid); } private void setGridViewProperties(Grid gameGrid) { GridView gameGridView = (GridView)findViewById(R.id.gameGrid); gameGridView.setNumColumns(gameGrid.getWidth()); ArrayAdapter<Integer> gridAdapter = new ArrayAdapter<Integer>(this, R.layout.grid_element_text_view, gameGrid.getGameGrid()); gameGridView.setAdapter(gridAdapter); } /** * Set up the {@link android.app.ActionBar}. */ private void setupActionBar() { getActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.game, menu); return true; } public void findMatchesInGrid(View showMatchesButton) { //disable "Show matches" button to prevent extra unnecessary calls showMatchesButton.setClickable(false); Collection<MatchingSet> matchingSets = currentGameGrid.findMatches(); //mark blocks deleted currentGameGrid.markMatchingBlocksDeleted(matchingSets); //generate match set string Collection<String> matchSetStrings = generateMatchSetStrings(matchingSets); //log match set information to logcat for(String matchSet : matchSetStrings) { Log.i("Matchset information", matchSet); } /* * display match information * 1. Show fragment * 2. Show match information in fragment's TextView */ //getFragmentManager().beginTransaction().add(R.id.matchingSetDisplay, new MatchingSetInfoDisplayFragment()).commit(); } /** * Returns a collection of strings that represent the matching sets passed in. * The collection of strings will not necessarily be in the same order as the * collection of matching sets passed in. * * @param matchingSets The collection of matching sets for which string representations need to be generated * @return The collection of strings representing the matching sets passed in * @see MatchingSet */ private static Collection<String> generateMatchSetStrings(Collection<MatchingSet> matchingSets) { Collection<String> matchSetStrings = new HashSet<String>(); for(MatchingSet ms : matchingSets) { matchSetStrings.add(ms.toString()); } return matchSetStrings; } }
src/com/provinggrounds/match3things/activity/GameActivity.java
package com.provinggrounds.match3things.activity; import java.util.Collection; import java.util.HashSet; import com.proving.grounds.match3things.R; import com.provinggrounds.match3things.game.Grid; import com.provinggrounds.match3things.game.MatchingSet; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.ArrayAdapter; import android.widget.GridView; public class GameActivity extends Activity { private static final int defaultNumBlockTypes = 6; private static final int defaultGridWidth = 4; private static final int defaultGridHeight = 4; Grid currentGameGrid; GridView gameGridView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game); // Show the Up button in the action bar. setupActionBar(); Intent callingIntent = getIntent(); int gridHeight = callingIntent.getIntExtra(IntentExtraReferences.HEIGHT, defaultGridHeight); int gridWidth = callingIntent.getIntExtra(IntentExtraReferences.WIDTH, defaultGridWidth); int gridNumBlockTypes = callingIntent.getIntExtra(IntentExtraReferences.NUMBLOCKTYPES, defaultNumBlockTypes); currentGameGrid = Grid.createGrid(gridWidth, gridHeight, gridNumBlockTypes); setGridViewProperties(currentGameGrid); } private void setGridViewProperties(Grid gameGrid) { GridView gameGridView = (GridView)findViewById(R.id.gameGrid); gameGridView.setNumColumns(gameGrid.getWidth()); ArrayAdapter<Integer> gridAdapter = new ArrayAdapter<Integer>(this, R.layout.grid_element_text_view, gameGrid.getGameGrid()); gameGridView.setAdapter(gridAdapter); } /** * Set up the {@link android.app.ActionBar}. */ private void setupActionBar() { getActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.game, menu); return true; } public void findMatchesInGrid(View showMatchesButton) { //disable "Show matches" button to prevent extra unnecessary calls showMatchesButton.setClickable(false); Collection<MatchingSet> matchingSets = currentGameGrid.findMatches(); //mark blocks deleted //generate match set string Collection<String> matchSetStrings = generateMatchSetStrings(matchingSets); //log match set information to logcat for(String matchSet : matchSetStrings) { Log.i("Matchset information", matchSet); } /* * display match information * 1. Show fragment * 2. Show match information in fragment's TextView */ //getFragmentManager().beginTransaction().add(R.id.matchingSetDisplay, new MatchingSetInfoDisplayFragment()).commit(); } /** * Returns a collection of strings that represent the matching sets passed in. * The collection of strings will not necessarily be in the same order as the * collection of matching sets passed in. * * @param matchingSets The collection of matching sets for which string representations need to be generated * @return The collection of strings representing the matching sets passed in * @see MatchingSet */ private static Collection<String> generateMatchSetStrings(Collection<MatchingSet> matchingSets) { Collection<String> matchSetStrings = new HashSet<String>(); for(MatchingSet ms : matchingSets) { matchSetStrings.add(ms.toString()); } return matchSetStrings; } }
GameActivity.findMatches: Use Grid.markMatchingBlocksDeleted
src/com/provinggrounds/match3things/activity/GameActivity.java
GameActivity.findMatches: Use Grid.markMatchingBlocksDeleted
<ide><path>rc/com/provinggrounds/match3things/activity/GameActivity.java <ide> showMatchesButton.setClickable(false); <ide> Collection<MatchingSet> matchingSets = currentGameGrid.findMatches(); <ide> //mark blocks deleted <add> currentGameGrid.markMatchingBlocksDeleted(matchingSets); <ide> //generate match set string <ide> Collection<String> matchSetStrings = generateMatchSetStrings(matchingSets); <ide> //log match set information to logcat
JavaScript
mit
a4ca5120ea6f5b67c64f6dd65cc2e68940d64756
0
cowboyhackr/bleno,cowboyhackr/bleno,cowboyhackr/bleno
var util = require('util'), os = require('os'), PythonShell = require('python-shell'), exec = require('child_process').exec, bleno = require('bleno'), gpio = require("pi-gpio"), Descriptor = bleno.Descriptor, Characteristic = bleno.Characteristic; var BatteryLevelCharacteristic = function() { BatteryLevelCharacteristic.super_.call(this, { uuid: '2A19', properties: ['read', 'write', 'notify'], descriptors: [ new Descriptor({ uuid: '2901', value: 'Battery level between 0 and 100 percent' }), new Descriptor({ uuid: '2904', value: new Buffer([0x04, 0x01, 0x27, 0xAD, 0x01, 0x00, 0x00 ]) // maybe 12 0xC unsigned 8 bit }) ] }); }; util.inherits(BatteryLevelCharacteristic, Characteristic); BatteryLevelCharacteristic.prototype.onReadRequest = function(offset, callback) { console.log("in read"); if (os.platform() === 'darwin') { exec('pmset -g batt', function (error, stdout, stderr) { var data = stdout.toString(); // data - 'Now drawing from \'Battery Power\'\n -InternalBattery-0\t95%; discharging; 4:11 remaining\n' var percent = data.split('\t')[1].split(';')[0]; console.log(percent); percent = parseInt(percent, 10); callback(this.RESULT_SUCCESS, new Buffer([percent])); }); } else { // return hardcoded value console.log("reading...") callback(this.RESULT_SUCCESS, new Buffer([98])); } }; BatteryLevelCharacteristic.prototype.onWriteRequest = function(data, offset, withoutResponse, callback) { //console.log("in write"); if (offset) { //console.log("in write - offset"); callback(this.RESULT_ATTR_NOT_LONG); } //else if (data.length !== 1) { // console.log("data length !== 1"); //console.log(JSON.stringify(data)); //callback(this.RESULT_INVALID_ATTRIBUTE_LENGTH); //} else { // console.log(JSON.stringify(data)); // console.log('processing write request'); // var receivedData = data.readUInt8(0); // console.log(typeof data); // console.log(data.toString('ascii')); // console.log(receivedData); // console.log(typeof receivedData); var command = data.toString('ascii'); //console.log('command'); console.log(command); if(command === "0"){ console.log("stop"); // print "Now stop" // GPIO.output(Motor1E,GPIO.LOW) gpio.open(22, "output", function(err) { if(err){ console.log(err); } // Open pin 22 for output gpio.write(22, 0, function() { // Set pin 22 low (0) console.log("set pin 22 low"); //gpio.close(22); // Close pin 22 }); }); } else if(command === "1"){ console.log("command left"); // var options = { // args: ['value1', 'value2', 'value3'] // }; console.log("1.0"); PythonShell.defaultOptions = { scriptPath: './gpiopython' }; console.log("1.1"); var pyshell = new PythonShell('pwm.py', { mode: 'text' }); console.log("1.2"); var output = ''; pyshell.stdout.on('data', function (data) { output += ''+data; console.log(output); }); console.log("1.3"); // pyshell.send('right').send('left').end(function (err) { // if (err) return console.log(err); // console.log(output); // console.log("here"); // }); console.log("1.4"); pyshell.send('left').end(function (err) { if (err) return console.log(err); console.log(output); }); // pythonShell.run('pwm.py', options, function (err, results) { // if (err) throw err; // // results is an array consisting of messages collected during execution // console.log('results: %j', results); // }); }else if(command === "2"){ console.log("command right"); console.log("1.0"); PythonShell.defaultOptions = { scriptPath: './gpiopython' }; var pyshell = new PythonShell('pwm.py', { mode: 'text' }); var output = ''; pyshell.stdout.on('data', function (data) { output += ''+data; console.log(output); }); pyshell.send('right').end(function (err) { if (err) return console.log(err); console.log(output); }); } else if(command === "3"){ console.log("forward"); gpio.open(16, "output", function(err) { if(err){ console.log(err); } // Open pin 16 for output gpio.write(16, 0, function() { // Set pin 16 high (1) console.log("set pin 16 low"); //gpio.close(16); // Close pin 16 //18 gpio.open(18, "output", function(err) { if(err){ console.log(err); } // Open pin 18 for output gpio.write(18, 1, function() { // Set pin 18 low (0) console.log("set pin 18 high"); //gpio.close(18); // Close pin 18 gpio.open(22, "output", function(err) { if(err){ console.log(err); } // Open pin 22 for output gpio.write(22, 1, function() { // Set pin 22 high (1) console.log("set pin 22 high"); //gpio.close(22); // Close pin 22 }); }); }); }); }); }); } else if(command === "4"){ console.log("back"); gpio.open(16, "output", function(err) { if(err){ console.log(err); } // Open pin 16 for output gpio.write(16, 1, function() { // Set pin 16 high (1) console.log("set pin 16 high"); //gpio.close(16); // Close pin 16 //18 gpio.open(18, "output", function(err) { if(err){ console.log(err); } // Open pin 18 for output gpio.write(18, 0, function() { // Set pin 18 low (0) console.log("set pin 18 low"); //gpio.close(18); // Close pin 18 gpio.open(22, "output", function(err) { if(err){ console.log(err); } // Open pin 22 for output gpio.write(22, 1, function() { // Set pin 22 high (1) console.log("set pin 22 high"); //gpio.close(22); // Close pin 22 }); }); }); }); }); }); } } callback(this.RESULT_SUCCESS); }; function setMotorDirection(direction) { console.log('Setting: ' + direction); var pin16 = 0; var pin18 = 0; var pin22 = 0; if(direction === 'forward'){ pin16 = 1; pin18 = 0; pin22 = 1; }else if (direction == 'reverse'){ pin16 = 1; pin18 = 0; pin22 = 1; } gpio.open(16, "output", function(err) { if(err){ console.log(err); } // Open pin 16 for output gpio.write(16, pin16, function() { // Set pin 16 high (1) console.log("set pin 16 " + pin16); //gpio.close(16); // Close pin 16 //18 gpio.open(18, "output", function(err) { if(err){ console.log(err); } // Open pin 18 for output gpio.write(18, pin18, function() { // Set pin 18 low (0) console.log("set pin 18 " + pin18); //gpio.close(18); // Close pin 18 gpio.open(22, "output", function(err) { if(err){ console.log(err); } // Open pin 22 for output gpio.write(22, pin22, function() { // Set pin 22 high (1) console.log("set pin 22 " + pin22); //gpio.close(22); // Close pin 22 }); }); }); }); }); }); } BatteryLevelCharacteristic.prototype.onNotify = function() { console.log('NotifyOnlyCharacteristic on notify'); }; module.exports = BatteryLevelCharacteristic;
examples/battery-service/battery-level-characteristic.js
var util = require('util'), os = require('os'), PythonShell = require('python-shell'), exec = require('child_process').exec, bleno = require('bleno'), gpio = require("pi-gpio"), Descriptor = bleno.Descriptor, Characteristic = bleno.Characteristic; var BatteryLevelCharacteristic = function() { BatteryLevelCharacteristic.super_.call(this, { uuid: '2A19', properties: ['read', 'write', 'notify'], descriptors: [ new Descriptor({ uuid: '2901', value: 'Battery level between 0 and 100 percent' }), new Descriptor({ uuid: '2904', value: new Buffer([0x04, 0x01, 0x27, 0xAD, 0x01, 0x00, 0x00 ]) // maybe 12 0xC unsigned 8 bit }) ] }); }; util.inherits(BatteryLevelCharacteristic, Characteristic); BatteryLevelCharacteristic.prototype.onReadRequest = function(offset, callback) { console.log("in read"); if (os.platform() === 'darwin') { exec('pmset -g batt', function (error, stdout, stderr) { var data = stdout.toString(); // data - 'Now drawing from \'Battery Power\'\n -InternalBattery-0\t95%; discharging; 4:11 remaining\n' var percent = data.split('\t')[1].split(';')[0]; console.log(percent); percent = parseInt(percent, 10); callback(this.RESULT_SUCCESS, new Buffer([percent])); }); } else { // return hardcoded value console.log("reading...") callback(this.RESULT_SUCCESS, new Buffer([98])); } }; BatteryLevelCharacteristic.prototype.onWriteRequest = function(data, offset, withoutResponse, callback) { //console.log("in write"); if (offset) { //console.log("in write - offset"); callback(this.RESULT_ATTR_NOT_LONG); } //else if (data.length !== 1) { // console.log("data length !== 1"); //console.log(JSON.stringify(data)); //callback(this.RESULT_INVALID_ATTRIBUTE_LENGTH); //} else { // console.log(JSON.stringify(data)); // console.log('processing write request'); // var receivedData = data.readUInt8(0); // console.log(typeof data); // console.log(data.toString('ascii')); // console.log(receivedData); // console.log(typeof receivedData); var command = data.toString('ascii'); //console.log('command'); console.log(command); if(command === "0"){ console.log("stop"); // print "Now stop" // GPIO.output(Motor1E,GPIO.LOW) gpio.open(22, "output", function(err) { if(err){ console.log(err); } // Open pin 22 for output gpio.write(22, 0, function() { // Set pin 22 low (0) console.log("set pin 22 low"); //gpio.close(22); // Close pin 22 }); }); } else if(command === "1"){ console.log("command left"); // var options = { // args: ['value1', 'value2', 'value3'] // }; console.log("1.0"); PythonShell.defaultOptions = { scriptPath: './gpiopython' }; console.log("1.1"); var pyshell = new PythonShell('pwm.py', { mode: 'text' }); console.log("1.2"); var output = ''; pyshell.stdout.on('data', function (data) { output += ''+data; console.log("here"); }); console.log("1.3"); // pyshell.send('right').send('left').end(function (err) { // if (err) return console.log(err); // console.log(output); // console.log("here"); // }); console.log("1.4"); pyshell.send('left').end(function (err) { if (err) return console.log(err); console.log(output); }); // pythonShell.run('pwm.py', options, function (err, results) { // if (err) throw err; // // results is an array consisting of messages collected during execution // console.log('results: %j', results); // }); }else if(command === "2"){ console.log("command right"); //test function pyshell.send('right').end(function (err) { if (err) return console.log(err); console.log(output); }); } else if(command === "3"){ console.log("forward"); gpio.open(16, "output", function(err) { if(err){ console.log(err); } // Open pin 16 for output gpio.write(16, 0, function() { // Set pin 16 high (1) console.log("set pin 16 low"); //gpio.close(16); // Close pin 16 //18 gpio.open(18, "output", function(err) { if(err){ console.log(err); } // Open pin 18 for output gpio.write(18, 1, function() { // Set pin 18 low (0) console.log("set pin 18 high"); //gpio.close(18); // Close pin 18 gpio.open(22, "output", function(err) { if(err){ console.log(err); } // Open pin 22 for output gpio.write(22, 1, function() { // Set pin 22 high (1) console.log("set pin 22 high"); //gpio.close(22); // Close pin 22 }); }); }); }); }); }); } else if(command === "4"){ console.log("back"); gpio.open(16, "output", function(err) { if(err){ console.log(err); } // Open pin 16 for output gpio.write(16, 1, function() { // Set pin 16 high (1) console.log("set pin 16 high"); //gpio.close(16); // Close pin 16 //18 gpio.open(18, "output", function(err) { if(err){ console.log(err); } // Open pin 18 for output gpio.write(18, 0, function() { // Set pin 18 low (0) console.log("set pin 18 low"); //gpio.close(18); // Close pin 18 gpio.open(22, "output", function(err) { if(err){ console.log(err); } // Open pin 22 for output gpio.write(22, 1, function() { // Set pin 22 high (1) console.log("set pin 22 high"); //gpio.close(22); // Close pin 22 }); }); }); }); }); }); } } callback(this.RESULT_SUCCESS); }; function setMotorDirection(direction) { console.log('Setting: ' + direction); var pin16 = 0; var pin18 = 0; var pin22 = 0; if(direction === 'forward'){ pin16 = 1; pin18 = 0; pin22 = 1; }else if (direction == 'reverse'){ pin16 = 1; pin18 = 0; pin22 = 1; } gpio.open(16, "output", function(err) { if(err){ console.log(err); } // Open pin 16 for output gpio.write(16, pin16, function() { // Set pin 16 high (1) console.log("set pin 16 " + pin16); //gpio.close(16); // Close pin 16 //18 gpio.open(18, "output", function(err) { if(err){ console.log(err); } // Open pin 18 for output gpio.write(18, pin18, function() { // Set pin 18 low (0) console.log("set pin 18 " + pin18); //gpio.close(18); // Close pin 18 gpio.open(22, "output", function(err) { if(err){ console.log(err); } // Open pin 22 for output gpio.write(22, pin22, function() { // Set pin 22 high (1) console.log("set pin 22 " + pin22); //gpio.close(22); // Close pin 22 }); }); }); }); }); }); } BatteryLevelCharacteristic.prototype.onNotify = function() { console.log('NotifyOnlyCharacteristic on notify'); }; module.exports = BatteryLevelCharacteristic;
still wiring python node.js
examples/battery-service/battery-level-characteristic.js
still wiring python node.js
<ide><path>xamples/battery-service/battery-level-characteristic.js <ide> var output = ''; <ide> pyshell.stdout.on('data', function (data) { <ide> output += ''+data; <del> console.log("here"); <add> console.log(output); <ide> }); <ide> console.log("1.3"); <ide> // pyshell.send('right').send('left').end(function (err) { <ide> <ide> }else if(command === "2"){ <ide> console.log("command right"); <del> //test function <add> <add> console.log("1.0"); <add> PythonShell.defaultOptions = { <add> scriptPath: './gpiopython' <add> }; <add> <add> var pyshell = new PythonShell('pwm.py', { <add> mode: 'text' <add> }); <add> <add> var output = ''; <add> pyshell.stdout.on('data', function (data) { <add> output += ''+data; <add> console.log(output); <add> }); <add> <ide> pyshell.send('right').end(function (err) { <ide> if (err) return console.log(err); <ide> console.log(output);
Java
apache-2.0
0e52d21471f82368b1ad950e6e49916fc133c8b3
0
tourea/docker-java,ollie314/docker-java,rockzeng/docker-java,sabre1041/docker-java,tejksat/docker-java,292388900/docker-java,tejksat/docker-java,klesgidis/docker-java,tourea/docker-java,signalfx/docker-java,marcust/docker-java,jamesmarva/docker-java,DICE-UNC/docker-java,sabre1041/docker-java,gesellix/docker-java,magnayn/docker-java,carlossg/docker-java,tschoots/docker-java,rohitkadam19/docker-java,MarcoLotz/docker-java,docker-java/docker-java,camunda-ci/docker-java,DICE-UNC/docker-java,rockzeng/docker-java,ndeloof/docker-java,vjuranek/docker-java,llamahunter/docker-java,MarcoLotz/docker-java,292388900/docker-java,docker-java/docker-java,jamesmarva/docker-java,signalfx/docker-java,klesgidis/docker-java,gesellix/docker-java,metavige/docker-java,vjuranek/docker-java,carlossg/docker-java,magnayn/docker-java,ndeloof/docker-java,camunda-ci/docker-java,ollie314/docker-java,marcust/docker-java,rohitkadam19/docker-java,metavige/docker-java,tschoots/docker-java,llamahunter/docker-java
package com.github.dockerjava.core.command; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.model.Frame; import com.github.dockerjava.api.model.StreamType; import com.github.dockerjava.core.DockerClientBuilder; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.io.IOException; import java.io.InputStream; import static org.testng.Assert.assertEquals; import static org.testng.AssertJUnit.assertNull; @Test(groups = "integration") public class FrameReaderITest { private DockerClient dockerClient; private DockerfileFixture dockerfileFixture; @BeforeTest public void beforeTest() throws Exception { dockerClient = DockerClientBuilder.getInstance().build(); dockerfileFixture = new DockerfileFixture(dockerClient, "frameReaderDockerfile"); dockerfileFixture.open(); } @AfterTest public void deleteDockerContainerImage() throws Exception { dockerfileFixture.close(); dockerClient.close(); } @Test public void canCloseFrameReaderAndReadExpectedLines() throws Exception { try (FrameReader reader = new FrameReader(getLoggerStream())) { assertEquals(reader.readFrame(), new Frame(StreamType.STDOUT, "to stdout\n".getBytes())); assertEquals(reader.readFrame(), new Frame(StreamType.STDERR, "to stderr\n".getBytes())); assertNull(reader.readFrame()); } } private InputStream getLoggerStream() { return dockerClient .logContainerCmd(dockerfileFixture.getContainerId()) .withStdOut() .withStdErr() .withTailAll() .withTail(10) .withFollowStream() .exec(); } @Test public void canLogInOneThreadAndExecuteCommandsInAnother() throws Exception { Thread thread = new Thread(new Runnable() { @Override public void run() { try { try (FrameReader reader = new FrameReader(getLoggerStream())) { //noinspection StatementWithEmptyBody while (reader.readFrame() != null) { // nop } } } catch (IOException e) { throw new RuntimeException(e); } } }); thread.start(); try (DockerfileFixture busyboxDockerfile = new DockerfileFixture(dockerClient, "busyboxDockerfile")) { busyboxDockerfile.open(); } thread.join(); } }
src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java
package com.github.dockerjava.core.command; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.model.Frame; import com.github.dockerjava.api.model.StreamType; import com.github.dockerjava.core.DockerClientBuilder; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.io.IOException; import java.io.InputStream; import static org.testng.Assert.assertEquals; import static org.testng.AssertJUnit.assertNull; @Test(groups = "integration") public class FrameReaderITest { private DockerClient dockerClient; private DockerfileFixture dockerfileFixture; @BeforeTest public void beforeTest() throws Exception { dockerClient = DockerClientBuilder.getInstance().build(); dockerfileFixture = new DockerfileFixture(dockerClient, "frameReaderDockerfile"); dockerfileFixture.open(); } @AfterTest public void deleteDockerContainerImage() throws Exception { dockerfileFixture.close(); dockerClient.close(); } @Test public void canCloseFrameReaderAndReadExpectedLines() throws Exception { try (FrameReader reader = new FrameReader(getLoggerStream())) { assertEquals(reader.readFrame(), new Frame(StreamType.STDOUT, String.format("to stdout%n").getBytes())); assertEquals(reader.readFrame(), new Frame(StreamType.STDERR, String.format("to stderr%n").getBytes())); assertNull(reader.readFrame()); } } private InputStream getLoggerStream() { return dockerClient .logContainerCmd(dockerfileFixture.getContainerId()) .withStdOut() .withStdErr() .withTailAll() .withTail(10) .withFollowStream() .exec(); } @Test public void canLogInOneThreadAndExecuteCommandsInAnother() throws Exception { Thread thread = new Thread(new Runnable() { @Override public void run() { try { try (FrameReader reader = new FrameReader(getLoggerStream())) { //noinspection StatementWithEmptyBody while (reader.readFrame() != null) { // nop } } } catch (IOException e) { throw new RuntimeException(e); } } }); thread.start(); try (DockerfileFixture busyboxDockerfile = new DockerfileFixture(dockerClient, "busyboxDockerfile")) { busyboxDockerfile.open(); } thread.join(); } }
Fix canCloseFrameReaderAndReadExpectedLines test on Windows
src/test/java/com/github/dockerjava/core/command/FrameReaderITest.java
Fix canCloseFrameReaderAndReadExpectedLines test on Windows
<ide><path>rc/test/java/com/github/dockerjava/core/command/FrameReaderITest.java <ide> public void canCloseFrameReaderAndReadExpectedLines() throws Exception { <ide> <ide> try (FrameReader reader = new FrameReader(getLoggerStream())) { <del> assertEquals(reader.readFrame(), new Frame(StreamType.STDOUT, String.format("to stdout%n").getBytes())); <del> assertEquals(reader.readFrame(), new Frame(StreamType.STDERR, String.format("to stderr%n").getBytes())); <add> assertEquals(reader.readFrame(), new Frame(StreamType.STDOUT, "to stdout\n".getBytes())); <add> assertEquals(reader.readFrame(), new Frame(StreamType.STDERR, "to stderr\n".getBytes())); <ide> assertNull(reader.readFrame()); <ide> } <ide> }
JavaScript
mit
824790dff3cf1e515c302537a3b74f946022fd39
0
exponentjs/xdl,exponentjs/xdl,exponentjs/xdl
// Copyright 2015-present 650 Industries. All rights reserved. 'use strict'; import 'instapromise'; import fs from 'fs'; import path from 'path'; import { getManifestAsync, saveUrlToPathAsync, spawnAsync, spawnAsyncThrowError, modifyIOSPropertyListAsync, cleanIOSPropertyListBackupAsync, configureIOSIconsAsync, } from './ExponentTools'; function validateConfigArguments(manifest, cmdArgs, configFilePath) { if (!configFilePath) { throw new Error('No path to config files provided'); } let bundleIdentifierFromManifest = (manifest.ios) ? manifest.ios.bundleIdentifier : null; if (!bundleIdentifierFromManifest && !cmdArgs.bundleIdentifier) { throw new Error('No bundle identifier found in either the manifest or argv'); } if (!manifest.name) { throw new Error('Manifest does not have a name'); } if (!cmdArgs.privateConfigFile) { console.warn('Warning: No config file specified.'); } return true; } /** * Writes Fabric config to private-shell-app-config.json if necessary. Used by * generate-dynamic-macros when building. */ async function configureShellAppSecretsAsync(args, iosDir) { if (!args.privateConfigFile) { return; } spawnAsyncThrowError('/bin/cp', [args.privateConfigFile, path.join(iosDir, 'private-shell-app-config.json')]); } /** * Configure an iOS Info.plist for a standalone app given its exponent configuration. * @param configFilePath Path to Info.plist * @param manifest the app's manifest * @param privateConfig optional config with the app's private keys * @param bundleIdentifier optional bundle id if the manifest doesn't contain one already */ async function configureStandaloneIOSInfoPlistAsync(configFilePath, manifest, privateConfig = null, bundleIdentifier = null) { let result = await modifyIOSPropertyListAsync(configFilePath, 'Info', (config) => { // bundle id config.CFBundleIdentifier = (manifest.ios && manifest.ios.bundleIdentifier) ? manifest.ios.bundleIdentifier : bundleIdentifier; if (!config.CFBundleIdentifier) { throw new Error(`Cannot configure an iOS app with no bundle identifier.`); } // app name config.CFBundleName = manifest.name; // determine app linking schemes let linkingSchemes = (manifest.scheme) ? [manifest.scheme] : []; if (manifest.facebookScheme && manifest.facebookScheme.startsWith('fb')) { linkingSchemes.push(manifest.facebookScheme); } if (privateConfig && privateConfig.googleSignIn && privateConfig.googleSignIn.reservedClientId) { linkingSchemes.push(privateConfig.googleSignIn.reservedClientId); } // remove exp scheme, add app scheme(s) config.CFBundleURLTypes = [{ CFBundleURLSchemes: linkingSchemes, }, { // Add the generic oauth redirect, it's important that it has the name // 'OAuthRedirect' so we can find it in app code. CFBundleURLName: 'OAuthRedirect', CFBundleURLSchemes: [config.CFBundleIdentifier], }]; // set ITSAppUsesNonExemptEncryption to let people skip manually // entering it in iTunes Connect if (privateConfig && privateConfig.hasOwnProperty('usesNonExemptEncryption') && privateConfig.usesNonExemptEncryption === false) { config.ITSAppUsesNonExemptEncryption = false; } // permanently save the exponent client version at time of configuration config.EXClientVersion = config.CFBundleVersion; // use version from manifest let version = (manifest.version) ? manifest.version : '0.0.0'; let buildNumber = (manifest.ios && manifest.ios.buildNumber) ? manifest.ios.buildNumber : '1'; config.CFBundleShortVersionString = version; config.CFBundleVersion = buildNumber; let internalKeys; try { internalKeys = require('../__internal__/keys.json'); // universe/exponent/tools } catch (e) { try { internalKeys = require('../template-files/keys.json'); // public/exponent/tools } catch (e) { // TODO (jesse): figure out a better place to put this internalKeys = require('../../client-keys.json'); // xdl } } const defaultFabricKey = internalKeys.FABRIC_API_KEY; config.Fabric = { APIKey: (privateConfig && privateConfig.fabric && privateConfig.fabric.apiKey) || defaultFabricKey, Kits: [{ KitInfo: {}, KitName: 'Crashlytics', }], }; let permissionsAppName = (manifest.name) ? manifest.name : 'this app'; for (let key in config) { if (config.hasOwnProperty(key) && key.indexOf('UsageDescription') !== -1) { config[key] = config[key].replace('Exponent experiences', permissionsAppName); } } // 1 is iPhone, 2 is iPad config.UIDeviceFamily = (manifest.ios && manifest.ios.supportsTablet) ? [1, 2] : [1]; return config; }); return result; } /** * Configure EXShell.plist for a standalone app given its exponent configuration. * @param configFilePath Path to Info.plist * @param manifest the app's manifest * @param manifestUrl the app's manifest url */ async function configureStandaloneIOSShellPlistAsync(configFilePath, manifest, manifestUrl) { await modifyIOSPropertyListAsync(configFilePath, 'EXShell', (shellConfig) => { shellConfig.isShell = true; shellConfig.manifestUrl = manifestUrl; if (manifest.ios && manifest.ios.permissions) { shellConfig.permissions = manifest.ios.permissions; } console.log('Using shell config:', shellConfig); return shellConfig; }); } async function configurePropertyListsAsync(manifest, args, configFilePath) { // make sure we have all the required info validateConfigArguments(manifest, args, configFilePath); console.log(`Modifying config files under ${configFilePath}...`); let { privateConfigFile, } = args; let privateConfig; if (privateConfigFile) { let privateConfigContents = await fs.promise.readFile(privateConfigFile, 'utf8'); privateConfig = JSON.parse(privateConfigContents); } // generate new shell config await configureStandaloneIOSShellPlistAsync(configFilePath, manifest, args.url); // Info.plist changes specific to turtle await modifyIOSPropertyListAsync(configFilePath, 'Info', (config) => { // use shell-specific launch screen config.UILaunchStoryboardName = 'LaunchScreenShell'; return config; }); // common standalone Info.plist config changes await configureStandaloneIOSInfoPlistAsync(configFilePath, manifest, privateConfig, args.bundleIdentifier); } /** * Write the manifest and JS bundle to the iOS NSBundle. */ async function preloadManifestAndBundleAsync(manifest, args, configFilePath) { let bundleUrl = manifest.bundleUrl; await fs.promise.writeFile(`${configFilePath}/shell-app-manifest.json`, JSON.stringify(manifest)); await saveUrlToPathAsync(bundleUrl, `${configFilePath}/shell-app.bundle`); return; } async function cleanPropertyListBackupsAsync(configFilePath, restoreOriginals) { console.log('Cleaning up...'); await cleanIOSPropertyListBackupAsync(configFilePath, 'EXShell', restoreOriginals); await cleanIOSPropertyListBackupAsync(configFilePath, 'Info', restoreOriginals); } /** * Build the iOS binary from source. * @return the path to the resulting .app */ async function buildAsync(args, iOSRootPath, relativeBuildDestination) { let { action, configuration, verbose, type } = args; let buildCmd, buildDest, pathToApp; if (type === 'simulator') { buildDest = `${iOSRootPath}/${relativeBuildDestination}-simulator`; buildCmd = `xcodebuild -workspace Exponent.xcworkspace -scheme Exponent -sdk iphonesimulator -configuration ${configuration} -arch i386 -derivedDataPath ${buildDest} CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO SKIP_INSTALL=NO | xcpretty`; pathToApp = `${buildDest}/Build/Products/${configuration}-iphonesimulator/Exponent.app`; } else if (type === 'archive') { buildDest = `${iOSRootPath}/${relativeBuildDestination}-archive`; buildCmd = `xcodebuild -workspace Exponent.xcworkspace -scheme Exponent archive -configuration ${configuration} -derivedDataPath ${buildDest} -archivePath ${buildDest}/Exponent.xcarchive CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO SKIP_INSTALL=NO | xcpretty`; pathToApp = `${buildDest}/Exponent.xcarchive/Products/Applications/Exponent.app`; } if (buildCmd) { console.log(`Building shell app under ${iOSRootPath}/${relativeBuildDestination}`); console.log(` (action: ${action}, configuration: ${configuration})...`); console.log(buildCmd); await spawnAsyncThrowError(buildCmd, null, { stdio: ( (verbose) ? 'inherit' : ['ignore', 'ignore', 'inherit'] // only stderr ), cwd: iOSRootPath, shell: true, }); let artifactLocation = `${iOSRootPath}/../shellAppBase-builds/${type}/${configuration}/`; await spawnAsyncThrowError('/bin/rm', ['-rf', artifactLocation]); await spawnAsyncThrowError('/bin/mkdir', ['-p', artifactLocation]); if (type === 'archive') { await spawnAsyncThrowError('/bin/cp', ['-R', `${buildDest}/Exponent.xcarchive`, artifactLocation]); } else if (type === 'simulator') { await spawnAsyncThrowError('/bin/cp', ['-R', pathToApp, artifactLocation]); } } return pathToApp; } function validateArgs(args) { args.type = args.type || 'archive'; args.configuration = args.configuration || 'Release'; args.verbose = args.verbose || false; switch (args.type) { case 'simulator': { if (args.configuration !== 'Debug' && args.configuration !== 'Release') { throw new Error(`Unsupported build configuration ${args.configuration}`); } break; } case 'archive': { if (args.configuration !== 'Release') { throw new Error('Release is the only supported configuration when archiving'); } break; } default: { throw new Error(`Unsupported build type ${args.type}`); } } switch (args.action) { case 'configure': { if (!args.url) { throw new Error('Must run with `--url MANIFEST_URL`'); } if (!args.sdkVersion) { throw new Error('Must run with `--sdkVersion SDK_VERSION`'); } if (!args.archivePath) { throw new Error('Need to provide --archivePath <path to existing archive for configuration>'); } break; } case 'build': { break; } default: { throw new Error(`Unsupported build action ${args.action}`); } } return args; } /** * @param url manifest url for shell experience * @param sdkVersion sdk to use when requesting the manifest * @param action * build - build a binary * configure - don't build anything, just configure the files in an existing .app bundle * @param type simulator or archive, for action == build * @param configuration Debug or Release, for type == simulator (default Release) * @param archivePath path to existing bundle, for action == configure * @param privateConfigFile path to a private config file containing, e.g., private api keys * @param bundleIdentifier iOS CFBundleIdentifier to use in the bundle config * @param verbose show all xcodebuild output (default false) */ async function createIOSShellAppAsync(args) { let configFilePath; args = validateArgs(args); if (args.action !== 'configure') { // build the app before configuring await configureShellAppSecretsAsync(args, '../ios'); configFilePath = await buildAsync(args, '../ios', '../shellAppBase'); } else { let { url, sdkVersion, output, type, } = args; // fetch manifest let manifest = await getManifestAsync(url, { 'Exponent-SDK-Version': sdkVersion, 'Exponent-Platform': 'ios', }); // action === 'configure' configFilePath = args.archivePath; // just configure, don't build anything await configurePropertyListsAsync(manifest, args, configFilePath); await configureIOSIconsAsync(manifest, configFilePath); await preloadManifestAndBundleAsync(manifest, args, configFilePath); await cleanPropertyListBackupsAsync(configFilePath, false); let archiveName = manifest.name.replace(/\s+/g, ''); if (type === 'simulator') { await spawnAsync(`mv Exponent.app ${archiveName}.app && tar cvf ${output} ${archiveName}.app`, null, { stdio: 'inherit', cwd: `${configFilePath}/..`, shell: true, }); } else if (type === 'archive') { await spawnAsync('/bin/mv', ['Exponent.xcarchive', output], { stdio: 'inherit', cwd: `${configFilePath}/../../../..`, }); } } return; } export { createIOSShellAppAsync, configureStandaloneIOSInfoPlistAsync, configureStandaloneIOSShellPlistAsync, };
src/detach/IosShellApp.js
// Copyright 2015-present 650 Industries. All rights reserved. 'use strict'; import 'instapromise'; import fs from 'fs'; import path from 'path'; import { getManifestAsync, saveUrlToPathAsync, spawnAsync, spawnAsyncThrowError, modifyIOSPropertyListAsync, cleanIOSPropertyListBackupAsync, configureIOSIconsAsync, } from './ExponentTools'; function validateConfigArguments(manifest, cmdArgs, configFilePath) { if (!configFilePath) { throw new Error('No path to config files provided'); } let bundleIdentifierFromManifest = (manifest.ios) ? manifest.ios.bundleIdentifier : null; if (!bundleIdentifierFromManifest && !cmdArgs.bundleIdentifier) { throw new Error('No bundle identifier found in either the manifest or argv'); } if (!manifest.name) { throw new Error('Manifest does not have a name'); } if (!cmdArgs.privateConfigFile) { console.warn('Warning: No config file specified.'); } return true; } /** * Writes Fabric config to private-shell-app-config.json if necessary. Used by * generate-dynamic-macros when building. */ async function configureShellAppSecretsAsync(args, iosDir) { if (!args.privateConfigFile) { return; } spawnAsyncThrowError('/bin/cp', [args.privateConfigFile, path.join(iosDir, 'private-shell-app-config.json')]); } /** * Configure an iOS Info.plist for a standalone app given its exponent configuration. * @param configFilePath Path to Info.plist * @param manifest the app's manifest * @param privateConfig optional config with the app's private keys * @param bundleIdentifier optional bundle id if the manifest doesn't contain one already */ async function configureStandaloneIOSInfoPlistAsync(configFilePath, manifest, privateConfig = null, bundleIdentifier = null) { let result = await modifyIOSPropertyListAsync(configFilePath, 'Info', (config) => { // bundle id config.CFBundleIdentifier = (manifest.ios && manifest.ios.bundleIdentifier) ? manifest.ios.bundleIdentifier : bundleIdentifier; if (!config.CFBundleIdentifier) { throw new Error(`Cannot configure an iOS app with no bundle identifier.`); } // app name config.CFBundleName = manifest.name; // determine app linking schemes let linkingSchemes = (manifest.scheme) ? [manifest.scheme] : []; if (manifest.facebookScheme && manifest.facebookScheme.startsWith('fb')) { linkingSchemes.push(manifest.facebookScheme); } if (privateConfig && privateConfig.googleSignIn && privateConfig.googleSignIn.reservedClientId) { linkingSchemes.push(privateConfig.googleSignIn.reservedClientId); } // remove exp scheme, add app scheme(s) config.CFBundleURLTypes = [{ CFBundleURLSchemes: linkingSchemes, }, { // Add the generic oauth redirect, it's important that it has the name // 'OAuthRedirect' so we can find it in app code. CFBundleURLName: 'OAuthRedirect', CFBundleURLSchemes: [config.CFBundleIdentifier], }]; // permanently save the exponent client version at time of configuration config.EXClientVersion = config.CFBundleVersion; // use version from manifest let version = (manifest.version) ? manifest.version : '0.0.0'; let buildNumber = (manifest.ios && manifest.ios.buildNumber) ? manifest.ios.buildNumber : '1'; config.CFBundleShortVersionString = version; config.CFBundleVersion = buildNumber; let internalKeys; try { internalKeys = require('../__internal__/keys.json'); // universe/exponent/tools } catch (e) { try { internalKeys = require('../template-files/keys.json'); // public/exponent/tools } catch (e) { // TODO (jesse): figure out a better place to put this internalKeys = require('../../client-keys.json'); // xdl } } const defaultFabricKey = internalKeys.FABRIC_API_KEY; config.Fabric = { APIKey: (privateConfig && privateConfig.fabric && privateConfig.fabric.apiKey) || defaultFabricKey, Kits: [{ KitInfo: {}, KitName: 'Crashlytics', }], }; let permissionsAppName = (manifest.name) ? manifest.name : 'this app'; for (let key in config) { if (config.hasOwnProperty(key) && key.indexOf('UsageDescription') !== -1) { config[key] = config[key].replace('Exponent experiences', permissionsAppName); } } // 1 is iPhone, 2 is iPad config.UIDeviceFamily = (manifest.ios && manifest.ios.supportsTablet) ? [1, 2] : [1]; return config; }); return result; } /** * Configure EXShell.plist for a standalone app given its exponent configuration. * @param configFilePath Path to Info.plist * @param manifest the app's manifest * @param manifestUrl the app's manifest url */ async function configureStandaloneIOSShellPlistAsync(configFilePath, manifest, manifestUrl) { await modifyIOSPropertyListAsync(configFilePath, 'EXShell', (shellConfig) => { shellConfig.isShell = true; shellConfig.manifestUrl = manifestUrl; if (manifest.ios && manifest.ios.permissions) { shellConfig.permissions = manifest.ios.permissions; } console.log('Using shell config:', shellConfig); return shellConfig; }); } async function configurePropertyListsAsync(manifest, args, configFilePath) { // make sure we have all the required info validateConfigArguments(manifest, args, configFilePath); console.log(`Modifying config files under ${configFilePath}...`); let { privateConfigFile, } = args; let privateConfig; if (privateConfigFile) { let privateConfigContents = await fs.promise.readFile(privateConfigFile, 'utf8'); privateConfig = JSON.parse(privateConfigContents); } // generate new shell config await configureStandaloneIOSShellPlistAsync(configFilePath, manifest, args.url); // Info.plist changes specific to turtle await modifyIOSPropertyListAsync(configFilePath, 'Info', (config) => { // use shell-specific launch screen config.UILaunchStoryboardName = 'LaunchScreenShell'; return config; }); // common standalone Info.plist config changes await configureStandaloneIOSInfoPlistAsync(configFilePath, manifest, privateConfig, args.bundleIdentifier); } /** * Write the manifest and JS bundle to the iOS NSBundle. */ async function preloadManifestAndBundleAsync(manifest, args, configFilePath) { let bundleUrl = manifest.bundleUrl; await fs.promise.writeFile(`${configFilePath}/shell-app-manifest.json`, JSON.stringify(manifest)); await saveUrlToPathAsync(bundleUrl, `${configFilePath}/shell-app.bundle`); return; } async function cleanPropertyListBackupsAsync(configFilePath, restoreOriginals) { console.log('Cleaning up...'); await cleanIOSPropertyListBackupAsync(configFilePath, 'EXShell', restoreOriginals); await cleanIOSPropertyListBackupAsync(configFilePath, 'Info', restoreOriginals); } /** * Build the iOS binary from source. * @return the path to the resulting .app */ async function buildAsync(args, iOSRootPath, relativeBuildDestination) { let { action, configuration, verbose, type } = args; let buildCmd, buildDest, pathToApp; if (type === 'simulator') { buildDest = `${iOSRootPath}/${relativeBuildDestination}-simulator`; buildCmd = `xcodebuild -workspace Exponent.xcworkspace -scheme Exponent -sdk iphonesimulator -configuration ${configuration} -arch i386 -derivedDataPath ${buildDest} CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO SKIP_INSTALL=NO | xcpretty`; pathToApp = `${buildDest}/Build/Products/${configuration}-iphonesimulator/Exponent.app`; } else if (type === 'archive') { buildDest = `${iOSRootPath}/${relativeBuildDestination}-archive`; buildCmd = `xcodebuild -workspace Exponent.xcworkspace -scheme Exponent archive -configuration ${configuration} -derivedDataPath ${buildDest} -archivePath ${buildDest}/Exponent.xcarchive CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO SKIP_INSTALL=NO | xcpretty`; pathToApp = `${buildDest}/Exponent.xcarchive/Products/Applications/Exponent.app`; } if (buildCmd) { console.log(`Building shell app under ${iOSRootPath}/${relativeBuildDestination}`); console.log(` (action: ${action}, configuration: ${configuration})...`); console.log(buildCmd); await spawnAsyncThrowError(buildCmd, null, { stdio: ( (verbose) ? 'inherit' : ['ignore', 'ignore', 'inherit'] // only stderr ), cwd: iOSRootPath, shell: true, }); let artifactLocation = `${iOSRootPath}/../shellAppBase-builds/${type}/${configuration}/`; await spawnAsyncThrowError('/bin/rm', ['-rf', artifactLocation]); await spawnAsyncThrowError('/bin/mkdir', ['-p', artifactLocation]); if (type === 'archive') { await spawnAsyncThrowError('/bin/cp', ['-R', `${buildDest}/Exponent.xcarchive`, artifactLocation]); } else if (type === 'simulator') { await spawnAsyncThrowError('/bin/cp', ['-R', pathToApp, artifactLocation]); } } return pathToApp; } function validateArgs(args) { args.type = args.type || 'archive'; args.configuration = args.configuration || 'Release'; args.verbose = args.verbose || false; switch (args.type) { case 'simulator': { if (args.configuration !== 'Debug' && args.configuration !== 'Release') { throw new Error(`Unsupported build configuration ${args.configuration}`); } break; } case 'archive': { if (args.configuration !== 'Release') { throw new Error('Release is the only supported configuration when archiving'); } break; } default: { throw new Error(`Unsupported build type ${args.type}`); } } switch (args.action) { case 'configure': { if (!args.url) { throw new Error('Must run with `--url MANIFEST_URL`'); } if (!args.sdkVersion) { throw new Error('Must run with `--sdkVersion SDK_VERSION`'); } if (!args.archivePath) { throw new Error('Need to provide --archivePath <path to existing archive for configuration>'); } break; } case 'build': { break; } default: { throw new Error(`Unsupported build action ${args.action}`); } } return args; } /** * @param url manifest url for shell experience * @param sdkVersion sdk to use when requesting the manifest * @param action * build - build a binary * configure - don't build anything, just configure the files in an existing .app bundle * @param type simulator or archive, for action == build * @param configuration Debug or Release, for type == simulator (default Release) * @param archivePath path to existing bundle, for action == configure * @param privateConfigFile path to a private config file containing, e.g., private api keys * @param bundleIdentifier iOS CFBundleIdentifier to use in the bundle config * @param verbose show all xcodebuild output (default false) */ async function createIOSShellAppAsync(args) { let configFilePath; args = validateArgs(args); if (args.action !== 'configure') { // build the app before configuring await configureShellAppSecretsAsync(args, '../ios'); configFilePath = await buildAsync(args, '../ios', '../shellAppBase'); } else { let { url, sdkVersion, output, type, } = args; // fetch manifest let manifest = await getManifestAsync(url, { 'Exponent-SDK-Version': sdkVersion, 'Exponent-Platform': 'ios', }); // action === 'configure' configFilePath = args.archivePath; // just configure, don't build anything await configurePropertyListsAsync(manifest, args, configFilePath); await configureIOSIconsAsync(manifest, configFilePath); await preloadManifestAndBundleAsync(manifest, args, configFilePath); await cleanPropertyListBackupsAsync(configFilePath, false); let archiveName = manifest.name.replace(/\s+/g, ''); if (type === 'simulator') { await spawnAsync(`mv Exponent.app ${archiveName}.app && tar cvf ${output} ${archiveName}.app`, null, { stdio: 'inherit', cwd: `${configFilePath}/..`, shell: true, }); } else if (type === 'archive') { await spawnAsync('/bin/mv', ['Exponent.xcarchive', output], { stdio: 'inherit', cwd: `${configFilePath}/../../../..`, }); } } return; } export { createIOSShellAppAsync, configureStandaloneIOSInfoPlistAsync, configureStandaloneIOSShellPlistAsync, };
Add usesNonExemptEncryption key to exp.json - Enables developers to set ITSAppUsesNonExemptEncryption and skip manually selecting "No" each time when uploading to ITC. fbshipit-source-id: 3340fcf
src/detach/IosShellApp.js
Add usesNonExemptEncryption key to exp.json - Enables developers to set ITSAppUsesNonExemptEncryption and skip manually selecting "No" each time when uploading to ITC.
<ide><path>rc/detach/IosShellApp.js <ide> CFBundleURLName: 'OAuthRedirect', <ide> CFBundleURLSchemes: [config.CFBundleIdentifier], <ide> }]; <add> <add> // set ITSAppUsesNonExemptEncryption to let people skip manually <add> // entering it in iTunes Connect <add> if (privateConfig && <add> privateConfig.hasOwnProperty('usesNonExemptEncryption') && <add> privateConfig.usesNonExemptEncryption === false) { <add> config.ITSAppUsesNonExemptEncryption = false; <add> } <ide> <ide> // permanently save the exponent client version at time of configuration <ide> config.EXClientVersion = config.CFBundleVersion;
Java
agpl-3.0
27021a31684c71d512cb1771ebeafbc5c626b061
0
MarkehMe/FactionsPlus
package markehme.factionsplus.config; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.util.Scanner; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import com.massivecraft.factions.entity.Faction; import com.massivecraft.factions.entity.FactionColl; import com.massivecraft.factions.entity.FactionColls; import com.massivecraft.massivecore.ps.PS; import markehme.factionsplus.FactionsPlus; import markehme.factionsplus.Utilities; import markehme.factionsplus.MCore.FactionData; import markehme.factionsplus.MCore.FactionDataColls; /** * This entire class is related to migrating data from the old systems (0.6) to the new * systems used by FactionsPlus. This is the only class that ignores deprecation notices * as it is the only class that should be accessing OldConfig. * @author markhughes * */ @SuppressWarnings("deprecation") public class OldMigrate { /** * At the end of migration the config file moves to config.yml.migrated, so * if the old config exists then it hasn't been migrated. * @return */ public boolean shouldMigrate() { return(OldConfig.fileConfig.exists()); } private static void msg(String m) { FactionsPlus.tellConsole("[Migration] " + m); } /** * Migrates all the fData */ public void migrateDatabase() { // Load the old configuration OldConfig.init(); OldConfig.reload(); for(FactionColl fColl : FactionColls.get().getColls()) { for(String id : fColl.getIds()) { Faction faction = fColl.get(id); msg(""); msg("[Faction] " + faction.getName() + " (" + faction.getId() + ")"); msg("[Faction] Migration starting for this faction"); // ----- Create FactionData file ----- // FactionData fData = FactionDataColls.get().getForUniverse(faction.getUniverse()).get(faction.getId()); if(fData == null) { FactionDataColls.get().getForUniverse(faction.getUniverse()).create(faction.getId()); msg("[Faction] [FData] FactionData file created."); fData = FactionDataColls.get().getForUniverse(faction.getUniverse()).get(faction.getId()); } else { msg("[Faction] [FData] FactionData file already exists, moving on."); } if(!fData.attached()) { msg("[Faction] [FData] " + ChatColor.RED + "[WARN]" + ChatColor.RESET + " The FactionData file exists/was created.. however, it's not attached."); } // ----- Migrate Announcement ----- // File fileAnnouncementFile = new File(OldConfig.folderAnnouncements, faction.getId()); if(fileAnnouncementFile.exists()) { if(fileAnnouncementFile.canRead()) { try { fData.announcement = (Utilities.readFileAsString(fileAnnouncementFile)).trim(); msg("[Faction] [Announcement] Announcement Migrated: " + fData.announcement); } catch (Exception e) { msg("[Faction] [Announcement] " + ChatColor.RED + "[ERROR]" + ChatColor.RESET + " Could not read the data for this announcement in this Faction" ); e.printStackTrace(); } } else { msg("[Faction] [Announcement] " + ChatColor.RED + "[WARN]" + ChatColor.RESET + " Although the announcement file exists, we can't read it. Please check permissions." ); } } else { msg("[Faction] [Announcement] No announcement data to migrate, moving on."); } // ----- Migrate Jails ----- // File jailLocationFile = new File(OldConfig.folderJails, "loc." + faction.getId()); // Check for a jail location if(!jailLocationFile.exists()) { // If theres no jail location, then theres also no jailed players msg("[Faction] [Jail] No jail location set, moving on."); } else { try { // Read the old database information String locationData[] = Utilities.readFileAsString(jailLocationFile).split(":"); Location jailLocation = new Location(Bukkit.getWorld(locationData[4]), Double.valueOf(locationData[0]), Double.valueOf(locationData[1]), Double.valueOf(locationData[2])); // Create the PS version PS psJailLocation = PS.valueOf(jailLocation); // Store the location in our fData object fData.jailLocation = psJailLocation; msg("[Faction] [Jail] Jail location found and moved to x: " + locationData[0]+", y: " + locationData[1] + ", z: " + locationData[2] + ", in world: " + locationData[4]); } catch(Exception e) { msg("[Faction] [Jail] " + ChatColor.RED + "[ERROR]" + ChatColor.RESET + " Could not read the data for the jail location in this Faction" ); e.printStackTrace(); } msg("[Faction] [Jailed Players] Reset!"); } // ----- Migrate Warps ----- // File warpsFile = new File(OldConfig.folderWarps, faction.getId()); if(!warpsFile.exists()) { msg("[Faction] [Warps] No warps have been found for this faction, moving on."); } else { FileInputStream fis = null; try { fis = new FileInputStream(new File(OldConfig.folderWarps, faction.getId())); int b = fis.read(); if(b == -1) { msg("[Faction] [Warps] No warps have been found for this faction, moving on."); fis.close(); } } catch(Exception e) { msg("[Faction] [Warps] " + ChatColor.RED + "[ERROR]" + ChatColor.RESET + " Could not read the data for the warps in this Faction"); fis = null; e.printStackTrace(); } finally { if(null != fis) { try { fis.close(); } catch(Exception e) { e.printStackTrace(); } } } Scanner scanner = null; FileReader fr = null; String warpData = ""; try { fr = new FileReader(warpsFile); scanner = new Scanner(fr); while(scanner.hasNextLine()) { warpData = scanner.nextLine(); if(!warpData.trim().isEmpty()) { String[] items = warpData.split(":"); if (items.length > 0) { msg("[Faction] [Warps] adding '"+items[0]+"' "); PS warpLoc = PS.valueOf(new Location(Bukkit.getWorld(items[6]), Double.valueOf(items[1]), Double.valueOf(items[2]), Double.valueOf(items[3]))); fData.warpLocation.put(items[0], warpLoc); if(!items[7].trim().toLowerCase().equalsIgnoreCase("nullvalue")) { fData.warpPasswords.put(items[0], items[7]); msg("[Faction] [Warps] adding '"+items[0]+"' "); msg(" set password: "+items[7]); } } } else { msg("[Faction] [Warps] Empty Warps File Line"); } } } catch(Exception e) { msg("[Faction] [Warps] " + ChatColor.RED + "[ERROR]" + ChatColor.RESET + " Error reading warp, last data: " + warpData); e.printStackTrace(); } finally { if(null != scanner) { scanner.close(); } if(null != fr) { try { fr.close(); } catch (Exception e) { e.printStackTrace(); } } } } } } // Migration finished - so we no longer need to use the database OldConfig.fileConfig.renameTo(new File( OldConfig.folderBase, "config_disabled.yml" )); OldConfig.deInit(); } public void deIntOld() { OldConfig.deInit(); } }
src/main/java/markehme/factionsplus/config/OldMigrate.java
package markehme.factionsplus.config; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.util.Scanner; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import com.massivecraft.factions.entity.Faction; import com.massivecraft.factions.entity.FactionColl; import com.massivecraft.factions.entity.FactionColls; import com.massivecraft.massivecore.ps.PS; import markehme.factionsplus.FactionsPlus; import markehme.factionsplus.Utilities; import markehme.factionsplus.MCore.FactionData; import markehme.factionsplus.MCore.FactionDataColls; /** * This entire class is related to migrating data from the old systems (0.6) to the new * systems used by FactionsPlus. This is the only class that ignores deprecation notices * as it is the only class that should be accessing OldConfig. * @author markhughes * */ @SuppressWarnings("deprecation") public class OldMigrate { /** * At the end of migration the config file moves to config.yml.migrated, so * if the old config exists then it hasn't been migrated. * @return */ public boolean shouldMigrate() { return(OldConfig.fileConfig.exists()); } private static void msg(String m) { FactionsPlus.tellConsole("[Migration] " + m); } /** * Migrates all the fData */ public void migrateDatabase() { // Load the old configuration OldConfig.init(); OldConfig.reload(); for(FactionColl fColl : FactionColls.get().getColls()) { for(String id : fColl.getIds()) { Faction faction = fColl.get(id); msg(""); msg("[Faction] " + faction.getName() + " (" + faction.getId() + ")"); msg("[Faction] Migration starting for this faction"); // ----- Create FactionData file ----- // FactionData fData = FactionDataColls.get().getForUniverse(faction.getUniverse()).get(faction.getId()); if(fData == null) { FactionDataColls.get().getForUniverse(faction.getUniverse()).create(); msg("[Faction] [FData] FactionData file created."); fData = FactionDataColls.get().getForUniverse(faction.getUniverse()).get(faction.getId()); } else { msg("[Faction] [FData] FactionData file already exists, moving on."); } if(!fData.attached()) { msg("[Faction] [FData] " + ChatColor.RED + "[WARN]" + ChatColor.RESET + " The FactionData file exists/was created.. however, it's not attached."); } // ----- Migrate Announcement ----- // File fileAnnouncementFile = new File(OldConfig.folderAnnouncements, faction.getId()); if(fileAnnouncementFile.exists()) { if(fileAnnouncementFile.canRead()) { try { fData.announcement = (Utilities.readFileAsString(fileAnnouncementFile)).trim(); msg("[Faction] [Announcement] Announcement Migrated: " + fData.announcement); } catch (Exception e) { msg("[Faction] [Announcement] " + ChatColor.RED + "[ERROR]" + ChatColor.RESET + " Could not read the data for this announcement in this Faction" ); e.printStackTrace(); } } else { msg("[Faction] [Announcement] " + ChatColor.RED + "[WARN]" + ChatColor.RESET + " Although the announcement file exists, we can't read it. Please check permissions." ); } } else { msg("[Faction] [Announcement] No announcement data to migrate, moving on."); } // ----- Migrate Jails ----- // File jailLocationFile = new File(OldConfig.folderJails, "loc." + faction.getId()); // Check for a jail location if(!jailLocationFile.exists()) { // If theres no jail location, then theres also no jailed players msg("[Faction] [Jail] No jail location set, moving on."); } else { try { // Read the old database information String locationData[] = Utilities.readFileAsString(jailLocationFile).split(":"); Location jailLocation = new Location(Bukkit.getWorld(locationData[4]), Double.valueOf(locationData[0]), Double.valueOf(locationData[1]), Double.valueOf(locationData[2])); // Create the PS version PS psJailLocation = PS.valueOf(jailLocation); // Store the location in our fData object fData.jailLocation = psJailLocation; msg("[Faction] [Jail] Jail location found and moved to x: " + locationData[0]+", y: " + locationData[1] + ", z: " + locationData[2] + ", in world: " + locationData[4]); } catch(Exception e) { msg("[Faction] [Jail] " + ChatColor.RED + "[ERROR]" + ChatColor.RESET + " Could not read the data for the jail location in this Faction" ); e.printStackTrace(); } msg("[Faction] [Jailed Players] Reset!"); } // ----- Migrate Warps ----- // File warpsFile = new File(OldConfig.folderWarps, faction.getId()); if(!warpsFile.exists()) { msg("[Faction] [Warps] No warps have been found for this faction, moving on."); } else { FileInputStream fis = null; try { fis = new FileInputStream(new File(OldConfig.folderWarps, faction.getId())); int b = fis.read(); if(b == -1) { msg("[Faction] [Warps] No warps have been found for this faction, moving on."); fis.close(); } } catch(Exception e) { msg("[Faction] [Warps] " + ChatColor.RED + "[ERROR]" + ChatColor.RESET + " Could not read the data for the warps in this Faction"); fis = null; e.printStackTrace(); } finally { if(null != fis) { try { fis.close(); } catch(Exception e) { e.printStackTrace(); } } } Scanner scanner = null; FileReader fr = null; String warpData = ""; try { fr = new FileReader(warpsFile); scanner = new Scanner(fr); while(scanner.hasNextLine()) { warpData = scanner.nextLine(); if(!warpData.trim().isEmpty()) { String[] items = warpData.split(":"); if (items.length > 0) { msg("[Faction] [Warps] adding '"+items[0]+"' "); PS warpLoc = PS.valueOf(new Location(Bukkit.getWorld(items[6]), Double.valueOf(items[1]), Double.valueOf(items[2]), Double.valueOf(items[3]))); fData.warpLocation.put(items[0], warpLoc); if(!items[7].trim().toLowerCase().equalsIgnoreCase("nullvalue")) { fData.warpPasswords.put(items[0], items[7]); msg("[Faction] [Warps] adding '"+items[0]+"' "); msg(" set password: "+items[7]); } } } else { msg("[Faction] [Warps] Empty Warps File Line"); } } } catch(Exception e) { msg("[Faction] [Warps] " + ChatColor.RED + "[ERROR]" + ChatColor.RESET + " Error reading warp, last data: " + warpData); e.printStackTrace(); } finally { if(null != scanner) { scanner.close(); } if(null != fr) { try { fr.close(); } catch (Exception e) { e.printStackTrace(); } } } } } } // Migration finished - so we no longer need to use the database OldConfig.fileConfig.renameTo(new File( OldConfig.folderBase, "config_disabled.yml" )); OldConfig.deInit(); } public void deIntOld() { OldConfig.deInit(); } }
fData Fix
src/main/java/markehme/factionsplus/config/OldMigrate.java
fData Fix
<ide><path>rc/main/java/markehme/factionsplus/config/OldMigrate.java <ide> FactionData fData = FactionDataColls.get().getForUniverse(faction.getUniverse()).get(faction.getId()); <ide> <ide> if(fData == null) { <del> FactionDataColls.get().getForUniverse(faction.getUniverse()).create(); <add> FactionDataColls.get().getForUniverse(faction.getUniverse()).create(faction.getId()); <ide> msg("[Faction] [FData] FactionData file created."); <ide> <ide> fData = FactionDataColls.get().getForUniverse(faction.getUniverse()).get(faction.getId());