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 | b0395ed512f656b87f6194a91f4914eebdf78893 | 0 | mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid | /*
* 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.usergrid.services.notifications.gcm;
import org.apache.usergrid.persistence.*;
import org.apache.usergrid.persistence.index.query.Query;
import org.apache.usergrid.services.ServiceParameter;
import org.apache.usergrid.services.notifications.*;
import org.apache.usergrid.persistence.entities.Notification;
import org.apache.usergrid.persistence.entities.Notifier;
import org.apache.usergrid.persistence.entities.Receipt;
import org.junit.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import org.apache.usergrid.persistence.entities.Device;
import org.apache.usergrid.services.ServiceAction;
import static org.junit.Assert.*;
import static org.apache.usergrid.services.notifications.NotificationsService.NOTIFIER_ID_POSTFIX;
public class NotificationsServiceIT extends AbstractServiceNotificationIT {
private static final Logger LOG = LoggerFactory
.getLogger(NotificationsServiceIT.class);
/**
* set to true to run tests against actual GCM servers - but they may not
* all run correctly
*/
private static final boolean USE_REAL_CONNECTIONS = false;
private static final String PROVIDER = USE_REAL_CONNECTIONS ? "google"
: "noop";
private static final String API_KEY = "AIzaSyCIH_7WC0mOqBGMOXyQnFgrBpOePgHvQJM";
private static final String PUSH_TOKEN = "APA91bGxRGnMK8tKgVPzSlxtCFvwSVqx0xEPjA06sBmiK0k"
+ "QsiwUt6ipSYF0iPRHyUgpXle0P8OlRWJADkQrcN7yxG4pLMg1CVmrqDu8tfSe63mZ-MRU2IW0cOhmo"
+ "sqzC9trl33moS3OvT7qjDjkP4Qq8LYdwwYC5A";
private Notifier notifier;
private Device device1, device2;
private NotificationsService ns;
private QueueListener listener;
@Override
@Before
public void before() throws Exception {
super.before();
// create gcm notifier //
app.clear();
app.put("name", "gcm");
app.put("provider", PROVIDER);
app.put("environment", "development");
app.put("apiKey", API_KEY);
notifier = (Notifier) app
.testRequest(ServiceAction.POST, 1, "notifiers").getEntity()
.toTypedEntity();
String key = notifier.getName() + NOTIFIER_ID_POSTFIX;
// create devices //
app.clear();
app.put(key, PUSH_TOKEN);
Entity e = app.testRequest(ServiceAction.POST, 1, "devices")
.getEntity();
app.testRequest(ServiceAction.GET, 1, "devices", e.getUuid());
device1 = app.getEm().get(e.getUuid(), Device.class);
assertEquals(device1.getProperty(key), PUSH_TOKEN);
app.put(key, PUSH_TOKEN);
e = app.testRequest(ServiceAction.POST, 1, "devices").getEntity();
device2 = app.getEm().get(e.getUuid(), Device.class);
ns = getNotificationService();
Query query = new Query();
//query.addIdentifier(sp.getIdentifier());
query.setLimit(100);
query.setCollection("devices");
query.setResultsLevel(Query.Level.ALL_PROPERTIES);
PathQuery pathQuery = new PathQuery(new SimpleEntityRef( app.getEm().getApplicationRef()), query);
ns.getQueueManager().TEST_PATH_QUERY = pathQuery;
ApplicationQueueManager.QUEUE_NAME = "notifications/test/" + UUID.randomUUID().toString();
listener = new QueueListener(ns.getServiceManagerFactory(),
ns.getEntityManagerFactory(),ns.getMetricsFactory(), new Properties());
listener.run();
}
@After
public void after(){
if(listener!=null) {
listener.stop();
listener = null;
}
}
@Test
public void emptyPushNotification() throws Exception {
app.clear();
app.put("name", "foo");
app.put("provider", PROVIDER);
app.put("environment", "development");
app.put("apiKey", API_KEY);
Notifier n = (Notifier) app
.testRequest(ServiceAction.POST, 1, "notifiers").getEntity()
.toTypedEntity();
app.clear();
String payload = "Hello, World!";
Map<String, String> payloads = new HashMap<String, String>(1);
payloads.put("foo", payload);
app.put("payloads", payloads);
app.put("queued", System.currentTimeMillis());
Entity e = app.testRequest(ServiceAction.POST, 1, "notifications")
.getEntity();
app.testRequest(ServiceAction.GET, 1, "notifications", e.getUuid());
Notification notification = app.getEm().get(e.getUuid(),
Notification.class);
// perform push //
notification = scheduleNotificationAndWait(notification);
checkReceipts(notification, 0);
}
@Test
public void singlePushNotification() throws Exception {
Query pQuery = new Query();
pQuery.setLimit(100);
pQuery.setCollection("devices");
pQuery.setResultsLevel(Query.Level.ALL_PROPERTIES);
pQuery.addIdentifier(new ServiceParameter.NameParameter(device1.getUuid().toString()).getIdentifier());
ns.getQueueManager().TEST_PATH_QUERY = new PathQuery(new SimpleEntityRef( app.getEm().getApplicationRef()), pQuery);
app.clear();
String payload = "Hello, World!";
Map<String, String> payloads = new HashMap<String, String>(1);
payloads.put(notifier.getUuid().toString(), payload);
app.put("payloads", payloads);
app.put("queued", System.currentTimeMillis());
Entity e = app.testRequest(ServiceAction.POST, 1, "notifications")
.getEntity();
app.testRequest(ServiceAction.GET, 1, "notifications", e.getUuid());
Notification notification = app.getEm().get(e.getUuid(),
Notification.class);
assertEquals(
notification.getPayloads().get(notifier.getUuid().toString()),
payload);
// perform push //
notification = scheduleNotificationAndWait(notification);
checkReceipts(notification, 1);
}
@Test
public void singlePushNotificationViaUser() throws Exception {
app.clear();
// create user asdf
app.put("username", "asdf");
app.put("email", "[email protected]");
Entity user = app.testRequest(ServiceAction.POST, 1, "users").getEntity();
assertNotNull(user);
// post an existing device to user's devices collection
Entity device = app.testRequest(ServiceAction.POST, 1, "users",
user.getUuid(), "devices", device1.getUuid()).getEntity();
assertEquals(device.getUuid(), device1.getUuid());
// create query that searches for that device by providing UUID of the user
Query pQuery = new Query();
pQuery.setLimit(100);
pQuery.setCollection("devices");
pQuery.setResultsLevel(Query.Level.ALL_PROPERTIES);
pQuery.addIdentifier(new ServiceParameter.NameParameter(
user.getUuid().toString()).getIdentifier());
ns.getQueueManager().TEST_PATH_QUERY = new PathQuery(user), pQuery);
// create a push notification
String payload = "Hello, World!";
Map<String, String> payloads = new HashMap<String, String>(1);
payloads.put(notifier.getUuid().toString(), payload);
app.put("payloads", payloads);
app.put("queued", System.currentTimeMillis());
// post that notification
Entity e = app.testRequest(ServiceAction.POST, 1, "notifications").getEntity();
app.testRequest(ServiceAction.GET, 1, "notifications", e.getUuid());
Notification notification = app.getEm().get(e.getUuid(), Notification.class);
// perform push //
notification = scheduleNotificationAndWait(notification);
app.getEm().refreshIndex();
checkReceipts(notification, 1);
}
@Test
public void twoBatchNotification() throws Exception {
app.clear();
String payload = "Hello, World!";
Map<String, String> payloads = new HashMap<String, String>(1);
payloads.put(notifier.getUuid().toString(), payload);
app.put("payloads", payloads);
app.put("queued", System.currentTimeMillis());
Entity e = app.testRequest(ServiceAction.POST, 1, "notifications")
.getEntity();
app.testRequest(ServiceAction.GET, 1, "notifications", e.getUuid());
Notification notification = app.getEm().get(e.getUuid(),
Notification.class);
assertEquals(
notification.getPayloads().get(notifier.getUuid().toString()),
payload);
// reduce Batch size to 1
Field field = GCMAdapter.class.getDeclaredField("BATCH_SIZE");
field.setAccessible(true);
int multicastSize = field.getInt(GCMAdapter.class);
try {
field.setInt(GCMAdapter.class, 1);
// perform push //
notification = scheduleNotificationAndWait(notification);
checkReceipts(notification, 2);
} finally {
field.setInt(GCMAdapter.class, multicastSize);
}
}
@Ignore("todo: how can I mock this?")
@Test
public void providerIdUpdate() throws Exception {
// mock action (based on verified actual behavior) //
final String newProviderId = "newProviderId";
ns.providerAdapters.put("google", new MockSuccessfulProviderAdapter() {
@Override
public void sendNotification(String providerId, Notifier notifier,
Object payload, Notification notification,
TaskTracker tracker) throws Exception {
tracker.completed(newProviderId);
}
});
// create push notification //
app.clear();
String payload = "Hello, World!";
Map<String, String> payloads = new HashMap<String, String>(1);
payloads.put(notifier.getUuid().toString(), payload);
app.put("payloads", payloads);
app.put("queued", System.currentTimeMillis());
Entity e = app.testRequest(ServiceAction.POST, 1, "notifications")
.getEntity();
app.testRequest(ServiceAction.GET, 1, "notifications", e.getUuid());
Notification notification = app.getEm().get(e.getUuid(),
Notification.class);
assertEquals(
notification.getPayloads().get(notifier.getUuid().toString()),
payload);
ns.addDevice(notification, device1);
// perform push //
notification = scheduleNotificationAndWait(notification);
checkReceipts(notification, 1);
Device device = (Device) app.getEm().get(device1).toTypedEntity();
assertEquals(newProviderId,
device.getProperty(notifier.getName() + NOTIFIER_ID_POSTFIX));
}
@Test
public void badPayloads() throws Exception {
// bad payloads format
app.clear();
app.put("payloads", "{asdf}");
try {
app.testRequest(ServiceAction.POST, 1, "notifications");
fail("invalid payload should have been rejected");
} catch (IllegalArgumentException ex) {
// ok
}
// bad notifier
Map<String, String> payloads = new HashMap<String, String>(2);
app.put("payloads", payloads);
payloads.put("xxx", "");
try {
app.testRequest(ServiceAction.POST, 1, "notifications");
fail("invalid payload should have been rejected");
} catch (IllegalArgumentException ex) {
// ok
}
// payload too long
// need the real provider for this one...
app.clear();
app.put("name", "gcm2");
app.put("provider", "google");
app.put("environment", "development");
app.put("apiKey", API_KEY);
Entity e = app.testRequest(ServiceAction.POST, 1, "notifiers")
.getEntity();
Notifier notifier2 = app.getEm().get(e.getUuid(), Notifier.class);
payloads.clear();
StringBuilder sb = new StringBuilder();
sb.append("{\"x\":\"");
while (sb.length() < 4080) {
sb.append("x");
}
sb.append("\"}");
payloads.put(notifier2.getUuid().toString(), sb.toString());
app.clear();
app.put("payloads", payloads);
try {
app.testRequest(ServiceAction.POST, 1, "notifications");
fail("invalid payload should have been rejected");
} catch (Exception ex) {
assertEquals("java.lang.IllegalArgumentException: GCM payloads must be 4096 characters or less",
ex.getMessage());
// ok
}
}
@Ignore("todo: how can I mock this?")
@Test
public void badToken() throws Exception {
// mock action (based on verified actual behavior) //
if (!USE_REAL_CONNECTIONS) {
ns.providerAdapters.put("google",
new MockSuccessfulProviderAdapter() {
@Override
public void sendNotification(String providerId,
Notifier notifier, Object payload,
Notification notification, TaskTracker tracker)
throws Exception {
tracker.failed("InvalidRegistration",
"InvalidRegistration");
}
});
}
// create push notification //
app.clear();
String payload = "Hello, World!";
Map<String, String> payloads = new HashMap<String, String>(1);
payloads.put(notifier.getUuid().toString(), payload);
app.put("payloads", payloads);
app.put("queued", System.currentTimeMillis());
Entity e = app.testRequest(ServiceAction.POST, 1, "notifications")
.getEntity();
app.testRequest(ServiceAction.GET, 1, "notifications", e.getUuid());
Notification notification = app.getEm().get(e.getUuid(),
Notification.class);
assertEquals(
notification.getPayloads().get(notifier.getUuid().toString()),
payload);
// device w/ bad token
app.clear();
app.put(notifier.getName() + NOTIFIER_ID_POSTFIX, PUSH_TOKEN + "x");
e = app.testRequest(ServiceAction.POST, 1, "devices").getEntity();
device1 = app.getEm().get(e.getUuid(), Device.class);
ns.addDevice(notification, device1);
// perform push //
notification = scheduleNotificationAndWait(notification);
List<EntityRef> receipts = getNotificationReceipts(notification);
assertEquals(1, receipts.size());
Receipt receipt = app.getEm().get(receipts.get(0), Receipt.class);
assertEquals("InvalidRegistration", receipt.getErrorCode());
}
@Ignore("todo: how can I mock this?")
@Test
public void badAPIKey() throws Exception {
if (!USE_REAL_CONNECTIONS) {
// mock action (based on verified actual behavior) //
ns.providerAdapters.put("google",
new MockSuccessfulProviderAdapter() {
@Override
public void sendNotification(String providerId,
Notifier notifier, Object payload,
Notification notification, TaskTracker tracker)
throws Exception {
Exception e = new IOException();
throw new ConnectionException(e.getMessage(), e);
}
});
}
// create push notification //
app.clear();
String payload = "Hello, World!";
Map<String, String> payloads = new HashMap<String, String>(1);
payloads.put(notifier.getUuid().toString(), payload);
app.put("payloads", payloads);
app.put("queued", System.currentTimeMillis());
Entity e = app.testRequest(ServiceAction.POST, 1, "notifications")
.getEntity();
app.testRequest(ServiceAction.GET, 1, "notifications", e.getUuid());
Notification notification = app.getEm().get(e.getUuid(),
Notification.class);
assertEquals(
notification.getPayloads().get(notifier.getUuid().toString()),
payload);
ns.addDevice(notification, device1);
// save bad API key
app.getEm().setProperty(notifier, "apiKey", API_KEY + "x");
// perform push //
// ns.getQueueManager().processBatchAndReschedule(notification, null);
fail("Should have received a ConnectionException");
}
@Ignore("Run only if you need to.")
@Test
public void loadTest() throws Exception {
final int NUM_DEVICES = 10000;
// create notification //
HashMap<String, Object> properties = new LinkedHashMap<String, Object>();
String payload = "Hello, World!";
Map<String, String> payloads = new HashMap<String, String>(1);
payloads.put(notifier.getUuid().toString(), payload);
properties.put("payloads", payloads);
properties.put("queued", System.currentTimeMillis());
Entity e = app.testRequest(ServiceAction.POST, 1, "notifications")
.getEntity();
app.testRequest(ServiceAction.GET, 1, "notifications", e.getUuid());
Notification notification = app.getEm().get(e.getUuid(),
Notification.class);
assertEquals(
notification.getPayloads().get(notifier.getUuid().toString()),
payload);
// create a bunch of devices and add them to the notification
properties = new LinkedHashMap<String, Object>();
properties.put(notifier.getName() + NOTIFIER_ID_POSTFIX, PUSH_TOKEN);
for (int i = 0; i < NUM_DEVICES; i++) {
Entity entity = app.getEm().create("device", properties);
ns.addDevice(notification, entity);
}
long time = System.currentTimeMillis();
LOG.error("START DELIVERY OF {} NOTIFICATIONS", NUM_DEVICES);
// perform push //
notification = scheduleNotificationAndWait(notification);
LOG.error("END DELIVERY OF {} NOTIFICATIONS ({})", NUM_DEVICES,
System.currentTimeMillis() - time);
// check receipts //
checkReceipts(notification, NUM_DEVICES);
checkStatistics(notification, NUM_DEVICES, 0);
}
// @Test
// public void inactiveDeviceUpdate() throws Exception {
//
// if (!USE_REAL_CONNECTIONS) {
// // mock action (based on verified actual behavior) //
// NotificationsService.providerAdapters.put("apple", new
// MockSuccessfulProviderAdapter() {
// public Map<String,Date> getInactiveDevices(Notifier notifier,
// EntityManager em) throws Exception {
// return Collections.singletonMap(PUSH_TOKEN, new Date());
// }
// });
// }
//
// // create push notification //
//
// HashMap<String, Object> properties = new LinkedHashMap<String, Object>();
// String payload =
// APNS.newPayload().alertBody("Hello, World!").sound("chime").build();
// Map<String, String> payloads = new HashMap<String, String>(1);
// payloads.put(notifier.getUuid().toString(), payload);
// properties.put("payloads", payloads);
// properties.put("queued", System.currentTimeMillis());
//
// Entity e = testRequest(sm, ServiceAction.POST, 1, properties,
// "notifications").getEntity();
// testRequest(sm, ServiceAction.GET, 1, null, "notifications",
// e.getUuid());
//
// Notification notification = em.get(e.getUuid(), Notification.class);
// assertEquals(notification.getPayloads().get(notifier.getUuid().toString()),
// payload);
//
// ns.addDevice(notification, device1);
// ns.addDevice(notification, device2);
//
// assertNotNull(device1.getProperty(notifier.getName() +
// NOTIFIER_ID_POSTFIX));
// assertNotNull(device2.getProperty(notifier.getName() +
// NOTIFIER_ID_POSTFIX));
//
// // perform push //
// notification = scheduleNotificationAndWait(notification);
//
// // check provider IDs //
//
// device1 = em.get(device1, Device.class);
// assertNull(device1.getProperty(notifier.getName() +
// NOTIFIER_ID_POSTFIX));
// device2 = em.get(device2, Device.class);
// assertNull(device2.getProperty(notifier.getName() +
// NOTIFIER_ID_POSTFIX));
// }
} | stack/services/src/test/java/org/apache/usergrid/services/notifications/gcm/NotificationsServiceIT.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.usergrid.services.notifications.gcm;
import org.apache.usergrid.persistence.*;
import org.apache.usergrid.persistence.index.query.Query;
import org.apache.usergrid.services.ServiceParameter;
import org.apache.usergrid.services.notifications.*;
import org.apache.usergrid.persistence.entities.Notification;
import org.apache.usergrid.persistence.entities.Notifier;
import org.apache.usergrid.persistence.entities.Receipt;
import org.junit.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import org.apache.usergrid.persistence.entities.Device;
import org.apache.usergrid.services.ServiceAction;
import static org.junit.Assert.*;
import static org.apache.usergrid.services.notifications.NotificationsService.NOTIFIER_ID_POSTFIX;
public class NotificationsServiceIT extends AbstractServiceNotificationIT {
private static final Logger LOG = LoggerFactory
.getLogger(NotificationsServiceIT.class);
/**
* set to true to run tests against actual GCM servers - but they may not
* all run correctly
*/
private static final boolean USE_REAL_CONNECTIONS = false;
private static final String PROVIDER = USE_REAL_CONNECTIONS ? "google"
: "noop";
private static final String API_KEY = "AIzaSyCIH_7WC0mOqBGMOXyQnFgrBpOePgHvQJM";
private static final String PUSH_TOKEN = "APA91bGxRGnMK8tKgVPzSlxtCFvwSVqx0xEPjA06sBmiK0k"
+ "QsiwUt6ipSYF0iPRHyUgpXle0P8OlRWJADkQrcN7yxG4pLMg1CVmrqDu8tfSe63mZ-MRU2IW0cOhmo"
+ "sqzC9trl33moS3OvT7qjDjkP4Qq8LYdwwYC5A";
private Notifier notifier;
private Device device1, device2;
private NotificationsService ns;
private QueueListener listener;
@Override
@Before
public void before() throws Exception {
super.before();
// create gcm notifier //
app.clear();
app.put("name", "gcm");
app.put("provider", PROVIDER);
app.put("environment", "development");
app.put("apiKey", API_KEY);
notifier = (Notifier) app
.testRequest(ServiceAction.POST, 1, "notifiers").getEntity()
.toTypedEntity();
String key = notifier.getName() + NOTIFIER_ID_POSTFIX;
// create devices //
app.clear();
app.put(key, PUSH_TOKEN);
Entity e = app.testRequest(ServiceAction.POST, 1, "devices")
.getEntity();
app.testRequest(ServiceAction.GET, 1, "devices", e.getUuid());
device1 = app.getEm().get(e.getUuid(), Device.class);
assertEquals(device1.getProperty(key), PUSH_TOKEN);
app.put(key, PUSH_TOKEN);
e = app.testRequest(ServiceAction.POST, 1, "devices").getEntity();
device2 = app.getEm().get(e.getUuid(), Device.class);
ns = getNotificationService();
Query query = new Query();
//query.addIdentifier(sp.getIdentifier());
query.setLimit(100);
query.setCollection("devices");
query.setResultsLevel(Query.Level.ALL_PROPERTIES);
PathQuery pathQuery = new PathQuery(new SimpleEntityRef( app.getEm().getApplicationRef()), query);
ns.getQueueManager().TEST_PATH_QUERY = pathQuery;
ApplicationQueueManager.QUEUE_NAME = "notifications/test/" + UUID.randomUUID().toString();
listener = new QueueListener(ns.getServiceManagerFactory(),
ns.getEntityManagerFactory(),ns.getMetricsFactory(), new Properties());
listener.run();
}
@After
public void after(){
if(listener!=null) {
listener.stop();
listener = null;
}
}
@Test
public void emptyPushNotification() throws Exception {
app.clear();
app.put("name", "foo");
app.put("provider", PROVIDER);
app.put("environment", "development");
app.put("apiKey", API_KEY);
Notifier n = (Notifier) app
.testRequest(ServiceAction.POST, 1, "notifiers").getEntity()
.toTypedEntity();
app.clear();
String payload = "Hello, World!";
Map<String, String> payloads = new HashMap<String, String>(1);
payloads.put("foo", payload);
app.put("payloads", payloads);
app.put("queued", System.currentTimeMillis());
Entity e = app.testRequest(ServiceAction.POST, 1, "notifications")
.getEntity();
app.testRequest(ServiceAction.GET, 1, "notifications", e.getUuid());
Notification notification = app.getEm().get(e.getUuid(),
Notification.class);
// perform push //
notification = scheduleNotificationAndWait(notification);
checkReceipts(notification, 0);
}
@Test
public void singlePushNotification() throws Exception {
Query pQuery = new Query();
pQuery.setLimit(100);
pQuery.setCollection("devices");
pQuery.setResultsLevel(Query.Level.ALL_PROPERTIES);
pQuery.addIdentifier(new ServiceParameter.NameParameter(device1.getUuid().toString()).getIdentifier());
ns.getQueueManager().TEST_PATH_QUERY = new PathQuery(new SimpleEntityRef( app.getEm().getApplicationRef()), pQuery);
app.clear();
String payload = "Hello, World!";
Map<String, String> payloads = new HashMap<String, String>(1);
payloads.put(notifier.getUuid().toString(), payload);
app.put("payloads", payloads);
app.put("queued", System.currentTimeMillis());
Entity e = app.testRequest(ServiceAction.POST, 1, "notifications")
.getEntity();
app.testRequest(ServiceAction.GET, 1, "notifications", e.getUuid());
Notification notification = app.getEm().get(e.getUuid(),
Notification.class);
assertEquals(
notification.getPayloads().get(notifier.getUuid().toString()),
payload);
// perform push //
notification = scheduleNotificationAndWait(notification);
checkReceipts(notification, 1);
}
@Test
public void singlePushNotificationViaUser() throws Exception {
app.clear();
// create user asdf
app.put("username", "asdf");
app.put("email", "[email protected]");
Entity user = app.testRequest(ServiceAction.POST, 1, "users").getEntity();
assertNotNull(user);
// post an existing device to user's devices collection
Entity device = app.testRequest(ServiceAction.POST, 1, "users",
user.getUuid(), "devices", device1.getUuid()).getEntity();
assertEquals(device.getUuid(), device1.getUuid());
// create query that searches for that device by uuid
Query pQuery = new Query();
pQuery.setLimit(100);
pQuery.setCollection("devices");
pQuery.setResultsLevel(Query.Level.ALL_PROPERTIES);
pQuery.addIdentifier(new ServiceParameter.NameParameter(
device.getUuid().toString()).getIdentifier());
ns.getQueueManager().TEST_PATH_QUERY =
new PathQuery(new SimpleEntityRef( app.getEm().getApplicationRef()), pQuery);
// create a push notification
String payload = "Hello, World!";
Map<String, String> payloads = new HashMap<String, String>(1);
payloads.put(notifier.getUuid().toString(), payload);
app.put("payloads", payloads);
app.put("queued", System.currentTimeMillis());
// post that notification
Entity e = app.testRequest(ServiceAction.POST, 1, "notifications").getEntity();
app.testRequest(ServiceAction.GET, 1, "notifications", e.getUuid());
Notification notification = app.getEm().get(e.getUuid(), Notification.class);
// perform push //
notification = scheduleNotificationAndWait(notification);
app.getEm().refreshIndex();
checkReceipts(notification, 1);
}
@Test
public void twoBatchNotification() throws Exception {
app.clear();
String payload = "Hello, World!";
Map<String, String> payloads = new HashMap<String, String>(1);
payloads.put(notifier.getUuid().toString(), payload);
app.put("payloads", payloads);
app.put("queued", System.currentTimeMillis());
Entity e = app.testRequest(ServiceAction.POST, 1, "notifications")
.getEntity();
app.testRequest(ServiceAction.GET, 1, "notifications", e.getUuid());
Notification notification = app.getEm().get(e.getUuid(),
Notification.class);
assertEquals(
notification.getPayloads().get(notifier.getUuid().toString()),
payload);
// reduce Batch size to 1
Field field = GCMAdapter.class.getDeclaredField("BATCH_SIZE");
field.setAccessible(true);
int multicastSize = field.getInt(GCMAdapter.class);
try {
field.setInt(GCMAdapter.class, 1);
// perform push //
notification = scheduleNotificationAndWait(notification);
checkReceipts(notification, 2);
} finally {
field.setInt(GCMAdapter.class, multicastSize);
}
}
@Ignore("todo: how can I mock this?")
@Test
public void providerIdUpdate() throws Exception {
// mock action (based on verified actual behavior) //
final String newProviderId = "newProviderId";
ns.providerAdapters.put("google", new MockSuccessfulProviderAdapter() {
@Override
public void sendNotification(String providerId, Notifier notifier,
Object payload, Notification notification,
TaskTracker tracker) throws Exception {
tracker.completed(newProviderId);
}
});
// create push notification //
app.clear();
String payload = "Hello, World!";
Map<String, String> payloads = new HashMap<String, String>(1);
payloads.put(notifier.getUuid().toString(), payload);
app.put("payloads", payloads);
app.put("queued", System.currentTimeMillis());
Entity e = app.testRequest(ServiceAction.POST, 1, "notifications")
.getEntity();
app.testRequest(ServiceAction.GET, 1, "notifications", e.getUuid());
Notification notification = app.getEm().get(e.getUuid(),
Notification.class);
assertEquals(
notification.getPayloads().get(notifier.getUuid().toString()),
payload);
ns.addDevice(notification, device1);
// perform push //
notification = scheduleNotificationAndWait(notification);
checkReceipts(notification, 1);
Device device = (Device) app.getEm().get(device1).toTypedEntity();
assertEquals(newProviderId,
device.getProperty(notifier.getName() + NOTIFIER_ID_POSTFIX));
}
@Test
public void badPayloads() throws Exception {
// bad payloads format
app.clear();
app.put("payloads", "{asdf}");
try {
app.testRequest(ServiceAction.POST, 1, "notifications");
fail("invalid payload should have been rejected");
} catch (IllegalArgumentException ex) {
// ok
}
// bad notifier
Map<String, String> payloads = new HashMap<String, String>(2);
app.put("payloads", payloads);
payloads.put("xxx", "");
try {
app.testRequest(ServiceAction.POST, 1, "notifications");
fail("invalid payload should have been rejected");
} catch (IllegalArgumentException ex) {
// ok
}
// payload too long
// need the real provider for this one...
app.clear();
app.put("name", "gcm2");
app.put("provider", "google");
app.put("environment", "development");
app.put("apiKey", API_KEY);
Entity e = app.testRequest(ServiceAction.POST, 1, "notifiers")
.getEntity();
Notifier notifier2 = app.getEm().get(e.getUuid(), Notifier.class);
payloads.clear();
StringBuilder sb = new StringBuilder();
sb.append("{\"x\":\"");
while (sb.length() < 4080) {
sb.append("x");
}
sb.append("\"}");
payloads.put(notifier2.getUuid().toString(), sb.toString());
app.clear();
app.put("payloads", payloads);
try {
app.testRequest(ServiceAction.POST, 1, "notifications");
fail("invalid payload should have been rejected");
} catch (Exception ex) {
assertEquals("java.lang.IllegalArgumentException: GCM payloads must be 4096 characters or less",
ex.getMessage());
// ok
}
}
@Ignore("todo: how can I mock this?")
@Test
public void badToken() throws Exception {
// mock action (based on verified actual behavior) //
if (!USE_REAL_CONNECTIONS) {
ns.providerAdapters.put("google",
new MockSuccessfulProviderAdapter() {
@Override
public void sendNotification(String providerId,
Notifier notifier, Object payload,
Notification notification, TaskTracker tracker)
throws Exception {
tracker.failed("InvalidRegistration",
"InvalidRegistration");
}
});
}
// create push notification //
app.clear();
String payload = "Hello, World!";
Map<String, String> payloads = new HashMap<String, String>(1);
payloads.put(notifier.getUuid().toString(), payload);
app.put("payloads", payloads);
app.put("queued", System.currentTimeMillis());
Entity e = app.testRequest(ServiceAction.POST, 1, "notifications")
.getEntity();
app.testRequest(ServiceAction.GET, 1, "notifications", e.getUuid());
Notification notification = app.getEm().get(e.getUuid(),
Notification.class);
assertEquals(
notification.getPayloads().get(notifier.getUuid().toString()),
payload);
// device w/ bad token
app.clear();
app.put(notifier.getName() + NOTIFIER_ID_POSTFIX, PUSH_TOKEN + "x");
e = app.testRequest(ServiceAction.POST, 1, "devices").getEntity();
device1 = app.getEm().get(e.getUuid(), Device.class);
ns.addDevice(notification, device1);
// perform push //
notification = scheduleNotificationAndWait(notification);
List<EntityRef> receipts = getNotificationReceipts(notification);
assertEquals(1, receipts.size());
Receipt receipt = app.getEm().get(receipts.get(0), Receipt.class);
assertEquals("InvalidRegistration", receipt.getErrorCode());
}
@Ignore("todo: how can I mock this?")
@Test
public void badAPIKey() throws Exception {
if (!USE_REAL_CONNECTIONS) {
// mock action (based on verified actual behavior) //
ns.providerAdapters.put("google",
new MockSuccessfulProviderAdapter() {
@Override
public void sendNotification(String providerId,
Notifier notifier, Object payload,
Notification notification, TaskTracker tracker)
throws Exception {
Exception e = new IOException();
throw new ConnectionException(e.getMessage(), e);
}
});
}
// create push notification //
app.clear();
String payload = "Hello, World!";
Map<String, String> payloads = new HashMap<String, String>(1);
payloads.put(notifier.getUuid().toString(), payload);
app.put("payloads", payloads);
app.put("queued", System.currentTimeMillis());
Entity e = app.testRequest(ServiceAction.POST, 1, "notifications")
.getEntity();
app.testRequest(ServiceAction.GET, 1, "notifications", e.getUuid());
Notification notification = app.getEm().get(e.getUuid(),
Notification.class);
assertEquals(
notification.getPayloads().get(notifier.getUuid().toString()),
payload);
ns.addDevice(notification, device1);
// save bad API key
app.getEm().setProperty(notifier, "apiKey", API_KEY + "x");
// perform push //
// ns.getQueueManager().processBatchAndReschedule(notification, null);
fail("Should have received a ConnectionException");
}
@Ignore("Run only if you need to.")
@Test
public void loadTest() throws Exception {
final int NUM_DEVICES = 10000;
// create notification //
HashMap<String, Object> properties = new LinkedHashMap<String, Object>();
String payload = "Hello, World!";
Map<String, String> payloads = new HashMap<String, String>(1);
payloads.put(notifier.getUuid().toString(), payload);
properties.put("payloads", payloads);
properties.put("queued", System.currentTimeMillis());
Entity e = app.testRequest(ServiceAction.POST, 1, "notifications")
.getEntity();
app.testRequest(ServiceAction.GET, 1, "notifications", e.getUuid());
Notification notification = app.getEm().get(e.getUuid(),
Notification.class);
assertEquals(
notification.getPayloads().get(notifier.getUuid().toString()),
payload);
// create a bunch of devices and add them to the notification
properties = new LinkedHashMap<String, Object>();
properties.put(notifier.getName() + NOTIFIER_ID_POSTFIX, PUSH_TOKEN);
for (int i = 0; i < NUM_DEVICES; i++) {
Entity entity = app.getEm().create("device", properties);
ns.addDevice(notification, entity);
}
long time = System.currentTimeMillis();
LOG.error("START DELIVERY OF {} NOTIFICATIONS", NUM_DEVICES);
// perform push //
notification = scheduleNotificationAndWait(notification);
LOG.error("END DELIVERY OF {} NOTIFICATIONS ({})", NUM_DEVICES,
System.currentTimeMillis() - time);
// check receipts //
checkReceipts(notification, NUM_DEVICES);
checkStatistics(notification, NUM_DEVICES, 0);
}
// @Test
// public void inactiveDeviceUpdate() throws Exception {
//
// if (!USE_REAL_CONNECTIONS) {
// // mock action (based on verified actual behavior) //
// NotificationsService.providerAdapters.put("apple", new
// MockSuccessfulProviderAdapter() {
// public Map<String,Date> getInactiveDevices(Notifier notifier,
// EntityManager em) throws Exception {
// return Collections.singletonMap(PUSH_TOKEN, new Date());
// }
// });
// }
//
// // create push notification //
//
// HashMap<String, Object> properties = new LinkedHashMap<String, Object>();
// String payload =
// APNS.newPayload().alertBody("Hello, World!").sound("chime").build();
// Map<String, String> payloads = new HashMap<String, String>(1);
// payloads.put(notifier.getUuid().toString(), payload);
// properties.put("payloads", payloads);
// properties.put("queued", System.currentTimeMillis());
//
// Entity e = testRequest(sm, ServiceAction.POST, 1, properties,
// "notifications").getEntity();
// testRequest(sm, ServiceAction.GET, 1, null, "notifications",
// e.getUuid());
//
// Notification notification = em.get(e.getUuid(), Notification.class);
// assertEquals(notification.getPayloads().get(notifier.getUuid().toString()),
// payload);
//
// ns.addDevice(notification, device1);
// ns.addDevice(notification, device2);
//
// assertNotNull(device1.getProperty(notifier.getName() +
// NOTIFIER_ID_POSTFIX));
// assertNotNull(device2.getProperty(notifier.getName() +
// NOTIFIER_ID_POSTFIX));
//
// // perform push //
// notification = scheduleNotificationAndWait(notification);
//
// // check provider IDs //
//
// device1 = em.get(device1, Device.class);
// assertNull(device1.getProperty(notifier.getName() +
// NOTIFIER_ID_POSTFIX));
// device2 = em.get(device2, Device.class);
// assertNull(device2.getProperty(notifier.getName() +
// NOTIFIER_ID_POSTFIX));
// }
} | Fix test to look for devices of user not of application.
| stack/services/src/test/java/org/apache/usergrid/services/notifications/gcm/NotificationsServiceIT.java | Fix test to look for devices of user not of application. | <ide><path>tack/services/src/test/java/org/apache/usergrid/services/notifications/gcm/NotificationsServiceIT.java
<ide> user.getUuid(), "devices", device1.getUuid()).getEntity();
<ide> assertEquals(device.getUuid(), device1.getUuid());
<ide>
<del> // create query that searches for that device by uuid
<add> // create query that searches for that device by providing UUID of the user
<ide> Query pQuery = new Query();
<ide> pQuery.setLimit(100);
<ide> pQuery.setCollection("devices");
<ide> pQuery.setResultsLevel(Query.Level.ALL_PROPERTIES);
<add>
<ide> pQuery.addIdentifier(new ServiceParameter.NameParameter(
<del> device.getUuid().toString()).getIdentifier());
<del> ns.getQueueManager().TEST_PATH_QUERY =
<del> new PathQuery(new SimpleEntityRef( app.getEm().getApplicationRef()), pQuery);
<add> user.getUuid().toString()).getIdentifier());
<add> ns.getQueueManager().TEST_PATH_QUERY = new PathQuery(user), pQuery);
<ide>
<ide> // create a push notification
<ide> String payload = "Hello, World!"; |
|
Java | apache-2.0 | e0c970a5fe46940ac9ab2355dd5913f2f7fc2a69 | 0 | shroman/ignite,agura/incubator-ignite,SharplEr/ignite,pperalta/ignite,NSAmelchev/ignite,sk0x50/ignite,a1vanov/ignite,ilantukh/ignite,f7753/ignite,apache/ignite,dmagda/incubator-ignite,SomeFire/ignite,voipp/ignite,ptupitsyn/ignite,chandresh-pancholi/ignite,voipp/ignite,ilantukh/ignite,nivanov/ignite,vldpyatkov/ignite,dream-x/ignite,daradurvs/ignite,alexzaitzev/ignite,murador/ignite,xtern/ignite,voipp/ignite,rfqu/ignite,vadopolski/ignite,ilantukh/ignite,alexzaitzev/ignite,BiryukovVA/ignite,endian675/ignite,sk0x50/ignite,f7753/ignite,rfqu/ignite,irudyak/ignite,wmz7year/ignite,dmagda/incubator-ignite,tkpanther/ignite,murador/ignite,ascherbakoff/ignite,tkpanther/ignite,ascherbakoff/ignite,voipp/ignite,WilliamDo/ignite,VladimirErshov/ignite,NSAmelchev/ignite,ryanzz/ignite,VladimirErshov/ignite,samaitra/ignite,amirakhmedov/ignite,kromulan/ignite,SharplEr/ignite,ryanzz/ignite,StalkXT/ignite,agura/incubator-ignite,tkpanther/ignite,dmagda/incubator-ignite,alexzaitzev/ignite,leveyj/ignite,daradurvs/ignite,DoudTechData/ignite,irudyak/ignite,SharplEr/ignite,samaitra/ignite,StalkXT/ignite,murador/ignite,amirakhmedov/ignite,xtern/ignite,nizhikov/ignite,vadopolski/ignite,psadusumilli/ignite,f7753/ignite,amirakhmedov/ignite,ntikhonov/ignite,tkpanther/ignite,StalkXT/ignite,samaitra/ignite,VladimirErshov/ignite,leveyj/ignite,DoudTechData/ignite,SharplEr/ignite,mcherkasov/ignite,kromulan/ignite,DoudTechData/ignite,NSAmelchev/ignite,ryanzz/ignite,xtern/ignite,ntikhonov/ignite,ptupitsyn/ignite,rfqu/ignite,chandresh-pancholi/ignite,murador/ignite,chandresh-pancholi/ignite,nizhikov/ignite,wmz7year/ignite,nizhikov/ignite,dream-x/ignite,amirakhmedov/ignite,xtern/ignite,amirakhmedov/ignite,BiryukovVA/ignite,andrey-kuznetsov/ignite,murador/ignite,shroman/ignite,WilliamDo/ignite,ascherbakoff/ignite,ilantukh/ignite,irudyak/ignite,ilantukh/ignite,vldpyatkov/ignite,nizhikov/ignite,ilantukh/ignite,ryanzz/ignite,daradurvs/ignite,apache/ignite,voipp/ignite,nivanov/ignite,psadusumilli/ignite,pperalta/ignite,psadusumilli/ignite,wmz7year/ignite,shroman/ignite,alexzaitzev/ignite,a1vanov/ignite,DoudTechData/ignite,ascherbakoff/ignite,sk0x50/ignite,vldpyatkov/ignite,ptupitsyn/ignite,voipp/ignite,psadusumilli/ignite,leveyj/ignite,agura/incubator-ignite,endian675/ignite,pperalta/ignite,mcherkasov/ignite,rfqu/ignite,VladimirErshov/ignite,amirakhmedov/ignite,DoudTechData/ignite,kromulan/ignite,alexzaitzev/ignite,andrey-kuznetsov/ignite,irudyak/ignite,StalkXT/ignite,agura/incubator-ignite,samaitra/ignite,SomeFire/ignite,BiryukovVA/ignite,SomeFire/ignite,dream-x/ignite,kromulan/ignite,leveyj/ignite,shroman/ignite,andrey-kuznetsov/ignite,DoudTechData/ignite,dream-x/ignite,leveyj/ignite,vadopolski/ignite,sk0x50/ignite,samaitra/ignite,shroman/ignite,SomeFire/ignite,nivanov/ignite,shroman/ignite,xtern/ignite,vadopolski/ignite,murador/ignite,apache/ignite,alexzaitzev/ignite,dmagda/incubator-ignite,apache/ignite,chandresh-pancholi/ignite,BiryukovVA/ignite,nivanov/ignite,ryanzz/ignite,sk0x50/ignite,voipp/ignite,murador/ignite,DoudTechData/ignite,agura/incubator-ignite,mcherkasov/ignite,rfqu/ignite,andrey-kuznetsov/ignite,irudyak/ignite,endian675/ignite,f7753/ignite,wmz7year/ignite,ryanzz/ignite,psadusumilli/ignite,mcherkasov/ignite,rfqu/ignite,dmagda/incubator-ignite,mcherkasov/ignite,apache/ignite,SomeFire/ignite,endian675/ignite,ptupitsyn/ignite,amirakhmedov/ignite,agura/incubator-ignite,samaitra/ignite,daradurvs/ignite,voipp/ignite,afinka77/ignite,endian675/ignite,kromulan/ignite,vldpyatkov/ignite,daradurvs/ignite,wmz7year/ignite,sk0x50/ignite,vladisav/ignite,StalkXT/ignite,alexzaitzev/ignite,vadopolski/ignite,ptupitsyn/ignite,afinka77/ignite,vladisav/ignite,ascherbakoff/ignite,samaitra/ignite,kromulan/ignite,apache/ignite,daradurvs/ignite,mcherkasov/ignite,kromulan/ignite,VladimirErshov/ignite,BiryukovVA/ignite,pperalta/ignite,afinka77/ignite,afinka77/ignite,agura/incubator-ignite,NSAmelchev/ignite,a1vanov/ignite,WilliamDo/ignite,dmagda/incubator-ignite,dmagda/incubator-ignite,a1vanov/ignite,daradurvs/ignite,BiryukovVA/ignite,nizhikov/ignite,ntikhonov/ignite,SharplEr/ignite,afinka77/ignite,endian675/ignite,andrey-kuznetsov/ignite,samaitra/ignite,shroman/ignite,leveyj/ignite,ryanzz/ignite,ntikhonov/ignite,tkpanther/ignite,irudyak/ignite,ptupitsyn/ignite,chandresh-pancholi/ignite,SharplEr/ignite,xtern/ignite,StalkXT/ignite,andrey-kuznetsov/ignite,tkpanther/ignite,vadopolski/ignite,ryanzz/ignite,daradurvs/ignite,daradurvs/ignite,rfqu/ignite,BiryukovVA/ignite,SomeFire/ignite,samaitra/ignite,ilantukh/ignite,nizhikov/ignite,chandresh-pancholi/ignite,psadusumilli/ignite,nizhikov/ignite,ntikhonov/ignite,afinka77/ignite,ptupitsyn/ignite,xtern/ignite,shroman/ignite,WilliamDo/ignite,WilliamDo/ignite,vladisav/ignite,SomeFire/ignite,ascherbakoff/ignite,VladimirErshov/ignite,nivanov/ignite,leveyj/ignite,dream-x/ignite,BiryukovVA/ignite,nivanov/ignite,amirakhmedov/ignite,vldpyatkov/ignite,nivanov/ignite,SomeFire/ignite,daradurvs/ignite,f7753/ignite,samaitra/ignite,nizhikov/ignite,alexzaitzev/ignite,ascherbakoff/ignite,WilliamDo/ignite,alexzaitzev/ignite,pperalta/ignite,chandresh-pancholi/ignite,pperalta/ignite,psadusumilli/ignite,NSAmelchev/ignite,nizhikov/ignite,vldpyatkov/ignite,a1vanov/ignite,vladisav/ignite,vldpyatkov/ignite,WilliamDo/ignite,SharplEr/ignite,amirakhmedov/ignite,SomeFire/ignite,SharplEr/ignite,NSAmelchev/ignite,ntikhonov/ignite,ilantukh/ignite,vladisav/ignite,f7753/ignite,NSAmelchev/ignite,leveyj/ignite,apache/ignite,chandresh-pancholi/ignite,vadopolski/ignite,mcherkasov/ignite,dream-x/ignite,DoudTechData/ignite,SharplEr/ignite,wmz7year/ignite,vldpyatkov/ignite,pperalta/ignite,agura/incubator-ignite,BiryukovVA/ignite,ilantukh/ignite,BiryukovVA/ignite,wmz7year/ignite,shroman/ignite,andrey-kuznetsov/ignite,vladisav/ignite,f7753/ignite,andrey-kuznetsov/ignite,sk0x50/ignite,kromulan/ignite,dmagda/incubator-ignite,NSAmelchev/ignite,ascherbakoff/ignite,murador/ignite,ptupitsyn/ignite,ptupitsyn/ignite,vladisav/ignite,nivanov/ignite,StalkXT/ignite,vadopolski/ignite,pperalta/ignite,andrey-kuznetsov/ignite,NSAmelchev/ignite,xtern/ignite,ascherbakoff/ignite,voipp/ignite,ptupitsyn/ignite,ntikhonov/ignite,ntikhonov/ignite,tkpanther/ignite,endian675/ignite,xtern/ignite,dream-x/ignite,irudyak/ignite,tkpanther/ignite,a1vanov/ignite,f7753/ignite,VladimirErshov/ignite,shroman/ignite,StalkXT/ignite,psadusumilli/ignite,apache/ignite,WilliamDo/ignite,afinka77/ignite,SomeFire/ignite,a1vanov/ignite,apache/ignite,afinka77/ignite,ilantukh/ignite,dream-x/ignite,endian675/ignite,mcherkasov/ignite,wmz7year/ignite,irudyak/ignite,chandresh-pancholi/ignite,andrey-kuznetsov/ignite,vladisav/ignite,sk0x50/ignite,sk0x50/ignite,a1vanov/ignite,VladimirErshov/ignite,irudyak/ignite,rfqu/ignite,StalkXT/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.internal.processors.rest.handlers.query;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteException;
import org.apache.ignite.cache.query.Query;
import org.apache.ignite.cache.query.QueryCursor;
import org.apache.ignite.cache.query.ScanQuery;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.cache.query.SqlQuery;
import org.apache.ignite.internal.GridKernalContext;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.processors.cache.QueryCursorImpl;
import org.apache.ignite.internal.processors.query.GridQueryFieldMetadata;
import org.apache.ignite.internal.processors.rest.GridRestCommand;
import org.apache.ignite.internal.processors.rest.GridRestResponse;
import org.apache.ignite.internal.processors.rest.handlers.GridRestCommandHandlerAdapter;
import org.apache.ignite.internal.processors.rest.request.GridRestRequest;
import org.apache.ignite.internal.processors.rest.request.RestQueryRequest;
import org.apache.ignite.internal.util.future.GridFinishedFuture;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteBiPredicate;
import static org.apache.ignite.internal.processors.rest.GridRestCommand.CLOSE_SQL_QUERY;
import static org.apache.ignite.internal.processors.rest.GridRestCommand.EXECUTE_SCAN_QUERY;
import static org.apache.ignite.internal.processors.rest.GridRestCommand.EXECUTE_SQL_FIELDS_QUERY;
import static org.apache.ignite.internal.processors.rest.GridRestCommand.EXECUTE_SQL_QUERY;
import static org.apache.ignite.internal.processors.rest.GridRestCommand.FETCH_SQL_QUERY;
/**
* Query command handler.
*/
public class QueryCommandHandler extends GridRestCommandHandlerAdapter {
/** Supported commands. */
private static final Collection<GridRestCommand> SUPPORTED_COMMANDS = U.sealList(EXECUTE_SQL_QUERY,
EXECUTE_SQL_FIELDS_QUERY,
EXECUTE_SCAN_QUERY,
FETCH_SQL_QUERY,
CLOSE_SQL_QUERY);
/** Query ID sequence. */
private static final AtomicLong qryIdGen = new AtomicLong();
/** Current queries cursors. */
private final ConcurrentHashMap<Long, QueryCursorIterator> qryCurs = new ConcurrentHashMap<>();
/**
* @param ctx Context.
*/
public QueryCommandHandler(GridKernalContext ctx) {
super(ctx);
final long idleQryCurTimeout = ctx.config().getConnectorConfiguration().getIdleQueryCursorTimeout();
long idleQryCurCheckFreq = ctx.config().getConnectorConfiguration().getIdleQueryCursorCheckFrequency();
ctx.timeout().schedule(new Runnable() {
@Override public void run() {
long time = U.currentTimeMillis();
for (Map.Entry<Long, QueryCursorIterator> e : qryCurs.entrySet()) {
QueryCursorIterator qryCurIt = e.getValue();
long createTime = qryCurIt.timestamp();
if (time > createTime + idleQryCurTimeout && qryCurIt.tryLock()) {
try {
qryCurIt.timestamp(-1);
qryCurs.remove(e.getKey(), qryCurIt);
qryCurIt.close();
}
finally {
qryCurIt.unlock();
}
}
}
}
}, idleQryCurCheckFreq, idleQryCurCheckFreq);
}
/**
* @param cur Current cursor.
* @param req Sql request.
* @param qryId Query id.
* @param qryCurs Query cursors.
* @return Query result with items.
*/
private static CacheQueryResult createQueryResult(
Iterator cur, RestQueryRequest req, Long qryId, ConcurrentHashMap<Long, QueryCursorIterator> qryCurs) {
CacheQueryResult res = new CacheQueryResult();
List<Object> items = new ArrayList<>();
for (int i = 0; i < req.pageSize() && cur.hasNext(); ++i)
items.add(cur.next());
res.setItems(items);
res.setLast(!cur.hasNext());
res.setQueryId(qryId);
if (!cur.hasNext())
removeQueryCursor(qryId, qryCurs);
return res;
}
/**
* Removes query cursor.
*
* @param qryId Query id.
* @param qryCurs Query cursors.
*/
private static void removeQueryCursor(Long qryId, ConcurrentHashMap<Long, QueryCursorIterator> qryCurs) {
QueryCursorIterator qryCurIt = qryCurs.get(qryId);
if (qryCurIt == null)
return;
qryCurIt.lock();
try {
if (qryCurIt.timestamp() == -1)
return;
qryCurIt.close();
qryCurs.remove(qryId);
}
finally {
qryCurIt.unlock();
}
}
/**
* Creates class instance.
*
* @param cls Target class.
* @param clsName Implementing class name.
* @return Class instance.
* @throws IgniteException If failed.
*/
private static <T> T instance(Class<? extends T> cls, String clsName) throws IgniteException {
try {
Class<?> implCls = Class.forName(clsName);
if (!cls.isAssignableFrom(implCls))
throw new IgniteException("Failed to create instance (target class does not extend or implement " +
"required class or interface) [cls=" + cls.getName() + ", clsName=" + clsName + ']');
Constructor<?> ctor = implCls.getConstructor();
return (T)ctor.newInstance();
}
catch (ClassNotFoundException e) {
throw new IgniteException("Failed to find target class: " + clsName, e);
}
catch (NoSuchMethodException e) {
throw new IgniteException("Failed to find constructor for provided arguments " +
"[clsName=" + clsName + ']', e);
}
catch (InstantiationException e) {
throw new IgniteException("Failed to instantiate target class " +
"[clsName=" + clsName + ']', e);
}
catch (IllegalAccessException e) {
throw new IgniteException("Failed to instantiate class (constructor is not available) " +
"[clsName=" + clsName + ']', e);
}
catch (InvocationTargetException e) {
throw new IgniteException("Failed to instantiate class (constructor threw an exception) " +
"[clsName=" + clsName + ']', e.getCause());
}
}
/** {@inheritDoc} */
@Override public Collection<GridRestCommand> supportedCommands() {
return SUPPORTED_COMMANDS;
}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<GridRestResponse> handleAsync(GridRestRequest req) {
assert req != null;
assert SUPPORTED_COMMANDS.contains(req.command());
assert req instanceof RestQueryRequest : "Invalid type of query request.";
switch (req.command()) {
case EXECUTE_SQL_QUERY:
case EXECUTE_SQL_FIELDS_QUERY:
case EXECUTE_SCAN_QUERY: {
return ctx.closure().callLocalSafe(
new ExecuteQueryCallable(ctx, (RestQueryRequest)req, qryCurs), false);
}
case FETCH_SQL_QUERY: {
return ctx.closure().callLocalSafe(
new FetchQueryCallable((RestQueryRequest)req, qryCurs), false);
}
case CLOSE_SQL_QUERY: {
return ctx.closure().callLocalSafe(
new CloseQueryCallable((RestQueryRequest)req, qryCurs), false);
}
}
return new GridFinishedFuture<>();
}
/**
* Execute query callable.
*/
private static class ExecuteQueryCallable implements Callable<GridRestResponse> {
/** Kernal context. */
private GridKernalContext ctx;
/** Execute query request. */
private RestQueryRequest req;
/** Current queries cursors. */
private final ConcurrentHashMap<Long, QueryCursorIterator> qryCurs;
/**
* @param ctx Kernal context.
* @param req Execute query request.
* @param qryCurs Query cursors.
*/
public ExecuteQueryCallable(GridKernalContext ctx, RestQueryRequest req,
ConcurrentHashMap<Long, QueryCursorIterator> qryCurs) {
this.ctx = ctx;
this.req = req;
this.qryCurs = qryCurs;
}
/** {@inheritDoc} */
@Override public GridRestResponse call() throws Exception {
final long qryId = qryIdGen.getAndIncrement();
try {
Query qry;
switch (req.queryType()) {
case SQL:
qry = new SqlQuery(req.typeName(), req.sqlQuery());
((SqlQuery)qry).setArgs(req.arguments());
break;
case SQL_FIELDS:
qry = new SqlFieldsQuery(req.sqlQuery());
((SqlFieldsQuery)qry).setArgs(req.arguments());
break;
case SCAN:
IgniteBiPredicate pred = null;
if (req.className() != null)
pred = instance(IgniteBiPredicate.class, req.className());
qry = new ScanQuery(pred);
break;
default:
throw new IgniteException("Incorrect query type [type=" + req.queryType() + "]");
}
IgniteCache<Object, Object> cache = ctx.grid().cache(req.cacheName());
if (cache == null)
return new GridRestResponse(GridRestResponse.STATUS_FAILED,
"Failed to find cache with name: " + req.cacheName());
final QueryCursor qryCur = cache.query(qry);
Iterator cur = qryCur.iterator();
QueryCursorIterator qryCurIt = new QueryCursorIterator(qryCur, cur);
qryCurIt.lock();
try {
qryCurs.put(qryId, qryCurIt);
CacheQueryResult res = createQueryResult(cur, req, qryId, qryCurs);
switch (req.queryType()) {
case SQL:
case SQL_FIELDS:
List<GridQueryFieldMetadata> fieldsMeta = ((QueryCursorImpl)qryCur).fieldsMeta();
res.setFieldsMetadata(convertMetadata(fieldsMeta));
break;
case SCAN:
CacheQueryFieldsMetaResult keyField = new CacheQueryFieldsMetaResult();
keyField.setFieldName("key");
CacheQueryFieldsMetaResult valField = new CacheQueryFieldsMetaResult();
valField.setFieldName("value");
res.setFieldsMetadata(U.sealList(keyField, valField));
break;
}
return new GridRestResponse(res);
}
finally {
qryCurIt.unlock();
}
}
catch (Exception e) {
removeQueryCursor(qryId, qryCurs);
return new GridRestResponse(GridRestResponse.STATUS_FAILED, e.getMessage());
}
}
/**
* @param meta Internal query field metadata.
* @return Rest query field metadata.
*/
private Collection<CacheQueryFieldsMetaResult> convertMetadata(Collection<GridQueryFieldMetadata> meta) {
List<CacheQueryFieldsMetaResult> res = new ArrayList<>();
if (meta != null) {
for (GridQueryFieldMetadata info : meta)
res.add(new CacheQueryFieldsMetaResult(info));
}
return res;
}
}
/**
* Close query callable.
*/
private static class CloseQueryCallable implements Callable<GridRestResponse> {
/** Current queries cursors. */
private final ConcurrentHashMap<Long, QueryCursorIterator> qryCurs;
/** Execute query request. */
private RestQueryRequest req;
/**
* @param req Execute query request.
* @param qryCurs Query cursors.
*/
public CloseQueryCallable(RestQueryRequest req, ConcurrentHashMap<Long, QueryCursorIterator> qryCurs) {
this.req = req;
this.qryCurs = qryCurs;
}
/** {@inheritDoc} */
@Override public GridRestResponse call() throws Exception {
try {
QueryCursorIterator qryCurIt = qryCurs.get(req.queryId());
if (qryCurIt == null)
return new GridRestResponse(true);
qryCurIt.lock();
try {
if (qryCurIt.timestamp() == -1)
return new GridRestResponse(true);
qryCurIt.close();
qryCurs.remove(req.queryId());
}
finally {
qryCurIt.unlock();
}
return new GridRestResponse(true);
}
catch (Exception e) {
removeQueryCursor(req.queryId(), qryCurs);
return new GridRestResponse(GridRestResponse.STATUS_FAILED, e.getMessage());
}
}
}
/**
* Fetch query callable.
*/
private static class FetchQueryCallable implements Callable<GridRestResponse> {
/** Current queries cursors. */
private final ConcurrentHashMap<Long, QueryCursorIterator> qryCurs;
/** Execute query request. */
private RestQueryRequest req;
/**
* @param req Execute query request.
* @param qryCurs Query cursors.
*/
public FetchQueryCallable(RestQueryRequest req, ConcurrentHashMap<Long, QueryCursorIterator> qryCurs) {
this.req = req;
this.qryCurs = qryCurs;
}
/** {@inheritDoc} */
@Override public GridRestResponse call() throws Exception {
try {
QueryCursorIterator qryCurIt = qryCurs.get(req.queryId());
if (qryCurIt == null)
return new GridRestResponse(GridRestResponse.STATUS_FAILED,
"Failed to find query with ID: " + req.queryId());
qryCurIt.lock();
try {
if (qryCurIt.timestamp() == -1)
return new GridRestResponse(GridRestResponse.STATUS_FAILED,
"Query is closed by timeout. Restart query with ID: " + req.queryId());
qryCurIt.timestamp(U.currentTimeMillis());
Iterator cur = qryCurIt.iterator();
CacheQueryResult res = createQueryResult(cur, req, req.queryId(), qryCurs);
return new GridRestResponse(res);
}
finally {
qryCurIt.unlock();
}
}
catch (Exception e) {
removeQueryCursor(req.queryId(), qryCurs);
return new GridRestResponse(GridRestResponse.STATUS_FAILED, e.getMessage());
}
}
}
/**
* Query cursor iterator.
*/
private static class QueryCursorIterator extends ReentrantLock {
/** */
private static final long serialVersionUID = 0L;
/** Query cursor. */
private QueryCursor cur;
/** Query iterator. */
private Iterator it;
/** Last timestamp. */
private volatile long ts;
/**
* @param cur Query cursor.
* @param it Query iterator.
*/
public QueryCursorIterator(QueryCursor cur, Iterator it) {
this.cur = cur;
this.it = it;
ts = U.currentTimeMillis();
}
/**
* @return Query iterator.
*/
public Iterator iterator() {
return it;
}
/**
* @return Timestamp.
*/
public long timestamp() {
return ts;
}
/**
* @param time Current time or -1 if cursor is closed.
*/
public void timestamp(long time) {
ts = time;
}
/**
* Close query cursor.
*/
public void close() {
cur.close();
}
}
}
| modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/query/QueryCommandHandler.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.internal.processors.rest.handlers.query;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteException;
import org.apache.ignite.cache.query.Query;
import org.apache.ignite.cache.query.QueryCursor;
import org.apache.ignite.cache.query.ScanQuery;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.cache.query.SqlQuery;
import org.apache.ignite.internal.GridKernalContext;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.processors.cache.QueryCursorImpl;
import org.apache.ignite.internal.processors.query.GridQueryFieldMetadata;
import org.apache.ignite.internal.processors.rest.GridRestCommand;
import org.apache.ignite.internal.processors.rest.GridRestResponse;
import org.apache.ignite.internal.processors.rest.handlers.GridRestCommandHandlerAdapter;
import org.apache.ignite.internal.processors.rest.request.GridRestRequest;
import org.apache.ignite.internal.processors.rest.request.RestQueryRequest;
import org.apache.ignite.internal.util.future.GridFinishedFuture;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteBiPredicate;
import static org.apache.ignite.internal.processors.rest.GridRestCommand.CLOSE_SQL_QUERY;
import static org.apache.ignite.internal.processors.rest.GridRestCommand.EXECUTE_SCAN_QUERY;
import static org.apache.ignite.internal.processors.rest.GridRestCommand.EXECUTE_SQL_FIELDS_QUERY;
import static org.apache.ignite.internal.processors.rest.GridRestCommand.EXECUTE_SQL_QUERY;
import static org.apache.ignite.internal.processors.rest.GridRestCommand.FETCH_SQL_QUERY;
/**
* Query command handler.
*/
public class QueryCommandHandler extends GridRestCommandHandlerAdapter {
/** Supported commands. */
private static final Collection<GridRestCommand> SUPPORTED_COMMANDS = U.sealList(EXECUTE_SQL_QUERY,
EXECUTE_SQL_FIELDS_QUERY,
EXECUTE_SCAN_QUERY,
FETCH_SQL_QUERY,
CLOSE_SQL_QUERY);
/** Query ID sequence. */
private static final AtomicLong qryIdGen = new AtomicLong();
/** Current queries cursors. */
private final ConcurrentHashMap<Long, QueryCursorIterator> qryCurs = new ConcurrentHashMap<>();
/**
* @param ctx Context.
*/
public QueryCommandHandler(GridKernalContext ctx) {
super(ctx);
final long idleQryCurTimeout = ctx.config().getConnectorConfiguration().getIdleQueryCursorTimeout();
long idleQryCurCheckFreq = ctx.config().getConnectorConfiguration().getIdleQueryCursorCheckFrequency();
ctx.timeout().schedule(new Runnable() {
@Override public void run() {
long time = U.currentTimeMillis();
for (Map.Entry<Long, QueryCursorIterator> e : qryCurs.entrySet()) {
QueryCursorIterator qryCurIt = e.getValue();
long createTime = qryCurIt.timestamp();
if (createTime + idleQryCurTimeout > time && qryCurIt.tryLock()) {
try {
qryCurIt.timestamp(-1);
qryCurs.remove(e.getKey(), qryCurIt);
qryCurIt.close();
}
finally {
qryCurIt.unlock();
}
}
}
}
}, idleQryCurCheckFreq, idleQryCurCheckFreq);
}
/**
* @param cur Current cursor.
* @param req Sql request.
* @param qryId Query id.
* @param qryCurs Query cursors.
* @return Query result with items.
*/
private static CacheQueryResult createQueryResult(
Iterator cur, RestQueryRequest req, Long qryId, ConcurrentHashMap<Long, QueryCursorIterator> qryCurs) {
CacheQueryResult res = new CacheQueryResult();
List<Object> items = new ArrayList<>();
for (int i = 0; i < req.pageSize() && cur.hasNext(); ++i)
items.add(cur.next());
res.setItems(items);
res.setLast(!cur.hasNext());
res.setQueryId(qryId);
if (!cur.hasNext())
removeQueryCursor(qryId, qryCurs);
return res;
}
/**
* Removes query cursor.
*
* @param qryId Query id.
* @param qryCurs Query cursors.
*/
private static void removeQueryCursor(Long qryId, ConcurrentHashMap<Long, QueryCursorIterator> qryCurs) {
QueryCursorIterator qryCurIt = qryCurs.get(qryId);
if (qryCurIt == null)
return;
qryCurIt.lock();
try {
if (qryCurIt.timestamp() == -1)
return;
qryCurIt.close();
qryCurs.remove(qryId);
}
finally {
qryCurIt.unlock();
}
}
/**
* Creates class instance.
*
* @param cls Target class.
* @param clsName Implementing class name.
* @return Class instance.
* @throws IgniteException If failed.
*/
private static <T> T instance(Class<? extends T> cls, String clsName) throws IgniteException {
try {
Class<?> implCls = Class.forName(clsName);
if (!cls.isAssignableFrom(implCls))
throw new IgniteException("Failed to create instance (target class does not extend or implement " +
"required class or interface) [cls=" + cls.getName() + ", clsName=" + clsName + ']');
Constructor<?> ctor = implCls.getConstructor();
return (T)ctor.newInstance();
}
catch (ClassNotFoundException e) {
throw new IgniteException("Failed to find target class: " + clsName, e);
}
catch (NoSuchMethodException e) {
throw new IgniteException("Failed to find constructor for provided arguments " +
"[clsName=" + clsName + ']', e);
}
catch (InstantiationException e) {
throw new IgniteException("Failed to instantiate target class " +
"[clsName=" + clsName + ']', e);
}
catch (IllegalAccessException e) {
throw new IgniteException("Failed to instantiate class (constructor is not available) " +
"[clsName=" + clsName + ']', e);
}
catch (InvocationTargetException e) {
throw new IgniteException("Failed to instantiate class (constructor threw an exception) " +
"[clsName=" + clsName + ']', e.getCause());
}
}
/** {@inheritDoc} */
@Override public Collection<GridRestCommand> supportedCommands() {
return SUPPORTED_COMMANDS;
}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<GridRestResponse> handleAsync(GridRestRequest req) {
assert req != null;
assert SUPPORTED_COMMANDS.contains(req.command());
assert req instanceof RestQueryRequest : "Invalid type of query request.";
switch (req.command()) {
case EXECUTE_SQL_QUERY:
case EXECUTE_SQL_FIELDS_QUERY:
case EXECUTE_SCAN_QUERY: {
return ctx.closure().callLocalSafe(
new ExecuteQueryCallable(ctx, (RestQueryRequest)req, qryCurs), false);
}
case FETCH_SQL_QUERY: {
return ctx.closure().callLocalSafe(
new FetchQueryCallable((RestQueryRequest)req, qryCurs), false);
}
case CLOSE_SQL_QUERY: {
return ctx.closure().callLocalSafe(
new CloseQueryCallable((RestQueryRequest)req, qryCurs), false);
}
}
return new GridFinishedFuture<>();
}
/**
* Execute query callable.
*/
private static class ExecuteQueryCallable implements Callable<GridRestResponse> {
/** Kernal context. */
private GridKernalContext ctx;
/** Execute query request. */
private RestQueryRequest req;
/** Current queries cursors. */
private final ConcurrentHashMap<Long, QueryCursorIterator> qryCurs;
/**
* @param ctx Kernal context.
* @param req Execute query request.
* @param qryCurs Query cursors.
*/
public ExecuteQueryCallable(GridKernalContext ctx, RestQueryRequest req,
ConcurrentHashMap<Long, QueryCursorIterator> qryCurs) {
this.ctx = ctx;
this.req = req;
this.qryCurs = qryCurs;
}
/** {@inheritDoc} */
@Override public GridRestResponse call() throws Exception {
final long qryId = qryIdGen.getAndIncrement();
try {
Query qry;
switch (req.queryType()) {
case SQL:
qry = new SqlQuery(req.typeName(), req.sqlQuery());
((SqlQuery)qry).setArgs(req.arguments());
break;
case SQL_FIELDS:
qry = new SqlFieldsQuery(req.sqlQuery());
((SqlFieldsQuery)qry).setArgs(req.arguments());
break;
case SCAN:
IgniteBiPredicate pred = null;
if (req.className() != null)
pred = instance(IgniteBiPredicate.class, req.className());
qry = new ScanQuery(pred);
break;
default:
throw new IgniteException("Incorrect query type [type=" + req.queryType() + "]");
}
IgniteCache<Object, Object> cache = ctx.grid().cache(req.cacheName());
if (cache == null)
return new GridRestResponse(GridRestResponse.STATUS_FAILED,
"Failed to find cache with name: " + req.cacheName());
final QueryCursor qryCur = cache.query(qry);
Iterator cur = qryCur.iterator();
QueryCursorIterator qryCurIt = new QueryCursorIterator(qryCur, cur);
qryCurIt.lock();
try {
qryCurs.put(qryId, qryCurIt);
CacheQueryResult res = createQueryResult(cur, req, qryId, qryCurs);
switch (req.queryType()) {
case SQL:
case SQL_FIELDS:
List<GridQueryFieldMetadata> fieldsMeta = ((QueryCursorImpl)qryCur).fieldsMeta();
res.setFieldsMetadata(convertMetadata(fieldsMeta));
break;
case SCAN:
CacheQueryFieldsMetaResult keyField = new CacheQueryFieldsMetaResult();
keyField.setFieldName("key");
CacheQueryFieldsMetaResult valField = new CacheQueryFieldsMetaResult();
valField.setFieldName("value");
res.setFieldsMetadata(U.sealList(keyField, valField));
break;
}
return new GridRestResponse(res);
}
finally {
qryCurIt.unlock();
}
}
catch (Exception e) {
removeQueryCursor(qryId, qryCurs);
return new GridRestResponse(GridRestResponse.STATUS_FAILED, e.getMessage());
}
}
/**
* @param meta Internal query field metadata.
* @return Rest query field metadata.
*/
private Collection<CacheQueryFieldsMetaResult> convertMetadata(Collection<GridQueryFieldMetadata> meta) {
List<CacheQueryFieldsMetaResult> res = new ArrayList<>();
if (meta != null) {
for (GridQueryFieldMetadata info : meta)
res.add(new CacheQueryFieldsMetaResult(info));
}
return res;
}
}
/**
* Close query callable.
*/
private static class CloseQueryCallable implements Callable<GridRestResponse> {
/** Current queries cursors. */
private final ConcurrentHashMap<Long, QueryCursorIterator> qryCurs;
/** Execute query request. */
private RestQueryRequest req;
/**
* @param req Execute query request.
* @param qryCurs Query cursors.
*/
public CloseQueryCallable(RestQueryRequest req, ConcurrentHashMap<Long, QueryCursorIterator> qryCurs) {
this.req = req;
this.qryCurs = qryCurs;
}
/** {@inheritDoc} */
@Override public GridRestResponse call() throws Exception {
try {
QueryCursorIterator qryCurIt = qryCurs.get(req.queryId());
if (qryCurIt == null)
return new GridRestResponse(true);
qryCurIt.lock();
try {
if (qryCurIt.timestamp() == -1)
return new GridRestResponse(true);
qryCurIt.close();
qryCurs.remove(req.queryId());
}
finally {
qryCurIt.unlock();
}
return new GridRestResponse(true);
}
catch (Exception e) {
removeQueryCursor(req.queryId(), qryCurs);
return new GridRestResponse(GridRestResponse.STATUS_FAILED, e.getMessage());
}
}
}
/**
* Fetch query callable.
*/
private static class FetchQueryCallable implements Callable<GridRestResponse> {
/** Current queries cursors. */
private final ConcurrentHashMap<Long, QueryCursorIterator> qryCurs;
/** Execute query request. */
private RestQueryRequest req;
/**
* @param req Execute query request.
* @param qryCurs Query cursors.
*/
public FetchQueryCallable(RestQueryRequest req, ConcurrentHashMap<Long, QueryCursorIterator> qryCurs) {
this.req = req;
this.qryCurs = qryCurs;
}
/** {@inheritDoc} */
@Override public GridRestResponse call() throws Exception {
try {
QueryCursorIterator qryCurIt = qryCurs.get(req.queryId());
if (qryCurIt == null)
return new GridRestResponse(GridRestResponse.STATUS_FAILED,
"Failed to find query with ID: " + req.queryId());
qryCurIt.lock();
try {
if (qryCurIt.timestamp() == -1)
return new GridRestResponse(GridRestResponse.STATUS_FAILED,
"Query is closed by timeout. Restart query with ID: " + req.queryId());
qryCurIt.timestamp(U.currentTimeMillis());
Iterator cur = qryCurIt.iterator();
CacheQueryResult res = createQueryResult(cur, req, req.queryId(), qryCurs);
return new GridRestResponse(res);
}
finally {
qryCurIt.unlock();
}
}
catch (Exception e) {
removeQueryCursor(req.queryId(), qryCurs);
return new GridRestResponse(GridRestResponse.STATUS_FAILED, e.getMessage());
}
}
}
/**
* Query cursor iterator.
*/
private static class QueryCursorIterator extends ReentrantLock {
/** */
private static final long serialVersionUID = 0L;
/** Query cursor. */
private QueryCursor cur;
/** Query iterator. */
private Iterator it;
/** Last timestamp. */
private volatile long ts;
/**
* @param cur Query cursor.
* @param it Query iterator.
*/
public QueryCursorIterator(QueryCursor cur, Iterator it) {
this.cur = cur;
this.it = it;
ts = U.currentTimeMillis();
}
/**
* @return Query iterator.
*/
public Iterator iterator() {
return it;
}
/**
* @return Timestamp.
*/
public long timestamp() {
return ts;
}
/**
* @param time Current time or -1 if cursor is closed.
*/
public void timestamp(long time) {
ts = time;
}
/**
* Close query cursor.
*/
public void close() {
cur.close();
}
}
}
| IGNITE-1161 Typo.
| modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/query/QueryCommandHandler.java | IGNITE-1161 Typo. | <ide><path>odules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/query/QueryCommandHandler.java
<ide>
<ide> long createTime = qryCurIt.timestamp();
<ide>
<del> if (createTime + idleQryCurTimeout > time && qryCurIt.tryLock()) {
<add> if (time > createTime + idleQryCurTimeout && qryCurIt.tryLock()) {
<ide> try {
<ide> qryCurIt.timestamp(-1);
<ide> |
|
Java | apache-2.0 | 9f688b68763860ddd6f622945987986f24df53b7 | 0 | pranavpandey/small-app-support | /*
* Copyright (C) 2016 Pranav Pandey
*
* 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.pranavpandey.smallapp.database;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v4.util.Pair;
import android.widget.Toast;
/**
* Database helper functions to manage file and intent association. If
* user selects to save preferences then, this class will be used to save
* the selected app and automatically open it again when next time user
* launches the same file or intent.
*
* It has all the basic functions to read, create update and delete the
* saved apps.
*/
public class Associations {
/**
* SQLiteOpenHelper object to perform database operations
*/
private final SQLiteHelper mSQLiteHelper;
/**
* Initialize associations before performing any operation. It will
* initialize the SQLiteHelper and setup the database so that we can
* perform read and write operations.
*/
public Associations(Context context) {
if (context == null) {
throw new NullPointerException("Context should not be null");
}
mSQLiteHelper = new SQLiteHelper(context);
}
/**
* Get instance of {@link #mSQLiteHelper}.
*/
public SQLiteHelper getHelper() {
return mSQLiteHelper;
}
/**
* A SQLiteOpenHelper class to perform read, create update and delete
* operations on our database to manage file or intent associations.
*/
public static class SQLiteHelper extends SQLiteOpenHelper {
/**
* Name of the database.
*/
private static final String DB_NAME = "Assocations";
/**
* Name of the table in which we have to store associations.
*/
private static final String TABLE_NAME = "associations";
/**
* Name of the Key Column in which we store intent or file type.
*/
private static final String COL_KEY = "intent_type";
/**
* Name of the Value Column in which we store associated package name.
*/
private static final String COL_VALUE = "intent_package";
/**
* Version of the database.
*/
private static final int VERSION = 1;
/**
* Context to retrieve resources.
*/
private Context context;
public SQLiteHelper(Context context) {
super(context, DB_NAME, null, VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXIST " + TABLE_NAME +
" ( " + COL_KEY + " text primary key not null, " +
COL_VALUE + " text null);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
/**
* Insert a <key, value> pair into the database.
*
* @param key to be inserted.
* @param value of the key.
*
* @return <code>true</code> if inserts successfully.
*/
public boolean put(String key, String value) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("INSERT OR REPLACE INTO " + TABLE_NAME +
" (" + COL_KEY + ", " + COL_VALUE + ") " +
" VALUES('" + key + "', '" + value + "')");
db.close();
return true;
}
/**
* Insert a list of <key, value> pairs into the database.
*
* @param list if pairs.
*
* @return <code>true</code> if inserts successfully.
*/
public boolean put(List<Pair<String, ?>> list) {
SQLiteDatabase db = getWritableDatabase();
boolean result = true;
try {
db.beginTransaction();
for (Pair<String, ?> pair : list) {
db.execSQL("INSERT OR REPLACE INTO " + TABLE_NAME +
" (" + COL_KEY + ", " + COL_VALUE + ") " +
" VALUES('" + pair.first + "', '" + String.valueOf(pair.second) + "')");
}
db.setTransactionSuccessful();
} catch (Exception e) {
result = false;
} finally {
db.endTransaction();
db.close();
}
return result;
}
/**
* Delete a entry form the database.
*
* @param key to be deleted.
*
* @return <code>true</code> if deletes successfully.
*/
public boolean delete(String key) {
SQLiteDatabase db = getWritableDatabase();
int count = db.delete(TABLE_NAME, COL_KEY + "='" + key + "'", null);
db.close();
return count != -1;
}
/**
* Delete multiple entries form the database.
*
* @param keys to be deleted.
*
* @return <code>true</code> if deletes successfully.
*/
public boolean delete(String... keys) {
SQLiteDatabase db = getWritableDatabase();
boolean result = true;
try {
db.beginTransaction();
for (String key : keys) {
if (key == null) {
continue;
}
db.delete(TABLE_NAME, COL_KEY + "='" + key + "'", null);
}
db.setTransactionSuccessful();
} catch (Exception e) {
result = false;
} finally {
db.endTransaction();
db.close();
}
return result;
}
/**
* Check if a key already exist in the database or not.
*
* @param key to check.
*
* @return <code>true</code> key of same name already exist.
*/
public boolean contains(String key) {
return get(key) != null;
}
/**
* Retrieve the value of a key from the database.
*
* @param key to retrieve value.
*
* @return Value of the key.
*/
public String get(String key) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME +
" WHERE " + COL_KEY + " = '" + key + "'", null);
if (cursor == null) {
return null;
}
cursor.moveToFirst();
if (cursor.getCount() == 0) {
return null;
}
String value = cursor.getString(1);
cursor.close();
db.close();
return value;
}
/**
* Clear all the entries and associations in the database.
*
* @param showToast <code>true</code> to show a toast to notify
* user.
*/
public boolean clearAll(boolean showToast) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME);
db.close();
if (showToast) {
Toast.makeText(context, com.pranavpandey.smallapp.R.string.sas_clear_defaults_reset,
Toast.LENGTH_SHORT).show();
}
return true;
}
/**
* @return No. of entries in the database.
*/
public long count() {
SQLiteDatabase db = getWritableDatabase();
long count = DatabaseUtils.queryNumEntries(db, TABLE_NAME);
db.close();
return count;
}
}
}
| eclipse/library/src/com/pranavpandey/smallapp/database/Associations.java | /*
* Copyright (C) 2016 Pranav Pandey
*
* 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.pranavpandey.smallapp.database;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v4.util.Pair;
import android.widget.Toast;
/**
* Database helper functions to manage file and intent association. If
* user selects to save preferences then, this class will be used to save
* the selected app and automatically open it again when next time user
* launches the same file or intent.
*
* It has all the basic functions to read, create update and delete the
* saved apps.
*/
public class Associations {
/**
* SQLiteOpenHelper object to perform database operations
*/
private final SQLiteHelper mSQLiteHelper;
/**
* Initialize associations before performing any operation. It will
* initialize the SQLiteHelper and setup the database so that we can
* perform read and write operations.
*/
public Associations(Context context) {
if (context == null) {
throw new NullPointerException("Context should not be null");
}
mSQLiteHelper = new SQLiteHelper(context);
}
/**
* Get instance of {@link #mSQLiteHelper}.
*/
public SQLiteHelper getHelper() {
return mSQLiteHelper;
}
/**
* A SQLiteOpenHelper class to perform read, create update and delete
* operations on our database to manage file or intent associations.
*/
public static class SQLiteHelper extends SQLiteOpenHelper {
/**
* Name of the database.
*/
private static final String DB_NAME = "Assocations";
/**
* Name of the table in which we have to store associations.
*/
private static final String TABLE_NAME = "associations";
/**
* Name of the Key Column in which we store intent or file type.
*/
private static final String COL_KEY = "intent_type";
/**
* Name of the Value Column in which we store associated package name.
*/
private static final String COL_VALUE = "intent_package";
/**
* Version of the database.
*/
private static final int VERSION = 1;
/**
* Context to retrieve resources.
*/
private Context context;
public SQLiteHelper(Context context) {
super(context, DB_NAME, null, VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXIST " + TABLE_NAME +
" ( " + COL_KEY + " text primary key not null, " +
COL_VALUE + " text null);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
/**
* Insert a <key, value> pair into the database.
*
* @param key to be inserted.
* @param value of the key.
*
* @return <code>true</code> if inserts successfully.
*/
public boolean put(String key, String value) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("INSERT OR REPLACE INTO " + TABLE_NAME +
" (" + COL_KEY + ", " + COL_VALUE + ") " +
" VALUES('" + key + "', '" + value + "')");
db.close();
return true;
}
/**
* Insert a list of <key, value> pairs into the database.
*
* @param list if pairs.
*
* @return <code>true</code> if inserts successfully.
*/
public boolean put(List<Pair<String, ?>> list) {
SQLiteDatabase db = getWritableDatabase();
boolean result = true;
try {
db.beginTransaction();
for (Pair<String, ?> pair : list) {
db.execSQL("INSERT OR REPLACE INTO " + TABLE_NAME +
" (" + COL_KEY + ", " + COL_VALUE + ") " +
" VALUES('" + pair.first + "', '" + String.valueOf(pair.second) + "')");
}
db.setTransactionSuccessful();
} catch (Exception e) {
result = false;
} finally {
db.endTransaction();
db.close();
}
return result;
}
/**
* Delete a entry form the database.
*
* @param key to be deleted.
*
* @return <code>true</code> if deletes successfully.
*/
public boolean delete(String key) {
SQLiteDatabase db = getWritableDatabase();
int count = db.delete(TABLE_NAME, COL_KEY + "='" + key + "'", null);
db.close();
return count != -1;
}
/**
* Delete multiple entries form the database.
*
* @param keys to be deleted.
*
* @return <code>true</code> if deletes successfully.
*/
public boolean delete(String... keys) {
SQLiteDatabase db = getWritableDatabase();
boolean result = true;
try {
db.beginTransaction();
for (String key : keys) {
if (key == null) {
continue;
}
db.delete(TABLE_NAME, COL_KEY + "='" + key + "'", null);
}
db.setTransactionSuccessful();
} catch (Exception e) {
result = false;
} finally {
db.endTransaction();
db.close();
}
return result;
}
/**
* Check if a key already exist in the database or not.
*
* @param key to check.
*
* @return <code>true</code> key of same name already exist.
*/
public boolean contains(String key) {
return get(key) != null;
}
/**
* Retrieve the value of a key from the database.
*
* @param key to retrieve value.
*
* @return Value of the key.
*/
public String get(String key) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME +
" WHERE " + COL_KEY + " = '" + key + "'", null);
if (cursor == null) {
return null;
}
cursor.moveToFirst();
if (cursor.getCount() == 0) {
return null;
}
String value = cursor.getString(1);
cursor.close();
db.close();
return value;
}
/**
* Clear all the entries and associations in the database.
*
* @param showToast <code>true</code> to show a toast to notify
* user.
*/
public boolean clearAll(boolean showToast) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME);
db.close();
if (showToast) {
Toast.makeText(context, com.pranavpandey.smallapp.R.string.sas_clear_defaults_reset,
Toast.LENGTH_SHORT).show();
}
return true;
}
/**
* @return No. of entries in the database.
*/
public long count() {
SQLiteDatabase db = getWritableDatabase();
long count = DatabaseUtils.queryNumEntries(db, TABLE_NAME);
db.close();
return count;
}
}
}
| Update Associations | eclipse/library/src/com/pranavpandey/smallapp/database/Associations.java | Update Associations | <ide><path>clipse/library/src/com/pranavpandey/smallapp/database/Associations.java
<ide>
<ide> @Override
<ide> public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
<del> db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
<del> onCreate(db);
<del> }
<add> db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
<add> onCreate(db);
<add> }
<ide>
<ide> /**
<ide> * Insert a <key, value> pair into the database. |
|
Java | mit | 31bcac4e77130d388d2826c3a0874aee73af9160 | 0 | GluuFederation/oxAuth,GluuFederation/oxAuth,GluuFederation/oxAuth,GluuFederation/oxAuth,GluuFederation/oxAuth | Server/src/main/java/org/xdi/oxauth/exception/GlobalExceptionMapper.java | package org.xdi.oxauth.exception;
import org.slf4j.Logger;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
/**
* @author Yuriy Zabrovarnyy
*/
@ApplicationScoped
@Provider
public class GlobalExceptionMapper implements ExceptionMapper<WebApplicationException> {
@Inject
private Logger log;
@Override
public Response toResponse(WebApplicationException ex) {
log.trace("Handle WebApplicationException", ex);
return ex.getResponse();
}
}
| Don't catch internal resteasy exception | Server/src/main/java/org/xdi/oxauth/exception/GlobalExceptionMapper.java | Don't catch internal resteasy exception | <ide><path>erver/src/main/java/org/xdi/oxauth/exception/GlobalExceptionMapper.java
<del>package org.xdi.oxauth.exception;
<del>
<del>import org.slf4j.Logger;
<del>
<del>import javax.enterprise.context.ApplicationScoped;
<del>import javax.inject.Inject;
<del>import javax.ws.rs.WebApplicationException;
<del>import javax.ws.rs.core.Response;
<del>import javax.ws.rs.ext.ExceptionMapper;
<del>import javax.ws.rs.ext.Provider;
<del>
<del>/**
<del> * @author Yuriy Zabrovarnyy
<del> */
<del>@ApplicationScoped
<del>@Provider
<del>public class GlobalExceptionMapper implements ExceptionMapper<WebApplicationException> {
<del>
<del> @Inject
<del> private Logger log;
<del>
<del> @Override
<del> public Response toResponse(WebApplicationException ex) {
<del> log.trace("Handle WebApplicationException", ex);
<del>
<del> return ex.getResponse();
<del> }
<del>
<del>}
<del> |
||
Java | lgpl-2.1 | 35947c41b12dcc66465cf63303f8cd4d2ecace8e | 0 | spotbugs/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,KengoTODA/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,johnscancella/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,sewe/spotbugs | /*
* FindBugs - Find bugs in Java programs
* Copyright (C) 2003, University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* FindBugsFrame.java
*
* Created on March 30, 2003, 12:05 PM
*/
package edu.umd.cs.findbugs.gui;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Shape;
import java.awt.Rectangle;
import java.awt.Point;
import java.awt.Color;
import java.io.File;
import java.io.StringWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.StringReader;
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.filechooser.*;
import edu.umd.cs.daveho.ba.SourceFinder;
import edu.umd.cs.findbugs.*;
/**
* The main GUI frame for FindBugs.
*
* @author David Hovemeyer
*/
public class FindBugsFrame extends javax.swing.JFrame {
/* ----------------------------------------------------------------------
* Helper classes
* ---------------------------------------------------------------------- */
private static final Color HIGH_PRIORITY_COLOR = new Color(0xff0000);
private static final Color NORMAL_PRIORITY_COLOR = new Color(0x9f0000);
private static final Color LOW_PRIORITY_COLOR = Color.BLACK;
/**
* Custom cell renderer for the bug tree.
* We use this to select the tree icons, and to set the
* text color based on the bug priority.
*/
private static class BugCellRenderer extends DefaultTreeCellRenderer {
private ImageIcon bugGroupIcon;
private ImageIcon packageIcon;
private ImageIcon bugIcon;
private ImageIcon classIcon;
private ImageIcon methodIcon;
private ImageIcon fieldIcon;
private ImageIcon sourceFileIcon;
private Object value;
public BugCellRenderer() {
ClassLoader classLoader = this.getClass().getClassLoader();
bugGroupIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/bug.png"));
packageIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/package.png"));
bugIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/bug2.png"));
classIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/class.png"));
methodIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/method.png"));
fieldIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/field.png"));
sourceFileIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/sourcefile.png"));
}
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel,
boolean expanded, boolean leaf, int row, boolean hasFocus) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
Object obj = node.getUserObject();
this.value = obj;
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
// Set the icon, depending on what kind of node it is
if (obj instanceof BugInstance) {
setIcon(bugIcon);
} else if (obj instanceof ClassAnnotation) {
setIcon(classIcon);
} else if (obj instanceof MethodAnnotation) {
setIcon(methodIcon);
} else if (obj instanceof FieldAnnotation) {
setIcon(fieldIcon);
} else if (obj instanceof SourceLineAnnotation) {
setIcon(sourceFileIcon);
} else if (obj instanceof BugInstanceGroup) {
// This is a "group" node
BugInstanceGroup groupNode = (BugInstanceGroup) obj;
String groupType = groupNode.getGroupType();
if (groupType == GROUP_BY_CLASS) {
setIcon(classIcon);
} else if (groupType == GROUP_BY_PACKAGE) {
setIcon(packageIcon);
} else if (groupType == GROUP_BY_BUG_TYPE) {
setIcon(bugGroupIcon);
}
} else {
setIcon(null);
}
return this;
}
public Color getTextNonSelectionColor() {
return getCellTextColor();
}
private Color getCellTextColor() {
// Based on the priority, color-code the bug instance.
Color color = Color.BLACK;
if (value instanceof BugInstance) {
BugInstance bugInstance = (BugInstance) value;
switch (bugInstance.getPriority()) {
case Detector.LOW_PRIORITY:
color = LOW_PRIORITY_COLOR; break;
case Detector.NORMAL_PRIORITY:
color = NORMAL_PRIORITY_COLOR; break;
case Detector.HIGH_PRIORITY:
color = HIGH_PRIORITY_COLOR; break;
}
}
return color;
}
}
/** The instance of BugCellRenderer. */
private static final FindBugsFrame.BugCellRenderer bugCellRenderer = new FindBugsFrame.BugCellRenderer();
/**
* Tree node type for BugInstances.
* We use this instead of plain DefaultMutableTreeNodes in order to
* get more control over the exact text that is shown in the tree.
*/
private class BugTreeNode extends DefaultMutableTreeNode {
private int count;
public BugTreeNode(BugInstance bugInstance) {
super(bugInstance);
count = -1;
}
public void setCount(int count) {
this.count = count;
}
public String toString() {
try {
BugInstance bugInstance = (BugInstance) getUserObject();
StringBuffer result = new StringBuffer();
if (count >= 0) {
result.append(count);
result.append(": ");
}
if (bugInstance.isExperimental())
result.append("EXP: ");
result.append(fullDescriptionsItem.isSelected() ? bugInstance.getMessage() : bugInstance.toString());
return result.toString();
} catch (Exception e) {
return "Error formatting message for bug: " + e.toString();
}
}
}
/**
* Compare BugInstance class names.
* This is useful for grouping bug instances by class.
* Note that all instances with the same class name will compare
* as equal.
*/
private static class BugInstanceClassComparator implements Comparator<BugInstance> {
public int compare(BugInstance lhs, BugInstance rhs) {
return lhs.getPrimaryClass().compareTo(rhs.getPrimaryClass());
}
}
/** The instance of BugInstanceClassComparator. */
private static final Comparator<BugInstance> bugInstanceClassComparator = new BugInstanceClassComparator();
/**
* Compare BugInstance package names.
* This is useful for grouping bug instances by package.
* Note that all instances with the same package name will compare
* as equal.
*/
private static class BugInstancePackageComparator implements Comparator<BugInstance> {
public int compare(BugInstance lhs, BugInstance rhs) {
return lhs.getPrimaryClass().getPackageName().compareTo(
rhs.getPrimaryClass().getPackageName());
}
}
/** The instance of BugInstancePackageComparator. */
private static final Comparator<BugInstance> bugInstancePackageComparator = new BugInstancePackageComparator();
/**
* Compare BugInstance bug types.
* This is useful for grouping bug instances by bug type.
* Note that all instances with the same bug type will compare
* as equal.
*/
private static class BugInstanceTypeComparator implements Comparator<BugInstance> {
public int compare(BugInstance lhs, BugInstance rhs) {
String lhsString = lhs.toString();
String rhsString = rhs.toString();
return lhsString.substring(0, lhsString.indexOf(':')).compareTo(
rhsString.substring(0, rhsString.indexOf(':')));
}
}
/** The instance of BugInstanceTypeComparator. */
private static final Comparator<BugInstance> bugInstanceTypeComparator = new BugInstanceTypeComparator();
/**
* Two-level comparison of bug instances by class name and
* BugInstance natural ordering.
*/
private static class BugInstanceByClassComparator implements Comparator<BugInstance> {
public int compare(BugInstance a, BugInstance b) {
int cmp = bugInstanceClassComparator.compare(a, b);
if (cmp != 0)
return cmp;
return a.compareTo(b);
}
}
/** The instance of BugInstanceByClassComparator. */
private static final Comparator<BugInstance> bugInstanceByClassComparator = new FindBugsFrame.BugInstanceByClassComparator();
/**
* Two-level comparison of bug instances by package and
* BugInstance natural ordering.
*/
private static class BugInstanceByPackageComparator implements Comparator<BugInstance> {
public int compare(BugInstance a, BugInstance b) {
int cmp = bugInstancePackageComparator.compare(a, b);
if (cmp != 0)
return cmp;
return a.compareTo(b);
}
}
/** The instance of BugInstanceByPackageComparator. */
private static final Comparator<BugInstance> bugInstanceByPackageComparator = new FindBugsFrame.BugInstanceByPackageComparator();
/**
* Two-level comparison of bug instances by bug type and
* BugInstance natural ordering.
*/
private static class BugInstanceByTypeComparator implements Comparator<BugInstance> {
public int compare(BugInstance a, BugInstance b) {
int cmp = bugInstanceTypeComparator.compare(a, b);
if (cmp != 0)
return cmp;
return a.compareTo(b);
}
}
/** The instance of BugTypeByTypeComparator. */
private static final Comparator<BugInstance> bugInstanceByTypeComparator = new FindBugsFrame.BugInstanceByTypeComparator();
/**
* Swing FileFilter class for file selection dialogs for FindBugs project files.
*/
private static class ProjectFileFilter extends FileFilter {
public boolean accept(File file) { return file.isDirectory() || file.getName().endsWith(".fb"); }
public String getDescription() { return "FindBugs projects (*.fb)"; }
}
/** The instance of ProjectFileFilter. */
private static final FileFilter projectFileFilter = new ProjectFileFilter();
/**
* Swing FileFilter for choosing an auxiliary classpath entry.
* Both Jar files and directories can be chosen.
*/
private static class AuxClasspathEntryFileFilter extends FileFilter {
public boolean accept(File file) { return file.isDirectory() || file.getName().endsWith(".jar"); }
public String getDescription() { return "Jar files and directories"; }
}
/** The instance of AuxClasspathEntryFileFilter. */
private static final FileFilter auxClasspathEntryFileFilter = new AuxClasspathEntryFileFilter();
/**
* Swing FileFilter for choosing XML saved bug files.
*/
private static class XMLFileFilter extends FileFilter {
public boolean accept(File file) { return file.isDirectory() || file.getName().endsWith(".xml"); }
public String getDescription() { return "XML saved bug files"; }
}
/** The instance of XMLFileFilter. */
private static final FileFilter xmlFileFilter = new XMLFileFilter();
/* ----------------------------------------------------------------------
* Constants
* ---------------------------------------------------------------------- */
private static final String DEFAULT_PROJECT_NAME = Project.UNNAMED_PROJECT;
private static final String GROUP_BY_CLASS = "By class";
private static final String GROUP_BY_PACKAGE = "By package";
private static final String GROUP_BY_BUG_TYPE = "By bug type";
private static final String[] GROUP_BY_ORDER_LIST = {
GROUP_BY_CLASS, GROUP_BY_PACKAGE, GROUP_BY_BUG_TYPE
};
/**
* A fudge value required in our hack to get the REAL maximum
* divider location for a JSplitPane. Experience suggests that
* the value "1" would work here, but setting it a little higher
* makes the code a bit more robust.
*/
private static final int DIVIDER_FUDGE = 3;
private static final boolean BUG_COUNT = Boolean.getBoolean("findbugs.gui.bugCount");
/* ----------------------------------------------------------------------
* Constructor
* ---------------------------------------------------------------------- */
/** Creates new form FindBugsFrame. */
public FindBugsFrame() {
initComponents();
postInitComponents();
}
/* ----------------------------------------------------------------------
* Component initialization and event handlers
* ---------------------------------------------------------------------- */
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
private void initComponents() {//GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
consoleSplitter = new javax.swing.JSplitPane();
viewPanel = new javax.swing.JPanel();
emptyPanel = new javax.swing.JPanel();
reportPanel = new javax.swing.JPanel();
editProjectPanel = new javax.swing.JPanel();
jarFileLabel = new javax.swing.JLabel();
jarNameTextField = new javax.swing.JTextField();
addJarButton = new javax.swing.JButton();
jarFileListLabel = new javax.swing.JLabel();
sourceDirLabel = new javax.swing.JLabel();
srcDirTextField = new javax.swing.JTextField();
addSourceDirButton = new javax.swing.JButton();
sourceDirListLabel = new javax.swing.JLabel();
removeJarButton = new javax.swing.JButton();
removeSrcDirButton = new javax.swing.JButton();
jSeparator1 = new javax.swing.JSeparator();
browseJarButton = new javax.swing.JButton();
browseSrcDirButton = new javax.swing.JButton();
editProjectLabel = new javax.swing.JLabel();
jSeparator2 = new javax.swing.JSeparator();
findBugsButton = new javax.swing.JButton();
jSeparator4 = new javax.swing.JSeparator();
jarFileListScrollPane = new javax.swing.JScrollPane();
jarFileList = new javax.swing.JList();
sourceDirListScrollPane = new javax.swing.JScrollPane();
sourceDirList = new javax.swing.JList();
classpathEntryLabel = new javax.swing.JLabel();
classpathEntryListLabel = new javax.swing.JLabel();
classpathEntryTextField = new javax.swing.JTextField();
browseClasspathEntryButton = new javax.swing.JButton();
addClasspathEntryButton = new javax.swing.JButton();
removeClasspathEntryButton = new javax.swing.JButton();
classpathEntryListScrollPane = new javax.swing.JScrollPane();
classpathEntryList = new javax.swing.JList();
jSeparator5 = new javax.swing.JSeparator();
bugTreePanel = new javax.swing.JPanel();
bugTreeBugDetailsSplitter = new javax.swing.JSplitPane();
groupByTabbedPane = new javax.swing.JTabbedPane();
byClassScrollPane = new javax.swing.JScrollPane();
byClassBugTree = new javax.swing.JTree();
byPackageScrollPane = new javax.swing.JScrollPane();
byPackageBugTree = new javax.swing.JTree();
byBugTypeScrollPane = new javax.swing.JScrollPane();
byBugTypeBugTree = new javax.swing.JTree();
bySummary = new javax.swing.JScrollPane();
bugSummaryEditorPane = new javax.swing.JEditorPane();
bugDetailsTabbedPane = new javax.swing.JTabbedPane();
bugDescriptionScrollPane = new javax.swing.JScrollPane();
bugDescriptionEditorPane = new javax.swing.JEditorPane();
sourceTextAreaScrollPane = new javax.swing.JScrollPane();
sourceTextArea = new javax.swing.JTextArea();
annotationTextAreaScrollPane = new javax.swing.JScrollPane();
annotationTextArea = new javax.swing.JTextArea();
consoleScrollPane = new javax.swing.JScrollPane();
consoleMessageArea = new javax.swing.JTextArea();
theMenuBar = new javax.swing.JMenuBar();
fileMenu = new javax.swing.JMenu();
newProjectItem = new javax.swing.JMenuItem();
openProjectItem = new javax.swing.JMenuItem();
saveProjectItem = new javax.swing.JMenuItem();
saveProjectAsItem = new javax.swing.JMenuItem();
reloadProjectItem = new javax.swing.JMenuItem();
closeProjectItem = new javax.swing.JMenuItem();
jSeparator3 = new javax.swing.JSeparator();
loadBugsItem = new javax.swing.JMenuItem();
saveBugsItem = new javax.swing.JMenuItem();
jSeparator6 = new javax.swing.JSeparator();
exitItem = new javax.swing.JMenuItem();
viewMenu = new javax.swing.JMenu();
viewConsoleItem = new javax.swing.JCheckBoxMenuItem();
viewBugDetailsItem = new javax.swing.JCheckBoxMenuItem();
fullDescriptionsItem = new javax.swing.JCheckBoxMenuItem();
jSeparator7 = new javax.swing.JSeparator();
lowPriorityButton = new javax.swing.JRadioButtonMenuItem();
mediumPriorityButton = new javax.swing.JRadioButtonMenuItem();
highPriorityButton = new javax.swing.JRadioButtonMenuItem();
settingsMenu = new javax.swing.JMenu();
configureDetectorsItem = new javax.swing.JMenuItem();
helpMenu = new javax.swing.JMenu();
aboutItem = new javax.swing.JMenuItem();
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
consoleSplitter.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
consoleSplitter.setResizeWeight(1.0);
consoleSplitter.setOneTouchExpandable(true);
consoleSplitter.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
consoleSplitterPropertyChange(evt);
}
});
viewPanel.setLayout(new java.awt.CardLayout());
viewPanel.add(emptyPanel, "EmptyPanel");
viewPanel.add(reportPanel, "ReportPanel");
editProjectPanel.setLayout(new java.awt.GridBagLayout());
jarFileLabel.setFont(new java.awt.Font("Dialog", 0, 12));
jarFileLabel.setText("Archive or directory:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(jarFileLabel, gridBagConstraints);
jarNameTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jarNameTextFieldActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0);
editProjectPanel.add(jarNameTextField, gridBagConstraints);
addJarButton.setFont(new java.awt.Font("Dialog", 0, 12));
addJarButton.setText("Add");
addJarButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addJarButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(addJarButton, gridBagConstraints);
jarFileListLabel.setFont(new java.awt.Font("Dialog", 0, 12));
jarFileListLabel.setText("Archives/directories:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(jarFileListLabel, gridBagConstraints);
sourceDirLabel.setFont(new java.awt.Font("Dialog", 0, 12));
sourceDirLabel.setText("Source directory:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 6;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(sourceDirLabel, gridBagConstraints);
srcDirTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
srcDirTextFieldActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 6;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0);
editProjectPanel.add(srcDirTextField, gridBagConstraints);
addSourceDirButton.setFont(new java.awt.Font("Dialog", 0, 12));
addSourceDirButton.setText("Add");
addSourceDirButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addSourceDirButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 6;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(addSourceDirButton, gridBagConstraints);
sourceDirListLabel.setFont(new java.awt.Font("Dialog", 0, 12));
sourceDirListLabel.setText("Source directories:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 7;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(sourceDirListLabel, gridBagConstraints);
removeJarButton.setFont(new java.awt.Font("Dialog", 0, 12));
removeJarButton.setText("Remove");
removeJarButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeJarButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(removeJarButton, gridBagConstraints);
removeSrcDirButton.setFont(new java.awt.Font("Dialog", 0, 12));
removeSrcDirButton.setText("Remove");
removeSrcDirButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeSrcDirButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 7;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(removeSrcDirButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
editProjectPanel.add(jSeparator1, gridBagConstraints);
browseJarButton.setFont(new java.awt.Font("Dialog", 0, 12));
browseJarButton.setText("Browse");
browseJarButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
browseJarButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 3;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(browseJarButton, gridBagConstraints);
browseSrcDirButton.setFont(new java.awt.Font("Dialog", 0, 12));
browseSrcDirButton.setText("Browse");
browseSrcDirButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
browseSrcDirButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 6;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(browseSrcDirButton, gridBagConstraints);
editProjectLabel.setBackground(new java.awt.Color(0, 0, 204));
editProjectLabel.setFont(new java.awt.Font("Dialog", 1, 24));
editProjectLabel.setForeground(new java.awt.Color(255, 255, 255));
editProjectLabel.setText("Project");
editProjectLabel.setOpaque(true);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
editProjectPanel.add(editProjectLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
editProjectPanel.add(jSeparator2, gridBagConstraints);
findBugsButton.setMnemonic('B');
findBugsButton.setText("Find Bugs!");
findBugsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
findBugsButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 13;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
editProjectPanel.add(findBugsButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 8;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
editProjectPanel.add(jSeparator4, gridBagConstraints);
jarFileListScrollPane.setPreferredSize(new java.awt.Dimension(259, 1));
jarFileList.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED));
jarFileList.setFont(new java.awt.Font("Dialog", 0, 12));
jarFileList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jarFileListScrollPane.setViewportView(jarFileList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.6;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(jarFileListScrollPane, gridBagConstraints);
sourceDirListScrollPane.setPreferredSize(new java.awt.Dimension(259, 1));
sourceDirList.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED));
sourceDirList.setFont(new java.awt.Font("Dialog", 0, 12));
sourceDirList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
sourceDirListScrollPane.setViewportView(sourceDirList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 7;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.2;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(sourceDirListScrollPane, gridBagConstraints);
classpathEntryLabel.setFont(new java.awt.Font("Dialog", 0, 12));
classpathEntryLabel.setText("Classpath entry:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 9;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3);
editProjectPanel.add(classpathEntryLabel, gridBagConstraints);
classpathEntryListLabel.setFont(new java.awt.Font("Dialog", 0, 12));
classpathEntryListLabel.setText("Classpath entries:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 10;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3);
editProjectPanel.add(classpathEntryListLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 9;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0);
editProjectPanel.add(classpathEntryTextField, gridBagConstraints);
browseClasspathEntryButton.setFont(new java.awt.Font("Dialog", 0, 12));
browseClasspathEntryButton.setText("Browse");
browseClasspathEntryButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
browseClasspathEntryButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 9;
editProjectPanel.add(browseClasspathEntryButton, gridBagConstraints);
addClasspathEntryButton.setFont(new java.awt.Font("Dialog", 0, 12));
addClasspathEntryButton.setText("Add");
addClasspathEntryButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addClasspathEntryButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 9;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0);
editProjectPanel.add(addClasspathEntryButton, gridBagConstraints);
removeClasspathEntryButton.setFont(new java.awt.Font("Dialog", 0, 12));
removeClasspathEntryButton.setText("Remove");
removeClasspathEntryButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeClasspathEntryButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 10;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0);
editProjectPanel.add(removeClasspathEntryButton, gridBagConstraints);
classpathEntryListScrollPane.setPreferredSize(new java.awt.Dimension(259, 1));
classpathEntryList.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED));
classpathEntryList.setFont(new java.awt.Font("Dialog", 0, 12));
classpathEntryListScrollPane.setViewportView(classpathEntryList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 10;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.2;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(classpathEntryListScrollPane, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 12;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(3, 0, 3, 0);
editProjectPanel.add(jSeparator5, gridBagConstraints);
viewPanel.add(editProjectPanel, "EditProjectPanel");
bugTreePanel.setLayout(new java.awt.GridBagLayout());
bugTreeBugDetailsSplitter.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
bugTreeBugDetailsSplitter.setResizeWeight(1.0);
bugTreeBugDetailsSplitter.setOneTouchExpandable(true);
bugTreeBugDetailsSplitter.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
bugTreeBugDetailsSplitterPropertyChange(evt);
}
});
byClassScrollPane.setViewportView(byClassBugTree);
groupByTabbedPane.addTab("By Class", byClassScrollPane);
byPackageScrollPane.setViewportView(byPackageBugTree);
groupByTabbedPane.addTab("By Package", byPackageScrollPane);
byBugTypeScrollPane.setViewportView(byBugTypeBugTree);
groupByTabbedPane.addTab("By Bug Type", byBugTypeScrollPane);
bySummary.setViewportView(bugSummaryEditorPane);
groupByTabbedPane.addTab("Summary", bySummary);
bugTreeBugDetailsSplitter.setTopComponent(groupByTabbedPane);
bugDescriptionEditorPane.setEditable(false);
bugDescriptionScrollPane.setViewportView(bugDescriptionEditorPane);
bugDetailsTabbedPane.addTab("Details", bugDescriptionScrollPane);
sourceTextAreaScrollPane.setMinimumSize(new java.awt.Dimension(22, 180));
sourceTextAreaScrollPane.setPreferredSize(new java.awt.Dimension(0, 100));
sourceTextArea.setEditable(false);
sourceTextArea.setFont(new java.awt.Font("Lucida Sans Typewriter", 0, 12));
sourceTextArea.setEnabled(false);
sourceTextAreaScrollPane.setViewportView(sourceTextArea);
bugDetailsTabbedPane.addTab("Source code", sourceTextAreaScrollPane);
annotationTextAreaScrollPane.setViewportView(annotationTextArea);
bugDetailsTabbedPane.addTab("Annotations", annotationTextAreaScrollPane);
bugTreeBugDetailsSplitter.setBottomComponent(bugDetailsTabbedPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
bugTreePanel.add(bugTreeBugDetailsSplitter, gridBagConstraints);
viewPanel.add(bugTreePanel, "BugTree");
consoleSplitter.setTopComponent(viewPanel);
consoleScrollPane.setMinimumSize(new java.awt.Dimension(22, 100));
consoleScrollPane.setPreferredSize(new java.awt.Dimension(0, 100));
consoleMessageArea.setBackground(new java.awt.Color(204, 204, 204));
consoleMessageArea.setEditable(false);
consoleMessageArea.setFont(new java.awt.Font("Lucida Sans Typewriter", 0, 12));
consoleMessageArea.setMinimumSize(new java.awt.Dimension(0, 0));
consoleMessageArea.setAutoscrolls(false);
consoleScrollPane.setViewportView(consoleMessageArea);
consoleSplitter.setBottomComponent(consoleScrollPane);
getContentPane().add(consoleSplitter, java.awt.BorderLayout.CENTER);
theMenuBar.setFont(new java.awt.Font("Dialog", 0, 12));
fileMenu.setMnemonic('F');
fileMenu.setText("File");
fileMenu.setFont(new java.awt.Font("Dialog", 0, 12));
fileMenu.addMenuListener(new javax.swing.event.MenuListener() {
public void menuCanceled(javax.swing.event.MenuEvent evt) {
}
public void menuDeselected(javax.swing.event.MenuEvent evt) {
}
public void menuSelected(javax.swing.event.MenuEvent evt) {
fileMenuMenuSelected(evt);
}
});
newProjectItem.setFont(new java.awt.Font("Dialog", 0, 12));
newProjectItem.setMnemonic('N');
newProjectItem.setText("New Project");
newProjectItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newProjectItemActionPerformed(evt);
}
});
fileMenu.add(newProjectItem);
openProjectItem.setFont(new java.awt.Font("Dialog", 0, 12));
openProjectItem.setMnemonic('O');
openProjectItem.setText("Open Project");
openProjectItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openProjectItemActionPerformed(evt);
}
});
fileMenu.add(openProjectItem);
saveProjectItem.setFont(new java.awt.Font("Dialog", 0, 12));
saveProjectItem.setMnemonic('S');
saveProjectItem.setText("Save Project");
saveProjectItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveProjectItemActionPerformed(evt);
}
});
fileMenu.add(saveProjectItem);
saveProjectAsItem.setFont(new java.awt.Font("Dialog", 0, 12));
saveProjectAsItem.setMnemonic('A');
saveProjectAsItem.setText("Save Project As");
saveProjectAsItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveProjectAsItemActionPerformed(evt);
}
});
fileMenu.add(saveProjectAsItem);
reloadProjectItem.setFont(new java.awt.Font("Dialog", 0, 12));
reloadProjectItem.setMnemonic('R');
reloadProjectItem.setText("Reload Project");
reloadProjectItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
reloadProjectItemActionPerformed(evt);
}
});
fileMenu.add(reloadProjectItem);
closeProjectItem.setFont(new java.awt.Font("Dialog", 0, 12));
closeProjectItem.setMnemonic('C');
closeProjectItem.setText("Close Project");
closeProjectItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeProjectItemActionPerformed(evt);
}
});
fileMenu.add(closeProjectItem);
fileMenu.add(jSeparator3);
loadBugsItem.setFont(new java.awt.Font("Dialog", 0, 12));
loadBugsItem.setMnemonic('L');
loadBugsItem.setText("Load Bugs");
loadBugsItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loadBugsItemActionPerformed(evt);
}
});
fileMenu.add(loadBugsItem);
saveBugsItem.setFont(new java.awt.Font("Dialog", 0, 12));
saveBugsItem.setMnemonic('B');
saveBugsItem.setText("Save Bugs");
saveBugsItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveBugsItemActionPerformed(evt);
}
});
fileMenu.add(saveBugsItem);
fileMenu.add(jSeparator6);
exitItem.setFont(new java.awt.Font("Dialog", 0, 12));
exitItem.setMnemonic('X');
exitItem.setText("Exit");
exitItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitItemActionPerformed(evt);
}
});
fileMenu.add(exitItem);
theMenuBar.add(fileMenu);
viewMenu.setMnemonic('V');
viewMenu.setText("View");
viewMenu.setFont(new java.awt.Font("Dialog", 0, 12));
viewMenu.addMenuListener(new javax.swing.event.MenuListener() {
public void menuCanceled(javax.swing.event.MenuEvent evt) {
}
public void menuDeselected(javax.swing.event.MenuEvent evt) {
}
public void menuSelected(javax.swing.event.MenuEvent evt) {
viewMenuMenuSelected(evt);
}
});
viewConsoleItem.setFont(new java.awt.Font("Dialog", 0, 12));
viewConsoleItem.setMnemonic('C');
viewConsoleItem.setText("Console");
viewConsoleItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewConsoleItemActionPerformed(evt);
}
});
viewMenu.add(viewConsoleItem);
viewBugDetailsItem.setFont(new java.awt.Font("Dialog", 0, 12));
viewBugDetailsItem.setMnemonic('D');
viewBugDetailsItem.setSelected(true);
viewBugDetailsItem.setText("Bug Details");
viewBugDetailsItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewBugDetailsItemActionPerformed(evt);
}
});
viewMenu.add(viewBugDetailsItem);
fullDescriptionsItem.setFont(new java.awt.Font("Dialog", 0, 12));
fullDescriptionsItem.setMnemonic('F');
fullDescriptionsItem.setSelected(true);
fullDescriptionsItem.setText("Full Descriptions");
fullDescriptionsItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fullDescriptionsItemActionPerformed(evt);
}
});
viewMenu.add(fullDescriptionsItem);
viewMenu.add(jSeparator7);
lowPriorityButton.setFont(new java.awt.Font("Dialog", 0, 12));
lowPriorityButton.setMnemonic('L');
lowPriorityButton.setText("Low priority");
lowPriorityButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
lowPriorityButtonActionPerformed(evt);
}
});
viewMenu.add(lowPriorityButton);
mediumPriorityButton.setFont(new java.awt.Font("Dialog", 0, 12));
mediumPriorityButton.setMnemonic('M');
mediumPriorityButton.setSelected(true);
mediumPriorityButton.setText("Medium priority");
mediumPriorityButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mediumPriorityButtonActionPerformed(evt);
}
});
viewMenu.add(mediumPriorityButton);
highPriorityButton.setFont(new java.awt.Font("Dialog", 0, 12));
highPriorityButton.setMnemonic('H');
highPriorityButton.setText("High priority");
highPriorityButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
highPriorityButtonActionPerformed(evt);
}
});
viewMenu.add(highPriorityButton);
theMenuBar.add(viewMenu);
settingsMenu.setMnemonic('S');
settingsMenu.setText("Settings");
settingsMenu.setFont(new java.awt.Font("Dialog", 0, 12));
configureDetectorsItem.setFont(new java.awt.Font("Dialog", 0, 12));
configureDetectorsItem.setMnemonic('C');
configureDetectorsItem.setText("Configure Detectors...");
configureDetectorsItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
configureDetectorsItemActionPerformed(evt);
}
});
settingsMenu.add(configureDetectorsItem);
theMenuBar.add(settingsMenu);
helpMenu.setMnemonic('H');
helpMenu.setText("Help");
helpMenu.setFont(new java.awt.Font("Dialog", 0, 12));
aboutItem.setFont(new java.awt.Font("Dialog", 0, 12));
aboutItem.setMnemonic('A');
aboutItem.setText("About");
aboutItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
aboutItemActionPerformed(evt);
}
});
helpMenu.add(aboutItem);
theMenuBar.add(helpMenu);
setJMenuBar(theMenuBar);
pack();
}//GEN-END:initComponents
private void highPriorityButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_highPriorityButtonActionPerformed
mediumPriorityButton.setSelected(false);
lowPriorityButton.setSelected(false);
setPriorityThreshold(Detector.HIGH_PRIORITY);
}//GEN-LAST:event_highPriorityButtonActionPerformed
private void mediumPriorityButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mediumPriorityButtonActionPerformed
highPriorityButton.setSelected(false);
lowPriorityButton.setSelected(false);
setPriorityThreshold(Detector.NORMAL_PRIORITY);
}//GEN-LAST:event_mediumPriorityButtonActionPerformed
private void lowPriorityButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lowPriorityButtonActionPerformed
highPriorityButton.setSelected(false);
mediumPriorityButton.setSelected(false);
setPriorityThreshold(Detector.LOW_PRIORITY);
}//GEN-LAST:event_lowPriorityButtonActionPerformed
private void saveBugsItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveBugsItemActionPerformed
try {
if (currentAnalysisRun == null) {
logger.logMessage(ConsoleLogger.ERROR, "No bugs are loaded!");
return;
}
JFileChooser chooser = createFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setFileFilter(xmlFileFilter);
int result = chooseFile(chooser, "Save bugs");
if (result != JFileChooser.CANCEL_OPTION) {
// Make sure current annotation text is up to date with its
// corresponding bug instance
if (currentBugInstance != null)
synchBugAnnotation(currentBugInstance);
// Save bugs to file
File selectedFile = chooser.getSelectedFile();
currentAnalysisRun.saveBugsToFile(selectedFile);
}
} catch (Exception e) {
e.printStackTrace();
logger.logMessage(ConsoleLogger.ERROR, "Could not save bugs: " + e.toString());
}
}//GEN-LAST:event_saveBugsItemActionPerformed
private void loadBugsItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadBugsItemActionPerformed
// FIXME: offer to save current project and bugs
try {
JFileChooser chooser = createFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setFileFilter(xmlFileFilter);
int result = chooseFile(chooser, "Load bugs");
if (result != JFileChooser.CANCEL_OPTION) {
File selectedFile = chooser.getSelectedFile();
Project project = new Project();
AnalysisRun analysisRun = new AnalysisRun(project, this);
analysisRun.loadBugsFromFile(selectedFile);
setProject(project);
synchAnalysisRun(analysisRun);
}
} catch (Exception e) {
e.printStackTrace();
logger.logMessage(ConsoleLogger.ERROR, "Could not load bugs: " + e.toString());
}
}//GEN-LAST:event_loadBugsItemActionPerformed
private void configureDetectorsItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_configureDetectorsItemActionPerformed
ConfigureDetectorsDialog dialog = new ConfigureDetectorsDialog(this, true);
dialog.setSize(700, 520);
dialog.setLocationRelativeTo(null); // center the dialog
dialog.show();
}//GEN-LAST:event_configureDetectorsItemActionPerformed
private void reloadProjectItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_reloadProjectItemActionPerformed
Project current = getCurrentProject();
if ( current == null )
return;
try {
String filename = current.getFileName();
File file = new File( filename );
Project project = new Project(file.getPath());
FileInputStream in = new FileInputStream(file);
project.read(in);
setProject( null );
setProject(project);
findBugsButtonActionPerformed( evt );
} catch (IOException e) {
logger.logMessage(ConsoleLogger.ERROR, "Could not reload project: " + e.getMessage());
}
}//GEN-LAST:event_reloadProjectItemActionPerformed
private void saveProjectAsItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveProjectAsItemActionPerformed
saveProject(getCurrentProject(), "Save project as", true);
}//GEN-LAST:event_saveProjectAsItemActionPerformed
private void viewMenuMenuSelected(javax.swing.event.MenuEvent evt) {//GEN-FIRST:event_viewMenuMenuSelected
// View bug details and full descriptions items,
// are only enabled if there is a project open.
boolean hasProject = getCurrentProject() != null;
viewBugDetailsItem.setEnabled(hasProject);
fullDescriptionsItem.setEnabled(hasProject);
}//GEN-LAST:event_viewMenuMenuSelected
private void fileMenuMenuSelected(javax.swing.event.MenuEvent evt) {//GEN-FIRST:event_fileMenuMenuSelected
// Save and close project items are only enabled if there is a project open.
boolean hasProject = getCurrentProject() != null;
saveProjectItem.setEnabled(hasProject);
saveProjectAsItem.setEnabled(hasProject);
reloadProjectItem.setEnabled(hasProject);
closeProjectItem.setEnabled(hasProject);
}//GEN-LAST:event_fileMenuMenuSelected
private void closeProjectItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeProjectItemActionPerformed
if (closeProjectHook(getCurrentProject(), "Close project")) {
setProject(null);
}
}//GEN-LAST:event_closeProjectItemActionPerformed
private void removeClasspathEntryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeClasspathEntryButtonActionPerformed
int selIndex = classpathEntryList.getSelectedIndex();
if (selIndex >= 0) {
Project project = getCurrentProject();
project.removeAuxClasspathEntry(selIndex);
DefaultListModel listModel = (DefaultListModel) classpathEntryList.getModel();
listModel.removeElementAt(selIndex);
}
}//GEN-LAST:event_removeClasspathEntryButtonActionPerformed
private void addClasspathEntryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addClasspathEntryButtonActionPerformed
addClasspathEntryToList();
}//GEN-LAST:event_addClasspathEntryButtonActionPerformed
private void browseClasspathEntryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseClasspathEntryButtonActionPerformed
JFileChooser chooser = createFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setFileFilter(auxClasspathEntryFileFilter);
chooser.setMultiSelectionEnabled(true);
int result = chooseFile(chooser, "Add entry");
if (result != JFileChooser.CANCEL_OPTION) {
File[] selectedFileList = chooser.getSelectedFiles();
for (int i = 0; i < selectedFileList.length; ++i) {
String entry = selectedFileList[i].getPath();
addClasspathEntryToProject(entry);
}
}
}//GEN-LAST:event_browseClasspathEntryButtonActionPerformed
private void fullDescriptionsItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fullDescriptionsItemActionPerformed
for (int j = 0; j < bugTreeList.length; ++j) {
JTree bugTree = bugTreeList[j];
// Redisplay the displayed bug instance nodes
DefaultTreeModel bugTreeModel = (DefaultTreeModel) bugTree.getModel();
int numRows = bugTree.getRowCount();
for (int i = 0; i < numRows; ++i) {
//System.out.println("Getting path for row " + i);
TreePath path = bugTree.getPathForRow(i);
if (path == null)
continue;
DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
if (node instanceof BugTreeNode)
bugTreeModel.valueForPathChanged(path, node.getUserObject());
}
}
}//GEN-LAST:event_fullDescriptionsItemActionPerformed
private void viewBugDetailsItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewBugDetailsItemActionPerformed
String view = getView();
if (view.equals("BugTree")) {
checkBugDetailsVisibility();
}
}//GEN-LAST:event_viewBugDetailsItemActionPerformed
private void bugTreeBugDetailsSplitterPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_bugTreeBugDetailsSplitterPropertyChange
// Here we want to
// (1) Keep the View:Bug details checkbox item up to date, and
// (2) keep the details window synchronized with the current bug instance
String propertyName = evt.getPropertyName();
if (propertyName.equals(JSplitPane.DIVIDER_LOCATION_PROPERTY)) {
boolean isMaximized = isSplitterMaximized(bugTreeBugDetailsSplitter, evt);
viewBugDetailsItem.setSelected(!isMaximized);
if (!isMaximized) {
// Details window is shown, so make sure it is populated
// with bug detail information
synchBugInstance();
}
}
}//GEN-LAST:event_bugTreeBugDetailsSplitterPropertyChange
private void openProjectItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openProjectItemActionPerformed
if (!closeProjectHook(getCurrentProject(), "Open Project"))
return;
JFileChooser chooser = createFileChooser();
chooser.setFileFilter(projectFileFilter);
int result = chooseFileToOpen(chooser);
if (result == JFileChooser.CANCEL_OPTION)
return;
try {
File file = chooser.getSelectedFile();
Project project = new Project(file.getPath());
FileInputStream in = new FileInputStream(file);
project.read(in);
setProject(project);
} catch (IOException e) {
logger.logMessage(ConsoleLogger.ERROR, "Could not open project: " + e.getMessage());
}
}//GEN-LAST:event_openProjectItemActionPerformed
private void saveProjectItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveProjectItemActionPerformed
saveProject(getCurrentProject(), "Save project");
}//GEN-LAST:event_saveProjectItemActionPerformed
private void aboutItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutItemActionPerformed
AboutDialog dialog = new AboutDialog(this, true);
dialog.setSize(500, 354);
dialog.setLocationRelativeTo(null); // center the dialog
dialog.show();
}//GEN-LAST:event_aboutItemActionPerformed
private void consoleSplitterPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_consoleSplitterPropertyChange
// The idea here is to keep the View:Console checkbox up to date with
// the real location of the divider of the consoleSplitter.
// What we want is if any part of the console window is visible,
// then the checkbox should be checked.
String propertyName = evt.getPropertyName();
if (propertyName.equals(JSplitPane.DIVIDER_LOCATION_PROPERTY)) {
boolean isMaximized = isSplitterMaximized(consoleSplitter, evt);
viewConsoleItem.setSelected(!isMaximized);
}
}//GEN-LAST:event_consoleSplitterPropertyChange
private void viewConsoleItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewConsoleItemActionPerformed
if (viewConsoleItem.isSelected()) {
consoleSplitter.resetToPreferredSizes();
} else {
consoleSplitter.setDividerLocation(1.0);
}
}//GEN-LAST:event_viewConsoleItemActionPerformed
private void findBugsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_findBugsButtonActionPerformed
Project project = getCurrentProject();
if (project.getNumJarFiles() == 0) {
logger.logMessage(ConsoleLogger.ERROR, "Project " + project + " has no Jar files selected");
return;
}
bugDescriptionEditorPane.setText("");
sourceTextArea.setText("");
AnalysisRun analysisRun = new AnalysisRun(project, this);
logger.logMessage(ConsoleLogger.INFO, "Beginning analysis of " + project);
// Run the analysis!
RunAnalysisDialog dialog = new RunAnalysisDialog(this, analysisRun);
dialog.setSize(400, 300);
dialog.setLocationRelativeTo(null); // center the dialog
dialog.show();
if (dialog.isCompleted()) {
logger.logMessage(ConsoleLogger.INFO, "Analysis " + project + " completed");
// Report any errors that might have occurred during analysis
analysisRun.reportAnalysisErrors();
// Now we have an analysis run to look at
synchAnalysisRun(analysisRun);
} else {
logger.logMessage(ConsoleLogger.INFO, "Analysis of " + project + " cancelled by user");
}
}//GEN-LAST:event_findBugsButtonActionPerformed
private void browseSrcDirButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseSrcDirButtonActionPerformed
JFileChooser chooser = createFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int rc = chooseFile(chooser, "Add source directory");
if (rc == JFileChooser.APPROVE_OPTION) {
srcDirTextField.setText(chooser.getSelectedFile().getPath());
addSourceDirToList();
}
}//GEN-LAST:event_browseSrcDirButtonActionPerformed
private void srcDirTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_srcDirTextFieldActionPerformed
addSourceDirToList();
}//GEN-LAST:event_srcDirTextFieldActionPerformed
private void jarNameTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jarNameTextFieldActionPerformed
addJarToList();
}//GEN-LAST:event_jarNameTextFieldActionPerformed
private static final HashSet<String> archiveExtensionSet = new HashSet<String>();
static {
archiveExtensionSet.add(".jar");
archiveExtensionSet.add(".zip");
archiveExtensionSet.add(".ear");
archiveExtensionSet.add(".war");
}
private void browseJarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseJarButtonActionPerformed
JFileChooser chooser = createFileChooser();
FileFilter filter = new FileFilter() {
public boolean accept(File file) {
if (file.isDirectory())
return true;
String fileName = file.getName();
int dot = fileName.lastIndexOf('.');
if (dot < 0)
return false;
String extension = fileName.substring(dot);
return archiveExtensionSet.contains(extension);
}
public String getDescription() { return "Java archives (*.jar,*.zip,*.ear,*.war)"; }
};
chooser.setFileFilter(filter);
chooser.setMultiSelectionEnabled(true);
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int rc = chooseFile(chooser, "Add archive or directory");
if (rc == JFileChooser.APPROVE_OPTION) {
File[] selectedFileList = chooser.getSelectedFiles();
for (int i = 0; i < selectedFileList.length; ++i) {
String entry = selectedFileList[i].getPath();
addJarToProject(entry);
}
}
}//GEN-LAST:event_browseJarButtonActionPerformed
private void newProjectItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newProjectItemActionPerformed
Project project = new Project(DEFAULT_PROJECT_NAME);
setProject(project);
}//GEN-LAST:event_newProjectItemActionPerformed
private void exitItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitItemActionPerformed
exitFindBugs();
}//GEN-LAST:event_exitItemActionPerformed
private void removeSrcDirButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeSrcDirButtonActionPerformed
int selIndex = sourceDirList.getSelectedIndex();
if (selIndex >= 0) {
Project project = getCurrentProject();
project.removeSourceDir(selIndex);
DefaultListModel listModel = (DefaultListModel) sourceDirList.getModel();
listModel.removeElementAt(selIndex);
}
}//GEN-LAST:event_removeSrcDirButtonActionPerformed
private void removeJarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeJarButtonActionPerformed
int selIndex = jarFileList.getSelectedIndex();
if (selIndex >= 0) {
Project project = getCurrentProject();
project.removeJarFile(selIndex);
DefaultListModel listModel = (DefaultListModel) jarFileList.getModel();
listModel.removeElementAt(selIndex);
}
}//GEN-LAST:event_removeJarButtonActionPerformed
private void addSourceDirButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addSourceDirButtonActionPerformed
addSourceDirToList();
}//GEN-LAST:event_addSourceDirButtonActionPerformed
private void addJarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addJarButtonActionPerformed
addJarToList();
}//GEN-LAST:event_addJarButtonActionPerformed
/** Exit the Application */
private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
exitFindBugs();
}//GEN-LAST:event_exitForm
/**
* This is called whenever the selection is changed in the bug tree.
* @param e the TreeSelectionEvent
*/
private void bugTreeSelectionChanged(TreeSelectionEvent e) {
BugInstance selected = getCurrentBugInstance();
if (selected != null) {
synchBugInstance();
}
}
/* ----------------------------------------------------------------------
* Component initialization support
* ---------------------------------------------------------------------- */
/**
* This is called from the constructor to perform post-initialization
* of the components in the form.
*/
private void postInitComponents() {
logger = new ConsoleLogger(this);
viewPanelLayout = (CardLayout) viewPanel.getLayout();
// Console starts out disabled
consoleSplitter.setDividerLocation(1.0);
// List of bug group tabs.
// This must be in the same order as GROUP_BY_ORDER_LIST!
bugTreeList = new JTree[]{byClassBugTree, byPackageBugTree, byBugTypeBugTree};
// Configure bug trees
for (int i = 0; i < bugTreeList.length; ++i) {
JTree bugTree = bugTreeList[i];
bugTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
bugTree.setCellRenderer(bugCellRenderer);
bugTree.setRootVisible(false);
bugTree.setShowsRootHandles(true);
bugTree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
bugTreeSelectionChanged(e);
}
});
}
jarFileList.setModel(new DefaultListModel());
sourceDirList.setModel(new DefaultListModel());
classpathEntryList.setModel(new DefaultListModel());
// We use a special highlight painter to ensure that the highlights cover
// complete source lines, even though the source text doesn't
// fill the lines completely.
final Highlighter.HighlightPainter painter =
new DefaultHighlighter.DefaultHighlightPainter(sourceTextArea.getSelectionColor()) {
public Shape paintLayer(Graphics g, int offs0, int offs1,
Shape bounds, JTextComponent c, View view) {
try {
Shape extent = view.modelToView(offs0, Position.Bias.Forward, offs1, Position.Bias.Backward, bounds);
Rectangle rect = extent.getBounds();
rect.x = 0;
rect.width = bounds.getBounds().width;
g.setColor(getColor());
g.fillRect(rect.x, rect.y, rect.width, rect.height);
return rect;
} catch (BadLocationException e) {
return null;
}
}
};
Highlighter sourceHighlighter = new DefaultHighlighter() {
public Object addHighlight(int p0, int p1, Highlighter.HighlightPainter p)
throws BadLocationException {
return super.addHighlight(p0, p1, painter);
}
};
sourceTextArea.setHighlighter(sourceHighlighter);
updateTitle(getCurrentProject());
priorityThreshold = Detector.NORMAL_PRIORITY;
}
/* ----------------------------------------------------------------------
* Helpers for accessing and modifying UI components
* ---------------------------------------------------------------------- */
/**
* Based on the current tree selection path, get a user object
* whose class is the same as the given class.
* @param tree the tree
* @param c the class
* @return an instance of the given kind of object which is in the
* current selection, or null if there is no matching object
*/
private static Object getTreeSelectionOf(JTree tree, Class c) {
TreePath selPath = tree.getSelectionPath();
// There may not be anything selected at the moment
if (selPath == null)
return null;
// Work backwards from end until we get to the kind of
// object we're looking for.
Object[] nodeList = selPath.getPath();
for (int i = nodeList.length - 1; i >= 0; --i) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodeList[i];
Object nodeInfo = node.getUserObject();
if (nodeInfo != null && nodeInfo.getClass() == c)
return nodeInfo;
}
return null;
}
/**
* Get the current project.
*/
private Project getCurrentProject() {
return currentProject;
}
/**
* Get the current analysis run.
*/
private AnalysisRun getCurrentAnalysisRun() {
return currentAnalysisRun;
}
/**
* Get the bug instance currently selected in the bug tree.
*/
private BugInstance getCurrentBugInstance() {
JTree bugTree = getCurrentBugTree();
if ( bugTree != null ) {
return (BugInstance) getTreeSelectionOf(bugTree, BugInstance.class);
}
return null;
}
/**
* Return whether or not the given splitter is "maximized", meaning that
* the top window of the split has been given all of the space.
* Note that this window assumes that the split is vertical (meaning
* that we have top and bottom components).
* @param splitter the JSplitPane
* @param evt the event that is changing the splitter value
*/
private boolean isSplitterMaximized(JSplitPane splitter, java.beans.PropertyChangeEvent evt) {
Integer location = (Integer) evt.getNewValue();
java.awt.Container parent = splitter.getParent();
int height = splitter.getHeight();
int hopefullyMaxDivider = height - (splitter.getDividerSize() + DIVIDER_FUDGE);
//System.out.println("Splitter: "+(splitter==consoleSplitter?"consoleSplitter":"bugTreeBugDetailsSplitter")+
// ": height="+height+",location="+location+
// ",hopefullyMax="+hopefullyMaxDivider);
boolean isMaximized = location.intValue() >= hopefullyMaxDivider;
return isMaximized;
}
private void checkBugDetailsVisibility() {
if (viewBugDetailsItem.isSelected()) {
bugTreeBugDetailsSplitter.resetToPreferredSizes();
} else {
bugTreeBugDetailsSplitter.setDividerLocation(1.0);
}
//System.out.("New bug detail splitter location " + bugTreeBugDetailsSplitter.getDividerLocation());
}
private JTree getCurrentBugTree() {
JScrollPane selected = (JScrollPane) groupByTabbedPane.getSelectedComponent();
Object view = selected.getViewport().getView();
if ( view instanceof JTree ) {
return (JTree)view;
}
return null;
}
/* ----------------------------------------------------------------------
* Synchronization of data model and UI
* ---------------------------------------------------------------------- */
/**
* Set the priority threshold for display of bugs in the bug tree.
* @param threshold the threshold
*/
private void setPriorityThreshold(int threshold) {
if (threshold != priorityThreshold) {
priorityThreshold = threshold;
if (currentAnalysisRun != null)
synchAnalysisRun(currentAnalysisRun);
}
}
private void setProject(Project project) {
currentProject = project;
if (project != null) {
synchProject(project);
setView("EditProjectPanel");
} else {
setView("EmptyPanel");
}
updateTitle(project);
}
private void updateTitle(Project project) {
if (project == null)
this.setTitle("FindBugs - no project");
else
this.setTitle("FindBugs - " + project.toString());
}
/**
* Save given project.
* If the project already has a valid filename, use that filename.
* Otherwise, prompt for one.
* @param project the Project to save
* @param dialogTitle the title for the save dialog (if needed)
*/
private boolean saveProject(Project project, String dialogTitle) {
return saveProject(project, dialogTitle, false);
}
/**
* Offer to save the current Project to a file.
* @param project the Project to save
* @param dialogTitle the title for the save dialog (if needed)
* @param chooseFilename if true, force a dialog to prompt the user
* for a filename
* @return true if the project is saved successfully, false if the user
* cancels or an error occurs
*/
private boolean saveProject(Project project, String dialogTitle, boolean chooseFilename) {
try {
if (project == null)
return true;
File file;
String fileName = project.getFileName();
if (!fileName.startsWith("<") && !chooseFilename) {
file = new File(fileName);
} else {
JFileChooser chooser = createFileChooser();
chooser.setFileFilter(projectFileFilter);
int result = chooseFile(chooser, dialogTitle);
if (result == JFileChooser.CANCEL_OPTION)
return false;
file = chooser.getSelectedFile();
fileName = Project.transformFilename(file.getPath());
file = new File(fileName);
}
FileOutputStream out = new FileOutputStream(file);
project.write(out);
logger.logMessage(ConsoleLogger.INFO, "Project saved");
project.setFileName(file.getPath());
updateTitle(project);
return true;
} catch (IOException e) {
logger.logMessage(ConsoleLogger.ERROR, "Could not save project: " + e.toString());
JOptionPane.showMessageDialog(this, "Error saving project: " + e.toString(),
"Error", JOptionPane.ERROR_MESSAGE);
return false;
}
}
/**
* Hook to call before closing a project.
* @param project the project being closed
* @param savePromptTitle title to use for the "Save project?" dialog
* @return true if user has confirmed that the project should be closed,
* false if the close is cancelled
*/
private boolean closeProjectHook(Project project, String savePromptTitle) {
if (project == null || !project.isModified())
return true;
// Confirm that the project should be closed.
int option = JOptionPane.showConfirmDialog(this, "Save project?", savePromptTitle,
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (option == JOptionPane.CANCEL_OPTION)
return false;
else if (option == JOptionPane.YES_OPTION) {
boolean result = saveProject(project, "Save project");
if (result)
JOptionPane.showMessageDialog(this, "Project saved");
return result;
} else
return true;
}
/**
* Synchronize the edit project dialog with given project.
* @param project the selected project
*/
private void synchProject(Project project) {
// Clear text fields
jarNameTextField.setText("");
srcDirTextField.setText("");
classpathEntryTextField.setText("");
// Populate jar file, source directory, and aux classpath entry lists
DefaultListModel jarListModel = (DefaultListModel) jarFileList.getModel();
jarListModel.clear();
for (int i = 0; i < project.getNumJarFiles(); ++i) {
jarListModel.addElement(project.getJarFile(i));
}
DefaultListModel srcDirListModel = (DefaultListModel) sourceDirList.getModel();
srcDirListModel.clear();
for (int i = 0; i < project.getNumSourceDirs(); ++i) {
srcDirListModel.addElement(project.getSourceDir(i));
}
DefaultListModel classpathEntryListModel = (DefaultListModel) classpathEntryList.getModel();
classpathEntryListModel.clear();
for (int i = 0; i < project.getNumAuxClasspathEntries(); ++i) {
classpathEntryListModel.addElement(project.getAuxClasspathEntry(i));
}
}
/**
* Synchronize the bug trees with the given analysisRun object.
* @param analysisRun the selected analysis run
*/
private void synchAnalysisRun(AnalysisRun analysisRun) {
// Create and populate tree models
for (int i = 0; i < GROUP_BY_ORDER_LIST.length; ++i) {
DefaultMutableTreeNode bugRootNode = new DefaultMutableTreeNode();
DefaultTreeModel bugTreeModel = new DefaultTreeModel(bugRootNode);
String groupByOrder = GROUP_BY_ORDER_LIST[i];
analysisRun.setTreeModel(groupByOrder, bugTreeModel);
populateAnalysisRunTreeModel(analysisRun, groupByOrder);
if (i < bugTreeList.length)
bugTreeList[i].setModel(bugTreeModel);
}
currentAnalysisRun = analysisRun;
//set the summary output
setSummary( analysisRun.getSummary() );
setView("BugTree");
}
private void setSummary( String summaryXML ) {
bugSummaryEditorPane.setContentType("text/html");
bugSummaryEditorPane.setText(summaryXML);
// FIXME: unfortunately, using setText() on the editor pane
// results in the contents being scrolled to the bottom of the pane.
// An immediate inline call to set the scroll position does nothing.
// So, use invokeLater(), even though this results in flashing.
// [What we really need is a way to set the text WITHOUT changing
// the caret position. Need to investigate.]
SwingUtilities.invokeLater(new Runnable() {
public void run() {
bySummary.getViewport().setViewPosition(new Point(0, 0));
}
});
}
/**
* Populate an analysis run's tree model for given sort order.
*/
private void populateAnalysisRunTreeModel(AnalysisRun analysisRun, final String groupBy) {
//System.out.println("Populating bug tree for order " + groupBy);
// Set busy cursor - this is potentially a time-consuming operation
Cursor orig = this.getCursor();
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
final DefaultTreeModel bugTreeModel = analysisRun.getTreeModel(groupBy);
final DefaultMutableTreeNode bugRootNode = (DefaultMutableTreeNode) bugTreeModel.getRoot();
// Delete all children from root node
bugRootNode.removeAllChildren();
// Sort the instances (considering only those that meet the
// priority threshold)
TreeSet<BugInstance> sortedCollection = new TreeSet<BugInstance>(getBugInstanceComparator(groupBy));
for (Iterator<BugInstance> i = analysisRun.getBugInstances().iterator(); i.hasNext(); ) {
BugInstance bugInstance = i.next();
if (bugInstance.getPriority() <= priorityThreshold)
sortedCollection.add(bugInstance);
}
// The grouper callback is what actually adds the group and bug
// nodes to the tree.
Grouper.Callback<BugInstance> callback = new Grouper.Callback<BugInstance>() {
private BugInstanceGroup currentGroup;
private DefaultMutableTreeNode currentGroupNode;
public void startGroup(BugInstance member) {
String groupName;
if (groupBy == GROUP_BY_CLASS)
groupName = member.getPrimaryClass().getClassName();
else if (groupBy == GROUP_BY_PACKAGE) {
groupName = member.getPrimaryClass().getPackageName();
if (groupName.equals(""))
groupName = "Unnamed package";
} else if (groupBy == GROUP_BY_BUG_TYPE) {
String desc = member.toString();
String shortBugType = desc.substring(0, desc.indexOf(':'));
String bugTypeDescription = I18N.instance().getBugTypeDescription(shortBugType);
groupName = shortBugType + ": " + bugTypeDescription;
} else
throw new IllegalStateException("Unknown sort order: " + groupBy);
currentGroup = new BugInstanceGroup(groupBy, groupName);
currentGroupNode = new DefaultMutableTreeNode(currentGroup);
bugTreeModel.insertNodeInto(currentGroupNode, bugRootNode, bugRootNode.getChildCount());
insertIntoGroup(member);
}
public void addToGroup(BugInstance member) {
insertIntoGroup(member);
}
private void insertIntoGroup(BugInstance member) {
currentGroup.incrementMemberCount();
BugTreeNode bugNode = new BugTreeNode(member);
if (BUG_COUNT)
bugNode.setCount(currentGroup.getMemberCount());
bugTreeModel.insertNodeInto(bugNode, currentGroupNode, currentGroupNode.getChildCount());
// Insert annotations
Iterator j = member.annotationIterator();
while (j.hasNext()) {
BugAnnotation annotation = (BugAnnotation) j.next();
DefaultMutableTreeNode annotationNode = new DefaultMutableTreeNode(annotation);
bugTreeModel.insertNodeInto(annotationNode, bugNode, bugNode.getChildCount());
}
}
};
// Create the grouper, and execute it to populate the bug tree
Grouper<BugInstance> grouper = new Grouper<BugInstance>(callback);
Comparator<BugInstance> groupComparator = getGroupComparator(groupBy);
grouper.group(sortedCollection, groupComparator);
// Let the tree know it needs to update itself
bugTreeModel.nodeStructureChanged(bugRootNode);
// Now we're done
this.setCursor(orig);
}
/**
* Get a BugInstance Comparator for given sort order.
*/
private Comparator<BugInstance> getBugInstanceComparator(String sortOrder) {
if (sortOrder.equals(GROUP_BY_CLASS))
return bugInstanceByClassComparator;
else if (sortOrder.equals(GROUP_BY_PACKAGE))
return bugInstanceByPackageComparator;
else if (sortOrder.equals(GROUP_BY_BUG_TYPE))
return bugInstanceByTypeComparator;
else
throw new IllegalArgumentException("Bad sort order: " + sortOrder);
}
/**
* Get a Grouper for a given sort order.
*/
private Comparator<BugInstance> getGroupComparator(String groupBy) {
if (groupBy.equals(GROUP_BY_CLASS)) {
return bugInstanceClassComparator;
} else if (groupBy.equals(GROUP_BY_PACKAGE)) {
return bugInstancePackageComparator;
} else if (groupBy.equals(GROUP_BY_BUG_TYPE)) {
return bugInstanceTypeComparator;
} else
throw new IllegalArgumentException("Bad sort order: " + groupBy);
}
/**
* Set the view panel to display the named view.
*/
private void setView(String viewName) {
//System.out.println("Showing view " + viewName);
viewPanelLayout.show(viewPanel, viewName);
if (viewName.equals("BugTree"))
checkBugDetailsVisibility();
currentView = viewName;
}
/**
* Get which view is displayed currently.
*/
private String getView() {
return currentView;
}
/**
* Called to add the jar file in the jarNameTextField to the
* Jar file list (and the project it represents).
*/
private void addJarToList() {
String jarFile = jarNameTextField.getText();
if (!jarFile.equals("")) {
addJarToProject(jarFile);
jarNameTextField.setText("");
}
}
/**
* Add a Jar file to the current project.
* @param jarFile the jar file to add to the project
*/
private void addJarToProject(String jarFile) {
Project project = getCurrentProject();
if (project.addJar(jarFile)) {
DefaultListModel listModel = (DefaultListModel) jarFileList.getModel();
listModel.addElement(jarFile);
}
}
/**
* Called to add the source directory in the sourceDirTextField
* to the source directory list (and the project it represents).
*/
private void addSourceDirToList() {
String sourceDir = srcDirTextField.getText();
if (!sourceDir.equals("")) {
Project project = getCurrentProject();
if (project.addSourceDir(sourceDir)) {
DefaultListModel listModel = (DefaultListModel) sourceDirList.getModel();
listModel.addElement(sourceDir);
}
srcDirTextField.setText("");
}
}
/**
* Called to add the classpath entry in the classpathEntryTextField
* to the classpath entry list (and the project it represents).
*/
private void addClasspathEntryToList() {
String classpathEntry = classpathEntryTextField.getText();
if (!classpathEntry.equals("")) {
addClasspathEntryToProject(classpathEntry);
classpathEntryTextField.setText("");
}
}
/**
* Add a classpath entry to the current project.
* @param classpathEntry the classpath entry to add
*/
private void addClasspathEntryToProject(String classpathEntry) {
Project project = getCurrentProject();
if (project.addAuxClasspathEntry(classpathEntry)) {
DefaultListModel listModel = (DefaultListModel) classpathEntryList.getModel();
listModel.addElement(classpathEntry);
}
}
/**
* Synchronize current bug instance with the bug detail
* window (source view, details window, etc.)
*/
private void synchBugInstance() {
// Get current bug instance
BugInstance selected = getCurrentBugInstance();
if (selected == null)
return;
// If the details window is minimized, then the user can't see
// it and there is no point in updating it.
if (!viewBugDetailsItem.isSelected())
return;
// Get the current source line annotation.
// If the current leaf selected is not a source line annotation,
// use the default source line annotation from the current bug instance
// (if any).
JTree bugTree = getCurrentBugTree();
// if the summary window is shown then skip it
if ( bugTree == null ) {
return;
}
SourceLineAnnotation srcLine = null;
TreePath selPath = bugTree.getSelectionPath();
if (selPath != null) {
Object leaf = ((DefaultMutableTreeNode)selPath.getLastPathComponent()).getUserObject();
if (leaf instanceof SourceLineAnnotation)
srcLine = (SourceLineAnnotation) leaf;
else
srcLine = selected.getPrimarySourceLineAnnotation();
}
// Show source code.
if (srcLine == null || srcLine != currentSourceLineAnnotation) {
Project project = getCurrentProject();
AnalysisRun analysisRun = getCurrentAnalysisRun();
if (project == null) throw new IllegalStateException("null project!");
if (analysisRun == null) throw new IllegalStateException("null analysis run!");
try {
boolean success = viewSource(project, analysisRun, srcLine);
sourceTextArea.setEnabled(success);
if (!success)
sourceTextArea.setText("No source line information for this bug");
} catch (IOException e) {
sourceTextArea.setText("Could not find source: " + e.getMessage());
logger.logMessage(ConsoleLogger.WARNING, e.getMessage());
}
currentSourceLineAnnotation = srcLine;
}
// Show bug info.
showBugInfo(selected);
// Synch annotation text.
synchBugAnnotation(selected);
// Now the bug details are up to date.
currentBugInstance = selected;
}
private static final int SELECTION_VOFFSET = 2;
/**
* Update the source view window.
* @param project the project (containing the source directories to search)
* @param analysisRun the analysis run (containing the mapping of classes to source files)
* @param srcLine the source line annotation (specifying source file to load and
* which lines to highlight)
* @return true if the source was shown successfully, false otherwise
*/
private boolean viewSource(Project project, AnalysisRun analysisRun, final SourceLineAnnotation srcLine)
throws IOException {
// Get rid of old source code text
sourceTextArea.setText("");
// There is nothing to do without a source annotation
// TODO: actually, might want to put a message in the source window
// explaining that we don't have the source file, and that
// they might want to recompile with debugging info turned on.
if (srcLine == null)
return false;
// Look up the source file for this class.
sourceFinder.setSourceBaseList(project.getSourceDirList());
String sourceFile = srcLine.getSourceFile();
if (sourceFile == null || sourceFile.equals("<Unknown>")) {
logger.logMessage(ConsoleLogger.WARNING, "No source file for class " + srcLine.getClassName());
return false;
}
// Try to open the source file and display its contents
// in the source text area.
InputStream in = sourceFinder.openSource(srcLine.getPackageName(), sourceFile);
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
sourceTextArea.append(line + "\n");
}
} finally {
if (reader != null)
reader.close();
}
if (srcLine.isUnknown()) {
// No line number information, so can't highlight anything
SwingUtilities.invokeLater(new Runnable() {
public void run() {
sourceTextAreaScrollPane.getViewport().setViewPosition(new Point(0, 0));
}
});
return true;
}
// Highlight the annotation.
// There seems to be some bug in Swing that sometimes prevents this code
// from working when executed immediately after populating the
// text in the text area. My guess is that when a large amount of text
// is added, Swing defers some UI update work until "later" that is needed
// to compute the visibility of text in the text area.
// So, post some code to do the update to the Swing event queue.
// Not really an ideal solution, but it seems to work.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Highlight the lines from the source annotation.
// Note that the source lines start at 1, while the line numbers
// in the text area start at 0.
try {
int startLine = srcLine.getStartLine() - 1;
int endLine = srcLine.getEndLine();
// Compute number of rows visible.
// What a colossal pain in the ass this is.
// You'd think there would be a convenient method to
// return this information, but no.
JViewport viewport = sourceTextAreaScrollPane.getViewport();
Rectangle viewportRect = viewport.getViewRect();
int height = sourceTextArea.getHeight();
int topRow = sourceTextArea.getLineOfOffset(sourceTextArea.viewToModel(viewportRect.getLocation()));
int bottomRow = sourceTextArea.getLineOfOffset(
sourceTextArea.viewToModel(new Point(viewportRect.x, (viewportRect.y + viewportRect.height) - 1)));
int numRowsVisible = bottomRow - topRow;
// Scroll the window so the beginning of the
// annotation text will be (approximately) centered.
int viewLine = Math.max(startLine - (numRowsVisible > 0 ? numRowsVisible / 2 : 0), 0);
int viewBegin = sourceTextArea.getLineStartOffset(viewLine);
Rectangle viewRect = sourceTextArea.modelToView(viewBegin);
viewport.setViewPosition(new Point(viewRect.x, viewRect.y));
// Select (and highlight) the annotation.
int selBegin = sourceTextArea.getLineStartOffset(startLine);
int selEnd = sourceTextArea.getLineStartOffset(endLine);
sourceTextArea.select(selBegin, selEnd);
sourceTextArea.getCaret().setSelectionVisible(true);
} catch (javax.swing.text.BadLocationException e) {
logger.logMessage(ConsoleLogger.ERROR, e.toString());
}
}
});
return true;
}
/**
* Show descriptive text about the type of bug
* @param bugInstance the bug instance
*/
private void showBugInfo(BugInstance bugInstance) {
// Are we already showing details for this kind of bug?
String bugDetailsKey = bugInstance.getType();
if (bugDetailsKey.equals(currentBugDetailsKey))
return;
// Display the details
String html = I18N.instance().getDetailHTML(bugDetailsKey);
bugDescriptionEditorPane.setContentType("text/html");
bugDescriptionEditorPane.setText(html);
currentBugDetailsKey = bugDetailsKey;
// FIXME: unfortunately, using setText() on the editor pane
// results in the contents being scrolled to the bottom of the pane.
// An immediate inline call to set the scroll position does nothing.
// So, use invokeLater(), even though this results in flashing.
// [What we really need is a way to set the text WITHOUT changing
// the caret position. Need to investigate.]
SwingUtilities.invokeLater(new Runnable() {
public void run() {
bugDescriptionScrollPane.getViewport().setViewPosition(new Point(0, 0));
}
});
}
/**
* Synchronize the bug annotation text with the current bug instance,
* and update the annotation text with the new bug instance.
* @param selected the new BugInstance
*/
private void synchBugAnnotation(BugInstance selected) {
if (currentBugInstance != null) {
String text = annotationTextArea.getText();
currentBugInstance.setAnnotationText(text);
}
annotationTextArea.setText(selected.getAnnotationText());
}
/* ----------------------------------------------------------------------
* Misc. helpers
* ---------------------------------------------------------------------- */
/**
* Exit the application.
*/
private void exitFindBugs() {
// TODO: offer to save work, etc.
System.exit(0);
}
/**
* Create a file chooser dialog.
* Ensures that the dialog will start in the current directory.
* @return the file chooser
*/
private JFileChooser createFileChooser() {
return new JFileChooser(currentDirectory);
}
/**
* Run a file chooser dialog.
* If a file is chosen, then the current directory is updated.
* @param dialog the file chooser dialog
* @param dialogTitle the dialog title
* @return the outcome
*/
private int chooseFile(JFileChooser dialog, String dialogTitle) {
int outcome = dialog.showDialog(this, dialogTitle);
return updateCurrentDirectoryFromDialog(dialog, outcome);
}
/**
* Run a file chooser dialog to choose a file to open.
* If a file is chosen, then the current directory is updated.
* @param dialog the file chooser dialog
* @return the outcome
*/
private int chooseFileToOpen(JFileChooser dialog) {
int outcome = dialog.showOpenDialog(this);
return updateCurrentDirectoryFromDialog(dialog, outcome);
}
private int updateCurrentDirectoryFromDialog(JFileChooser dialog, int outcome) {
if (outcome != JFileChooser.CANCEL_OPTION) {
File selectedFile = dialog.getSelectedFile();
currentDirectory = selectedFile.getParentFile();
}
return outcome;
}
/**
* Get the ConsoleLogger.
*/
public ConsoleLogger getLogger() {
return logger;
}
/**
* Show an error dialog.
*/
public void error(String message) {
JOptionPane.showMessageDialog(this, message, "Error", JOptionPane.ERROR_MESSAGE);
}
/**
* Write a message to the console window.
*/
public void writeToConsole(String message) {
consoleMessageArea.append(message);
consoleMessageArea.append("\n");
}
/* ----------------------------------------------------------------------
* main() method
* ---------------------------------------------------------------------- */
/**
* Invoke from the command line.
* @param args the command line arguments
*/
public static void main(String args[]) {
for (int i = 0; i < args.length; ++i) {
String arg = args[i];
if (arg.equals("-debug")) {
System.out.println("Setting findbugs.debug=true");
System.setProperty("findbugs.debug", "true");
} else if (arg.equals("-plastic")) {
// You can get the Plastic look and feel from jgoodies.com:
// http://www.jgoodies.com/downloads/libraries.html
// Just put "plastic.jar" in the lib directory, right next
// to the other jar files.
try {
UIManager.setLookAndFeel("com.jgoodies.plaf.plastic.PlasticXPLookAndFeel");
} catch (Exception e) {
System.err.println("Couldn't load plastic look and feel: " + e.toString());
}
}
}
// Load plugins!
DetectorFactoryCollection.instance();
FindBugsFrame frame = new FindBugsFrame();
frame.setSize(800, 600);
frame.show();
}
/* ----------------------------------------------------------------------
* Instance variables
* ---------------------------------------------------------------------- */
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenuItem aboutItem;
private javax.swing.JButton addClasspathEntryButton;
private javax.swing.JButton addJarButton;
private javax.swing.JButton addSourceDirButton;
private javax.swing.JTextArea annotationTextArea;
private javax.swing.JScrollPane annotationTextAreaScrollPane;
private javax.swing.JButton browseClasspathEntryButton;
private javax.swing.JButton browseJarButton;
private javax.swing.JButton browseSrcDirButton;
private javax.swing.JEditorPane bugDescriptionEditorPane;
private javax.swing.JScrollPane bugDescriptionScrollPane;
private javax.swing.JTabbedPane bugDetailsTabbedPane;
private javax.swing.JEditorPane bugSummaryEditorPane;
private javax.swing.JSplitPane bugTreeBugDetailsSplitter;
private javax.swing.JPanel bugTreePanel;
private javax.swing.JTree byBugTypeBugTree;
private javax.swing.JScrollPane byBugTypeScrollPane;
private javax.swing.JTree byClassBugTree;
private javax.swing.JScrollPane byClassScrollPane;
private javax.swing.JTree byPackageBugTree;
private javax.swing.JScrollPane byPackageScrollPane;
private javax.swing.JScrollPane bySummary;
private javax.swing.JLabel classpathEntryLabel;
private javax.swing.JList classpathEntryList;
private javax.swing.JLabel classpathEntryListLabel;
private javax.swing.JScrollPane classpathEntryListScrollPane;
private javax.swing.JTextField classpathEntryTextField;
private javax.swing.JMenuItem closeProjectItem;
private javax.swing.JMenuItem configureDetectorsItem;
private javax.swing.JTextArea consoleMessageArea;
private javax.swing.JScrollPane consoleScrollPane;
private javax.swing.JSplitPane consoleSplitter;
private javax.swing.JLabel editProjectLabel;
private javax.swing.JPanel editProjectPanel;
private javax.swing.JPanel emptyPanel;
private javax.swing.JMenuItem exitItem;
private javax.swing.JMenu fileMenu;
private javax.swing.JButton findBugsButton;
private javax.swing.JCheckBoxMenuItem fullDescriptionsItem;
private javax.swing.JTabbedPane groupByTabbedPane;
private javax.swing.JMenu helpMenu;
private javax.swing.JRadioButtonMenuItem highPriorityButton;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JSeparator jSeparator4;
private javax.swing.JSeparator jSeparator5;
private javax.swing.JSeparator jSeparator6;
private javax.swing.JSeparator jSeparator7;
private javax.swing.JLabel jarFileLabel;
private javax.swing.JList jarFileList;
private javax.swing.JLabel jarFileListLabel;
private javax.swing.JScrollPane jarFileListScrollPane;
private javax.swing.JTextField jarNameTextField;
private javax.swing.JMenuItem loadBugsItem;
private javax.swing.JRadioButtonMenuItem lowPriorityButton;
private javax.swing.JRadioButtonMenuItem mediumPriorityButton;
private javax.swing.JMenuItem newProjectItem;
private javax.swing.JMenuItem openProjectItem;
private javax.swing.JMenuItem reloadProjectItem;
private javax.swing.JButton removeClasspathEntryButton;
private javax.swing.JButton removeJarButton;
private javax.swing.JButton removeSrcDirButton;
private javax.swing.JPanel reportPanel;
private javax.swing.JMenuItem saveBugsItem;
private javax.swing.JMenuItem saveProjectAsItem;
private javax.swing.JMenuItem saveProjectItem;
private javax.swing.JMenu settingsMenu;
private javax.swing.JLabel sourceDirLabel;
private javax.swing.JList sourceDirList;
private javax.swing.JLabel sourceDirListLabel;
private javax.swing.JScrollPane sourceDirListScrollPane;
private javax.swing.JTextArea sourceTextArea;
private javax.swing.JScrollPane sourceTextAreaScrollPane;
private javax.swing.JTextField srcDirTextField;
private javax.swing.JMenuBar theMenuBar;
private javax.swing.JCheckBoxMenuItem viewBugDetailsItem;
private javax.swing.JCheckBoxMenuItem viewConsoleItem;
private javax.swing.JMenu viewMenu;
private javax.swing.JPanel viewPanel;
// End of variables declaration//GEN-END:variables
// My variable declarations
private ConsoleLogger logger;
private CardLayout viewPanelLayout;
private String currentView;
private File currentDirectory;
private Project currentProject;
private JTree[] bugTreeList;
private AnalysisRun currentAnalysisRun;
private SourceFinder sourceFinder = new SourceFinder();
private BugInstance currentBugInstance; // be lazy in switching bug instance details
private SourceLineAnnotation currentSourceLineAnnotation; // as above
private String currentBugDetailsKey;
private int priorityThreshold;
}
| findbugs/src/java/edu/umd/cs/findbugs/gui/FindBugsFrame.java | /*
* FindBugs - Find bugs in Java programs
* Copyright (C) 2003, University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* FindBugsFrame.java
*
* Created on March 30, 2003, 12:05 PM
*/
package edu.umd.cs.findbugs.gui;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Shape;
import java.awt.Rectangle;
import java.awt.Point;
import java.awt.Color;
import java.io.File;
import java.io.StringWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.StringReader;
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.filechooser.*;
import edu.umd.cs.daveho.ba.SourceFinder;
import edu.umd.cs.findbugs.*;
/**
* The main GUI frame for FindBugs.
*
* @author David Hovemeyer
*/
public class FindBugsFrame extends javax.swing.JFrame {
/* ----------------------------------------------------------------------
* Helper classes
* ---------------------------------------------------------------------- */
private static final Color HIGH_PRIORITY_COLOR = new Color(0xff0000);
private static final Color NORMAL_PRIORITY_COLOR = new Color(0x9f0000);
private static final Color LOW_PRIORITY_COLOR = Color.BLACK;
/**
* Custom cell renderer for the bug tree.
* We use this to select the tree icons, and to set the
* text color based on the bug priority.
*/
private static class BugCellRenderer extends DefaultTreeCellRenderer {
private ImageIcon bugGroupIcon;
private ImageIcon packageIcon;
private ImageIcon bugIcon;
private ImageIcon classIcon;
private ImageIcon methodIcon;
private ImageIcon fieldIcon;
private ImageIcon sourceFileIcon;
private Object value;
public BugCellRenderer() {
ClassLoader classLoader = this.getClass().getClassLoader();
bugGroupIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/bug.png"));
packageIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/package.png"));
bugIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/bug2.png"));
classIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/class.png"));
methodIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/method.png"));
fieldIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/field.png"));
sourceFileIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/sourcefile.png"));
}
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel,
boolean expanded, boolean leaf, int row, boolean hasFocus) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
Object obj = node.getUserObject();
this.value = obj;
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
// Set the icon, depending on what kind of node it is
if (obj instanceof BugInstance) {
setIcon(bugIcon);
} else if (obj instanceof ClassAnnotation) {
setIcon(classIcon);
} else if (obj instanceof MethodAnnotation) {
setIcon(methodIcon);
} else if (obj instanceof FieldAnnotation) {
setIcon(fieldIcon);
} else if (obj instanceof SourceLineAnnotation) {
setIcon(sourceFileIcon);
} else if (obj instanceof BugInstanceGroup) {
// This is a "group" node
BugInstanceGroup groupNode = (BugInstanceGroup) obj;
String groupType = groupNode.getGroupType();
if (groupType == GROUP_BY_CLASS) {
setIcon(classIcon);
} else if (groupType == GROUP_BY_PACKAGE) {
setIcon(packageIcon);
} else if (groupType == GROUP_BY_BUG_TYPE) {
setIcon(bugGroupIcon);
}
} else {
setIcon(null);
}
return this;
}
public Color getTextNonSelectionColor() {
return getCellTextColor();
}
private Color getCellTextColor() {
// Based on the priority, color-code the bug instance.
Color color = Color.BLACK;
if (value instanceof BugInstance) {
BugInstance bugInstance = (BugInstance) value;
switch (bugInstance.getPriority()) {
case Detector.LOW_PRIORITY:
color = LOW_PRIORITY_COLOR; break;
case Detector.NORMAL_PRIORITY:
color = NORMAL_PRIORITY_COLOR; break;
case Detector.HIGH_PRIORITY:
color = HIGH_PRIORITY_COLOR; break;
}
}
return color;
}
}
/** The instance of BugCellRenderer. */
private static final FindBugsFrame.BugCellRenderer bugCellRenderer = new FindBugsFrame.BugCellRenderer();
/**
* Tree node type for BugInstances.
* We use this instead of plain DefaultMutableTreeNodes in order to
* get more control over the exact text that is shown in the tree.
*/
private class BugTreeNode extends DefaultMutableTreeNode {
public BugTreeNode(BugInstance bugInstance) {
super(bugInstance);
}
public String toString() {
try {
BugInstance bugInstance = (BugInstance) getUserObject();
String result;
if (fullDescriptionsItem.isSelected()) {
result = bugInstance.getMessage();
} else {
result = bugInstance.toString();
}
boolean experimental = bugInstance.isExperimental();
if (experimental)
return "EXP: " + result;
else
return result;
} catch (Exception e) {
return "Error formatting message for bug: " + e.toString();
}
}
}
/**
* Compare BugInstance class names.
* This is useful for grouping bug instances by class.
* Note that all instances with the same class name will compare
* as equal.
*/
private static class BugInstanceClassComparator implements Comparator<BugInstance> {
public int compare(BugInstance lhs, BugInstance rhs) {
return lhs.getPrimaryClass().compareTo(rhs.getPrimaryClass());
}
}
/** The instance of BugInstanceClassComparator. */
private static final Comparator<BugInstance> bugInstanceClassComparator = new BugInstanceClassComparator();
/**
* Compare BugInstance package names.
* This is useful for grouping bug instances by package.
* Note that all instances with the same package name will compare
* as equal.
*/
private static class BugInstancePackageComparator implements Comparator<BugInstance> {
public int compare(BugInstance lhs, BugInstance rhs) {
return lhs.getPrimaryClass().getPackageName().compareTo(
rhs.getPrimaryClass().getPackageName());
}
}
/** The instance of BugInstancePackageComparator. */
private static final Comparator<BugInstance> bugInstancePackageComparator = new BugInstancePackageComparator();
/**
* Compare BugInstance bug types.
* This is useful for grouping bug instances by bug type.
* Note that all instances with the same bug type will compare
* as equal.
*/
private static class BugInstanceTypeComparator implements Comparator<BugInstance> {
public int compare(BugInstance lhs, BugInstance rhs) {
String lhsString = lhs.toString();
String rhsString = rhs.toString();
return lhsString.substring(0, lhsString.indexOf(':')).compareTo(
rhsString.substring(0, rhsString.indexOf(':')));
}
}
/** The instance of BugInstanceTypeComparator. */
private static final Comparator<BugInstance> bugInstanceTypeComparator = new BugInstanceTypeComparator();
/**
* Two-level comparison of bug instances by class name and
* BugInstance natural ordering.
*/
private static class BugInstanceByClassComparator implements Comparator<BugInstance> {
public int compare(BugInstance a, BugInstance b) {
int cmp = bugInstanceClassComparator.compare(a, b);
if (cmp != 0)
return cmp;
return a.compareTo(b);
}
}
/** The instance of BugInstanceByClassComparator. */
private static final Comparator<BugInstance> bugInstanceByClassComparator = new FindBugsFrame.BugInstanceByClassComparator();
/**
* Two-level comparison of bug instances by package and
* BugInstance natural ordering.
*/
private static class BugInstanceByPackageComparator implements Comparator<BugInstance> {
public int compare(BugInstance a, BugInstance b) {
int cmp = bugInstancePackageComparator.compare(a, b);
if (cmp != 0)
return cmp;
return a.compareTo(b);
}
}
/** The instance of BugInstanceByPackageComparator. */
private static final Comparator<BugInstance> bugInstanceByPackageComparator = new FindBugsFrame.BugInstanceByPackageComparator();
/**
* Two-level comparison of bug instances by bug type and
* BugInstance natural ordering.
*/
private static class BugInstanceByTypeComparator implements Comparator<BugInstance> {
public int compare(BugInstance a, BugInstance b) {
int cmp = bugInstanceTypeComparator.compare(a, b);
if (cmp != 0)
return cmp;
return a.compareTo(b);
}
}
/** The instance of BugTypeByTypeComparator. */
private static final Comparator<BugInstance> bugInstanceByTypeComparator = new FindBugsFrame.BugInstanceByTypeComparator();
/**
* Swing FileFilter class for file selection dialogs for FindBugs project files.
*/
private static class ProjectFileFilter extends FileFilter {
public boolean accept(File file) { return file.isDirectory() || file.getName().endsWith(".fb"); }
public String getDescription() { return "FindBugs projects (*.fb)"; }
}
/** The instance of ProjectFileFilter. */
private static final FileFilter projectFileFilter = new ProjectFileFilter();
/**
* Swing FileFilter for choosing an auxiliary classpath entry.
* Both Jar files and directories can be chosen.
*/
private static class AuxClasspathEntryFileFilter extends FileFilter {
public boolean accept(File file) { return file.isDirectory() || file.getName().endsWith(".jar"); }
public String getDescription() { return "Jar files and directories"; }
}
/** The instance of AuxClasspathEntryFileFilter. */
private static final FileFilter auxClasspathEntryFileFilter = new AuxClasspathEntryFileFilter();
/**
* Swing FileFilter for choosing XML saved bug files.
*/
private static class XMLFileFilter extends FileFilter {
public boolean accept(File file) { return file.isDirectory() || file.getName().endsWith(".xml"); }
public String getDescription() { return "XML saved bug files"; }
}
/** The instance of XMLFileFilter. */
private static final FileFilter xmlFileFilter = new XMLFileFilter();
/* ----------------------------------------------------------------------
* Constants
* ---------------------------------------------------------------------- */
private static final String DEFAULT_PROJECT_NAME = Project.UNNAMED_PROJECT;
private static final String GROUP_BY_CLASS = "By class";
private static final String GROUP_BY_PACKAGE = "By package";
private static final String GROUP_BY_BUG_TYPE = "By bug type";
private static final String[] GROUP_BY_ORDER_LIST = {
GROUP_BY_CLASS, GROUP_BY_PACKAGE, GROUP_BY_BUG_TYPE
};
/**
* A fudge value required in our hack to get the REAL maximum
* divider location for a JSplitPane. Experience suggests that
* the value "1" would work here, but setting it a little higher
* makes the code a bit more robust.
*/
private static final int DIVIDER_FUDGE = 3;
/* ----------------------------------------------------------------------
* Constructor
* ---------------------------------------------------------------------- */
/** Creates new form FindBugsFrame. */
public FindBugsFrame() {
initComponents();
postInitComponents();
}
/* ----------------------------------------------------------------------
* Component initialization and event handlers
* ---------------------------------------------------------------------- */
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
private void initComponents() {//GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
consoleSplitter = new javax.swing.JSplitPane();
viewPanel = new javax.swing.JPanel();
emptyPanel = new javax.swing.JPanel();
reportPanel = new javax.swing.JPanel();
editProjectPanel = new javax.swing.JPanel();
jarFileLabel = new javax.swing.JLabel();
jarNameTextField = new javax.swing.JTextField();
addJarButton = new javax.swing.JButton();
jarFileListLabel = new javax.swing.JLabel();
sourceDirLabel = new javax.swing.JLabel();
srcDirTextField = new javax.swing.JTextField();
addSourceDirButton = new javax.swing.JButton();
sourceDirListLabel = new javax.swing.JLabel();
removeJarButton = new javax.swing.JButton();
removeSrcDirButton = new javax.swing.JButton();
jSeparator1 = new javax.swing.JSeparator();
browseJarButton = new javax.swing.JButton();
browseSrcDirButton = new javax.swing.JButton();
editProjectLabel = new javax.swing.JLabel();
jSeparator2 = new javax.swing.JSeparator();
findBugsButton = new javax.swing.JButton();
jSeparator4 = new javax.swing.JSeparator();
jarFileListScrollPane = new javax.swing.JScrollPane();
jarFileList = new javax.swing.JList();
sourceDirListScrollPane = new javax.swing.JScrollPane();
sourceDirList = new javax.swing.JList();
classpathEntryLabel = new javax.swing.JLabel();
classpathEntryListLabel = new javax.swing.JLabel();
classpathEntryTextField = new javax.swing.JTextField();
browseClasspathEntryButton = new javax.swing.JButton();
addClasspathEntryButton = new javax.swing.JButton();
removeClasspathEntryButton = new javax.swing.JButton();
classpathEntryListScrollPane = new javax.swing.JScrollPane();
classpathEntryList = new javax.swing.JList();
jSeparator5 = new javax.swing.JSeparator();
bugTreePanel = new javax.swing.JPanel();
bugTreeBugDetailsSplitter = new javax.swing.JSplitPane();
groupByTabbedPane = new javax.swing.JTabbedPane();
byClassScrollPane = new javax.swing.JScrollPane();
byClassBugTree = new javax.swing.JTree();
byPackageScrollPane = new javax.swing.JScrollPane();
byPackageBugTree = new javax.swing.JTree();
byBugTypeScrollPane = new javax.swing.JScrollPane();
byBugTypeBugTree = new javax.swing.JTree();
bySummary = new javax.swing.JScrollPane();
bugSummaryEditorPane = new javax.swing.JEditorPane();
bugDetailsTabbedPane = new javax.swing.JTabbedPane();
bugDescriptionScrollPane = new javax.swing.JScrollPane();
bugDescriptionEditorPane = new javax.swing.JEditorPane();
sourceTextAreaScrollPane = new javax.swing.JScrollPane();
sourceTextArea = new javax.swing.JTextArea();
annotationTextAreaScrollPane = new javax.swing.JScrollPane();
annotationTextArea = new javax.swing.JTextArea();
consoleScrollPane = new javax.swing.JScrollPane();
consoleMessageArea = new javax.swing.JTextArea();
theMenuBar = new javax.swing.JMenuBar();
fileMenu = new javax.swing.JMenu();
newProjectItem = new javax.swing.JMenuItem();
openProjectItem = new javax.swing.JMenuItem();
saveProjectItem = new javax.swing.JMenuItem();
saveProjectAsItem = new javax.swing.JMenuItem();
reloadProjectItem = new javax.swing.JMenuItem();
closeProjectItem = new javax.swing.JMenuItem();
jSeparator3 = new javax.swing.JSeparator();
loadBugsItem = new javax.swing.JMenuItem();
saveBugsItem = new javax.swing.JMenuItem();
jSeparator6 = new javax.swing.JSeparator();
exitItem = new javax.swing.JMenuItem();
viewMenu = new javax.swing.JMenu();
viewConsoleItem = new javax.swing.JCheckBoxMenuItem();
viewBugDetailsItem = new javax.swing.JCheckBoxMenuItem();
fullDescriptionsItem = new javax.swing.JCheckBoxMenuItem();
jSeparator7 = new javax.swing.JSeparator();
lowPriorityButton = new javax.swing.JRadioButtonMenuItem();
mediumPriorityButton = new javax.swing.JRadioButtonMenuItem();
highPriorityButton = new javax.swing.JRadioButtonMenuItem();
settingsMenu = new javax.swing.JMenu();
configureDetectorsItem = new javax.swing.JMenuItem();
helpMenu = new javax.swing.JMenu();
aboutItem = new javax.swing.JMenuItem();
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
consoleSplitter.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
consoleSplitter.setResizeWeight(1.0);
consoleSplitter.setOneTouchExpandable(true);
consoleSplitter.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
consoleSplitterPropertyChange(evt);
}
});
viewPanel.setLayout(new java.awt.CardLayout());
viewPanel.add(emptyPanel, "EmptyPanel");
viewPanel.add(reportPanel, "ReportPanel");
editProjectPanel.setLayout(new java.awt.GridBagLayout());
jarFileLabel.setFont(new java.awt.Font("Dialog", 0, 12));
jarFileLabel.setText("Archive or directory:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(jarFileLabel, gridBagConstraints);
jarNameTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jarNameTextFieldActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0);
editProjectPanel.add(jarNameTextField, gridBagConstraints);
addJarButton.setFont(new java.awt.Font("Dialog", 0, 12));
addJarButton.setText("Add");
addJarButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addJarButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(addJarButton, gridBagConstraints);
jarFileListLabel.setFont(new java.awt.Font("Dialog", 0, 12));
jarFileListLabel.setText("Archives/directories:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(jarFileListLabel, gridBagConstraints);
sourceDirLabel.setFont(new java.awt.Font("Dialog", 0, 12));
sourceDirLabel.setText("Source directory:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 6;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(sourceDirLabel, gridBagConstraints);
srcDirTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
srcDirTextFieldActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 6;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0);
editProjectPanel.add(srcDirTextField, gridBagConstraints);
addSourceDirButton.setFont(new java.awt.Font("Dialog", 0, 12));
addSourceDirButton.setText("Add");
addSourceDirButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addSourceDirButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 6;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(addSourceDirButton, gridBagConstraints);
sourceDirListLabel.setFont(new java.awt.Font("Dialog", 0, 12));
sourceDirListLabel.setText("Source directories:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 7;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(sourceDirListLabel, gridBagConstraints);
removeJarButton.setFont(new java.awt.Font("Dialog", 0, 12));
removeJarButton.setText("Remove");
removeJarButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeJarButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(removeJarButton, gridBagConstraints);
removeSrcDirButton.setFont(new java.awt.Font("Dialog", 0, 12));
removeSrcDirButton.setText("Remove");
removeSrcDirButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeSrcDirButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 7;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(removeSrcDirButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
editProjectPanel.add(jSeparator1, gridBagConstraints);
browseJarButton.setFont(new java.awt.Font("Dialog", 0, 12));
browseJarButton.setText("Browse");
browseJarButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
browseJarButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 3;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(browseJarButton, gridBagConstraints);
browseSrcDirButton.setFont(new java.awt.Font("Dialog", 0, 12));
browseSrcDirButton.setText("Browse");
browseSrcDirButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
browseSrcDirButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 6;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(browseSrcDirButton, gridBagConstraints);
editProjectLabel.setBackground(new java.awt.Color(0, 0, 204));
editProjectLabel.setFont(new java.awt.Font("Dialog", 1, 24));
editProjectLabel.setForeground(new java.awt.Color(255, 255, 255));
editProjectLabel.setText("Project");
editProjectLabel.setOpaque(true);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
editProjectPanel.add(editProjectLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
editProjectPanel.add(jSeparator2, gridBagConstraints);
findBugsButton.setMnemonic('B');
findBugsButton.setText("Find Bugs!");
findBugsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
findBugsButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 13;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
editProjectPanel.add(findBugsButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 8;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
editProjectPanel.add(jSeparator4, gridBagConstraints);
jarFileListScrollPane.setPreferredSize(new java.awt.Dimension(259, 1));
jarFileList.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED));
jarFileList.setFont(new java.awt.Font("Dialog", 0, 12));
jarFileList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jarFileListScrollPane.setViewportView(jarFileList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.6;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(jarFileListScrollPane, gridBagConstraints);
sourceDirListScrollPane.setPreferredSize(new java.awt.Dimension(259, 1));
sourceDirList.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED));
sourceDirList.setFont(new java.awt.Font("Dialog", 0, 12));
sourceDirList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
sourceDirListScrollPane.setViewportView(sourceDirList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 7;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.2;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(sourceDirListScrollPane, gridBagConstraints);
classpathEntryLabel.setFont(new java.awt.Font("Dialog", 0, 12));
classpathEntryLabel.setText("Classpath entry:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 9;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3);
editProjectPanel.add(classpathEntryLabel, gridBagConstraints);
classpathEntryListLabel.setFont(new java.awt.Font("Dialog", 0, 12));
classpathEntryListLabel.setText("Classpath entries:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 10;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3);
editProjectPanel.add(classpathEntryListLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 9;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0);
editProjectPanel.add(classpathEntryTextField, gridBagConstraints);
browseClasspathEntryButton.setFont(new java.awt.Font("Dialog", 0, 12));
browseClasspathEntryButton.setText("Browse");
browseClasspathEntryButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
browseClasspathEntryButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 9;
editProjectPanel.add(browseClasspathEntryButton, gridBagConstraints);
addClasspathEntryButton.setFont(new java.awt.Font("Dialog", 0, 12));
addClasspathEntryButton.setText("Add");
addClasspathEntryButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addClasspathEntryButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 9;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0);
editProjectPanel.add(addClasspathEntryButton, gridBagConstraints);
removeClasspathEntryButton.setFont(new java.awt.Font("Dialog", 0, 12));
removeClasspathEntryButton.setText("Remove");
removeClasspathEntryButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeClasspathEntryButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 10;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0);
editProjectPanel.add(removeClasspathEntryButton, gridBagConstraints);
classpathEntryListScrollPane.setPreferredSize(new java.awt.Dimension(259, 1));
classpathEntryList.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED));
classpathEntryList.setFont(new java.awt.Font("Dialog", 0, 12));
classpathEntryListScrollPane.setViewportView(classpathEntryList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 10;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.2;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3);
editProjectPanel.add(classpathEntryListScrollPane, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 12;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(3, 0, 3, 0);
editProjectPanel.add(jSeparator5, gridBagConstraints);
viewPanel.add(editProjectPanel, "EditProjectPanel");
bugTreePanel.setLayout(new java.awt.GridBagLayout());
bugTreeBugDetailsSplitter.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
bugTreeBugDetailsSplitter.setResizeWeight(1.0);
bugTreeBugDetailsSplitter.setOneTouchExpandable(true);
bugTreeBugDetailsSplitter.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
bugTreeBugDetailsSplitterPropertyChange(evt);
}
});
byClassScrollPane.setViewportView(byClassBugTree);
groupByTabbedPane.addTab("By Class", byClassScrollPane);
byPackageScrollPane.setViewportView(byPackageBugTree);
groupByTabbedPane.addTab("By Package", byPackageScrollPane);
byBugTypeScrollPane.setViewportView(byBugTypeBugTree);
groupByTabbedPane.addTab("By Bug Type", byBugTypeScrollPane);
bySummary.setViewportView(bugSummaryEditorPane);
groupByTabbedPane.addTab("Summary", bySummary);
bugTreeBugDetailsSplitter.setTopComponent(groupByTabbedPane);
bugDescriptionEditorPane.setEditable(false);
bugDescriptionScrollPane.setViewportView(bugDescriptionEditorPane);
bugDetailsTabbedPane.addTab("Details", bugDescriptionScrollPane);
sourceTextAreaScrollPane.setMinimumSize(new java.awt.Dimension(22, 180));
sourceTextAreaScrollPane.setPreferredSize(new java.awt.Dimension(0, 100));
sourceTextArea.setEditable(false);
sourceTextArea.setFont(new java.awt.Font("Lucida Sans Typewriter", 0, 12));
sourceTextArea.setEnabled(false);
sourceTextAreaScrollPane.setViewportView(sourceTextArea);
bugDetailsTabbedPane.addTab("Source code", sourceTextAreaScrollPane);
annotationTextAreaScrollPane.setViewportView(annotationTextArea);
bugDetailsTabbedPane.addTab("Annotations", annotationTextAreaScrollPane);
bugTreeBugDetailsSplitter.setBottomComponent(bugDetailsTabbedPane);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
bugTreePanel.add(bugTreeBugDetailsSplitter, gridBagConstraints);
viewPanel.add(bugTreePanel, "BugTree");
consoleSplitter.setTopComponent(viewPanel);
consoleScrollPane.setMinimumSize(new java.awt.Dimension(22, 100));
consoleScrollPane.setPreferredSize(new java.awt.Dimension(0, 100));
consoleMessageArea.setBackground(new java.awt.Color(204, 204, 204));
consoleMessageArea.setEditable(false);
consoleMessageArea.setFont(new java.awt.Font("Lucida Sans Typewriter", 0, 12));
consoleMessageArea.setMinimumSize(new java.awt.Dimension(0, 0));
consoleMessageArea.setAutoscrolls(false);
consoleScrollPane.setViewportView(consoleMessageArea);
consoleSplitter.setBottomComponent(consoleScrollPane);
getContentPane().add(consoleSplitter, java.awt.BorderLayout.CENTER);
theMenuBar.setFont(new java.awt.Font("Dialog", 0, 12));
fileMenu.setMnemonic('F');
fileMenu.setText("File");
fileMenu.setFont(new java.awt.Font("Dialog", 0, 12));
fileMenu.addMenuListener(new javax.swing.event.MenuListener() {
public void menuCanceled(javax.swing.event.MenuEvent evt) {
}
public void menuDeselected(javax.swing.event.MenuEvent evt) {
}
public void menuSelected(javax.swing.event.MenuEvent evt) {
fileMenuMenuSelected(evt);
}
});
newProjectItem.setFont(new java.awt.Font("Dialog", 0, 12));
newProjectItem.setMnemonic('N');
newProjectItem.setText("New Project");
newProjectItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newProjectItemActionPerformed(evt);
}
});
fileMenu.add(newProjectItem);
openProjectItem.setFont(new java.awt.Font("Dialog", 0, 12));
openProjectItem.setMnemonic('O');
openProjectItem.setText("Open Project");
openProjectItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openProjectItemActionPerformed(evt);
}
});
fileMenu.add(openProjectItem);
saveProjectItem.setFont(new java.awt.Font("Dialog", 0, 12));
saveProjectItem.setMnemonic('S');
saveProjectItem.setText("Save Project");
saveProjectItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveProjectItemActionPerformed(evt);
}
});
fileMenu.add(saveProjectItem);
saveProjectAsItem.setFont(new java.awt.Font("Dialog", 0, 12));
saveProjectAsItem.setMnemonic('A');
saveProjectAsItem.setText("Save Project As");
saveProjectAsItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveProjectAsItemActionPerformed(evt);
}
});
fileMenu.add(saveProjectAsItem);
reloadProjectItem.setFont(new java.awt.Font("Dialog", 0, 12));
reloadProjectItem.setMnemonic('R');
reloadProjectItem.setText("Reload Project");
reloadProjectItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
reloadProjectItemActionPerformed(evt);
}
});
fileMenu.add(reloadProjectItem);
closeProjectItem.setFont(new java.awt.Font("Dialog", 0, 12));
closeProjectItem.setMnemonic('C');
closeProjectItem.setText("Close Project");
closeProjectItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeProjectItemActionPerformed(evt);
}
});
fileMenu.add(closeProjectItem);
fileMenu.add(jSeparator3);
loadBugsItem.setFont(new java.awt.Font("Dialog", 0, 12));
loadBugsItem.setMnemonic('L');
loadBugsItem.setText("Load Bugs");
loadBugsItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loadBugsItemActionPerformed(evt);
}
});
fileMenu.add(loadBugsItem);
saveBugsItem.setFont(new java.awt.Font("Dialog", 0, 12));
saveBugsItem.setMnemonic('B');
saveBugsItem.setText("Save Bugs");
saveBugsItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveBugsItemActionPerformed(evt);
}
});
fileMenu.add(saveBugsItem);
fileMenu.add(jSeparator6);
exitItem.setFont(new java.awt.Font("Dialog", 0, 12));
exitItem.setMnemonic('X');
exitItem.setText("Exit");
exitItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitItemActionPerformed(evt);
}
});
fileMenu.add(exitItem);
theMenuBar.add(fileMenu);
viewMenu.setMnemonic('V');
viewMenu.setText("View");
viewMenu.setFont(new java.awt.Font("Dialog", 0, 12));
viewMenu.addMenuListener(new javax.swing.event.MenuListener() {
public void menuCanceled(javax.swing.event.MenuEvent evt) {
}
public void menuDeselected(javax.swing.event.MenuEvent evt) {
}
public void menuSelected(javax.swing.event.MenuEvent evt) {
viewMenuMenuSelected(evt);
}
});
viewConsoleItem.setFont(new java.awt.Font("Dialog", 0, 12));
viewConsoleItem.setMnemonic('C');
viewConsoleItem.setText("Console");
viewConsoleItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewConsoleItemActionPerformed(evt);
}
});
viewMenu.add(viewConsoleItem);
viewBugDetailsItem.setFont(new java.awt.Font("Dialog", 0, 12));
viewBugDetailsItem.setMnemonic('D');
viewBugDetailsItem.setSelected(true);
viewBugDetailsItem.setText("Bug Details");
viewBugDetailsItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewBugDetailsItemActionPerformed(evt);
}
});
viewMenu.add(viewBugDetailsItem);
fullDescriptionsItem.setFont(new java.awt.Font("Dialog", 0, 12));
fullDescriptionsItem.setMnemonic('F');
fullDescriptionsItem.setSelected(true);
fullDescriptionsItem.setText("Full Descriptions");
fullDescriptionsItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fullDescriptionsItemActionPerformed(evt);
}
});
viewMenu.add(fullDescriptionsItem);
viewMenu.add(jSeparator7);
lowPriorityButton.setFont(new java.awt.Font("Dialog", 0, 12));
lowPriorityButton.setMnemonic('L');
lowPriorityButton.setText("Low priority");
lowPriorityButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
lowPriorityButtonActionPerformed(evt);
}
});
viewMenu.add(lowPriorityButton);
mediumPriorityButton.setFont(new java.awt.Font("Dialog", 0, 12));
mediumPriorityButton.setMnemonic('M');
mediumPriorityButton.setSelected(true);
mediumPriorityButton.setText("Medium priority");
mediumPriorityButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mediumPriorityButtonActionPerformed(evt);
}
});
viewMenu.add(mediumPriorityButton);
highPriorityButton.setFont(new java.awt.Font("Dialog", 0, 12));
highPriorityButton.setMnemonic('H');
highPriorityButton.setText("High priority");
highPriorityButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
highPriorityButtonActionPerformed(evt);
}
});
viewMenu.add(highPriorityButton);
theMenuBar.add(viewMenu);
settingsMenu.setMnemonic('S');
settingsMenu.setText("Settings");
settingsMenu.setFont(new java.awt.Font("Dialog", 0, 12));
configureDetectorsItem.setFont(new java.awt.Font("Dialog", 0, 12));
configureDetectorsItem.setMnemonic('C');
configureDetectorsItem.setText("Configure Detectors...");
configureDetectorsItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
configureDetectorsItemActionPerformed(evt);
}
});
settingsMenu.add(configureDetectorsItem);
theMenuBar.add(settingsMenu);
helpMenu.setMnemonic('H');
helpMenu.setText("Help");
helpMenu.setFont(new java.awt.Font("Dialog", 0, 12));
aboutItem.setFont(new java.awt.Font("Dialog", 0, 12));
aboutItem.setMnemonic('A');
aboutItem.setText("About");
aboutItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
aboutItemActionPerformed(evt);
}
});
helpMenu.add(aboutItem);
theMenuBar.add(helpMenu);
setJMenuBar(theMenuBar);
pack();
}//GEN-END:initComponents
private void highPriorityButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_highPriorityButtonActionPerformed
mediumPriorityButton.setSelected(false);
lowPriorityButton.setSelected(false);
setPriorityThreshold(Detector.HIGH_PRIORITY);
}//GEN-LAST:event_highPriorityButtonActionPerformed
private void mediumPriorityButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mediumPriorityButtonActionPerformed
highPriorityButton.setSelected(false);
lowPriorityButton.setSelected(false);
setPriorityThreshold(Detector.NORMAL_PRIORITY);
}//GEN-LAST:event_mediumPriorityButtonActionPerformed
private void lowPriorityButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lowPriorityButtonActionPerformed
highPriorityButton.setSelected(false);
mediumPriorityButton.setSelected(false);
setPriorityThreshold(Detector.LOW_PRIORITY);
}//GEN-LAST:event_lowPriorityButtonActionPerformed
private void saveBugsItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveBugsItemActionPerformed
try {
if (currentAnalysisRun == null) {
logger.logMessage(ConsoleLogger.ERROR, "No bugs are loaded!");
return;
}
JFileChooser chooser = createFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setFileFilter(xmlFileFilter);
int result = chooseFile(chooser, "Save bugs");
if (result != JFileChooser.CANCEL_OPTION) {
// Make sure current annotation text is up to date with its
// corresponding bug instance
if (currentBugInstance != null)
synchBugAnnotation(currentBugInstance);
// Save bugs to file
File selectedFile = chooser.getSelectedFile();
currentAnalysisRun.saveBugsToFile(selectedFile);
}
} catch (Exception e) {
e.printStackTrace();
logger.logMessage(ConsoleLogger.ERROR, "Could not save bugs: " + e.toString());
}
}//GEN-LAST:event_saveBugsItemActionPerformed
private void loadBugsItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadBugsItemActionPerformed
// FIXME: offer to save current project and bugs
try {
JFileChooser chooser = createFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setFileFilter(xmlFileFilter);
int result = chooseFile(chooser, "Load bugs");
if (result != JFileChooser.CANCEL_OPTION) {
File selectedFile = chooser.getSelectedFile();
Project project = new Project();
AnalysisRun analysisRun = new AnalysisRun(project, this);
analysisRun.loadBugsFromFile(selectedFile);
setProject(project);
synchAnalysisRun(analysisRun);
}
} catch (Exception e) {
e.printStackTrace();
logger.logMessage(ConsoleLogger.ERROR, "Could not load bugs: " + e.toString());
}
}//GEN-LAST:event_loadBugsItemActionPerformed
private void configureDetectorsItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_configureDetectorsItemActionPerformed
ConfigureDetectorsDialog dialog = new ConfigureDetectorsDialog(this, true);
dialog.setSize(700, 520);
dialog.setLocationRelativeTo(null); // center the dialog
dialog.show();
}//GEN-LAST:event_configureDetectorsItemActionPerformed
private void reloadProjectItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_reloadProjectItemActionPerformed
Project current = getCurrentProject();
if ( current == null )
return;
try {
String filename = current.getFileName();
File file = new File( filename );
Project project = new Project(file.getPath());
FileInputStream in = new FileInputStream(file);
project.read(in);
setProject( null );
setProject(project);
findBugsButtonActionPerformed( evt );
} catch (IOException e) {
logger.logMessage(ConsoleLogger.ERROR, "Could not reload project: " + e.getMessage());
}
}//GEN-LAST:event_reloadProjectItemActionPerformed
private void saveProjectAsItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveProjectAsItemActionPerformed
saveProject(getCurrentProject(), "Save project as", true);
}//GEN-LAST:event_saveProjectAsItemActionPerformed
private void viewMenuMenuSelected(javax.swing.event.MenuEvent evt) {//GEN-FIRST:event_viewMenuMenuSelected
// View bug details and full descriptions items,
// are only enabled if there is a project open.
boolean hasProject = getCurrentProject() != null;
viewBugDetailsItem.setEnabled(hasProject);
fullDescriptionsItem.setEnabled(hasProject);
}//GEN-LAST:event_viewMenuMenuSelected
private void fileMenuMenuSelected(javax.swing.event.MenuEvent evt) {//GEN-FIRST:event_fileMenuMenuSelected
// Save and close project items are only enabled if there is a project open.
boolean hasProject = getCurrentProject() != null;
saveProjectItem.setEnabled(hasProject);
saveProjectAsItem.setEnabled(hasProject);
reloadProjectItem.setEnabled(hasProject);
closeProjectItem.setEnabled(hasProject);
}//GEN-LAST:event_fileMenuMenuSelected
private void closeProjectItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeProjectItemActionPerformed
if (closeProjectHook(getCurrentProject(), "Close project")) {
setProject(null);
}
}//GEN-LAST:event_closeProjectItemActionPerformed
private void removeClasspathEntryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeClasspathEntryButtonActionPerformed
int selIndex = classpathEntryList.getSelectedIndex();
if (selIndex >= 0) {
Project project = getCurrentProject();
project.removeAuxClasspathEntry(selIndex);
DefaultListModel listModel = (DefaultListModel) classpathEntryList.getModel();
listModel.removeElementAt(selIndex);
}
}//GEN-LAST:event_removeClasspathEntryButtonActionPerformed
private void addClasspathEntryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addClasspathEntryButtonActionPerformed
addClasspathEntryToList();
}//GEN-LAST:event_addClasspathEntryButtonActionPerformed
private void browseClasspathEntryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseClasspathEntryButtonActionPerformed
JFileChooser chooser = createFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setFileFilter(auxClasspathEntryFileFilter);
chooser.setMultiSelectionEnabled(true);
int result = chooseFile(chooser, "Add entry");
if (result != JFileChooser.CANCEL_OPTION) {
File[] selectedFileList = chooser.getSelectedFiles();
for (int i = 0; i < selectedFileList.length; ++i) {
String entry = selectedFileList[i].getPath();
addClasspathEntryToProject(entry);
}
}
}//GEN-LAST:event_browseClasspathEntryButtonActionPerformed
private void fullDescriptionsItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fullDescriptionsItemActionPerformed
for (int j = 0; j < bugTreeList.length; ++j) {
JTree bugTree = bugTreeList[j];
// Redisplay the displayed bug instance nodes
DefaultTreeModel bugTreeModel = (DefaultTreeModel) bugTree.getModel();
int numRows = bugTree.getRowCount();
for (int i = 0; i < numRows; ++i) {
//System.out.println("Getting path for row " + i);
TreePath path = bugTree.getPathForRow(i);
if (path == null)
continue;
DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
if (node instanceof BugTreeNode)
bugTreeModel.valueForPathChanged(path, node.getUserObject());
}
}
}//GEN-LAST:event_fullDescriptionsItemActionPerformed
private void viewBugDetailsItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewBugDetailsItemActionPerformed
String view = getView();
if (view.equals("BugTree")) {
checkBugDetailsVisibility();
}
}//GEN-LAST:event_viewBugDetailsItemActionPerformed
private void bugTreeBugDetailsSplitterPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_bugTreeBugDetailsSplitterPropertyChange
// Here we want to
// (1) Keep the View:Bug details checkbox item up to date, and
// (2) keep the details window synchronized with the current bug instance
String propertyName = evt.getPropertyName();
if (propertyName.equals(JSplitPane.DIVIDER_LOCATION_PROPERTY)) {
boolean isMaximized = isSplitterMaximized(bugTreeBugDetailsSplitter, evt);
viewBugDetailsItem.setSelected(!isMaximized);
if (!isMaximized) {
// Details window is shown, so make sure it is populated
// with bug detail information
synchBugInstance();
}
}
}//GEN-LAST:event_bugTreeBugDetailsSplitterPropertyChange
private void openProjectItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openProjectItemActionPerformed
if (!closeProjectHook(getCurrentProject(), "Open Project"))
return;
JFileChooser chooser = createFileChooser();
chooser.setFileFilter(projectFileFilter);
int result = chooseFileToOpen(chooser);
if (result == JFileChooser.CANCEL_OPTION)
return;
try {
File file = chooser.getSelectedFile();
Project project = new Project(file.getPath());
FileInputStream in = new FileInputStream(file);
project.read(in);
setProject(project);
} catch (IOException e) {
logger.logMessage(ConsoleLogger.ERROR, "Could not open project: " + e.getMessage());
}
}//GEN-LAST:event_openProjectItemActionPerformed
private void saveProjectItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveProjectItemActionPerformed
saveProject(getCurrentProject(), "Save project");
}//GEN-LAST:event_saveProjectItemActionPerformed
private void aboutItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutItemActionPerformed
AboutDialog dialog = new AboutDialog(this, true);
dialog.setSize(500, 354);
dialog.setLocationRelativeTo(null); // center the dialog
dialog.show();
}//GEN-LAST:event_aboutItemActionPerformed
private void consoleSplitterPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_consoleSplitterPropertyChange
// The idea here is to keep the View:Console checkbox up to date with
// the real location of the divider of the consoleSplitter.
// What we want is if any part of the console window is visible,
// then the checkbox should be checked.
String propertyName = evt.getPropertyName();
if (propertyName.equals(JSplitPane.DIVIDER_LOCATION_PROPERTY)) {
boolean isMaximized = isSplitterMaximized(consoleSplitter, evt);
viewConsoleItem.setSelected(!isMaximized);
}
}//GEN-LAST:event_consoleSplitterPropertyChange
private void viewConsoleItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewConsoleItemActionPerformed
if (viewConsoleItem.isSelected()) {
consoleSplitter.resetToPreferredSizes();
} else {
consoleSplitter.setDividerLocation(1.0);
}
}//GEN-LAST:event_viewConsoleItemActionPerformed
private void findBugsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_findBugsButtonActionPerformed
Project project = getCurrentProject();
if (project.getNumJarFiles() == 0) {
logger.logMessage(ConsoleLogger.ERROR, "Project " + project + " has no Jar files selected");
return;
}
bugDescriptionEditorPane.setText("");
sourceTextArea.setText("");
AnalysisRun analysisRun = new AnalysisRun(project, this);
logger.logMessage(ConsoleLogger.INFO, "Beginning analysis of " + project);
// Run the analysis!
RunAnalysisDialog dialog = new RunAnalysisDialog(this, analysisRun);
dialog.setSize(400, 300);
dialog.setLocationRelativeTo(null); // center the dialog
dialog.show();
if (dialog.isCompleted()) {
logger.logMessage(ConsoleLogger.INFO, "Analysis " + project + " completed");
// Report any errors that might have occurred during analysis
analysisRun.reportAnalysisErrors();
// Now we have an analysis run to look at
synchAnalysisRun(analysisRun);
} else {
logger.logMessage(ConsoleLogger.INFO, "Analysis of " + project + " cancelled by user");
}
}//GEN-LAST:event_findBugsButtonActionPerformed
private void browseSrcDirButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseSrcDirButtonActionPerformed
JFileChooser chooser = createFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int rc = chooseFile(chooser, "Add source directory");
if (rc == JFileChooser.APPROVE_OPTION) {
srcDirTextField.setText(chooser.getSelectedFile().getPath());
addSourceDirToList();
}
}//GEN-LAST:event_browseSrcDirButtonActionPerformed
private void srcDirTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_srcDirTextFieldActionPerformed
addSourceDirToList();
}//GEN-LAST:event_srcDirTextFieldActionPerformed
private void jarNameTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jarNameTextFieldActionPerformed
addJarToList();
}//GEN-LAST:event_jarNameTextFieldActionPerformed
private static final HashSet<String> archiveExtensionSet = new HashSet<String>();
static {
archiveExtensionSet.add(".jar");
archiveExtensionSet.add(".zip");
archiveExtensionSet.add(".ear");
archiveExtensionSet.add(".war");
}
private void browseJarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseJarButtonActionPerformed
JFileChooser chooser = createFileChooser();
FileFilter filter = new FileFilter() {
public boolean accept(File file) {
if (file.isDirectory())
return true;
String fileName = file.getName();
int dot = fileName.lastIndexOf('.');
if (dot < 0)
return false;
String extension = fileName.substring(dot);
return archiveExtensionSet.contains(extension);
}
public String getDescription() { return "Java archives (*.jar,*.zip,*.ear,*.war)"; }
};
chooser.setFileFilter(filter);
chooser.setMultiSelectionEnabled(true);
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int rc = chooseFile(chooser, "Add archive or directory");
if (rc == JFileChooser.APPROVE_OPTION) {
File[] selectedFileList = chooser.getSelectedFiles();
for (int i = 0; i < selectedFileList.length; ++i) {
String entry = selectedFileList[i].getPath();
addJarToProject(entry);
}
}
}//GEN-LAST:event_browseJarButtonActionPerformed
private void newProjectItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newProjectItemActionPerformed
Project project = new Project(DEFAULT_PROJECT_NAME);
setProject(project);
}//GEN-LAST:event_newProjectItemActionPerformed
private void exitItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitItemActionPerformed
exitFindBugs();
}//GEN-LAST:event_exitItemActionPerformed
private void removeSrcDirButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeSrcDirButtonActionPerformed
int selIndex = sourceDirList.getSelectedIndex();
if (selIndex >= 0) {
Project project = getCurrentProject();
project.removeSourceDir(selIndex);
DefaultListModel listModel = (DefaultListModel) sourceDirList.getModel();
listModel.removeElementAt(selIndex);
}
}//GEN-LAST:event_removeSrcDirButtonActionPerformed
private void removeJarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeJarButtonActionPerformed
int selIndex = jarFileList.getSelectedIndex();
if (selIndex >= 0) {
Project project = getCurrentProject();
project.removeJarFile(selIndex);
DefaultListModel listModel = (DefaultListModel) jarFileList.getModel();
listModel.removeElementAt(selIndex);
}
}//GEN-LAST:event_removeJarButtonActionPerformed
private void addSourceDirButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addSourceDirButtonActionPerformed
addSourceDirToList();
}//GEN-LAST:event_addSourceDirButtonActionPerformed
private void addJarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addJarButtonActionPerformed
addJarToList();
}//GEN-LAST:event_addJarButtonActionPerformed
/** Exit the Application */
private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
exitFindBugs();
}//GEN-LAST:event_exitForm
/**
* This is called whenever the selection is changed in the bug tree.
* @param e the TreeSelectionEvent
*/
private void bugTreeSelectionChanged(TreeSelectionEvent e) {
BugInstance selected = getCurrentBugInstance();
if (selected != null) {
synchBugInstance();
}
}
/* ----------------------------------------------------------------------
* Component initialization support
* ---------------------------------------------------------------------- */
/**
* This is called from the constructor to perform post-initialization
* of the components in the form.
*/
private void postInitComponents() {
logger = new ConsoleLogger(this);
viewPanelLayout = (CardLayout) viewPanel.getLayout();
// Console starts out disabled
consoleSplitter.setDividerLocation(1.0);
// List of bug group tabs.
// This must be in the same order as GROUP_BY_ORDER_LIST!
bugTreeList = new JTree[]{byClassBugTree, byPackageBugTree, byBugTypeBugTree};
// Configure bug trees
for (int i = 0; i < bugTreeList.length; ++i) {
JTree bugTree = bugTreeList[i];
bugTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
bugTree.setCellRenderer(bugCellRenderer);
bugTree.setRootVisible(false);
bugTree.setShowsRootHandles(true);
bugTree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
bugTreeSelectionChanged(e);
}
});
}
jarFileList.setModel(new DefaultListModel());
sourceDirList.setModel(new DefaultListModel());
classpathEntryList.setModel(new DefaultListModel());
// We use a special highlight painter to ensure that the highlights cover
// complete source lines, even though the source text doesn't
// fill the lines completely.
final Highlighter.HighlightPainter painter =
new DefaultHighlighter.DefaultHighlightPainter(sourceTextArea.getSelectionColor()) {
public Shape paintLayer(Graphics g, int offs0, int offs1,
Shape bounds, JTextComponent c, View view) {
try {
Shape extent = view.modelToView(offs0, Position.Bias.Forward, offs1, Position.Bias.Backward, bounds);
Rectangle rect = extent.getBounds();
rect.x = 0;
rect.width = bounds.getBounds().width;
g.setColor(getColor());
g.fillRect(rect.x, rect.y, rect.width, rect.height);
return rect;
} catch (BadLocationException e) {
return null;
}
}
};
Highlighter sourceHighlighter = new DefaultHighlighter() {
public Object addHighlight(int p0, int p1, Highlighter.HighlightPainter p)
throws BadLocationException {
return super.addHighlight(p0, p1, painter);
}
};
sourceTextArea.setHighlighter(sourceHighlighter);
updateTitle(getCurrentProject());
priorityThreshold = Detector.NORMAL_PRIORITY;
}
/* ----------------------------------------------------------------------
* Helpers for accessing and modifying UI components
* ---------------------------------------------------------------------- */
/**
* Based on the current tree selection path, get a user object
* whose class is the same as the given class.
* @param tree the tree
* @param c the class
* @return an instance of the given kind of object which is in the
* current selection, or null if there is no matching object
*/
private static Object getTreeSelectionOf(JTree tree, Class c) {
TreePath selPath = tree.getSelectionPath();
// There may not be anything selected at the moment
if (selPath == null)
return null;
// Work backwards from end until we get to the kind of
// object we're looking for.
Object[] nodeList = selPath.getPath();
for (int i = nodeList.length - 1; i >= 0; --i) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodeList[i];
Object nodeInfo = node.getUserObject();
if (nodeInfo != null && nodeInfo.getClass() == c)
return nodeInfo;
}
return null;
}
/**
* Get the current project.
*/
private Project getCurrentProject() {
return currentProject;
}
/**
* Get the current analysis run.
*/
private AnalysisRun getCurrentAnalysisRun() {
return currentAnalysisRun;
}
/**
* Get the bug instance currently selected in the bug tree.
*/
private BugInstance getCurrentBugInstance() {
JTree bugTree = getCurrentBugTree();
if ( bugTree != null ) {
return (BugInstance) getTreeSelectionOf(bugTree, BugInstance.class);
}
return null;
}
/**
* Return whether or not the given splitter is "maximized", meaning that
* the top window of the split has been given all of the space.
* Note that this window assumes that the split is vertical (meaning
* that we have top and bottom components).
* @param splitter the JSplitPane
* @param evt the event that is changing the splitter value
*/
private boolean isSplitterMaximized(JSplitPane splitter, java.beans.PropertyChangeEvent evt) {
Integer location = (Integer) evt.getNewValue();
java.awt.Container parent = splitter.getParent();
int height = splitter.getHeight();
int hopefullyMaxDivider = height - (splitter.getDividerSize() + DIVIDER_FUDGE);
//System.out.println("Splitter: "+(splitter==consoleSplitter?"consoleSplitter":"bugTreeBugDetailsSplitter")+
// ": height="+height+",location="+location+
// ",hopefullyMax="+hopefullyMaxDivider);
boolean isMaximized = location.intValue() >= hopefullyMaxDivider;
return isMaximized;
}
private void checkBugDetailsVisibility() {
if (viewBugDetailsItem.isSelected()) {
bugTreeBugDetailsSplitter.resetToPreferredSizes();
} else {
bugTreeBugDetailsSplitter.setDividerLocation(1.0);
}
//System.out.("New bug detail splitter location " + bugTreeBugDetailsSplitter.getDividerLocation());
}
private JTree getCurrentBugTree() {
JScrollPane selected = (JScrollPane) groupByTabbedPane.getSelectedComponent();
Object view = selected.getViewport().getView();
if ( view instanceof JTree ) {
return (JTree)view;
}
return null;
}
/* ----------------------------------------------------------------------
* Synchronization of data model and UI
* ---------------------------------------------------------------------- */
/**
* Set the priority threshold for display of bugs in the bug tree.
* @param threshold the threshold
*/
private void setPriorityThreshold(int threshold) {
if (threshold != priorityThreshold) {
priorityThreshold = threshold;
if (currentAnalysisRun != null)
synchAnalysisRun(currentAnalysisRun);
}
}
private void setProject(Project project) {
currentProject = project;
if (project != null) {
synchProject(project);
setView("EditProjectPanel");
} else {
setView("EmptyPanel");
}
updateTitle(project);
}
private void updateTitle(Project project) {
if (project == null)
this.setTitle("FindBugs - no project");
else
this.setTitle("FindBugs - " + project.toString());
}
/**
* Save given project.
* If the project already has a valid filename, use that filename.
* Otherwise, prompt for one.
* @param project the Project to save
* @param dialogTitle the title for the save dialog (if needed)
*/
private boolean saveProject(Project project, String dialogTitle) {
return saveProject(project, dialogTitle, false);
}
/**
* Offer to save the current Project to a file.
* @param project the Project to save
* @param dialogTitle the title for the save dialog (if needed)
* @param chooseFilename if true, force a dialog to prompt the user
* for a filename
* @return true if the project is saved successfully, false if the user
* cancels or an error occurs
*/
private boolean saveProject(Project project, String dialogTitle, boolean chooseFilename) {
try {
if (project == null)
return true;
File file;
String fileName = project.getFileName();
if (!fileName.startsWith("<") && !chooseFilename) {
file = new File(fileName);
} else {
JFileChooser chooser = createFileChooser();
chooser.setFileFilter(projectFileFilter);
int result = chooseFile(chooser, dialogTitle);
if (result == JFileChooser.CANCEL_OPTION)
return false;
file = chooser.getSelectedFile();
fileName = Project.transformFilename(file.getPath());
file = new File(fileName);
}
FileOutputStream out = new FileOutputStream(file);
project.write(out);
logger.logMessage(ConsoleLogger.INFO, "Project saved");
project.setFileName(file.getPath());
updateTitle(project);
return true;
} catch (IOException e) {
logger.logMessage(ConsoleLogger.ERROR, "Could not save project: " + e.toString());
JOptionPane.showMessageDialog(this, "Error saving project: " + e.toString(),
"Error", JOptionPane.ERROR_MESSAGE);
return false;
}
}
/**
* Hook to call before closing a project.
* @param project the project being closed
* @param savePromptTitle title to use for the "Save project?" dialog
* @return true if user has confirmed that the project should be closed,
* false if the close is cancelled
*/
private boolean closeProjectHook(Project project, String savePromptTitle) {
if (project == null || !project.isModified())
return true;
// Confirm that the project should be closed.
int option = JOptionPane.showConfirmDialog(this, "Save project?", savePromptTitle,
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (option == JOptionPane.CANCEL_OPTION)
return false;
else if (option == JOptionPane.YES_OPTION) {
boolean result = saveProject(project, "Save project");
if (result)
JOptionPane.showMessageDialog(this, "Project saved");
return result;
} else
return true;
}
/**
* Synchronize the edit project dialog with given project.
* @param project the selected project
*/
private void synchProject(Project project) {
// Clear text fields
jarNameTextField.setText("");
srcDirTextField.setText("");
classpathEntryTextField.setText("");
// Populate jar file, source directory, and aux classpath entry lists
DefaultListModel jarListModel = (DefaultListModel) jarFileList.getModel();
jarListModel.clear();
for (int i = 0; i < project.getNumJarFiles(); ++i) {
jarListModel.addElement(project.getJarFile(i));
}
DefaultListModel srcDirListModel = (DefaultListModel) sourceDirList.getModel();
srcDirListModel.clear();
for (int i = 0; i < project.getNumSourceDirs(); ++i) {
srcDirListModel.addElement(project.getSourceDir(i));
}
DefaultListModel classpathEntryListModel = (DefaultListModel) classpathEntryList.getModel();
classpathEntryListModel.clear();
for (int i = 0; i < project.getNumAuxClasspathEntries(); ++i) {
classpathEntryListModel.addElement(project.getAuxClasspathEntry(i));
}
}
/**
* Synchronize the bug trees with the given analysisRun object.
* @param analysisRun the selected analysis run
*/
private void synchAnalysisRun(AnalysisRun analysisRun) {
// Create and populate tree models
for (int i = 0; i < GROUP_BY_ORDER_LIST.length; ++i) {
DefaultMutableTreeNode bugRootNode = new DefaultMutableTreeNode();
DefaultTreeModel bugTreeModel = new DefaultTreeModel(bugRootNode);
String groupByOrder = GROUP_BY_ORDER_LIST[i];
analysisRun.setTreeModel(groupByOrder, bugTreeModel);
populateAnalysisRunTreeModel(analysisRun, groupByOrder);
if (i < bugTreeList.length)
bugTreeList[i].setModel(bugTreeModel);
}
currentAnalysisRun = analysisRun;
//set the summary output
setSummary( analysisRun.getSummary() );
setView("BugTree");
}
private void setSummary( String summaryXML ) {
bugSummaryEditorPane.setContentType("text/html");
bugSummaryEditorPane.setText(summaryXML);
// FIXME: unfortunately, using setText() on the editor pane
// results in the contents being scrolled to the bottom of the pane.
// An immediate inline call to set the scroll position does nothing.
// So, use invokeLater(), even though this results in flashing.
// [What we really need is a way to set the text WITHOUT changing
// the caret position. Need to investigate.]
SwingUtilities.invokeLater(new Runnable() {
public void run() {
bySummary.getViewport().setViewPosition(new Point(0, 0));
}
});
}
/**
* Populate an analysis run's tree model for given sort order.
*/
private void populateAnalysisRunTreeModel(AnalysisRun analysisRun, final String groupBy) {
//System.out.println("Populating bug tree for order " + groupBy);
// Set busy cursor - this is potentially a time-consuming operation
Cursor orig = this.getCursor();
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
final DefaultTreeModel bugTreeModel = analysisRun.getTreeModel(groupBy);
final DefaultMutableTreeNode bugRootNode = (DefaultMutableTreeNode) bugTreeModel.getRoot();
// Delete all children from root node
bugRootNode.removeAllChildren();
// Sort the instances (considering only those that meet the
// priority threshold)
TreeSet<BugInstance> sortedCollection = new TreeSet<BugInstance>(getBugInstanceComparator(groupBy));
for (Iterator<BugInstance> i = analysisRun.getBugInstances().iterator(); i.hasNext(); ) {
BugInstance bugInstance = i.next();
if (bugInstance.getPriority() <= priorityThreshold)
sortedCollection.add(bugInstance);
}
// The grouper callback is what actually adds the group and bug
// nodes to the tree.
Grouper.Callback<BugInstance> callback = new Grouper.Callback<BugInstance>() {
private BugInstanceGroup currentGroup;
private DefaultMutableTreeNode currentGroupNode;
public void startGroup(BugInstance member) {
String groupName;
if (groupBy == GROUP_BY_CLASS)
groupName = member.getPrimaryClass().getClassName();
else if (groupBy == GROUP_BY_PACKAGE) {
groupName = member.getPrimaryClass().getPackageName();
if (groupName.equals(""))
groupName = "Unnamed package";
} else if (groupBy == GROUP_BY_BUG_TYPE) {
String desc = member.toString();
String shortBugType = desc.substring(0, desc.indexOf(':'));
String bugTypeDescription = I18N.instance().getBugTypeDescription(shortBugType);
groupName = shortBugType + ": " + bugTypeDescription;
} else
throw new IllegalStateException("Unknown sort order: " + groupBy);
currentGroup = new BugInstanceGroup(groupBy, groupName);
currentGroupNode = new DefaultMutableTreeNode(currentGroup);
bugTreeModel.insertNodeInto(currentGroupNode, bugRootNode, bugRootNode.getChildCount());
insertIntoGroup(member);
}
public void addToGroup(BugInstance member) {
insertIntoGroup(member);
}
private void insertIntoGroup(BugInstance member) {
currentGroup.incrementMemberCount();
DefaultMutableTreeNode bugNode = new BugTreeNode(member);
bugTreeModel.insertNodeInto(bugNode, currentGroupNode, currentGroupNode.getChildCount());
// Insert annotations
Iterator j = member.annotationIterator();
while (j.hasNext()) {
BugAnnotation annotation = (BugAnnotation) j.next();
DefaultMutableTreeNode annotationNode = new DefaultMutableTreeNode(annotation);
bugTreeModel.insertNodeInto(annotationNode, bugNode, bugNode.getChildCount());
}
}
};
// Create the grouper, and execute it to populate the bug tree
Grouper<BugInstance> grouper = new Grouper<BugInstance>(callback);
Comparator<BugInstance> groupComparator = getGroupComparator(groupBy);
grouper.group(sortedCollection, groupComparator);
// Let the tree know it needs to update itself
bugTreeModel.nodeStructureChanged(bugRootNode);
// Now we're done
this.setCursor(orig);
}
/**
* Get a BugInstance Comparator for given sort order.
*/
private Comparator<BugInstance> getBugInstanceComparator(String sortOrder) {
if (sortOrder.equals(GROUP_BY_CLASS))
return bugInstanceByClassComparator;
else if (sortOrder.equals(GROUP_BY_PACKAGE))
return bugInstanceByPackageComparator;
else if (sortOrder.equals(GROUP_BY_BUG_TYPE))
return bugInstanceByTypeComparator;
else
throw new IllegalArgumentException("Bad sort order: " + sortOrder);
}
/**
* Get a Grouper for a given sort order.
*/
private Comparator<BugInstance> getGroupComparator(String groupBy) {
if (groupBy.equals(GROUP_BY_CLASS)) {
return bugInstanceClassComparator;
} else if (groupBy.equals(GROUP_BY_PACKAGE)) {
return bugInstancePackageComparator;
} else if (groupBy.equals(GROUP_BY_BUG_TYPE)) {
return bugInstanceTypeComparator;
} else
throw new IllegalArgumentException("Bad sort order: " + groupBy);
}
/**
* Set the view panel to display the named view.
*/
private void setView(String viewName) {
//System.out.println("Showing view " + viewName);
viewPanelLayout.show(viewPanel, viewName);
if (viewName.equals("BugTree"))
checkBugDetailsVisibility();
currentView = viewName;
}
/**
* Get which view is displayed currently.
*/
private String getView() {
return currentView;
}
/**
* Called to add the jar file in the jarNameTextField to the
* Jar file list (and the project it represents).
*/
private void addJarToList() {
String jarFile = jarNameTextField.getText();
if (!jarFile.equals("")) {
addJarToProject(jarFile);
jarNameTextField.setText("");
}
}
/**
* Add a Jar file to the current project.
* @param jarFile the jar file to add to the project
*/
private void addJarToProject(String jarFile) {
Project project = getCurrentProject();
if (project.addJar(jarFile)) {
DefaultListModel listModel = (DefaultListModel) jarFileList.getModel();
listModel.addElement(jarFile);
}
}
/**
* Called to add the source directory in the sourceDirTextField
* to the source directory list (and the project it represents).
*/
private void addSourceDirToList() {
String sourceDir = srcDirTextField.getText();
if (!sourceDir.equals("")) {
Project project = getCurrentProject();
if (project.addSourceDir(sourceDir)) {
DefaultListModel listModel = (DefaultListModel) sourceDirList.getModel();
listModel.addElement(sourceDir);
}
srcDirTextField.setText("");
}
}
/**
* Called to add the classpath entry in the classpathEntryTextField
* to the classpath entry list (and the project it represents).
*/
private void addClasspathEntryToList() {
String classpathEntry = classpathEntryTextField.getText();
if (!classpathEntry.equals("")) {
addClasspathEntryToProject(classpathEntry);
classpathEntryTextField.setText("");
}
}
/**
* Add a classpath entry to the current project.
* @param classpathEntry the classpath entry to add
*/
private void addClasspathEntryToProject(String classpathEntry) {
Project project = getCurrentProject();
if (project.addAuxClasspathEntry(classpathEntry)) {
DefaultListModel listModel = (DefaultListModel) classpathEntryList.getModel();
listModel.addElement(classpathEntry);
}
}
/**
* Synchronize current bug instance with the bug detail
* window (source view, details window, etc.)
*/
private void synchBugInstance() {
// Get current bug instance
BugInstance selected = getCurrentBugInstance();
if (selected == null)
return;
// If the details window is minimized, then the user can't see
// it and there is no point in updating it.
if (!viewBugDetailsItem.isSelected())
return;
// Get the current source line annotation.
// If the current leaf selected is not a source line annotation,
// use the default source line annotation from the current bug instance
// (if any).
JTree bugTree = getCurrentBugTree();
// if the summary window is shown then skip it
if ( bugTree == null ) {
return;
}
SourceLineAnnotation srcLine = null;
TreePath selPath = bugTree.getSelectionPath();
if (selPath != null) {
Object leaf = ((DefaultMutableTreeNode)selPath.getLastPathComponent()).getUserObject();
if (leaf instanceof SourceLineAnnotation)
srcLine = (SourceLineAnnotation) leaf;
else
srcLine = selected.getPrimarySourceLineAnnotation();
}
// Show source code.
if (srcLine == null || srcLine != currentSourceLineAnnotation) {
Project project = getCurrentProject();
AnalysisRun analysisRun = getCurrentAnalysisRun();
if (project == null) throw new IllegalStateException("null project!");
if (analysisRun == null) throw new IllegalStateException("null analysis run!");
try {
boolean success = viewSource(project, analysisRun, srcLine);
sourceTextArea.setEnabled(success);
if (!success)
sourceTextArea.setText("No source line information for this bug");
} catch (IOException e) {
sourceTextArea.setText("Could not find source: " + e.getMessage());
logger.logMessage(ConsoleLogger.WARNING, e.getMessage());
}
currentSourceLineAnnotation = srcLine;
}
// Show bug info.
showBugInfo(selected);
// Synch annotation text.
synchBugAnnotation(selected);
// Now the bug details are up to date.
currentBugInstance = selected;
}
private static final int SELECTION_VOFFSET = 2;
/**
* Update the source view window.
* @param project the project (containing the source directories to search)
* @param analysisRun the analysis run (containing the mapping of classes to source files)
* @param srcLine the source line annotation (specifying source file to load and
* which lines to highlight)
* @return true if the source was shown successfully, false otherwise
*/
private boolean viewSource(Project project, AnalysisRun analysisRun, final SourceLineAnnotation srcLine)
throws IOException {
// Get rid of old source code text
sourceTextArea.setText("");
// There is nothing to do without a source annotation
// TODO: actually, might want to put a message in the source window
// explaining that we don't have the source file, and that
// they might want to recompile with debugging info turned on.
if (srcLine == null)
return false;
// Look up the source file for this class.
sourceFinder.setSourceBaseList(project.getSourceDirList());
String sourceFile = srcLine.getSourceFile();
if (sourceFile == null || sourceFile.equals("<Unknown>")) {
logger.logMessage(ConsoleLogger.WARNING, "No source file for class " + srcLine.getClassName());
return false;
}
// Try to open the source file and display its contents
// in the source text area.
InputStream in = sourceFinder.openSource(srcLine.getPackageName(), sourceFile);
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
sourceTextArea.append(line + "\n");
}
} finally {
if (reader != null)
reader.close();
}
if (srcLine.isUnknown()) {
// No line number information, so can't highlight anything
SwingUtilities.invokeLater(new Runnable() {
public void run() {
sourceTextAreaScrollPane.getViewport().setViewPosition(new Point(0, 0));
}
});
return true;
}
// Highlight the annotation.
// There seems to be some bug in Swing that sometimes prevents this code
// from working when executed immediately after populating the
// text in the text area. My guess is that when a large amount of text
// is added, Swing defers some UI update work until "later" that is needed
// to compute the visibility of text in the text area.
// So, post some code to do the update to the Swing event queue.
// Not really an ideal solution, but it seems to work.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Highlight the lines from the source annotation.
// Note that the source lines start at 1, while the line numbers
// in the text area start at 0.
try {
int startLine = srcLine.getStartLine() - 1;
int endLine = srcLine.getEndLine();
// Compute number of rows visible.
// What a colossal pain in the ass this is.
// You'd think there would be a convenient method to
// return this information, but no.
JViewport viewport = sourceTextAreaScrollPane.getViewport();
Rectangle viewportRect = viewport.getViewRect();
int height = sourceTextArea.getHeight();
int topRow = sourceTextArea.getLineOfOffset(sourceTextArea.viewToModel(viewportRect.getLocation()));
int bottomRow = sourceTextArea.getLineOfOffset(
sourceTextArea.viewToModel(new Point(viewportRect.x, (viewportRect.y + viewportRect.height) - 1)));
int numRowsVisible = bottomRow - topRow;
// Scroll the window so the beginning of the
// annotation text will be (approximately) centered.
int viewLine = Math.max(startLine - (numRowsVisible > 0 ? numRowsVisible / 2 : 0), 0);
int viewBegin = sourceTextArea.getLineStartOffset(viewLine);
Rectangle viewRect = sourceTextArea.modelToView(viewBegin);
viewport.setViewPosition(new Point(viewRect.x, viewRect.y));
// Select (and highlight) the annotation.
int selBegin = sourceTextArea.getLineStartOffset(startLine);
int selEnd = sourceTextArea.getLineStartOffset(endLine);
sourceTextArea.select(selBegin, selEnd);
sourceTextArea.getCaret().setSelectionVisible(true);
} catch (javax.swing.text.BadLocationException e) {
logger.logMessage(ConsoleLogger.ERROR, e.toString());
}
}
});
return true;
}
/**
* Show descriptive text about the type of bug
* @param bugInstance the bug instance
*/
private void showBugInfo(BugInstance bugInstance) {
// Are we already showing details for this kind of bug?
String bugDetailsKey = bugInstance.getType();
if (bugDetailsKey.equals(currentBugDetailsKey))
return;
// Display the details
String html = I18N.instance().getDetailHTML(bugDetailsKey);
bugDescriptionEditorPane.setContentType("text/html");
bugDescriptionEditorPane.setText(html);
currentBugDetailsKey = bugDetailsKey;
// FIXME: unfortunately, using setText() on the editor pane
// results in the contents being scrolled to the bottom of the pane.
// An immediate inline call to set the scroll position does nothing.
// So, use invokeLater(), even though this results in flashing.
// [What we really need is a way to set the text WITHOUT changing
// the caret position. Need to investigate.]
SwingUtilities.invokeLater(new Runnable() {
public void run() {
bugDescriptionScrollPane.getViewport().setViewPosition(new Point(0, 0));
}
});
}
/**
* Synchronize the bug annotation text with the current bug instance,
* and update the annotation text with the new bug instance.
* @param selected the new BugInstance
*/
private void synchBugAnnotation(BugInstance selected) {
if (currentBugInstance != null) {
String text = annotationTextArea.getText();
currentBugInstance.setAnnotationText(text);
}
annotationTextArea.setText(selected.getAnnotationText());
}
/* ----------------------------------------------------------------------
* Misc. helpers
* ---------------------------------------------------------------------- */
/**
* Exit the application.
*/
private void exitFindBugs() {
// TODO: offer to save work, etc.
System.exit(0);
}
/**
* Create a file chooser dialog.
* Ensures that the dialog will start in the current directory.
* @return the file chooser
*/
private JFileChooser createFileChooser() {
return new JFileChooser(currentDirectory);
}
/**
* Run a file chooser dialog.
* If a file is chosen, then the current directory is updated.
* @param dialog the file chooser dialog
* @param dialogTitle the dialog title
* @return the outcome
*/
private int chooseFile(JFileChooser dialog, String dialogTitle) {
int outcome = dialog.showDialog(this, dialogTitle);
return updateCurrentDirectoryFromDialog(dialog, outcome);
}
/**
* Run a file chooser dialog to choose a file to open.
* If a file is chosen, then the current directory is updated.
* @param dialog the file chooser dialog
* @return the outcome
*/
private int chooseFileToOpen(JFileChooser dialog) {
int outcome = dialog.showOpenDialog(this);
return updateCurrentDirectoryFromDialog(dialog, outcome);
}
private int updateCurrentDirectoryFromDialog(JFileChooser dialog, int outcome) {
if (outcome != JFileChooser.CANCEL_OPTION) {
File selectedFile = dialog.getSelectedFile();
currentDirectory = selectedFile.getParentFile();
}
return outcome;
}
/**
* Get the ConsoleLogger.
*/
public ConsoleLogger getLogger() {
return logger;
}
/**
* Show an error dialog.
*/
public void error(String message) {
JOptionPane.showMessageDialog(this, message, "Error", JOptionPane.ERROR_MESSAGE);
}
/**
* Write a message to the console window.
*/
public void writeToConsole(String message) {
consoleMessageArea.append(message);
consoleMessageArea.append("\n");
}
/* ----------------------------------------------------------------------
* main() method
* ---------------------------------------------------------------------- */
/**
* Invoke from the command line.
* @param args the command line arguments
*/
public static void main(String args[]) {
for (int i = 0; i < args.length; ++i) {
String arg = args[i];
if (arg.equals("-debug")) {
System.out.println("Setting findbugs.debug=true");
System.setProperty("findbugs.debug", "true");
} else if (arg.equals("-plastic")) {
// You can get the Plastic look and feel from jgoodies.com:
// http://www.jgoodies.com/downloads/libraries.html
// Just put "plastic.jar" in the lib directory, right next
// to the other jar files.
try {
UIManager.setLookAndFeel("com.jgoodies.plaf.plastic.PlasticXPLookAndFeel");
} catch (Exception e) {
System.err.println("Couldn't load plastic look and feel: " + e.toString());
}
}
}
// Load plugins!
DetectorFactoryCollection.instance();
FindBugsFrame frame = new FindBugsFrame();
frame.setSize(800, 600);
frame.show();
}
/* ----------------------------------------------------------------------
* Instance variables
* ---------------------------------------------------------------------- */
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenuItem aboutItem;
private javax.swing.JButton addClasspathEntryButton;
private javax.swing.JButton addJarButton;
private javax.swing.JButton addSourceDirButton;
private javax.swing.JTextArea annotationTextArea;
private javax.swing.JScrollPane annotationTextAreaScrollPane;
private javax.swing.JButton browseClasspathEntryButton;
private javax.swing.JButton browseJarButton;
private javax.swing.JButton browseSrcDirButton;
private javax.swing.JEditorPane bugDescriptionEditorPane;
private javax.swing.JScrollPane bugDescriptionScrollPane;
private javax.swing.JTabbedPane bugDetailsTabbedPane;
private javax.swing.JEditorPane bugSummaryEditorPane;
private javax.swing.JSplitPane bugTreeBugDetailsSplitter;
private javax.swing.JPanel bugTreePanel;
private javax.swing.JTree byBugTypeBugTree;
private javax.swing.JScrollPane byBugTypeScrollPane;
private javax.swing.JTree byClassBugTree;
private javax.swing.JScrollPane byClassScrollPane;
private javax.swing.JTree byPackageBugTree;
private javax.swing.JScrollPane byPackageScrollPane;
private javax.swing.JScrollPane bySummary;
private javax.swing.JLabel classpathEntryLabel;
private javax.swing.JList classpathEntryList;
private javax.swing.JLabel classpathEntryListLabel;
private javax.swing.JScrollPane classpathEntryListScrollPane;
private javax.swing.JTextField classpathEntryTextField;
private javax.swing.JMenuItem closeProjectItem;
private javax.swing.JMenuItem configureDetectorsItem;
private javax.swing.JTextArea consoleMessageArea;
private javax.swing.JScrollPane consoleScrollPane;
private javax.swing.JSplitPane consoleSplitter;
private javax.swing.JLabel editProjectLabel;
private javax.swing.JPanel editProjectPanel;
private javax.swing.JPanel emptyPanel;
private javax.swing.JMenuItem exitItem;
private javax.swing.JMenu fileMenu;
private javax.swing.JButton findBugsButton;
private javax.swing.JCheckBoxMenuItem fullDescriptionsItem;
private javax.swing.JTabbedPane groupByTabbedPane;
private javax.swing.JMenu helpMenu;
private javax.swing.JRadioButtonMenuItem highPriorityButton;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JSeparator jSeparator4;
private javax.swing.JSeparator jSeparator5;
private javax.swing.JSeparator jSeparator6;
private javax.swing.JSeparator jSeparator7;
private javax.swing.JLabel jarFileLabel;
private javax.swing.JList jarFileList;
private javax.swing.JLabel jarFileListLabel;
private javax.swing.JScrollPane jarFileListScrollPane;
private javax.swing.JTextField jarNameTextField;
private javax.swing.JMenuItem loadBugsItem;
private javax.swing.JRadioButtonMenuItem lowPriorityButton;
private javax.swing.JRadioButtonMenuItem mediumPriorityButton;
private javax.swing.JMenuItem newProjectItem;
private javax.swing.JMenuItem openProjectItem;
private javax.swing.JMenuItem reloadProjectItem;
private javax.swing.JButton removeClasspathEntryButton;
private javax.swing.JButton removeJarButton;
private javax.swing.JButton removeSrcDirButton;
private javax.swing.JPanel reportPanel;
private javax.swing.JMenuItem saveBugsItem;
private javax.swing.JMenuItem saveProjectAsItem;
private javax.swing.JMenuItem saveProjectItem;
private javax.swing.JMenu settingsMenu;
private javax.swing.JLabel sourceDirLabel;
private javax.swing.JList sourceDirList;
private javax.swing.JLabel sourceDirListLabel;
private javax.swing.JScrollPane sourceDirListScrollPane;
private javax.swing.JTextArea sourceTextArea;
private javax.swing.JScrollPane sourceTextAreaScrollPane;
private javax.swing.JTextField srcDirTextField;
private javax.swing.JMenuBar theMenuBar;
private javax.swing.JCheckBoxMenuItem viewBugDetailsItem;
private javax.swing.JCheckBoxMenuItem viewConsoleItem;
private javax.swing.JMenu viewMenu;
private javax.swing.JPanel viewPanel;
// End of variables declaration//GEN-END:variables
// My variable declarations
private ConsoleLogger logger;
private CardLayout viewPanelLayout;
private String currentView;
private File currentDirectory;
private Project currentProject;
private JTree[] bugTreeList;
private AnalysisRun currentAnalysisRun;
private SourceFinder sourceFinder = new SourceFinder();
private BugInstance currentBugInstance; // be lazy in switching bug instance details
private SourceLineAnnotation currentSourceLineAnnotation; // as above
private String currentBugDetailsKey;
private int priorityThreshold;
}
| Added property to number each bug in a group.
git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@1590 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
| findbugs/src/java/edu/umd/cs/findbugs/gui/FindBugsFrame.java | Added property to number each bug in a group. | <ide><path>indbugs/src/java/edu/umd/cs/findbugs/gui/FindBugsFrame.java
<ide> * get more control over the exact text that is shown in the tree.
<ide> */
<ide> private class BugTreeNode extends DefaultMutableTreeNode {
<add> private int count;
<add>
<ide> public BugTreeNode(BugInstance bugInstance) {
<ide> super(bugInstance);
<del> }
<add> count = -1;
<add> }
<add>
<add> public void setCount(int count) {
<add> this.count = count;
<add> }
<ide>
<ide> public String toString() {
<ide> try {
<ide> BugInstance bugInstance = (BugInstance) getUserObject();
<del> String result;
<del> if (fullDescriptionsItem.isSelected()) {
<del> result = bugInstance.getMessage();
<del> } else {
<del> result = bugInstance.toString();
<del> }
<del> boolean experimental = bugInstance.isExperimental();
<del> if (experimental)
<del> return "EXP: " + result;
<del> else
<del> return result;
<add> StringBuffer result = new StringBuffer();
<add>
<add> if (count >= 0) {
<add> result.append(count);
<add> result.append(": ");
<add> }
<add>
<add> if (bugInstance.isExperimental())
<add> result.append("EXP: ");
<add>
<add> result.append(fullDescriptionsItem.isSelected() ? bugInstance.getMessage() : bugInstance.toString());
<add>
<add> return result.toString();
<ide> } catch (Exception e) {
<ide> return "Error formatting message for bug: " + e.toString();
<ide> }
<ide> * makes the code a bit more robust.
<ide> */
<ide> private static final int DIVIDER_FUDGE = 3;
<add>
<add> private static final boolean BUG_COUNT = Boolean.getBoolean("findbugs.gui.bugCount");
<ide>
<ide> /* ----------------------------------------------------------------------
<ide> * Constructor
<ide>
<ide> private void insertIntoGroup(BugInstance member) {
<ide> currentGroup.incrementMemberCount();
<del> DefaultMutableTreeNode bugNode = new BugTreeNode(member);
<add> BugTreeNode bugNode = new BugTreeNode(member);
<add> if (BUG_COUNT)
<add> bugNode.setCount(currentGroup.getMemberCount());
<ide> bugTreeModel.insertNodeInto(bugNode, currentGroupNode, currentGroupNode.getChildCount());
<ide>
<ide> // Insert annotations |
|
Java | mit | c1bbd75e05e26db6baf6ca4206cd1a6bec837ac4 | 0 | savichris/spongycastle,isghe/bc-java,lesstif/spongycastle,iseki-masaya/spongycastle,iseki-masaya/spongycastle,sonork/spongycastle,Skywalker-11/spongycastle,savichris/spongycastle,Skywalker-11/spongycastle,bcgit/bc-java,isghe/bc-java,sergeypayu/bc-java,open-keychain/spongycastle,bcgit/bc-java,bcgit/bc-java,open-keychain/spongycastle,onessimofalconi/bc-java,FAU-Inf2/spongycastle,onessimofalconi/bc-java,sonork/spongycastle,iseki-masaya/spongycastle,FAU-Inf2/spongycastle,onessimofalconi/bc-java,savichris/spongycastle,lesstif/spongycastle,sergeypayu/bc-java,sonork/spongycastle,Skywalker-11/spongycastle,open-keychain/spongycastle,partheinstein/bc-java,partheinstein/bc-java,lesstif/spongycastle,sergeypayu/bc-java,FAU-Inf2/spongycastle,partheinstein/bc-java,isghe/bc-java | package org.bouncycastle.crypto.tls;
import java.io.IOException;
class DTLSRecordLayer implements DatagramTransport {
private static final int RECORD_HEADER_LENGTH = 13;
private static final int MAX_FRAGMENT_LENGTH = 1 << 14;
private static final long TCP_MSL = 1000L * 60 * 2;
private static final long RETRANSMIT_TIMEOUT = TCP_MSL * 2;
private final DatagramTransport transport;
private final TlsContext context;
private final TlsPeer peer;
private final ByteQueue recordQueue = new ByteQueue();
private volatile boolean closed = false;
private volatile boolean failed = false;
private volatile ProtocolVersion discoveredPeerVersion = null;
private volatile boolean inHandshake;
private DTLSEpoch currentEpoch, pendingEpoch;
private DTLSEpoch readEpoch, writeEpoch;
private DTLSHandshakeRetransmit retransmit = null;
private DTLSEpoch retransmitEpoch = null;
private long retransmitExpiry = 0;
DTLSRecordLayer(DatagramTransport transport, TlsContext context, TlsPeer peer, short contentType) {
this.transport = transport;
this.context = context;
this.peer = peer;
this.inHandshake = true;
this.currentEpoch = new DTLSEpoch(0, new TlsNullCipher(context));
this.pendingEpoch = null;
this.readEpoch = currentEpoch;
this.writeEpoch = currentEpoch;
}
ProtocolVersion getDiscoveredPeerVersion() {
return discoveredPeerVersion;
}
void initPendingEpoch(TlsCipher pendingCipher) {
if (pendingEpoch != null) {
throw new IllegalStateException();
}
/*
* TODO "In order to ensure that any given sequence/epoch pair is unique, implementations
* MUST NOT allow the same epoch value to be reused within two times the TCP maximum segment
* lifetime."
*/
// TODO Check for overflow
this.pendingEpoch = new DTLSEpoch(writeEpoch.getEpoch() + 1, pendingCipher);
}
void handshakeSuccessful(DTLSHandshakeRetransmit retransmit) {
if (readEpoch == currentEpoch || writeEpoch == currentEpoch) {
// TODO
throw new IllegalStateException();
}
if (retransmit != null) {
this.retransmit = retransmit;
this.retransmitEpoch = currentEpoch;
this.retransmitExpiry = System.currentTimeMillis() + RETRANSMIT_TIMEOUT;
}
this.inHandshake = false;
this.currentEpoch = pendingEpoch;
this.pendingEpoch = null;
}
void resetWriteEpoch() {
this.writeEpoch = currentEpoch;
}
public int getReceiveLimit() throws IOException {
return Math.min(MAX_FRAGMENT_LENGTH,
readEpoch.getCipher().getPlaintextLimit(transport.getReceiveLimit() - RECORD_HEADER_LENGTH));
}
public int getSendLimit() throws IOException {
return Math.min(MAX_FRAGMENT_LENGTH,
writeEpoch.getCipher().getPlaintextLimit(transport.getSendLimit() - RECORD_HEADER_LENGTH));
}
public int receive(byte[] buf, int off, int len, int waitMillis) throws IOException {
byte[] record = null;
for (;;) {
int receiveLimit = Math.min(len, getReceiveLimit()) + RECORD_HEADER_LENGTH;
if (record == null || record.length < receiveLimit) {
record = new byte[receiveLimit];
}
try {
if (retransmit != null && System.currentTimeMillis() > retransmitExpiry) {
retransmit = null;
retransmitEpoch = null;
}
int received = receiveRecord(record, 0, receiveLimit, waitMillis);
if (received < 0) {
return received;
}
if (received < RECORD_HEADER_LENGTH) {
continue;
}
int length = TlsUtils.readUint16(record, 11);
if (received != (length + RECORD_HEADER_LENGTH)) {
continue;
}
short type = TlsUtils.readUint8(record, 0);
// TODO Support user-specified custom protocols?
switch (type) {
case ContentType.alert:
case ContentType.application_data:
case ContentType.change_cipher_spec:
case ContentType.handshake:
break;
default:
// TODO Exception?
continue;
}
int epoch = TlsUtils.readUint16(record, 3);
DTLSEpoch recordEpoch = null;
if (epoch == readEpoch.getEpoch()) {
recordEpoch = readEpoch;
} else if (type == ContentType.handshake && retransmitEpoch != null
&& epoch == retransmitEpoch.getEpoch()) {
recordEpoch = retransmitEpoch;
}
if (recordEpoch == null)
continue;
long seq = TlsUtils.readUint48(record, 5);
if (recordEpoch.getReplayWindow().shouldDiscard(seq))
continue;
ProtocolVersion version = TlsUtils.readVersion(record, 1);
if (discoveredPeerVersion != null && !discoveredPeerVersion.equals(version))
continue;
byte[] plaintext = recordEpoch.getCipher().decodeCiphertext(
getMacSequenceNumber(recordEpoch.getEpoch(), seq), type, record, RECORD_HEADER_LENGTH,
received - RECORD_HEADER_LENGTH);
recordEpoch.getReplayWindow().reportAuthenticated(seq);
if (discoveredPeerVersion == null) {
discoveredPeerVersion = version;
}
switch (type) {
case ContentType.alert: {
if (plaintext.length == 2) {
short alertLevel = plaintext[0];
short alertDescription = plaintext[1];
peer.notifyAlertReceived(alertLevel, alertDescription);
if (alertLevel == AlertLevel.fatal) {
fail(alertDescription);
throw new TlsFatalAlert(alertDescription);
}
// TODO Can close_notify be a fatal alert?
if (alertDescription == AlertDescription.close_notify) {
closeTransport();
}
} else {
// TODO What exception?
}
continue;
}
case ContentType.application_data: {
if (inHandshake) {
// TODO Consider buffering application data for new epoch that arrives
// out-of-order with the Finished message
continue;
}
break;
}
case ContentType.change_cipher_spec: {
// Implicitly receive change_cipher_spec and change to pending cipher state
if (plaintext.length != 1 || plaintext[0] != 1) {
continue;
}
if (pendingEpoch != null) {
readEpoch = pendingEpoch;
}
continue;
}
case ContentType.handshake: {
if (!inHandshake) {
if (retransmit != null) {
retransmit.receivedHandshakeRecord(epoch, plaintext, 0, plaintext.length);
}
// TODO Consider support for HelloRequest
continue;
}
}
}
/*
* NOTE: If we receive any non-handshake data in the new epoch implies the peer has
* received our final flight.
*/
if (!inHandshake && retransmit != null) {
this.retransmit = null;
this.retransmitEpoch = null;
}
System.arraycopy(plaintext, 0, buf, off, plaintext.length);
return plaintext.length;
} catch (IOException e) {
// NOTE: Assume this is a timeout for the moment
throw e;
}
}
}
public void send(byte[] buf, int off, int len) throws IOException {
short contentType = ContentType.application_data;
if (this.inHandshake) {
contentType = ContentType.handshake;
short handshakeType = TlsUtils.readUint8(buf, off);
if (handshakeType == HandshakeType.finished) {
if (pendingEpoch == null) {
// TODO
throw new IllegalStateException();
}
// Implicitly send change_cipher_spec and change to pending cipher state
// TODO Send change_cipher_spec and finished records in single datagram?
byte[] data = new byte[] { 1 };
sendRecord(ContentType.change_cipher_spec, data, 0, data.length);
writeEpoch = pendingEpoch;
}
}
sendRecord(contentType, buf, off, len);
}
public void close() throws IOException {
if (!closed) {
if (inHandshake) {
warn(AlertDescription.user_canceled, "User canceled handshake");
}
closeTransport();
}
}
void fail(short alertDescription) {
if (!closed) {
try {
raiseAlert(AlertLevel.fatal, alertDescription, null, null);
} catch (Exception e) {
// Ignore
}
failed = true;
closeTransport();
}
}
void warn(short alertDescription, String message) throws IOException {
raiseAlert(AlertLevel.warning, alertDescription, message, null);
}
private void closeTransport() {
if (!closed) {
/*
* RFC 5246 7.2.1. Unless some other fatal alert has been transmitted, each party is
* required to send a close_notify alert before closing the write side of the
* connection. The other party MUST respond with a close_notify alert of its own and
* close down the connection immediately, discarding any pending writes.
*/
try {
if (!failed) {
warn(AlertDescription.close_notify, null);
}
transport.close();
} catch (Exception e) {
// Ignore
}
closed = true;
}
}
private void raiseAlert(short alertLevel, short alertDescription, String message, Exception cause)
throws IOException {
peer.notifyAlertRaised(alertLevel, alertDescription, message, cause);
byte[] error = new byte[2];
error[0] = (byte) alertLevel;
error[1] = (byte) alertDescription;
sendRecord(ContentType.alert, error, 0, 2);
}
private int receiveRecord(byte[] buf, int off, int len, int waitMillis) throws IOException {
if (recordQueue.size() > 0) {
int length = 0;
if (recordQueue.size() >= RECORD_HEADER_LENGTH) {
byte[] lengthBytes = new byte[2];
recordQueue.read(lengthBytes, 0, 2, 11);
length = TlsUtils.readUint16(lengthBytes, 0);
}
int received = Math.min(recordQueue.size(), RECORD_HEADER_LENGTH + length);
recordQueue.read(buf, off, received, 0);
recordQueue.removeData(received);
return received;
}
int received = transport.receive(buf, off, len, waitMillis);
if (received >= RECORD_HEADER_LENGTH) {
int fragmentLength = TlsUtils.readUint16(buf, off + 11);
int recordLength = RECORD_HEADER_LENGTH + fragmentLength;
if (received > recordLength) {
recordQueue.addData(buf, off + recordLength, received - recordLength);
received = recordLength;
}
}
return received;
}
private void sendRecord(short contentType, byte[] buf, int off, int len) throws IOException {
/*
* RFC 5264 6.2.1 Implementations MUST NOT send zero-length fragments of Handshake, Alert,
* or ChangeCipherSpec content types.
*/
if (len < 1 && contentType != ContentType.application_data) {
throw new TlsFatalAlert(AlertDescription.internal_error);
}
int recordEpoch = writeEpoch.getEpoch();
long recordSequenceNumber = writeEpoch.allocateSequenceNumber();
byte[] ciphertext = writeEpoch.getCipher().encodePlaintext(
getMacSequenceNumber(recordEpoch, recordSequenceNumber), contentType, buf, off, len);
if (ciphertext.length > MAX_FRAGMENT_LENGTH) {
throw new TlsFatalAlert(AlertDescription.internal_error);
}
byte[] record = new byte[ciphertext.length + RECORD_HEADER_LENGTH];
TlsUtils.writeUint8(contentType, record, 0);
ProtocolVersion version = discoveredPeerVersion != null ? discoveredPeerVersion : context.getClientVersion();
TlsUtils.writeVersion(version, record, 1);
TlsUtils.writeUint16(recordEpoch, record, 3);
TlsUtils.writeUint48(recordSequenceNumber, record, 5);
TlsUtils.writeUint16(ciphertext.length, record, 11);
System.arraycopy(ciphertext, 0, record, RECORD_HEADER_LENGTH, ciphertext.length);
transport.send(record, 0, record.length);
}
private static long getMacSequenceNumber(int epoch, long sequence_number) {
return ((long) epoch << 48) | sequence_number;
}
}
| src/main/java/org/bouncycastle/crypto/tls/DTLSRecordLayer.java | package org.bouncycastle.crypto.tls;
import java.io.IOException;
class DTLSRecordLayer implements DatagramTransport {
private static final int RECORD_HEADER_LENGTH = 13;
private static final int MAX_FRAGMENT_LENGTH = 1 << 14;
private static final long TCP_MSL = 1000L * 60 * 2;
private static final long RETRANSMIT_TIMEOUT = TCP_MSL * 2;
private final DatagramTransport transport;
private final TlsContext context;
private final TlsPeer peer;
private final ByteQueue recordQueue = new ByteQueue();
private volatile boolean closed = false;
private volatile boolean failed = false;
private volatile ProtocolVersion discoveredPeerVersion = null;
private volatile boolean inHandshake;
private DTLSEpoch currentEpoch, pendingEpoch;
private DTLSEpoch readEpoch, writeEpoch;
private DTLSHandshakeRetransmit retransmit = null;
private long retransmitExpiry = 0;
DTLSRecordLayer(DatagramTransport transport, TlsContext context, TlsPeer peer, short contentType) {
this.transport = transport;
this.context = context;
this.peer = peer;
this.inHandshake = true;
this.currentEpoch = new DTLSEpoch(0, new TlsNullCipher(context));
this.pendingEpoch = null;
this.readEpoch = currentEpoch;
this.writeEpoch = currentEpoch;
}
ProtocolVersion getDiscoveredPeerVersion() {
return discoveredPeerVersion;
}
void initPendingEpoch(TlsCipher pendingCipher) {
if (pendingEpoch != null) {
throw new IllegalStateException();
}
/*
* TODO "In order to ensure that any given sequence/epoch pair is unique, implementations
* MUST NOT allow the same epoch value to be reused within two times the TCP maximum segment
* lifetime."
*/
// TODO Check for overflow
this.pendingEpoch = new DTLSEpoch(writeEpoch.getEpoch() + 1, pendingCipher);
}
void handshakeSuccessful(DTLSHandshakeRetransmit retransmit) {
if (readEpoch == currentEpoch || writeEpoch == currentEpoch) {
// TODO
throw new IllegalStateException();
}
this.inHandshake = false;
this.currentEpoch = pendingEpoch;
this.pendingEpoch = null;
if (retransmit != null) {
this.retransmit = retransmit;
this.retransmitExpiry = System.currentTimeMillis() + RETRANSMIT_TIMEOUT;
}
}
void resetWriteEpoch() {
this.writeEpoch = currentEpoch;
}
public int getReceiveLimit() throws IOException {
return Math.min(MAX_FRAGMENT_LENGTH,
readEpoch.getCipher().getPlaintextLimit(transport.getReceiveLimit() - RECORD_HEADER_LENGTH));
}
public int getSendLimit() throws IOException {
return Math.min(MAX_FRAGMENT_LENGTH,
writeEpoch.getCipher().getPlaintextLimit(transport.getSendLimit() - RECORD_HEADER_LENGTH));
}
public int receive(byte[] buf, int off, int len, int waitMillis) throws IOException {
byte[] record = null;
for (;;) {
int receiveLimit = Math.min(len, getReceiveLimit()) + RECORD_HEADER_LENGTH;
if (record == null || record.length < receiveLimit) {
record = new byte[receiveLimit];
}
try {
if (retransmit != null && System.currentTimeMillis() > retransmitExpiry) {
retransmit = null;
}
int received = receiveRecord(record, 0, receiveLimit, waitMillis);
if (received < 0) {
return received;
}
if (received < RECORD_HEADER_LENGTH) {
continue;
}
int length = TlsUtils.readUint16(record, 11);
if (received != (length + RECORD_HEADER_LENGTH)) {
continue;
}
int epoch = TlsUtils.readUint16(record, 3);
if (epoch != readEpoch.getEpoch()) {
continue;
}
long seq = TlsUtils.readUint48(record, 5);
if (readEpoch.getReplayWindow().shouldDiscard(seq))
continue;
short type = TlsUtils.readUint8(record, 0);
// TODO Support user-specified custom protocols?
switch (type) {
case ContentType.alert:
case ContentType.application_data:
case ContentType.change_cipher_spec:
case ContentType.handshake:
break;
default:
// TODO Exception?
continue;
}
ProtocolVersion version = TlsUtils.readVersion(record, 1);
if (discoveredPeerVersion != null && !discoveredPeerVersion.equals(version)) {
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
byte[] plaintext = readEpoch.getCipher().decodeCiphertext(
getMacSequenceNumber(readEpoch.getEpoch(), seq), type, record, RECORD_HEADER_LENGTH,
received - RECORD_HEADER_LENGTH);
readEpoch.getReplayWindow().reportAuthenticated(seq);
if (discoveredPeerVersion == null) {
discoveredPeerVersion = version;
}
switch (type) {
case ContentType.alert: {
if (plaintext.length == 2) {
short alertLevel = plaintext[0];
short alertDescription = plaintext[1];
peer.notifyAlertReceived(alertLevel, alertDescription);
if (alertLevel == AlertLevel.fatal) {
fail(alertDescription);
throw new TlsFatalAlert(alertDescription);
}
// TODO Can close_notify be a fatal alert?
if (alertDescription == AlertDescription.close_notify) {
closeTransport();
}
} else {
// TODO What exception?
}
continue;
}
case ContentType.application_data: {
if (inHandshake) {
// TODO Consider buffering application data for new epoch that arrives
// out-of-order with the Finished message
continue;
}
break;
}
case ContentType.change_cipher_spec: {
// Implicitly receive change_cipher_spec and change to pending cipher state
if (plaintext.length != 1 || plaintext[0] != 1) {
continue;
}
if (pendingEpoch != null) {
readEpoch = pendingEpoch;
}
continue;
}
case ContentType.handshake: {
if (!inHandshake) {
if (retransmit != null) {
// TODO Need to cater to records from the previous epoch
retransmit.receivedHandshakeRecord(epoch, plaintext, 0, plaintext.length);
}
// TODO Consider support for HelloRequest
continue;
}
}
}
/*
* NOTE: If we receive any non-handshake data in the new epoch implies the peer has
* received our final flight.
*/
if (!inHandshake && retransmit != null) {
this.retransmit = null;
}
System.arraycopy(plaintext, 0, buf, off, plaintext.length);
return plaintext.length;
} catch (IOException e) {
// NOTE: Assume this is a timeout for the moment
throw e;
}
}
}
public void send(byte[] buf, int off, int len) throws IOException {
short contentType = ContentType.application_data;
if (this.inHandshake) {
contentType = ContentType.handshake;
short handshakeType = TlsUtils.readUint8(buf, off);
if (handshakeType == HandshakeType.finished) {
if (pendingEpoch == null) {
// TODO
throw new IllegalStateException();
}
// Implicitly send change_cipher_spec and change to pending cipher state
// TODO Send change_cipher_spec and finished records in single datagram?
byte[] data = new byte[] { 1 };
sendRecord(ContentType.change_cipher_spec, data, 0, data.length);
writeEpoch = pendingEpoch;
}
}
sendRecord(contentType, buf, off, len);
}
public void close() throws IOException {
if (!closed) {
if (inHandshake) {
warn(AlertDescription.user_canceled, "User canceled handshake");
}
closeTransport();
}
}
void fail(short alertDescription) {
if (!closed) {
try {
raiseAlert(AlertLevel.fatal, alertDescription, null, null);
} catch (Exception e) {
// Ignore
}
failed = true;
closeTransport();
}
}
void warn(short alertDescription, String message) throws IOException {
raiseAlert(AlertLevel.warning, alertDescription, message, null);
}
private void closeTransport() {
if (!closed) {
/*
* RFC 5246 7.2.1. Unless some other fatal alert has been transmitted, each party is
* required to send a close_notify alert before closing the write side of the
* connection. The other party MUST respond with a close_notify alert of its own and
* close down the connection immediately, discarding any pending writes.
*/
try {
if (!failed) {
warn(AlertDescription.close_notify, null);
}
transport.close();
} catch (Exception e) {
// Ignore
}
closed = true;
}
}
private void raiseAlert(short alertLevel, short alertDescription, String message, Exception cause)
throws IOException {
peer.notifyAlertRaised(alertLevel, alertDescription, message, cause);
byte[] error = new byte[2];
error[0] = (byte) alertLevel;
error[1] = (byte) alertDescription;
sendRecord(ContentType.alert, error, 0, 2);
}
private int receiveRecord(byte[] buf, int off, int len, int waitMillis) throws IOException {
if (recordQueue.size() > 0) {
int length = 0;
if (recordQueue.size() >= RECORD_HEADER_LENGTH) {
byte[] lengthBytes = new byte[2];
recordQueue.read(lengthBytes, 0, 2, 11);
length = TlsUtils.readUint16(lengthBytes, 0);
}
int received = Math.min(recordQueue.size(), RECORD_HEADER_LENGTH + length);
recordQueue.read(buf, off, received, 0);
recordQueue.removeData(received);
return received;
}
int received = transport.receive(buf, off, len, waitMillis);
if (received >= RECORD_HEADER_LENGTH) {
int fragmentLength = TlsUtils.readUint16(buf, off + 11);
int recordLength = RECORD_HEADER_LENGTH + fragmentLength;
if (received > recordLength) {
recordQueue.addData(buf, off + recordLength, received - recordLength);
received = recordLength;
}
}
return received;
}
private void sendRecord(short contentType, byte[] buf, int off, int len) throws IOException {
/*
* RFC 5264 6.2.1 Implementations MUST NOT send zero-length fragments of Handshake, Alert,
* or ChangeCipherSpec content types.
*/
if (len < 1 && contentType != ContentType.application_data) {
throw new TlsFatalAlert(AlertDescription.internal_error);
}
int recordEpoch = writeEpoch.getEpoch();
long recordSequenceNumber = writeEpoch.allocateSequenceNumber();
byte[] ciphertext = writeEpoch.getCipher().encodePlaintext(
getMacSequenceNumber(recordEpoch, recordSequenceNumber), contentType, buf, off, len);
if (ciphertext.length > MAX_FRAGMENT_LENGTH) {
throw new TlsFatalAlert(AlertDescription.internal_error);
}
byte[] record = new byte[ciphertext.length + RECORD_HEADER_LENGTH];
TlsUtils.writeUint8(contentType, record, 0);
ProtocolVersion version = discoveredPeerVersion != null ? discoveredPeerVersion : context.getClientVersion();
TlsUtils.writeVersion(version, record, 1);
TlsUtils.writeUint16(recordEpoch, record, 3);
TlsUtils.writeUint48(recordSequenceNumber, record, 5);
TlsUtils.writeUint16(ciphertext.length, record, 11);
System.arraycopy(ciphertext, 0, record, RECORD_HEADER_LENGTH, ciphertext.length);
transport.send(record, 0, record.length);
}
private static long getMacSequenceNumber(int epoch, long sequence_number) {
return ((long) epoch << 48) | sequence_number;
}
}
| Support retransmit of final flight from client (old epoch) | src/main/java/org/bouncycastle/crypto/tls/DTLSRecordLayer.java | Support retransmit of final flight from client (old epoch) | <ide><path>rc/main/java/org/bouncycastle/crypto/tls/DTLSRecordLayer.java
<ide> private DTLSEpoch readEpoch, writeEpoch;
<ide>
<ide> private DTLSHandshakeRetransmit retransmit = null;
<add> private DTLSEpoch retransmitEpoch = null;
<ide> private long retransmitExpiry = 0;
<ide>
<ide> DTLSRecordLayer(DatagramTransport transport, TlsContext context, TlsPeer peer, short contentType) {
<ide> // TODO
<ide> throw new IllegalStateException();
<ide> }
<add>
<add> if (retransmit != null) {
<add> this.retransmit = retransmit;
<add> this.retransmitEpoch = currentEpoch;
<add> this.retransmitExpiry = System.currentTimeMillis() + RETRANSMIT_TIMEOUT;
<add> }
<add>
<ide> this.inHandshake = false;
<ide> this.currentEpoch = pendingEpoch;
<ide> this.pendingEpoch = null;
<del>
<del> if (retransmit != null) {
<del> this.retransmit = retransmit;
<del> this.retransmitExpiry = System.currentTimeMillis() + RETRANSMIT_TIMEOUT;
<del> }
<ide> }
<ide>
<ide> void resetWriteEpoch() {
<ide> try {
<ide> if (retransmit != null && System.currentTimeMillis() > retransmitExpiry) {
<ide> retransmit = null;
<add> retransmitEpoch = null;
<ide> }
<ide>
<ide> int received = receiveRecord(record, 0, receiveLimit, waitMillis);
<ide> if (received != (length + RECORD_HEADER_LENGTH)) {
<ide> continue;
<ide> }
<del> int epoch = TlsUtils.readUint16(record, 3);
<del> if (epoch != readEpoch.getEpoch()) {
<del> continue;
<del> }
<del>
<del> long seq = TlsUtils.readUint48(record, 5);
<del> if (readEpoch.getReplayWindow().shouldDiscard(seq))
<del> continue;
<ide>
<ide> short type = TlsUtils.readUint8(record, 0);
<ide>
<ide> continue;
<ide> }
<ide>
<add> int epoch = TlsUtils.readUint16(record, 3);
<add>
<add> DTLSEpoch recordEpoch = null;
<add> if (epoch == readEpoch.getEpoch()) {
<add> recordEpoch = readEpoch;
<add> } else if (type == ContentType.handshake && retransmitEpoch != null
<add> && epoch == retransmitEpoch.getEpoch()) {
<add> recordEpoch = retransmitEpoch;
<add> }
<add>
<add> if (recordEpoch == null)
<add> continue;
<add>
<add> long seq = TlsUtils.readUint48(record, 5);
<add> if (recordEpoch.getReplayWindow().shouldDiscard(seq))
<add> continue;
<add>
<ide> ProtocolVersion version = TlsUtils.readVersion(record, 1);
<del> if (discoveredPeerVersion != null && !discoveredPeerVersion.equals(version)) {
<del> throw new TlsFatalAlert(AlertDescription.illegal_parameter);
<del> }
<del>
<del> byte[] plaintext = readEpoch.getCipher().decodeCiphertext(
<del> getMacSequenceNumber(readEpoch.getEpoch(), seq), type, record, RECORD_HEADER_LENGTH,
<add> if (discoveredPeerVersion != null && !discoveredPeerVersion.equals(version))
<add> continue;
<add>
<add> byte[] plaintext = recordEpoch.getCipher().decodeCiphertext(
<add> getMacSequenceNumber(recordEpoch.getEpoch(), seq), type, record, RECORD_HEADER_LENGTH,
<ide> received - RECORD_HEADER_LENGTH);
<ide>
<del> readEpoch.getReplayWindow().reportAuthenticated(seq);
<add> recordEpoch.getReplayWindow().reportAuthenticated(seq);
<ide>
<ide> if (discoveredPeerVersion == null) {
<ide> discoveredPeerVersion = version;
<ide> case ContentType.handshake: {
<ide> if (!inHandshake) {
<ide> if (retransmit != null) {
<del> // TODO Need to cater to records from the previous epoch
<ide> retransmit.receivedHandshakeRecord(epoch, plaintext, 0, plaintext.length);
<ide> }
<ide>
<ide> */
<ide> if (!inHandshake && retransmit != null) {
<ide> this.retransmit = null;
<add> this.retransmitEpoch = null;
<ide> }
<ide>
<ide> System.arraycopy(plaintext, 0, buf, off, plaintext.length); |
|
Java | mit | deb87509e450dbe483260ee54625fdfc4b52ed14 | 0 | godong9/spring-board,godong9/spring-board,godong9/spring-board,godong9/spring-board | package com.board.gd.domain.comment;
import com.board.gd.domain.comment.form.CreateForm;
import com.board.gd.domain.comment.form.DeleteForm;
import com.board.gd.domain.comment.form.UpdateForm;
import com.board.gd.domain.user.UserService;
import com.board.gd.response.ServerResponse;
import com.querydsl.core.types.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.querydsl.binding.QuerydslPredicate;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
/**
* Created by gd.godong9 on 2017. 4. 14.
*/
@Slf4j
@RestController
public class CommentController {
@Autowired
private ModelMapper modelMapper;
@Autowired
private CommentService commentService;
@Autowired
private UserService userService;
/**
* @api {get} /comments Request Comment list
* @apiName GetComments
* @apiGroup Comment
*
* @apiParam {Number} [size=20] 가져올 개수
* @apiParam {Number} [page=0] 가져올 페이지
* @apiParam {String="created_at,desc", "updated_at,desc"} [sort=created_at,desc] 정렬 조건
* @apiParam {Number} [post.id] post.id 가져올 포스트 id
* @apiParam {Number} [user.id] user.id 가져올 유저 id
*
* @apiSuccess {Number} status 상태코드
* @apiSuccess {Number} count 댓글 개수
* @apiSuccess {Object[]} data 댓글 리스트
* @apiSuccess {Number} data.id 댓글 id
* @apiSuccess {String} data.content 댓글 내용
* @apiSuccess {Date} data.created_at 댓글 생성일
* @apiSuccess {Date} data.updated_at 댓글 수정일
* @apiSuccess {Object} data.user 댓글 유저
* @apiSuccess {Number} data.user.id 댓글 유저 id
* @apiSuccess {String} data.user.name 댓글 유저 이름
*
* @apiSampleRequest http://localhost:9000/comments?page=1&size=10&sort=updatedAt,desc
*
* @apiUse BadRequestError
*/
@GetMapping("/comments")
public ServerResponse getComments(
@QuerydslPredicate(root = Comment.class) Predicate predicate,
@PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable) {
log.debug("[getPosts] pageable: {}", pageable.toString());
log.debug("[getPosts] predicate: {}", predicate);
Page<Comment> commentPage = commentService.findAll(predicate, pageable);
Long count = commentService.count(predicate);
return ServerResponse.success(CommentResult.getCommentResultList(commentPage), count);
}
/**
* @api {post} /comments Request Comment create
* @apiName CreateComment
* @apiGroup Comment
*
* @apiParam {Number} post_id 포스트 id
* @apiParam {String} content 내용
*
* @apiSuccess {Number} status 상태코드
* @apiSuccess {Object} data 댓글 객체
* @apiSuccess {Number} data.id 댓글 id
* @apiSuccess {String} data.content 댓글 내용
* @apiSuccess {Date} data.created_at 댓글 생성일
* @apiSuccess {Date} data.updated_at 댓글 수정일
* @apiSuccess {Object} data.user 댓글 유저
* @apiSuccess {Number} data.user.id 댓글 유저 id
* @apiSuccess {String} data.user.name 댓글 유저 이름
*
* @apiUse BadRequestError
*/
@PostMapping("/comments")
public ServerResponse postComment(@RequestBody @Valid CreateForm createForm) {
createForm.setUserId(userService.getCurrentUser().getId());
Comment comment = commentService.create(modelMapper.map(createForm, CommentDto.class));
return ServerResponse.success(CommentResult.getCommentResult(comment));
}
/**
* @api {put} /comments/:id Request Comment update
* @apiName UpdateComment
* @apiGroup Comment
*
* @apiParam {String} content 내용
*
* @apiSuccess {Number} status 상태코드
* @apiSuccess {Object} data 댓글 객체
* @apiSuccess {Number} data.id 댓글 id
* @apiSuccess {String} data.content 댓글 내용
* @apiSuccess {Date} data.created_at 댓글 생성일
* @apiSuccess {Date} data.updated_at 댓글 수정일
* @apiSuccess {Object} data.user 댓글 유저
* @apiSuccess {Number} data.user.id 댓글 유저 id
* @apiSuccess {String} data.user.name 댓글 유저 이름
*
* @apiUse BadRequestError
*/
@PutMapping("/comments/{id}")
public ServerResponse putComment(@PathVariable @Valid Long id, @RequestBody @Valid UpdateForm updateForm) {
updateForm.setId(id);
updateForm.setUserId(userService.getCurrentUser().getId());
Comment comment = commentService.update(modelMapper.map(updateForm, CommentDto.class));
return ServerResponse.success(CommentResult.getCommentResult(comment));
}
/**
* @api {delete} /comments/:id Request Comment delete
* @apiName DeleteComment
* @apiGroup Comment
*
* @apiSuccess {Number} status 상태코드
*
* @apiUse BadRequestError
*/
@DeleteMapping("/comments/{id}")
public ServerResponse deleteComment(@PathVariable @Valid Long id) {
DeleteForm deleteForm = new DeleteForm();
deleteForm.setId(id);
deleteForm.setUserId(userService.getCurrentUser().getId());
commentService.delete(modelMapper.map(deleteForm, CommentDto.class));
return ServerResponse.success();
}
}
| board/src/main/java/com/board/gd/domain/comment/CommentController.java | package com.board.gd.domain.comment;
import com.board.gd.domain.comment.form.CreateForm;
import com.board.gd.domain.comment.form.DeleteForm;
import com.board.gd.domain.comment.form.UpdateForm;
import com.board.gd.domain.user.UserService;
import com.board.gd.response.ServerResponse;
import com.querydsl.core.types.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.querydsl.binding.QuerydslPredicate;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
/**
* Created by gd.godong9 on 2017. 4. 14.
*/
@Slf4j
@RestController
public class CommentController {
@Autowired
private ModelMapper modelMapper;
@Autowired
private CommentService commentService;
@Autowired
private UserService userService;
/**
* @api {get} /comments Request Comment list
* @apiName GetComments
* @apiGroup Comment
*
* @apiParam {Number} [size=20] 가져올 개수
* @apiParam {Number} [page=0] 가져올 페이지
* @apiParam {String="created_at,desc", "updated_at,desc"} [sort=created_at,desc] 정렬 조건
* @apiParam {Number} [post.id] post.id 가져올 포스트 id
* @apiParam {Number} [user.id] user.id 가져올 유저 id
*
* @apiSuccess {Number} status 상태코드
* @apiSuccess {Number} count 댓글 개수
* @apiSuccess {Object[]} data 댓글 리스트
* @apiSuccess {Number} data.id 댓글 id
* @apiSuccess {String} data.content 댓글 내용
* @apiSuccess {Date} data.created_at 댓글 생성일
* @apiSuccess {Date} data.updated_at 댓글 수정일
* @apiSuccess {Object} data.user 댓글 유저
* @apiSuccess {Number} data.user.id 댓글 유저 id
* @apiSuccess {String} data.user.name 댓글 유저 이름
*
* @apiSampleRequest http://localhost:9000/comments?page=1&size=10&sort=updatedAt,desc
*
* @apiUse BadRequestError
*/
@GetMapping("/comments")
public ServerResponse getComments(
@QuerydslPredicate(root = Comment.class) Predicate predicate,
@PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable) {
log.debug("[getPosts] pageable: {}", pageable.toString());
log.debug("[getPosts] predicate: {}", predicate);
Page<Comment> commentPage = commentService.findAll(predicate, pageable);
Long count = commentService.count(predicate);
return ServerResponse.success(CommentResult.getCommentResultList(commentPage), count);
}
/**
* @api {post} /comments Request Comment create
* @apiName CreateComment
* @apiGroup Comment
*
* @apiParam {Number} postId 제목
* @apiParam {String} content 내용
*
* @apiSuccess {Number} status 상태코드
* @apiSuccess {Object} data 댓글 객체
* @apiSuccess {Number} data.id 댓글 id
* @apiSuccess {String} data.content 댓글 내용
* @apiSuccess {Date} data.created_at 댓글 생성일
* @apiSuccess {Date} data.updated_at 댓글 수정일
* @apiSuccess {Object} data.user 댓글 유저
* @apiSuccess {Number} data.user.id 댓글 유저 id
* @apiSuccess {String} data.user.name 댓글 유저 이름
*
* @apiUse BadRequestError
*/
@PostMapping("/comments")
public ServerResponse postComment(@RequestBody @Valid CreateForm createForm) {
createForm.setUserId(userService.getCurrentUser().getId());
Comment comment = commentService.create(modelMapper.map(createForm, CommentDto.class));
return ServerResponse.success(CommentResult.getCommentResult(comment));
}
/**
* @api {put} /comments/:id Request Comment update
* @apiName UpdateComment
* @apiGroup Comment
*
* @apiParam {String} content 내용
*
* @apiSuccess {Number} status 상태코드
* @apiSuccess {Object} data 댓글 객체
* @apiSuccess {Number} data.id 댓글 id
* @apiSuccess {String} data.content 댓글 내용
* @apiSuccess {Date} data.created_at 댓글 생성일
* @apiSuccess {Date} data.updated_at 댓글 수정일
* @apiSuccess {Object} data.user 댓글 유저
* @apiSuccess {Number} data.user.id 댓글 유저 id
* @apiSuccess {String} data.user.name 댓글 유저 이름
*
* @apiUse BadRequestError
*/
@PutMapping("/comments/{id}")
public ServerResponse putComment(@PathVariable @Valid Long id, @RequestBody @Valid UpdateForm updateForm) {
updateForm.setId(id);
updateForm.setUserId(userService.getCurrentUser().getId());
Comment comment = commentService.update(modelMapper.map(updateForm, CommentDto.class));
return ServerResponse.success(CommentResult.getCommentResult(comment));
}
/**
* @api {delete} /comments/:id Request Comment delete
* @apiName DeleteComment
* @apiGroup Comment
*
* @apiSuccess {Number} status 상태코드
*
* @apiUse BadRequestError
*/
@DeleteMapping("/comments/{id}")
public ServerResponse deleteComment(@PathVariable @Valid Long id) {
DeleteForm deleteForm = new DeleteForm();
deleteForm.setId(id);
deleteForm.setUserId(userService.getCurrentUser().getId());
commentService.delete(modelMapper.map(deleteForm, CommentDto.class));
return ServerResponse.success();
}
}
| [Server] 문서 수정
| board/src/main/java/com/board/gd/domain/comment/CommentController.java | [Server] 문서 수정 | <ide><path>oard/src/main/java/com/board/gd/domain/comment/CommentController.java
<ide> * @apiName CreateComment
<ide> * @apiGroup Comment
<ide> *
<del> * @apiParam {Number} postId 제목
<add> * @apiParam {Number} post_id 포스트 id
<ide> * @apiParam {String} content 내용
<ide> *
<ide> * @apiSuccess {Number} status 상태코드 |
|
Java | apache-2.0 | error: pathspec 'src/test/java/com/alibaba/json/bvt/parser/BigStringFieldTest.java' did not match any file(s) known to git
| 8c9767313d44a02c9974ae7c35c998be8501aeab | 1 | alibaba/fastjson,alibaba/fastjson,alibaba/fastjson,alibaba/fastjson | package com.alibaba.json.bvt.parser;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.junit.Assert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import junit.framework.TestCase;
public class BigStringFieldTest extends TestCase {
public void test_bigFieldString() throws Exception {
Model model = new Model();
model.f0 = random(1024);
model.f1 = random(1024);
model.f2 = random(1024);
model.f3 = random(1024);
model.f4 = random(1024);
String text = JSON.toJSONString(model);
Model model2 = JSON.parseObject(text, Model.class);
Assert.assertEquals(model2.f0, model.f0);
Assert.assertEquals(model2.f1, model.f1);
Assert.assertEquals(model2.f2, model.f2);
Assert.assertEquals(model2.f3, model.f3);
Assert.assertEquals(model2.f4, model.f4);
}
public void test_list() throws Exception {
List<Model> list = new ArrayList<Model>();
for (int i = 0; i < 1000; ++i) {
Model model = new Model();
model.f0 = random(64);
model.f1 = random(64);
model.f2 = random(64);
model.f3 = random(64);
model.f4 = random(64);
list.add(model);
}
String text = JSON.toJSONString(list);
List<Model> list2 = JSON.parseObject(text, new TypeReference<List<Model>>() {});
Assert.assertEquals(list.size(), list2.size());
for (int i = 0; i < 1000; ++i) {
Assert.assertEquals(list.get(i).f0, list2.get(i).f0);
Assert.assertEquals(list.get(i).f1, list2.get(i).f1);
Assert.assertEquals(list.get(i).f2, list2.get(i).f2);
Assert.assertEquals(list.get(i).f3, list2.get(i).f3);
Assert.assertEquals(list.get(i).f4, list2.get(i).f4);
}
}
public String random(int count) {
Random random = new Random();
char[] chars = new char[count];
for (int i = 0; i < count; ++i) {
chars[i] = (char) random.nextInt();
}
return new String(chars);
}
public static class Model {
public String f0;
public String f1;
public String f2;
public String f3;
public String f4;
}
}
| src/test/java/com/alibaba/json/bvt/parser/BigStringFieldTest.java | add testcase
| src/test/java/com/alibaba/json/bvt/parser/BigStringFieldTest.java | add testcase | <ide><path>rc/test/java/com/alibaba/json/bvt/parser/BigStringFieldTest.java
<add>package com.alibaba.json.bvt.parser;
<add>
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>import java.util.Random;
<add>
<add>import org.junit.Assert;
<add>
<add>import com.alibaba.fastjson.JSON;
<add>import com.alibaba.fastjson.TypeReference;
<add>
<add>import junit.framework.TestCase;
<add>
<add>public class BigStringFieldTest extends TestCase {
<add> public void test_bigFieldString() throws Exception {
<add> Model model = new Model();
<add> model.f0 = random(1024);
<add> model.f1 = random(1024);
<add> model.f2 = random(1024);
<add> model.f3 = random(1024);
<add> model.f4 = random(1024);
<add>
<add> String text = JSON.toJSONString(model);
<add> Model model2 = JSON.parseObject(text, Model.class);
<add> Assert.assertEquals(model2.f0, model.f0);
<add> Assert.assertEquals(model2.f1, model.f1);
<add> Assert.assertEquals(model2.f2, model.f2);
<add> Assert.assertEquals(model2.f3, model.f3);
<add> Assert.assertEquals(model2.f4, model.f4);
<add> }
<add>
<add> public void test_list() throws Exception {
<add> List<Model> list = new ArrayList<Model>();
<add> for (int i = 0; i < 1000; ++i) {
<add> Model model = new Model();
<add> model.f0 = random(64);
<add> model.f1 = random(64);
<add> model.f2 = random(64);
<add> model.f3 = random(64);
<add> model.f4 = random(64);
<add> list.add(model);
<add> }
<add> String text = JSON.toJSONString(list);
<add> List<Model> list2 = JSON.parseObject(text, new TypeReference<List<Model>>() {});
<add> Assert.assertEquals(list.size(), list2.size());
<add> for (int i = 0; i < 1000; ++i) {
<add> Assert.assertEquals(list.get(i).f0, list2.get(i).f0);
<add> Assert.assertEquals(list.get(i).f1, list2.get(i).f1);
<add> Assert.assertEquals(list.get(i).f2, list2.get(i).f2);
<add> Assert.assertEquals(list.get(i).f3, list2.get(i).f3);
<add> Assert.assertEquals(list.get(i).f4, list2.get(i).f4);
<add> }
<add> }
<add>
<add> public String random(int count) {
<add> Random random = new Random();
<add>
<add> char[] chars = new char[count];
<add> for (int i = 0; i < count; ++i) {
<add> chars[i] = (char) random.nextInt();
<add> }
<add>
<add> return new String(chars);
<add> }
<add>
<add> public static class Model {
<add> public String f0;
<add> public String f1;
<add> public String f2;
<add> public String f3;
<add> public String f4;
<add> }
<add>} |
|
Java | epl-1.0 | b5ccd90e0e9be92fb0ed4a727e8cd12836f14868 | 0 | JensErat/openhab,holgercn/openhab,JensErat/openhab,peuter/openhab,kreutpet/openhab,Jakey69/openhab,seebag/openhab,taupinfada/openhab,juri8/openhab,marcelrv/openhab,SwissKid/openhab,marcelrv/openhab,tarioch/openhab,jforge/openhab,resetnow/openhab,digitaldan/openhab,Mike-Petersen/openhab,gilhmauy/openhab,watou/openhab,mvolaart/openhab,wojtus/openhab,cslauritsen/openhab,docbender/openhab,TheOriginalAndrobot/openhab,robbyb67/openhab,svenschreier/openhab,revenz/openhab,andreasgebauer/openhab,steve-bate/openhab,wurtzel/openhab,dfliess/openhab,mrguessed/openhab,cvanorman/openhab,robnielsen/openhab,mash0304/openhab,Jakey69/openhab,hmerk/openhab,robbyb67/openhab,cslauritsen/openhab,steve-bate/openhab,computergeek1507/openhab,TheOriginalAndrobot/openhab,saydulk/openhab,falkena/openhab,paixaop/openhab,teichsta/openhab,stefanroellin/openhab,querdenker2k/openhab,andrey-desman/openhab-hdl,berndpfrommer/openhab,watou/openhab,mjsolidarios/openhab,fbeke/openhab,kbialek/openhab,magcode/openhab,andreasgebauer/openhab,dbadia/openhab,evansj/openhab,coolweb/openhab,kbialek/openhab,rmayr/openhab,sitewhere/openhab,robnielsen/openhab,kreutpet/openhab,MCherifiOSS/openhab,cyclingengineer/openhab,kuijp/openhab,cvanorman/openhab,johkin/openhab,steintore/openhab,mjsolidarios/openhab,MitchSUEW/openhab,falkena/openhab,svenschaefer74/openhab,SwissKid/openhab,openhab/openhab,jhonpaulrocha/openhabss,taupinfada/openhab,Jakey69/openhab,tarioch/openhab,tarioch/openhab,mvolaart/openhab,johkin/openhab,netwolfuk/openhab,jforge/openhab,paphko/openhab,dominicdesu/openhab,starwarsfan/openhab,kgoderis/openhab,sedstef/openhab,wurtzel/openhab,dmize/openhab,MCherifiOSS/openhab,tomtrath/openhab,svenschreier/openhab,ivanfmartinez/openhab,evansj/openhab,dmize/openhab,jforge/openhab,lewie/openhab,QuailAutomation/openhab,stefanroellin/openhab,Mixajlo/openhab,smerschjohann/openhab,tomtrath/openhab,wurtzel/openhab,dmize/openhab,docbender/openhab,Greblys/openhab,mroeckl/openhab,TheNetStriker/openhab,beowulfe/openhab,LaurensVanAcker/openhab,druciak/openhab,Gecko33/openhab,frami/openhab,jowiho/openhab,dfliess/openhab,paolodenti/openhab,RafalLukawiecki/openhab1-addons,bakrus/openhab,kreutpet/openhab,beowulfe/openhab,evansj/openhab,stefanroellin/openhab,TheNetStriker/openhab,smerschjohann/openhab,cesarmarinhorj/openhab,craigham/openhab,mvolaart/openhab,jhonpaulrocha/openhabss,Greblys/openhab,aschor/openhab,g8kmh/openhab,saydulk/openhab,kreutpet/openhab,ssalonen/openhab,paixaop/openhab,robnielsen/openhab,paixaop/openhab,sedstef/openhab,foxy82/openhab,g8kmh/openhab,savageautomate/openhab,AutoMates/openhab,TheOriginalAndrobot/openhab,LaurensVanAcker/openhab,AutoMates/openhab,magcode/openhab,hemantsangwan/openhab,mash0304/openhab,Mike-Petersen/openhab,svenschreier/openhab,wuellueb/openhab,paphko/openhab,dodger777/openhabMod,johkin/openhab,richbeales/openhab,sitewhere/openhab,Gecko33/openhab,wojtus/openhab,AutoMates/openhab,Gerguis/openhab2,QuailAutomation/openhab,andrey-desman/openhab-hdl,tomtrath/openhab,sibbi77/openhab,LaurensVanAcker/openhab,paphko/openhab,sja/openhab,dodger777/openhabMod,vgoldman/openhab,dbadia/openhab,beowulfe/openhab,steve-bate/openhab,foxy82/openhab,mvolaart/openhab,cyclingengineer/openhab,dmize/openhab,elifesy/openhab,robbyb67/openhab,dmize/openhab,mrguessed/openhab,smerschjohann/openhab,falkena/openhab,georgwiltschek/openhab,jowi24/openhab,theoweiss/openhab,kuijp/openhab,lmaertin/openhab,lewie/openhab,falkena/openhab,steintore/openhab,steve-bate/openhab,mdbergmann/openhab,cslauritsen/openhab,Gecko33/openhab,dbadia/openhab,holgercn/openhab,hmerk/openhab,foxy82/openhab,CondormanFr/openhab,rmayr/openhab,netwolfuk/openhab,andrey-desman/openhab-hdl,Greblys/openhab,paixaop/openhab,hemantsangwan/openhab,kbialek/openhab,berndpfrommer/openhab,MCherifiOSS/openhab,ssalonen/openhab,evansj/openhab,steintore/openhab,basriram/openhab,xsnrg/openhab,mleegwt/openhab,hemantsangwan/openhab,kbialek/openhab,Gerguis/open,mash0304/openhab,taimos/openhab,TheNetStriker/openhab,gunthor/openhab,SwissKid/openhab,wep4you/openhab,eschava/openhab,PolymorhicCode/openhab,magcode/openhab,wojtus/openhab,vgoldman/openhab,peuter/openhab,magcode/openhab,druciak/openhab,robnielsen/openhab,dodger777/openhabMod,magcode/openhab,wurtzel/openhab,dvanherbergen/openhab,querdenker2k/openhab,AutoMates/openhab,aruder77/openhab,georgwiltschek/openhab,tdiekmann/openhab,mash0304/openhab,revenz/openhab,eschava/openhab,kreutpet/openhab,steve-bate/openhab,openhab/openhab,AutoMates/openhab,gerrieg/openhab,ssalonen/openhab,PolymorhicCode/openhab,andreasgebauer/openhab,Gerguis/open,resetnow/openhab,sedstef/openhab,resetnow/openhab,wuellueb/openhab,peuter/openhab,lmaertin/openhab,xsnrg/openhab,openhab/openhab,digitaldan/openhab,rmayr/openhab,marcelerkel/openhab,falkena/openhab,sytone/openhab,elifesy/openhab,MitchSUEW/openhab,marcelrv/openhab,cschneider/openhab,CondormanFr/openhab,sitewhere/openhab,wep4you/openhab,sja/openhab,theoweiss/openhab,bakrus/openhab,ivanfmartinez/openhab,kaikreuzer/openhab,starwarsfan/openhab,saydulk/openhab,juri8/openhab,idserda/openhab,sja/openhab,sitewhere/openhab,taimos/openhab,jhonpaulrocha/openhabss,coolweb/openhab,lewie/openhab,kgoderis/openhab,peuter/openhab,theoweiss/openhab,steintore/openhab,cschneider/openhab,Greblys/openhab,Jakey69/openhab,JoeCob/openhab,aschor/openhab,sedstef/openhab,jforge/openhab,curtisstpierre/openhab,ollie-dev/openhab,andreasgebauer/openhab,theoweiss/openhab,georgwiltschek/openhab,steve-bate/openhab,watou/openhab,starwarsfan/openhab,LaurensVanAcker/openhab,swatchy2dot0/openhab,aruder77/openhab,magcode/openhab,doubled-ca/openhab1-addons,hmerk/openhab,frami/openhab,andrey-desman/openhab-hdl,aruder77/openhab,dfliess/openhab,Snickermicker/openhab,craigham/openhab,MitchSUEW/openhab,mroeckl/openhab,ollie-dev/openhab,cyclingengineer/openhab,juri8/openhab,bbesser/openhab1-addons,cschneider/openhab,gilhmauy/openhab,gunthor/openhab,paixaop/openhab,mrguessed/openhab,Gerguis/open,gunthor/openhab,bbesser/openhab1-addons,docbender/openhab,ollie-dev/openhab,gerrieg/openhab,digitaldan/openhab,dominicdesu/openhab,juri8/openhab,doubled-ca/openhab1-addons,dodger777/openhabMod,mash0304/openhab,richbeales/openhab,johkin/openhab,teichsta/openhab,beowulfe/openhab,sumnerboy12/openhab,teichsta/openhab,ivanfmartinez/openhab,Mixajlo/openhab,g8kmh/openhab,berndpfrommer/openhab,dfliess/openhab,hmerk/openhab,savageautomate/openhab,kuijp/openhab,gerrieg/openhab,georgwiltschek/openhab,falkena/openhab,QuailAutomation/openhab,dvanherbergen/openhab,JoeCob/openhab,wojtus/openhab,docbender/openhab,cesarmarinhorj/openhab,RafalLukawiecki/openhab1-addons,CrackerStealth/openhab,jowi24/openhab,resetnow/openhab,mrguessed/openhab,jforge/openhab,dominicdesu/openhab,marcelrv/openhab,dvanherbergen/openhab,JoeCob/openhab,xsnrg/openhab,Snickermicker/openhab,watou/openhab,mdbergmann/openhab,idserda/openhab,kgoderis/openhab,evansj/openhab,paolodenti/openhab,PolymorhicCode/openhab,netwolfuk/openhab,dominicdesu/openhab,robnielsen/openhab,docbender/openhab,robbyb67/openhab,digitaldan/openhab,wep4you/openhab,tomtrath/openhab,PolymorhicCode/openhab,coolweb/openhab,tarioch/openhab,gilhmauy/openhab,starwarsfan/openhab,hemantsangwan/openhab,sytone/openhab,hemantsangwan/openhab,wep4you/openhab,Gerguis/openhab2,taupinfada/openhab,QuailAutomation/openhab,teichsta/openhab,MCherifiOSS/openhab,mvolaart/openhab,mleegwt/openhab,JoeCob/openhab,georgwiltschek/openhab,berndpfrommer/openhab,lmaertin/openhab,taimos/openhab,fbeke/openhab,cyclingengineer/openhab,holgercn/openhab,TheOriginalAndrobot/openhab,theoweiss/openhab,Gerguis/openhab2,johkin/openhab,kreutpet/openhab,bakrus/openhab,lmaertin/openhab,richbeales/openhab,seebag/openhab,gilhmauy/openhab,doubled-ca/openhab1-addons,querdenker2k/openhab,lewie/openhab,g8kmh/openhab,wuellueb/openhab,craigham/openhab,doubled-ca/openhab1-addons,MitchSUEW/openhab,aruder77/openhab,cvanorman/openhab,svenschaefer74/openhab,theoweiss/openhab,paolodenti/openhab,querdenker2k/openhab,hmerk/openhab,CrackerStealth/openhab,mjsolidarios/openhab,maraszm/openhab,dominicdesu/openhab,richbeales/openhab,hemantsangwan/openhab,maraszm/openhab,MitchSUEW/openhab,Mixajlo/openhab,kaikreuzer/openhab,MCherifiOSS/openhab,marcelrv/openhab,mash0304/openhab,SwissKid/openhab,saydulk/openhab,bbesser/openhab1-addons,aschor/openhab,frami/openhab,paphko/openhab,CrackerStealth/openhab,bakrus/openhab,rmayr/openhab,eschava/openhab,frami/openhab,cyclingengineer/openhab,seebag/openhab,andreasgebauer/openhab,dfliess/openhab,beowulfe/openhab,mleegwt/openhab,sitewhere/openhab,paixaop/openhab,QuailAutomation/openhab,saydulk/openhab,bakrus/openhab,aruder77/openhab,kuijp/openhab,maraszm/openhab,cslauritsen/openhab,druciak/openhab,stefanroellin/openhab,gunthor/openhab,stefanroellin/openhab,Gerguis/open,foxy82/openhab,MitchSUEW/openhab,abrenk/openhab,querdenker2k/openhab,revenz/openhab,maraszm/openhab,openhab/openhab,wuellueb/openhab,resetnow/openhab,starwarsfan/openhab,jowiho/openhab,georgwiltschek/openhab,paolodenti/openhab,revenz/openhab,revenz/openhab,JensErat/openhab,digitaldan/openhab,mroeckl/openhab,sja/openhab,MCherifiOSS/openhab,marcelrv/openhab,eschava/openhab,cdjackson/openhab,tarioch/openhab,lmaertin/openhab,eschava/openhab,cesarmarinhorj/openhab,curtisstpierre/openhab,steintore/openhab,Snickermicker/openhab,druciak/openhab,marcelerkel/openhab,abrenk/openhab,gunthor/openhab,robnielsen/openhab,MCherifiOSS/openhab,holgercn/openhab,sja/openhab,dominicdesu/openhab,sumnerboy12/openhab,JoeCob/openhab,curtisstpierre/openhab,RafalLukawiecki/openhab1-addons,mroeckl/openhab,vgoldman/openhab,svenschreier/openhab,Greblys/openhab,openhab/openhab,svenschreier/openhab,robbyb67/openhab,sytone/openhab,paphko/openhab,elifesy/openhab,kbialek/openhab,marcelerkel/openhab,jowi24/openhab,basriram/openhab,Mike-Petersen/openhab,joek/openhab1-addons,cvanorman/openhab,cschneider/openhab,joek/openhab1-addons,johkin/openhab,peuter/openhab,paolodenti/openhab,jforge/openhab,savageautomate/openhab,TheNetStriker/openhab,PolymorhicCode/openhab,georgwiltschek/openhab,dbadia/openhab,wojtus/openhab,PolymorhicCode/openhab,swatchy2dot0/openhab,gerrieg/openhab,gunthor/openhab,Greblys/openhab,LaurensVanAcker/openhab,savageautomate/openhab,fbeke/openhab,marcelrv/openhab,docbender/openhab,jowiho/openhab,swatchy2dot0/openhab,lewie/openhab,cschneider/openhab,gerrieg/openhab,frami/openhab,cesarmarinhorj/openhab,dbadia/openhab,seebag/openhab,joek/openhab1-addons,mrguessed/openhab,docbender/openhab,jhonpaulrocha/openhabss,Snickermicker/openhab,maraszm/openhab,Mixajlo/openhab,sedstef/openhab,marcelerkel/openhab,sitewhere/openhab,cdjackson/openhab,mdbergmann/openhab,curtisstpierre/openhab,rmayr/openhab,vgoldman/openhab,aschor/openhab,mdbergmann/openhab,gilhmauy/openhab,eschava/openhab,jforge/openhab,savageautomate/openhab,netwolfuk/openhab,cdjackson/openhab,JoeCob/openhab,craigham/openhab,fbeke/openhab,basriram/openhab,Mike-Petersen/openhab,magcode/openhab,wuellueb/openhab,dvanherbergen/openhab,maraszm/openhab,aschor/openhab,Gerguis/open,craigham/openhab,computergeek1507/openhab,cvanorman/openhab,abrenk/openhab,robbyb67/openhab,sumnerboy12/openhab,Gerguis/openhab2,teichsta/openhab,marcelerkel/openhab,sumnerboy12/openhab,tomtrath/openhab,lewie/openhab,ollie-dev/openhab,cyclingengineer/openhab,kuijp/openhab,querdenker2k/openhab,SwissKid/openhab,idserda/openhab,digitaldan/openhab,abrenk/openhab,svenschaefer74/openhab,RafalLukawiecki/openhab1-addons,ollie-dev/openhab,elifesy/openhab,paolodenti/openhab,marcelerkel/openhab,TheOriginalAndrobot/openhab,resetnow/openhab,andreasgebauer/openhab,revenz/openhab,TheOriginalAndrobot/openhab,peuter/openhab,TheNetStriker/openhab,juri8/openhab,dodger777/openhabMod,JensErat/openhab,sedstef/openhab,tdiekmann/openhab,Mixajlo/openhab,CrackerStealth/openhab,dodger777/openhabMod,gilhmauy/openhab,svenschreier/openhab,basriram/openhab,lmaertin/openhab,JensErat/openhab,vgoldman/openhab,kbialek/openhab,sumnerboy12/openhab,dfliess/openhab,g8kmh/openhab,wurtzel/openhab,dodger777/openhabMod,tdiekmann/openhab,CondormanFr/openhab,xsnrg/openhab,netwolfuk/openhab,CrackerStealth/openhab,JoeCob/openhab,cesarmarinhorj/openhab,watou/openhab,foxy82/openhab,jowi24/openhab,mdbergmann/openhab,andrey-desman/openhab-hdl,dvanherbergen/openhab,ivanfmartinez/openhab,bbesser/openhab1-addons,dodger777/openhabMod,cslauritsen/openhab,idserda/openhab,ivanfmartinez/openhab,kgoderis/openhab,teichsta/openhab,cschneider/openhab,kuijp/openhab,Mike-Petersen/openhab,mjsolidarios/openhab,tomtrath/openhab,taimos/openhab,basriram/openhab,smerschjohann/openhab,lmaertin/openhab,computergeek1507/openhab,revenz/openhab,kgoderis/openhab,maraszm/openhab,Gecko33/openhab,cslauritsen/openhab,coolweb/openhab,teichsta/openhab,foxy82/openhab,hmerk/openhab,CondormanFr/openhab,holgercn/openhab,watou/openhab,bakrus/openhab,fbeke/openhab,berndpfrommer/openhab,fbeke/openhab,elifesy/openhab,kaikreuzer/openhab,andreasgebauer/openhab,digitaldan/openhab,steintore/openhab,sytone/openhab,Gerguis/open,xsnrg/openhab,tarioch/openhab,juri8/openhab,jowiho/openhab,berndpfrommer/openhab,joek/openhab1-addons,gerrieg/openhab,dbadia/openhab,mdbergmann/openhab,svenschaefer74/openhab,idserda/openhab,digitaldan/openhab,Jakey69/openhab,dvanherbergen/openhab,RafalLukawiecki/openhab1-addons,vgoldman/openhab,JensErat/openhab,ollie-dev/openhab,cvanorman/openhab,mroeckl/openhab,doubled-ca/openhab1-addons,kgoderis/openhab,cdjackson/openhab,smerschjohann/openhab,stefanroellin/openhab,cschneider/openhab,mrguessed/openhab,savageautomate/openhab,sibbi77/openhab,JensErat/openhab,mroeckl/openhab,sja/openhab,doubled-ca/openhab1-addons,eschava/openhab,sytone/openhab,taimos/openhab,taupinfada/openhab,bakrus/openhab,Gerguis/open,wojtus/openhab,richbeales/openhab,sja/openhab,ivanfmartinez/openhab,lewie/openhab,swatchy2dot0/openhab,taimos/openhab,wurtzel/openhab,xsnrg/openhab,Gerguis/openhab2,richbeales/openhab,bbesser/openhab1-addons,CondormanFr/openhab,PolymorhicCode/openhab,aruder77/openhab,evansj/openhab,druciak/openhab,cesarmarinhorj/openhab,AutoMates/openhab,tomtrath/openhab,AutoMates/openhab,Mixajlo/openhab,tomtrath/openhab,Snickermicker/openhab,druciak/openhab,starwarsfan/openhab,stefanroellin/openhab,fbeke/openhab,saydulk/openhab,mash0304/openhab,mleegwt/openhab,cslauritsen/openhab,aschor/openhab,taimos/openhab,computergeek1507/openhab,ssalonen/openhab,dfliess/openhab,Snickermicker/openhab,joek/openhab1-addons,ssalonen/openhab,Jakey69/openhab,taupinfada/openhab,mjsolidarios/openhab,CrackerStealth/openhab,sibbi77/openhab,wojtus/openhab,LaurensVanAcker/openhab,Gerguis/openhab2,jowiho/openhab,gilhmauy/openhab,andrey-desman/openhab-hdl,swatchy2dot0/openhab,kbialek/openhab,svenschaefer74/openhab,mleegwt/openhab,curtisstpierre/openhab,tdiekmann/openhab,jhonpaulrocha/openhabss,mjsolidarios/openhab,CondormanFr/openhab,wep4you/openhab,wurtzel/openhab,openhab/openhab,seebag/openhab,craigham/openhab,andrey-desman/openhab-hdl,watou/openhab,sytone/openhab,johkin/openhab,robbyb67/openhab,starwarsfan/openhab,abrenk/openhab,smerschjohann/openhab,gunthor/openhab,mleegwt/openhab,Gecko33/openhab,teichsta/openhab,cschneider/openhab,curtisstpierre/openhab,wuellueb/openhab,g8kmh/openhab,dmize/openhab,robbyb67/openhab,jhonpaulrocha/openhabss,curtisstpierre/openhab,kaikreuzer/openhab,Gecko33/openhab,basriram/openhab,svenschaefer74/openhab,CondormanFr/openhab,bbesser/openhab1-addons,paixaop/openhab,Gerguis/openhab2,xsnrg/openhab,resetnow/openhab,bakrus/openhab,kgoderis/openhab,sibbi77/openhab,Mike-Petersen/openhab,mleegwt/openhab,SwissKid/openhab,mroeckl/openhab,cyclingengineer/openhab,joek/openhab1-addons,computergeek1507/openhab,juri8/openhab,paixaop/openhab,paphko/openhab,jowiho/openhab,mroeckl/openhab,Greblys/openhab,swatchy2dot0/openhab,saydulk/openhab,mvolaart/openhab,peuter/openhab,jowi24/openhab,QuailAutomation/openhab,cdjackson/openhab,seebag/openhab,ssalonen/openhab,netwolfuk/openhab,smerschjohann/openhab,tdiekmann/openhab,MitchSUEW/openhab,falkena/openhab,RafalLukawiecki/openhab1-addons,g8kmh/openhab,Gecko33/openhab,abrenk/openhab,sibbi77/openhab,sitewhere/openhab,cesarmarinhorj/openhab,sibbi77/openhab,foxy82/openhab,taupinfada/openhab,Jakey69/openhab,mjsolidarios/openhab,kaikreuzer/openhab,TheNetStriker/openhab,coolweb/openhab,jowi24/openhab,cdjackson/openhab,holgercn/openhab,coolweb/openhab,Mike-Petersen/openhab,jowi24/openhab,elifesy/openhab,jhonpaulrocha/openhabss,mdbergmann/openhab,computergeek1507/openhab,holgercn/openhab,hemantsangwan/openhab,marcelerkel/openhab,rmayr/openhab,frami/openhab,richbeales/openhab,craigham/openhab,coolweb/openhab,elifesy/openhab,kaikreuzer/openhab,abrenk/openhab,AutoMates/openhab,idserda/openhab,TheNetStriker/openhab,sumnerboy12/openhab,wep4you/openhab,maraszm/openhab,tdiekmann/openhab,beowulfe/openhab | /**
* Copyright (c) 2010-2015, openHAB.org 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
*/
package org.openhab.binding.bticino.internal;
import be.devlaminck.openwebnet.IBticinoEventListener;
import be.devlaminck.openwebnet.OpenWebNet;
import be.devlaminck.openwebnet.ProtocolRead;
import java.util.List;
import org.openhab.binding.bticino.internal.BticinoGenericBindingProvider.BticinoBindingConfig;
import org.openhab.core.events.EventPublisher;
import org.openhab.core.items.Item;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.RollershutterItem;
import org.openhab.core.library.items.SwitchItem;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.StopMoveType;
import org.openhab.core.library.types.UpDownType;
import org.openhab.core.types.Command;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class connects to the openweb gateway of bticino (MH200(N)) It opens a
* monitor session to retrieve the events And creates (for every) command
* received a command on the bus
*
* @author Tom De Vlaminck
* @serial 1.0
* @since 1.7.0
*/
public class BticinoDevice implements IBticinoEventListener {
// The ID of this gateway (corresponds with the .cfg)
private String m_gateway_id;
// The Bticino binding object (needed to send the events back + retrieve
// information about the binding config of the items)
private BticinoBinding m_bticino_binding;
// Hostname or Host IP (of the MH200)
private String m_host = "";
// Port to connect to
private int m_port = 0;
// Rescan interval in seconds
private int m_rescan_interval_secs = 0;
// Indicator if this device is started
private boolean m_device_is_started = false;
// A lock object
private Object m_lock = new Object();
// The openweb object that handles connections and events
private OpenWebNet m_open_web_net;
private static final Logger logger = LoggerFactory.getLogger(BticinoDevice.class);
private EventPublisher eventPublisher;
public BticinoDevice(String p_gateway_id, BticinoBinding p_bticino_binding) {
m_gateway_id = p_gateway_id;
m_bticino_binding = p_bticino_binding;
}
public void setHost(String p_host) {
m_host = p_host;
}
public void setPort(int p_port) {
m_port = p_port;
}
public void setRescanInterval(int p_rescan_interval_secs) {
m_rescan_interval_secs = p_rescan_interval_secs;
}
public void setEventPublisher(EventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
public void unsetEventPublisher(EventPublisher eventPublisher) {
this.eventPublisher = null;
}
/**
* Initialize this device
*
* @throws InitializationException
*/
public void initialize() throws InitializationException {
// Add other initialization stuff here
logger.debug("Gateway [" + m_gateway_id + "], initialize OK");
}
/**
* Start this device
*
*/
public void startDevice() {
if (m_open_web_net == null) {
m_open_web_net = new OpenWebNet(m_host, m_port,
m_rescan_interval_secs);
m_open_web_net.addEventListener(this);
m_open_web_net.onStart();
}
m_device_is_started = true;
logger.debug("Gateway [" + m_gateway_id + "], started OK");
}
public void stopDevice() {
if (m_open_web_net != null) {
m_open_web_net.interrupt();
m_open_web_net = null;
}
m_device_is_started = false;
}
public boolean isDeviceStarted() {
return m_device_is_started;
}
public void receiveCommand(String itemName, Command command,
BticinoBindingConfig itemBindingConfig) {
try {
synchronized (m_lock) {
// An command is received from the openHab system
// analyse it and execute it
logger.debug(
"Gateway [" + m_gateway_id
+ "], Command '{}' received for item {}",
(Object[]) new String[] { command.toString(), itemName });
ProtocolRead l_pr = new ProtocolRead(itemBindingConfig.who
+ "*" + itemBindingConfig.where);
l_pr.addProperty("who", itemBindingConfig.who);
l_pr.addProperty("address", itemBindingConfig.where);
int l_who = Integer.parseInt(itemBindingConfig.who);
switch (l_who) {
// Lights
case 1: {
if (OnOffType.ON.equals(command))
l_pr.addProperty("what", "1");
else
l_pr.addProperty("what", "0");
break;
}
// Shutter
case 2: {
if (UpDownType.UP.equals(command))
l_pr.addProperty("what", "1");
else if (UpDownType.DOWN.equals(command))
l_pr.addProperty("what", "2");
else if (StopMoveType.STOP.equals(command))
l_pr.addProperty("what", "0");
break;
}
// CEN Basic & Evolved
case 15: {
// Only for the on type, send a CEN event (aka a pushbutton
// device)
// the CEN can start a scenario on eg. a MH200N gateway
// device
if (OnOffType.ON.equals(command))
l_pr.addProperty("what", itemBindingConfig.what);
break;
}
}
m_open_web_net.onCommand(l_pr);
}
} catch (Exception e) {
logger.error("Gateway [" + m_gateway_id
+ "], Error processing receiveCommand '{}'",
(Object[]) new String[] { e.getMessage() });
}
}
public void handleEvent(ProtocolRead p_protocol_read) throws Exception {
// the events on the bus are now received
// map them to events on the openhab bus
logger.debug("Gateway [" + m_gateway_id + "], Bticino WHO ["
+ p_protocol_read.getProperty("who") + "], WHAT ["
+ p_protocol_read.getProperty("what") + "], WHERE ["
+ p_protocol_read.getProperty("where") + "]");
// Get all the configs that are connected to this (who,where), multiple
// possible
List<BticinoBindingConfig> l_binding_configs = m_bticino_binding
.getItemForBticinoBindingConfig(
p_protocol_read.getProperty("who"),
p_protocol_read.getProperty("where"));
// log it when an event has occured that no item is bound to
if (l_binding_configs.isEmpty()) {
logger.debug("Gateway [" + m_gateway_id
+ "], No Item found for bticino event, WHO ["
+ p_protocol_read.getProperty("who") + "], WHAT ["
+ p_protocol_read.getProperty("what") + "], WHERE ["
+ p_protocol_read.getProperty("where") + "]");
}
// every item associated with this who/where update the status
for (BticinoBindingConfig l_binding_config : l_binding_configs) {
// Get the Item out of the config
Item l_item = l_binding_config.getItem();
if (l_item instanceof SwitchItem) {
// Lights
if (p_protocol_read.getProperty("messageType")
.equalsIgnoreCase("lighting")) {
logger.debug("Gateway [" + m_gateway_id
+ "], RECEIVED EVENT FOR SwitchItem ["
+ l_item.getName()
+ "], TRANSLATE TO OPENHAB BUS EVENT");
if (p_protocol_read.getProperty("messageDescription")
.equalsIgnoreCase("Light ON")) {
eventPublisher.postUpdate(l_item.getName(),
OnOffType.ON);
} else if (p_protocol_read
.getProperty("messageDescription")
.equalsIgnoreCase("Light OFF")) {
eventPublisher.postUpdate(l_item.getName(),
OnOffType.OFF);
}
}
// CENs
else if (p_protocol_read.getProperty("messageType")
.equalsIgnoreCase("CEN Basic and Evolved")) {
// Pushbutton virtual address must match
if (l_binding_config.what.equalsIgnoreCase(p_protocol_read
.getProperty("what"))) {
logger.debug("Gateway [" + m_gateway_id
+ "], RECEIVED EVENT FOR SwitchItem ["
+ l_item.getName()
+ "], TRANSLATE TO OPENHAB BUS EVENT");
if (p_protocol_read.getProperty("messageDescription")
.equalsIgnoreCase("Virtual pressure")) {
// only returns when finished
eventPublisher.sendCommand(l_item.getName(),
OnOffType.ON);
} else if (p_protocol_read.getProperty(
"messageDescription").equalsIgnoreCase(
"Virtual release after short pressure")) {
// only returns when finished
eventPublisher.sendCommand(l_item.getName(),
OnOffType.ON);
} else if (p_protocol_read.getProperty(
"messageDescription").equalsIgnoreCase(
"Virtual release after an extended pressure")) {
// only returns when finished
eventPublisher.sendCommand(l_item.getName(),
OnOffType.ON);
} else if (p_protocol_read.getProperty(
"messageDescription").equalsIgnoreCase(
"Virtual extended pressure")) {
// only returns when finished
eventPublisher.sendCommand(l_item.getName(),
OnOffType.ON);
}
}
}
} else if (l_item instanceof RollershutterItem) {
logger.debug("Gateway [" + m_gateway_id
+ "], RECEIVED EVENT FOR RollershutterItem ["
+ l_item.getName()
+ "], TRANSLATE TO OPENHAB BUS EVENT");
if (p_protocol_read.getProperty("messageType")
.equalsIgnoreCase("automation")) {
if (p_protocol_read.getProperty("messageDescription")
.equalsIgnoreCase("Automation UP")) {
eventPublisher.postUpdate(l_item.getName(),
UpDownType.UP);
} else if (p_protocol_read
.getProperty("messageDescription")
.equalsIgnoreCase("Automation DOWN")) {
eventPublisher.postUpdate(l_item.getName(),
UpDownType.DOWN);
}
}
} else if (l_item instanceof NumberItem) {
if (logger.isDebugEnabled())
logger.debug("Gateway [" + m_gateway_id + "], RECEIVED EVENT FOR NumberItem [" + l_item.getName() + "], TRANSLATE TO OPENHAB BUS EVENT");
// THERMOREGULATION
if (p_protocol_read.getProperty("messageType")
.equalsIgnoreCase("thermoregulation")) {
if (p_protocol_read.getProperty("messageDescription")
.equalsIgnoreCase("Temperature value")) {
eventPublisher.postUpdate(l_item.getName(), DecimalType.valueOf(p_protocol_read.getProperty("temperature")));
}
}
}
}
}
}
| bundles/binding/org.openhab.binding.bticino/src/main/java/org/openhab/binding/bticino/internal/BticinoDevice.java | /**
* Copyright (c) 2010-2015, openHAB.org 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
*/
package org.openhab.binding.bticino.internal;
import be.devlaminck.openwebnet.IBticinoEventListener;
import be.devlaminck.openwebnet.OpenWebNet;
import be.devlaminck.openwebnet.ProtocolRead;
import java.util.List;
import org.openhab.binding.bticino.internal.BticinoGenericBindingProvider.BticinoBindingConfig;
import org.openhab.core.events.EventPublisher;
import org.openhab.core.items.Item;
import org.openhab.core.library.items.RollershutterItem;
import org.openhab.core.library.items.SwitchItem;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.StopMoveType;
import org.openhab.core.library.types.UpDownType;
import org.openhab.core.types.Command;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class connects to the openweb gateway of bticino (MH200(N)) It opens a
* monitor session to retrieve the events And creates (for every) command
* received a command on the bus
*
* @author Tom De Vlaminck
* @serial 1.0
* @since 1.7.0
*/
public class BticinoDevice implements IBticinoEventListener {
// The ID of this gateway (corresponds with the .cfg)
private String m_gateway_id;
// The Bticino binding object (needed to send the events back + retrieve
// information about the binding config of the items)
private BticinoBinding m_bticino_binding;
// Hostname or Host IP (of the MH200)
private String m_host = "";
// Port to connect to
private int m_port = 0;
// Rescan interval in seconds
private int m_rescan_interval_secs = 0;
// Indicator if this device is started
private boolean m_device_is_started = false;
// A lock object
private Object m_lock = new Object();
// The openweb object that handles connections and events
private OpenWebNet m_open_web_net;
private static final Logger logger = LoggerFactory.getLogger(BticinoDevice.class);
private EventPublisher eventPublisher;
public BticinoDevice(String p_gateway_id, BticinoBinding p_bticino_binding) {
m_gateway_id = p_gateway_id;
m_bticino_binding = p_bticino_binding;
}
public void setHost(String p_host) {
m_host = p_host;
}
public void setPort(int p_port) {
m_port = p_port;
}
public void setRescanInterval(int p_rescan_interval_secs) {
m_rescan_interval_secs = p_rescan_interval_secs;
}
public void setEventPublisher(EventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
public void unsetEventPublisher(EventPublisher eventPublisher) {
this.eventPublisher = null;
}
/**
* Initialize this device
*
* @throws InitializationException
*/
public void initialize() throws InitializationException {
// Add other initialization stuff here
logger.debug("Gateway [" + m_gateway_id + "], initialize OK");
}
/**
* Start this device
*
*/
public void startDevice() {
if (m_open_web_net == null) {
m_open_web_net = new OpenWebNet(m_host, m_port,
m_rescan_interval_secs);
m_open_web_net.addEventListener(this);
m_open_web_net.onStart();
}
m_device_is_started = true;
logger.debug("Gateway [" + m_gateway_id + "], started OK");
}
public void stopDevice() {
if (m_open_web_net != null) {
m_open_web_net.interrupt();
m_open_web_net = null;
}
m_device_is_started = false;
}
public boolean isDeviceStarted() {
return m_device_is_started;
}
public void receiveCommand(String itemName, Command command,
BticinoBindingConfig itemBindingConfig) {
try {
synchronized (m_lock) {
// An command is received from the openHab system
// analyse it and execute it
logger.debug(
"Gateway [" + m_gateway_id
+ "], Command '{}' received for item {}",
(Object[]) new String[] { command.toString(), itemName });
ProtocolRead l_pr = new ProtocolRead(itemBindingConfig.who
+ "*" + itemBindingConfig.where);
l_pr.addProperty("who", itemBindingConfig.who);
l_pr.addProperty("address", itemBindingConfig.where);
int l_who = Integer.parseInt(itemBindingConfig.who);
switch (l_who) {
// Lights
case 1: {
if (OnOffType.ON.equals(command))
l_pr.addProperty("what", "1");
else
l_pr.addProperty("what", "0");
break;
}
// Shutter
case 2: {
if (UpDownType.UP.equals(command))
l_pr.addProperty("what", "1");
else if (UpDownType.DOWN.equals(command))
l_pr.addProperty("what", "2");
else if (StopMoveType.STOP.equals(command))
l_pr.addProperty("what", "0");
break;
}
// CEN Basic & Evolved
case 15: {
// Only for the on type, send a CEN event (aka a pushbutton
// device)
// the CEN can start a scenario on eg. a MH200N gateway
// device
if (OnOffType.ON.equals(command))
l_pr.addProperty("what", itemBindingConfig.what);
break;
}
}
m_open_web_net.onCommand(l_pr);
}
} catch (Exception e) {
logger.error("Gateway [" + m_gateway_id
+ "], Error processing receiveCommand '{}'",
(Object[]) new String[] { e.getMessage() });
}
}
public void handleEvent(ProtocolRead p_protocol_read) throws Exception {
// the events on the bus are now received
// map them to events on the openhab bus
logger.debug("Gateway [" + m_gateway_id + "], Bticino WHO ["
+ p_protocol_read.getProperty("who") + "], WHAT ["
+ p_protocol_read.getProperty("what") + "], WHERE ["
+ p_protocol_read.getProperty("where") + "]");
// Get all the configs that are connected to this (who,where), multiple
// possible
List<BticinoBindingConfig> l_binding_configs = m_bticino_binding
.getItemForBticinoBindingConfig(
p_protocol_read.getProperty("who"),
p_protocol_read.getProperty("where"));
// log it when an event has occured that no item is bound to
if (l_binding_configs.isEmpty()) {
logger.debug("Gateway [" + m_gateway_id
+ "], No Item found for bticino event, WHO ["
+ p_protocol_read.getProperty("who") + "], WHAT ["
+ p_protocol_read.getProperty("what") + "], WHERE ["
+ p_protocol_read.getProperty("where") + "]");
}
// every item associated with this who/where update the status
for (BticinoBindingConfig l_binding_config : l_binding_configs) {
// Get the Item out of the config
Item l_item = l_binding_config.getItem();
if (l_item instanceof SwitchItem) {
// Lights
if (p_protocol_read.getProperty("messageType")
.equalsIgnoreCase("lighting")) {
logger.debug("Gateway [" + m_gateway_id
+ "], RECEIVED EVENT FOR SwitchItem ["
+ l_item.getName()
+ "], TRANSLATE TO OPENHAB BUS EVENT");
if (p_protocol_read.getProperty("messageDescription")
.equalsIgnoreCase("Light ON")) {
eventPublisher.postUpdate(l_item.getName(),
OnOffType.ON);
} else if (p_protocol_read
.getProperty("messageDescription")
.equalsIgnoreCase("Light OFF")) {
eventPublisher.postUpdate(l_item.getName(),
OnOffType.OFF);
}
}
// CENs
else if (p_protocol_read.getProperty("messageType")
.equalsIgnoreCase("CEN Basic and Evolved")) {
// Pushbutton virtual address must match
if (l_binding_config.what.equalsIgnoreCase(p_protocol_read
.getProperty("what"))) {
logger.debug("Gateway [" + m_gateway_id
+ "], RECEIVED EVENT FOR SwitchItem ["
+ l_item.getName()
+ "], TRANSLATE TO OPENHAB BUS EVENT");
if (p_protocol_read.getProperty("messageDescription")
.equalsIgnoreCase("Virtual pressure")) {
// only returns when finished
eventPublisher.sendCommand(l_item.getName(),
OnOffType.ON);
} else if (p_protocol_read.getProperty(
"messageDescription").equalsIgnoreCase(
"Virtual release after short pressure")) {
// only returns when finished
eventPublisher.sendCommand(l_item.getName(),
OnOffType.ON);
} else if (p_protocol_read.getProperty(
"messageDescription").equalsIgnoreCase(
"Virtual release after an extended pressure")) {
// only returns when finished
eventPublisher.sendCommand(l_item.getName(),
OnOffType.ON);
} else if (p_protocol_read.getProperty(
"messageDescription").equalsIgnoreCase(
"Virtual extended pressure")) {
// only returns when finished
eventPublisher.sendCommand(l_item.getName(),
OnOffType.ON);
}
}
}
} else if (l_item instanceof RollershutterItem) {
logger.debug("Gateway [" + m_gateway_id
+ "], RECEIVED EVENT FOR RollershutterItem ["
+ l_item.getName()
+ "], TRANSLATE TO OPENHAB BUS EVENT");
if (p_protocol_read.getProperty("messageType")
.equalsIgnoreCase("automation")) {
if (p_protocol_read.getProperty("messageDescription")
.equalsIgnoreCase("Automation UP")) {
eventPublisher.postUpdate(l_item.getName(),
UpDownType.UP);
} else if (p_protocol_read
.getProperty("messageDescription")
.equalsIgnoreCase("Automation DOWN")) {
eventPublisher.postUpdate(l_item.getName(),
UpDownType.DOWN);
}
}
}
}
}
} | Update BticinoDevice.java
Add thermoregulation temperature reader | bundles/binding/org.openhab.binding.bticino/src/main/java/org/openhab/binding/bticino/internal/BticinoDevice.java | Update BticinoDevice.java | <ide><path>undles/binding/org.openhab.binding.bticino/src/main/java/org/openhab/binding/bticino/internal/BticinoDevice.java
<ide> import org.openhab.binding.bticino.internal.BticinoGenericBindingProvider.BticinoBindingConfig;
<ide> import org.openhab.core.events.EventPublisher;
<ide> import org.openhab.core.items.Item;
<add>import org.openhab.core.library.items.NumberItem;
<ide> import org.openhab.core.library.items.RollershutterItem;
<ide> import org.openhab.core.library.items.SwitchItem;
<add>import org.openhab.core.library.types.DecimalType;
<ide> import org.openhab.core.library.types.OnOffType;
<ide> import org.openhab.core.library.types.StopMoveType;
<ide> import org.openhab.core.library.types.UpDownType;
<ide> UpDownType.DOWN);
<ide> }
<ide> }
<add> } else if (l_item instanceof NumberItem) {
<add> if (logger.isDebugEnabled())
<add> logger.debug("Gateway [" + m_gateway_id + "], RECEIVED EVENT FOR NumberItem [" + l_item.getName() + "], TRANSLATE TO OPENHAB BUS EVENT");
<add>
<add> // THERMOREGULATION
<add> if (p_protocol_read.getProperty("messageType")
<add> .equalsIgnoreCase("thermoregulation")) {
<add>
<add> if (p_protocol_read.getProperty("messageDescription")
<add> .equalsIgnoreCase("Temperature value")) {
<add> eventPublisher.postUpdate(l_item.getName(), DecimalType.valueOf(p_protocol_read.getProperty("temperature")));
<add> }
<add> }
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | error: pathspec 'app/src/main/java/tn/droidcon/testprovider/TestProviderApplication.java' did not match any file(s) known to git
| 632b1c4e50cae9074da3398bf24fa7dd623130c4 | 1 | slim-benhammouda/droidcontn-2015 | package tn.droidcon.testprovider;
import android.app.Application;
import android.os.StrictMode;
public class TestProviderApplication extends Application {
public void onCreate() {
super.onCreate();
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll().penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectAll().penaltyLog().build());
}
}
| app/src/main/java/tn/droidcon/testprovider/TestProviderApplication.java | add strictMode
| app/src/main/java/tn/droidcon/testprovider/TestProviderApplication.java | add strictMode | <ide><path>pp/src/main/java/tn/droidcon/testprovider/TestProviderApplication.java
<add>package tn.droidcon.testprovider;
<add>
<add>import android.app.Application;
<add>import android.os.StrictMode;
<add>
<add>public class TestProviderApplication extends Application {
<add>
<add> public void onCreate() {
<add> super.onCreate();
<add>
<add> StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
<add> .detectAll().penaltyLog().build());
<add> StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
<add> .detectAll().penaltyLog().build());
<add>
<add> }
<add>
<add>} |
|
Java | bsd-3-clause | 6c038f1e2b48b1b5165d704436d68496e6a63045 | 0 | ox-it/oxpoints-legacy,ox-it/oxpoints-legacy,ox-it/oxpoints-legacy,ox-it/oxpoints-legacy | /**
* Copyright 2009 University of Oxford
*
* Written by Tim Pizey for the Erewhon Project
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the University of Oxford 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 uk.ac.ox.oucs.oxpoints;
import java.io.File;
import net.sf.gaboto.Gaboto;
import net.sf.gaboto.GabotoFactory;
import uk.ac.ox.oucs.oxpoints.gaboto.TEIImporter;
/**
* @author timp
* @since 11 September 2009
*
*/
public final class OxpointsFactory {
public static String filename = "src/test/data/oxpoints_plus.xml";
public static Gaboto getOxpointsFromXML() {
return getOxpointsFromXML(filename);
}
public static Gaboto getOxpointsFromXML(String filenameIn) {
System.err.println("Reading oxp from " + filenameIn);
File file = new File(filenameIn);
if(! file.exists()) {
file = new File("examples/oxpoints/" + filename);
if(! file.exists()) {
throw new RuntimeException ("Cannot open file " + filenameIn);
}
}
Gaboto oxp = GabotoFactory.getEmptyInMemoryGaboto();
synchronized (oxp) {
new TEIImporter(oxp, file).run();
}
return oxp;
}
}
| src/main/java/uk/ac/ox/oucs/oxpoints/OxpointsFactory.java | /**
* Copyright 2009 University of Oxford
*
* Written by Tim Pizey for the Erewhon Project
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the University of Oxford 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 uk.ac.ox.oucs.oxpoints;
import java.io.File;
import net.sf.gaboto.Gaboto;
import net.sf.gaboto.GabotoFactory;
import uk.ac.ox.oucs.oxpoints.gaboto.TEIImporter;
/**
* @author timp
* @since 11 September 2009
*
*/
public final class OxpointsFactory {
public static String filename = "src/test/data/oxpoints_plus.xml";
public static Gaboto getOxpointsFromXML() {
return getOxpointsFromXML(filename);
}
public static Gaboto getOxpointsFromXML(String filenameIn) {
System.err.println("Reading oxp from " + filenameIn);
File file = new File(filenameIn);
if(! file.exists()) {
file = new File("examples/oxpoints/" + filename);
if(! file.exists()) {
throw new RuntimeException ("Cannot open file " + filenameIn);
}
}
Gaboto oxp = null;
synchronized (oxp) {
oxp = GabotoFactory.getEmptyInMemoryGaboto();
new TEIImporter(oxp, file).run();
}
return oxp;
}
}
| Doh
git-svn-id: 3098d238ea56ce31e1b1f8accb41756148705ef9@886 447d1985-9db6-4ff4-aa49-62d8beba8372
| src/main/java/uk/ac/ox/oucs/oxpoints/OxpointsFactory.java | Doh | <ide><path>rc/main/java/uk/ac/ox/oucs/oxpoints/OxpointsFactory.java
<ide> throw new RuntimeException ("Cannot open file " + filenameIn);
<ide> }
<ide> }
<del> Gaboto oxp = null;
<add> Gaboto oxp = GabotoFactory.getEmptyInMemoryGaboto();
<ide> synchronized (oxp) {
<del> oxp = GabotoFactory.getEmptyInMemoryGaboto();
<ide> new TEIImporter(oxp, file).run();
<ide> }
<ide> return oxp; |
|
Java | apache-2.0 | d0949cef6bba140401f3b23126d62afbd4740501 | 0 | jay-hodgson/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,jay-hodgson/SynapseWebClient,jay-hodgson/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,jay-hodgson/SynapseWebClient,Sage-Bionetworks/SynapseWebClient | package org.sagebionetworks.web.unitclient.widget.entity.renderer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyList;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.sagebionetworks.web.client.ClientProperties.*;
import static org.sagebionetworks.web.client.widget.entity.renderer.PlotlyWidget.ALL_PARTS_MASK;
import static org.sagebionetworks.web.client.widget.entity.renderer.PlotlyWidget.LIMIT;
import static org.sagebionetworks.web.shared.WidgetConstants.BAR_MODE;
import static org.sagebionetworks.web.shared.WidgetConstants.*;
import static org.sagebionetworks.web.shared.WidgetConstants.TABLE_QUERY_KEY;
import static org.sagebionetworks.web.shared.WidgetConstants.TITLE;
import static org.sagebionetworks.web.shared.WidgetConstants.TYPE;
import static org.sagebionetworks.web.shared.WidgetConstants.X_AXIS_TITLE;
import static org.sagebionetworks.web.shared.WidgetConstants.Y_AXIS_TITLE;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.sagebionetworks.repo.model.asynch.AsynchronousJobStatus;
import org.sagebionetworks.repo.model.table.Query;
import org.sagebionetworks.repo.model.table.QueryBundleRequest;
import org.sagebionetworks.repo.model.table.QueryResult;
import org.sagebionetworks.repo.model.table.QueryResultBundle;
import org.sagebionetworks.repo.model.table.Row;
import org.sagebionetworks.repo.model.table.RowSet;
import org.sagebionetworks.repo.model.table.SelectColumn;
import org.sagebionetworks.schema.adapter.JSONObjectAdapterException;
import org.sagebionetworks.web.client.plotly.BarMode;
import org.sagebionetworks.web.client.plotly.GraphType;
import org.sagebionetworks.web.client.plotly.PlotlyTraceWrapper;
import org.sagebionetworks.web.client.resources.ResourceLoader;
import org.sagebionetworks.web.client.widget.asynch.AsynchronousJobTracker;
import org.sagebionetworks.web.client.widget.asynch.AsynchronousProgressWidget;
import org.sagebionetworks.web.client.widget.asynch.UpdatingAsynchProgressHandler;
import org.sagebionetworks.web.client.widget.entity.controller.SynapseAlert;
import org.sagebionetworks.web.client.widget.entity.renderer.PlotlyWidget;
import org.sagebionetworks.web.client.widget.entity.renderer.PlotlyWidgetView;
import org.sagebionetworks.web.client.widget.table.v2.QueryTokenProvider;
import org.sagebionetworks.web.shared.WikiPageKey;
import org.sagebionetworks.web.shared.asynch.AsynchType;
import com.google.gwt.user.client.rpc.AsyncCallback;
public class PlotlyWidgetTest {
PlotlyWidget widget;
@Mock
PlotlyWidgetView mockView;
@Mock
SynapseAlert mockSynAlert;
@Mock
AsynchronousJobTracker mockJobTracker;
@Captor
ArgumentCaptor<QueryBundleRequest> queryBundleRequestCaptor;
@Captor
ArgumentCaptor<UpdatingAsynchProgressHandler> jobTrackerCallbackCaptor;
@Mock
QueryResultBundle mockQueryResultBundle;
@Mock
QueryResult mockQueryResult;
@Mock
RowSet mockRowSet;
@Mock
Row mockRow;
@Mock
ResourceLoader mockResourceLoader;
@Mock
QueryTokenProvider mockQueryTokenProvider;
List<SelectColumn> selectColumns;
List<Row> rows;
List<String> rowValues;
@Mock
SelectColumn mockXColumn;
@Mock
SelectColumn mockY1Column;
@Mock
SelectColumn mockY2Column;
@Captor
ArgumentCaptor<List> plotlyTraceArrayCaptor;
@Mock
AsynchronousJobStatus mockAsynchronousJobStatus;
@Captor
ArgumentCaptor<String> stringCaptor;
@Captor
ArgumentCaptor<AsyncCallback> webResourceLoadedCallbackCaptor;
Map<String, String> params;
public static final String X_COLUMN_NAME = "x";
public static final String Y1_COLUMN_NAME = "y1";
public static final String Y2_COLUMN_NAME = "y2";
@Before
public void setup(){
MockitoAnnotations.initMocks(this);
widget = new PlotlyWidget(
mockView,
mockSynAlert,
mockJobTracker,
mockResourceLoader,
mockQueryTokenProvider);
params = new HashMap<>();
selectColumns = new ArrayList<>();
rows = new ArrayList<>();
rowValues = new ArrayList<>();
when(mockQueryResultBundle.getSelectColumns()).thenReturn(selectColumns);
when(mockQueryResultBundle.getQueryResult()).thenReturn(mockQueryResult);
when(mockQueryResult.getQueryResults()).thenReturn(mockRowSet);
when(mockRowSet.getRows()).thenReturn(rows);
when(mockXColumn.getName()).thenReturn(X_COLUMN_NAME);
when(mockY1Column.getName()).thenReturn(Y1_COLUMN_NAME);
when(mockY2Column.getName()).thenReturn(Y1_COLUMN_NAME);
when(mockRow.getValues()).thenReturn(rowValues);
when(mockResourceLoader.isLoaded(eq(PLOTLY_JS))).thenReturn(true);
when(mockResourceLoader.isLoaded(eq(PLOTLY_REACT_JS))).thenReturn(true);
}
@Test
public void testConstructor() {
verify(mockView).setSynAlertWidget(mockSynAlert);
verify(mockView).setPresenter(widget);
}
@Test
public void testAsWidget() {
widget.asWidget();
verify(mockView).asWidget();
}
@Test
public void testConfigure() {
String queryToken = "encoded sql which is passed to place";
when(mockQueryTokenProvider.queryToToken(any(Query.class))).thenReturn(queryToken);
WikiPageKey pageKey = null;
String xAxisLabel = "X Axis";
String yAxisLabel = "Y Axis";
GraphType type = GraphType.BAR;
BarMode mode = BarMode.STACK;
String plotTitle = "Plot Title";
String tableId = "syn12345";
boolean showLegend = false;
boolean isHorizontal = false;
String sql = "select x, y1, y2 from "+tableId+" where x>2";
params.put(TABLE_QUERY_KEY, sql);
params.put(TITLE, plotTitle);
params.put(X_AXIS_TITLE, xAxisLabel);
params.put(Y_AXIS_TITLE, yAxisLabel);
params.put(TYPE, type.toString());
params.put(BAR_MODE, mode.toString());
params.put(SHOW_LEGEND, Boolean.toString(showLegend));
params.put(IS_HORIZONTAL, Boolean.toString(isHorizontal));
selectColumns.add(mockXColumn);
selectColumns.add(mockY1Column);
selectColumns.add(mockY2Column);
rowValues.add("row1X");
rowValues.add("1.1");
rowValues.add("2.2");
rows.add(mockRow);
when(mockQueryResultBundle.getQueryCount()).thenReturn(LIMIT + 1);
widget.configure(pageKey, params, null, null);
verify(mockView).setSourceDataLink(stringCaptor.capture());
verify(mockView).setSourceDataLinkVisible(false);
verify(mockView, never()).setSourceDataLinkVisible(true);
String sourceDataLink = stringCaptor.getValue();
assertTrue(sourceDataLink.contains(tableId));
assertTrue(sourceDataLink.contains(queryToken));
//verify query params, and plot configuration based on results
verify(mockView).setLoadingVisible(true);
verify(mockJobTracker).startAndTrack(eq(AsynchType.TableQuery), queryBundleRequestCaptor.capture(), eq(AsynchronousProgressWidget.WAIT_MS), jobTrackerCallbackCaptor.capture());
//check query
QueryBundleRequest request = queryBundleRequestCaptor.getValue();
assertEquals(ALL_PARTS_MASK, request.getPartMask());
assertEquals("syn12345", request.getEntityId());
assertEquals((Long)0L, request.getQuery().getOffset());
assertEquals(sql, request.getQuery().getSql());
// complete first page load
jobTrackerCallbackCaptor.getValue().onComplete(mockQueryResultBundle);
verify(mockView, never()).showChart(eq(plotTitle), anyString(), anyString(), anyList(), anyString(), anyString(), anyString(), anyBoolean());
//test final page
rows.clear();
verify(mockJobTracker, times(2)).startAndTrack(eq(AsynchType.TableQuery), queryBundleRequestCaptor.capture(), eq(AsynchronousProgressWidget.WAIT_MS), jobTrackerCallbackCaptor.capture());
//verify offset updated
request = queryBundleRequestCaptor.getValue();
assertEquals(LIMIT, request.getQuery().getOffset());
verify(mockView, times(2)).setLoadingMessage(stringCaptor.capture());
String loadingMessage = stringCaptor.getValue();
assertTrue(loadingMessage.contains(LIMIT.toString()));
jobTrackerCallbackCaptor.getValue().onComplete(mockQueryResultBundle);
verify(mockView).showChart(eq(plotTitle), eq(xAxisLabel), eq(yAxisLabel), plotlyTraceArrayCaptor.capture(), eq(mode.toString().toLowerCase()), anyString(), anyString(), eq(showLegend));
List traces = plotlyTraceArrayCaptor.getValue();
assertTrue(traces.size() > 0);
assertEquals(type.toString().toLowerCase(), ((PlotlyTraceWrapper)traces.get(0)).getType());
assertEquals(isHorizontal, ((PlotlyTraceWrapper)traces.get(0)).isHorizontal());
verify(mockView).setSourceDataLinkVisible(true);
}
@Test
public void testTrackerOnCancel() {
GraphType type = GraphType.SCATTER;
params.put(TYPE, type.toString());
WikiPageKey pageKey = null;
widget.configure(pageKey, params, null, null);
verify(mockJobTracker).startAndTrack(eq(AsynchType.TableQuery), queryBundleRequestCaptor.capture(), eq(AsynchronousProgressWidget.WAIT_MS), jobTrackerCallbackCaptor.capture());
UpdatingAsynchProgressHandler progressHandler = jobTrackerCallbackCaptor.getValue();
//also verify attachment state is based on view
when(mockView.isAttached()).thenReturn(true);
assertTrue(progressHandler.isAttached());
when(mockView.isAttached()).thenReturn(false);
assertFalse(progressHandler.isAttached());
progressHandler.onCancel();
verify(mockView, times(2)).clearChart();
verify(mockView).setLoadingVisible(false);
}
@Test
public void testTrackerOnFailure() {
GraphType type = GraphType.SCATTER;
params.put(TYPE, type.toString());
WikiPageKey pageKey = null;
widget.configure(pageKey, params, null, null);
verify(mockJobTracker).startAndTrack(eq(AsynchType.TableQuery), queryBundleRequestCaptor.capture(), eq(AsynchronousProgressWidget.WAIT_MS), jobTrackerCallbackCaptor.capture());
UpdatingAsynchProgressHandler progressHandler = jobTrackerCallbackCaptor.getValue();
Exception error = new Exception();
progressHandler.onFailure(error);
verify(mockView, times(2)).clearChart();
verify(mockView).setLoadingVisible(false);
verify(mockSynAlert).handleException(error);
}
@Test
public void testLazyLoadPlotlyJS() throws JSONObjectAdapterException {
GraphType type = GraphType.SCATTER;
params.put(TYPE, type.toString());
boolean showLegend = true;
params.put(SHOW_LEGEND, Boolean.toString(showLegend));
WikiPageKey pageKey = null;
when(mockResourceLoader.isLoaded(eq(PLOTLY_JS))).thenReturn(false);
widget.configure(pageKey, params, null, null);
verify(mockJobTracker).startAndTrack(eq(AsynchType.TableQuery), queryBundleRequestCaptor.capture(), eq(AsynchronousProgressWidget.WAIT_MS), jobTrackerCallbackCaptor.capture());
jobTrackerCallbackCaptor.getValue().onComplete(mockQueryResultBundle);
verify(mockView, never()).showChart(anyString(), anyString(), anyString(), anyList(), anyString(), anyString(), anyString(), anyBoolean());
verify(mockResourceLoader).isLoaded(eq(PLOTLY_JS));
verify(mockResourceLoader).requires(eq(PLOTLY_JS), webResourceLoadedCallbackCaptor.capture());
AsyncCallback callback = webResourceLoadedCallbackCaptor.getValue();
Exception ex = new Exception();
callback.onFailure(ex);
verify(mockSynAlert).handleException(ex);
verify(mockView, never()).showChart(anyString(), anyString(), anyString(), anyList(), anyString(), anyString(), anyString(), anyBoolean());
when(mockResourceLoader.isLoaded(eq(PLOTLY_JS))).thenReturn(true);
callback.onSuccess(null);
verify(mockView).showChart(anyString(), anyString(), anyString(), anyList(), anyString(), anyString(), anyString(), eq(showLegend));
}
@Test
public void testLazyLoadPlotlyReactJS() throws JSONObjectAdapterException {
GraphType type = GraphType.SCATTER;
params.put(TYPE, type.toString());
boolean showLegend = true;
params.put(SHOW_LEGEND, Boolean.toString(showLegend));
WikiPageKey pageKey = null;
when(mockResourceLoader.isLoaded(eq(PLOTLY_REACT_JS))).thenReturn(false);
widget.configure(pageKey, params, null, null);
verify(mockJobTracker).startAndTrack(eq(AsynchType.TableQuery), queryBundleRequestCaptor.capture(), eq(AsynchronousProgressWidget.WAIT_MS), jobTrackerCallbackCaptor.capture());
jobTrackerCallbackCaptor.getValue().onComplete(mockQueryResultBundle);
verify(mockView, never()).showChart(anyString(), anyString(), anyString(), anyList(), anyString(), anyString(), anyString(), anyBoolean());
verify(mockResourceLoader).isLoaded(eq(PLOTLY_REACT_JS));
verify(mockResourceLoader).requires(eq(PLOTLY_REACT_JS), webResourceLoadedCallbackCaptor.capture());
AsyncCallback callback = webResourceLoadedCallbackCaptor.getValue();
Exception ex = new Exception();
callback.onFailure(ex);
verify(mockSynAlert).handleException(ex);
verify(mockView, never()).showChart(anyString(), anyString(), anyString(), anyList(), anyString(), anyString(), anyString(), anyBoolean());
when(mockResourceLoader.isLoaded(eq(PLOTLY_REACT_JS))).thenReturn(true);
callback.onSuccess(null);
verify(mockView).showChart(anyString(), anyString(), anyString(), anyList(), anyString(), anyString(), anyString(), eq(showLegend));
}
@Test
public void testTransformWithFill() {
/**
*
* Test the following table data
| x | fill | y1 |
|---|------|----|
| 1 | a | 40 |
| 1 | b | 50 |
| 2 | a | 60 |
*
* For each y, there should be a new series for each fill value.
* So this should result in 2 series, one for 'a' and one for 'b'.
*/
String xAxisColumnName = "x";
String y1ColumnName = "y1";
String fillColumnName = "fill";
GraphType graphType = GraphType.BAR;
Map<String, List<String>> graphData = new HashMap<>();
graphData.put(xAxisColumnName, Arrays.asList("1", "1", "2"));
graphData.put(fillColumnName, Arrays.asList("a", "b", "a"));
graphData.put(y1ColumnName, Arrays.asList("40", "50", "60"));
List<PlotlyTraceWrapper> traces = PlotlyWidget.transform(xAxisColumnName, fillColumnName, graphType, graphData);
assertEquals(2, traces.size());
PlotlyTraceWrapper a = traces.get(0).getName().equals("a") ? traces.get(0) : traces.get(1);
assertEquals(2, a.getX().length);
assertEquals("40", a.getY()[0]);
assertEquals("60", a.getY()[1]);
}
@Test
public void testTransformWithXColumnFill() {
String xAxisColumnName = "x";
String y1ColumnName = "y1";
String fillColumnName = xAxisColumnName;
GraphType graphType = GraphType.BAR;
Map<String, List<String>> graphData = new HashMap<>();
graphData.put(xAxisColumnName, Arrays.asList("1", "1", "2"));
graphData.put(y1ColumnName, Arrays.asList("40", "50", "60"));
List<PlotlyTraceWrapper> traces = PlotlyWidget.transform(xAxisColumnName, fillColumnName, graphType, graphData);
assertEquals(2, traces.size());
PlotlyTraceWrapper a = traces.get(0).getName().equals("1") ? traces.get(0) : traces.get(1);
assertEquals(2, a.getX().length);
assertEquals("40", a.getY()[0]);
assertEquals("50", a.getY()[1]);
}
@Test
public void testInitializeHorizontalOrientation() {
boolean isHorizontal = true;
String xAxisTitle = "x";
String yAxisTitle = "y";
params.put(X_AXIS_TITLE, xAxisTitle);
params.put(Y_AXIS_TITLE, yAxisTitle);
params.put(TYPE, GraphType.BAR.toString());
params.put(BAR_MODE, BarMode.STACK.toString());
params.put(IS_HORIZONTAL, Boolean.toString(isHorizontal));
selectColumns.add(mockXColumn);
selectColumns.add(mockY1Column);
rowValues.add("1.1");
rowValues.add("2.2");
rows.add(mockRow);
when(mockQueryResultBundle.getQueryCount()).thenReturn(1L);
widget.configure(null, params, null, null);
verify(mockJobTracker).startAndTrack(eq(AsynchType.TableQuery), queryBundleRequestCaptor.capture(), eq(AsynchronousProgressWidget.WAIT_MS), jobTrackerCallbackCaptor.capture());
jobTrackerCallbackCaptor.getValue().onComplete(mockQueryResultBundle);
verify(mockView).showChart(anyString(), eq(yAxisTitle), eq(xAxisTitle), plotlyTraceArrayCaptor.capture(), anyString(), anyString(), anyString(), anyBoolean());
List traces = plotlyTraceArrayCaptor.getValue();
assertTrue(traces.size() > 0);
assertEquals(isHorizontal, ((PlotlyTraceWrapper)traces.get(0)).isHorizontal());
}
}
| src/test/java/org/sagebionetworks/web/unitclient/widget/entity/renderer/PlotlyWidgetTest.java | package org.sagebionetworks.web.unitclient.widget.entity.renderer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyList;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.sagebionetworks.web.client.ClientProperties.PLOTLY_JS;
import static org.sagebionetworks.web.client.widget.entity.renderer.PlotlyWidget.ALL_PARTS_MASK;
import static org.sagebionetworks.web.client.widget.entity.renderer.PlotlyWidget.LIMIT;
import static org.sagebionetworks.web.shared.WidgetConstants.BAR_MODE;
import static org.sagebionetworks.web.shared.WidgetConstants.*;
import static org.sagebionetworks.web.shared.WidgetConstants.TABLE_QUERY_KEY;
import static org.sagebionetworks.web.shared.WidgetConstants.TITLE;
import static org.sagebionetworks.web.shared.WidgetConstants.TYPE;
import static org.sagebionetworks.web.shared.WidgetConstants.X_AXIS_TITLE;
import static org.sagebionetworks.web.shared.WidgetConstants.Y_AXIS_TITLE;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.sagebionetworks.repo.model.asynch.AsynchronousJobStatus;
import org.sagebionetworks.repo.model.table.Query;
import org.sagebionetworks.repo.model.table.QueryBundleRequest;
import org.sagebionetworks.repo.model.table.QueryResult;
import org.sagebionetworks.repo.model.table.QueryResultBundle;
import org.sagebionetworks.repo.model.table.Row;
import org.sagebionetworks.repo.model.table.RowSet;
import org.sagebionetworks.repo.model.table.SelectColumn;
import org.sagebionetworks.schema.adapter.JSONObjectAdapterException;
import org.sagebionetworks.web.client.plotly.BarMode;
import org.sagebionetworks.web.client.plotly.GraphType;
import org.sagebionetworks.web.client.plotly.PlotlyTraceWrapper;
import org.sagebionetworks.web.client.resources.ResourceLoader;
import org.sagebionetworks.web.client.widget.asynch.AsynchronousJobTracker;
import org.sagebionetworks.web.client.widget.asynch.AsynchronousProgressWidget;
import org.sagebionetworks.web.client.widget.asynch.UpdatingAsynchProgressHandler;
import org.sagebionetworks.web.client.widget.entity.controller.SynapseAlert;
import org.sagebionetworks.web.client.widget.entity.renderer.PlotlyWidget;
import org.sagebionetworks.web.client.widget.entity.renderer.PlotlyWidgetView;
import org.sagebionetworks.web.client.widget.table.v2.QueryTokenProvider;
import org.sagebionetworks.web.shared.WikiPageKey;
import org.sagebionetworks.web.shared.asynch.AsynchType;
import com.google.gwt.user.client.rpc.AsyncCallback;
public class PlotlyWidgetTest {
PlotlyWidget widget;
@Mock
PlotlyWidgetView mockView;
@Mock
SynapseAlert mockSynAlert;
@Mock
AsynchronousJobTracker mockJobTracker;
@Captor
ArgumentCaptor<QueryBundleRequest> queryBundleRequestCaptor;
@Captor
ArgumentCaptor<UpdatingAsynchProgressHandler> jobTrackerCallbackCaptor;
@Mock
QueryResultBundle mockQueryResultBundle;
@Mock
QueryResult mockQueryResult;
@Mock
RowSet mockRowSet;
@Mock
Row mockRow;
@Mock
ResourceLoader mockResourceLoader;
@Mock
QueryTokenProvider mockQueryTokenProvider;
List<SelectColumn> selectColumns;
List<Row> rows;
List<String> rowValues;
@Mock
SelectColumn mockXColumn;
@Mock
SelectColumn mockY1Column;
@Mock
SelectColumn mockY2Column;
@Captor
ArgumentCaptor<List> plotlyTraceArrayCaptor;
@Mock
AsynchronousJobStatus mockAsynchronousJobStatus;
@Captor
ArgumentCaptor<String> stringCaptor;
@Captor
ArgumentCaptor<AsyncCallback> webResourceLoadedCallbackCaptor;
Map<String, String> params;
public static final String X_COLUMN_NAME = "x";
public static final String Y1_COLUMN_NAME = "y1";
public static final String Y2_COLUMN_NAME = "y2";
@Before
public void setup(){
MockitoAnnotations.initMocks(this);
widget = new PlotlyWidget(
mockView,
mockSynAlert,
mockJobTracker,
mockResourceLoader,
mockQueryTokenProvider);
params = new HashMap<>();
selectColumns = new ArrayList<>();
rows = new ArrayList<>();
rowValues = new ArrayList<>();
when(mockQueryResultBundle.getSelectColumns()).thenReturn(selectColumns);
when(mockQueryResultBundle.getQueryResult()).thenReturn(mockQueryResult);
when(mockQueryResult.getQueryResults()).thenReturn(mockRowSet);
when(mockRowSet.getRows()).thenReturn(rows);
when(mockXColumn.getName()).thenReturn(X_COLUMN_NAME);
when(mockY1Column.getName()).thenReturn(Y1_COLUMN_NAME);
when(mockY2Column.getName()).thenReturn(Y1_COLUMN_NAME);
when(mockRow.getValues()).thenReturn(rowValues);
when(mockResourceLoader.isLoaded(eq(PLOTLY_JS))).thenReturn(true);
}
@Test
public void testConstructor() {
verify(mockView).setSynAlertWidget(mockSynAlert);
verify(mockView).setPresenter(widget);
}
@Test
public void testAsWidget() {
widget.asWidget();
verify(mockView).asWidget();
}
@Test
public void testConfigure() {
String queryToken = "encoded sql which is passed to place";
when(mockQueryTokenProvider.queryToToken(any(Query.class))).thenReturn(queryToken);
WikiPageKey pageKey = null;
String xAxisLabel = "X Axis";
String yAxisLabel = "Y Axis";
GraphType type = GraphType.BAR;
BarMode mode = BarMode.STACK;
String plotTitle = "Plot Title";
String tableId = "syn12345";
boolean showLegend = false;
boolean isHorizontal = false;
String sql = "select x, y1, y2 from "+tableId+" where x>2";
params.put(TABLE_QUERY_KEY, sql);
params.put(TITLE, plotTitle);
params.put(X_AXIS_TITLE, xAxisLabel);
params.put(Y_AXIS_TITLE, yAxisLabel);
params.put(TYPE, type.toString());
params.put(BAR_MODE, mode.toString());
params.put(SHOW_LEGEND, Boolean.toString(showLegend));
params.put(IS_HORIZONTAL, Boolean.toString(isHorizontal));
selectColumns.add(mockXColumn);
selectColumns.add(mockY1Column);
selectColumns.add(mockY2Column);
rowValues.add("row1X");
rowValues.add("1.1");
rowValues.add("2.2");
rows.add(mockRow);
when(mockQueryResultBundle.getQueryCount()).thenReturn(LIMIT + 1);
widget.configure(pageKey, params, null, null);
verify(mockView).setSourceDataLink(stringCaptor.capture());
verify(mockView).setSourceDataLinkVisible(false);
verify(mockView, never()).setSourceDataLinkVisible(true);
String sourceDataLink = stringCaptor.getValue();
assertTrue(sourceDataLink.contains(tableId));
assertTrue(sourceDataLink.contains(queryToken));
//verify query params, and plot configuration based on results
verify(mockView).setLoadingVisible(true);
verify(mockJobTracker).startAndTrack(eq(AsynchType.TableQuery), queryBundleRequestCaptor.capture(), eq(AsynchronousProgressWidget.WAIT_MS), jobTrackerCallbackCaptor.capture());
//check query
QueryBundleRequest request = queryBundleRequestCaptor.getValue();
assertEquals(ALL_PARTS_MASK, request.getPartMask());
assertEquals("syn12345", request.getEntityId());
assertEquals((Long)0L, request.getQuery().getOffset());
assertEquals(sql, request.getQuery().getSql());
// complete first page load
jobTrackerCallbackCaptor.getValue().onComplete(mockQueryResultBundle);
verify(mockView, never()).showChart(eq(plotTitle), anyString(), anyString(), anyList(), anyString(), anyString(), anyString(), anyBoolean());
//test final page
rows.clear();
verify(mockJobTracker, times(2)).startAndTrack(eq(AsynchType.TableQuery), queryBundleRequestCaptor.capture(), eq(AsynchronousProgressWidget.WAIT_MS), jobTrackerCallbackCaptor.capture());
//verify offset updated
request = queryBundleRequestCaptor.getValue();
assertEquals(LIMIT, request.getQuery().getOffset());
verify(mockView, times(2)).setLoadingMessage(stringCaptor.capture());
String loadingMessage = stringCaptor.getValue();
assertTrue(loadingMessage.contains(LIMIT.toString()));
jobTrackerCallbackCaptor.getValue().onComplete(mockQueryResultBundle);
verify(mockView).showChart(eq(plotTitle), eq(xAxisLabel), eq(yAxisLabel), plotlyTraceArrayCaptor.capture(), eq(mode.toString().toLowerCase()), anyString(), anyString(), eq(showLegend));
List traces = plotlyTraceArrayCaptor.getValue();
assertTrue(traces.size() > 0);
assertEquals(type.toString().toLowerCase(), ((PlotlyTraceWrapper)traces.get(0)).getType());
assertEquals(isHorizontal, ((PlotlyTraceWrapper)traces.get(0)).isHorizontal());
verify(mockView).setSourceDataLinkVisible(true);
}
@Test
public void testTrackerOnCancel() {
GraphType type = GraphType.SCATTER;
params.put(TYPE, type.toString());
WikiPageKey pageKey = null;
widget.configure(pageKey, params, null, null);
verify(mockJobTracker).startAndTrack(eq(AsynchType.TableQuery), queryBundleRequestCaptor.capture(), eq(AsynchronousProgressWidget.WAIT_MS), jobTrackerCallbackCaptor.capture());
UpdatingAsynchProgressHandler progressHandler = jobTrackerCallbackCaptor.getValue();
//also verify attachment state is based on view
when(mockView.isAttached()).thenReturn(true);
assertTrue(progressHandler.isAttached());
when(mockView.isAttached()).thenReturn(false);
assertFalse(progressHandler.isAttached());
progressHandler.onCancel();
verify(mockView, times(2)).clearChart();
verify(mockView).setLoadingVisible(false);
}
@Test
public void testTrackerOnFailure() {
GraphType type = GraphType.SCATTER;
params.put(TYPE, type.toString());
WikiPageKey pageKey = null;
widget.configure(pageKey, params, null, null);
verify(mockJobTracker).startAndTrack(eq(AsynchType.TableQuery), queryBundleRequestCaptor.capture(), eq(AsynchronousProgressWidget.WAIT_MS), jobTrackerCallbackCaptor.capture());
UpdatingAsynchProgressHandler progressHandler = jobTrackerCallbackCaptor.getValue();
Exception error = new Exception();
progressHandler.onFailure(error);
verify(mockView, times(2)).clearChart();
verify(mockView).setLoadingVisible(false);
verify(mockSynAlert).handleException(error);
}
@Test
public void testLazyLoadPlotlyJS() throws JSONObjectAdapterException {
GraphType type = GraphType.SCATTER;
params.put(TYPE, type.toString());
boolean showLegend = true;
params.put(SHOW_LEGEND, Boolean.toString(showLegend));
WikiPageKey pageKey = null;
when(mockResourceLoader.isLoaded(eq(PLOTLY_JS))).thenReturn(false);
widget.configure(pageKey, params, null, null);
verify(mockJobTracker).startAndTrack(eq(AsynchType.TableQuery), queryBundleRequestCaptor.capture(), eq(AsynchronousProgressWidget.WAIT_MS), jobTrackerCallbackCaptor.capture());
jobTrackerCallbackCaptor.getValue().onComplete(mockQueryResultBundle);
verify(mockView, never()).showChart(anyString(), anyString(), anyString(), anyList(), anyString(), anyString(), anyString(), anyBoolean());
verify(mockResourceLoader).isLoaded(eq(PLOTLY_JS));
verify(mockResourceLoader).requires(eq(PLOTLY_JS), webResourceLoadedCallbackCaptor.capture());
AsyncCallback callback = webResourceLoadedCallbackCaptor.getValue();
Exception ex = new Exception();
callback.onFailure(ex);
verify(mockSynAlert).handleException(ex);
verify(mockView, never()).showChart(anyString(), anyString(), anyString(), anyList(), anyString(), anyString(), anyString(), anyBoolean());
when(mockResourceLoader.isLoaded(eq(PLOTLY_JS))).thenReturn(true);
callback.onSuccess(null);
verify(mockView).showChart(anyString(), anyString(), anyString(), anyList(), anyString(), anyString(), anyString(), eq(showLegend));
}
@Test
public void testTransformWithFill() {
/**
*
* Test the following table data
| x | fill | y1 |
|---|------|----|
| 1 | a | 40 |
| 1 | b | 50 |
| 2 | a | 60 |
*
* For each y, there should be a new series for each fill value.
* So this should result in 2 series, one for 'a' and one for 'b'.
*/
String xAxisColumnName = "x";
String y1ColumnName = "y1";
String fillColumnName = "fill";
GraphType graphType = GraphType.BAR;
Map<String, List<String>> graphData = new HashMap<>();
graphData.put(xAxisColumnName, Arrays.asList("1", "1", "2"));
graphData.put(fillColumnName, Arrays.asList("a", "b", "a"));
graphData.put(y1ColumnName, Arrays.asList("40", "50", "60"));
List<PlotlyTraceWrapper> traces = PlotlyWidget.transform(xAxisColumnName, fillColumnName, graphType, graphData);
assertEquals(2, traces.size());
PlotlyTraceWrapper a = traces.get(0).getName().equals("a") ? traces.get(0) : traces.get(1);
assertEquals(2, a.getX().length);
assertEquals("40", a.getY()[0]);
assertEquals("60", a.getY()[1]);
}
@Test
public void testTransformWithXColumnFill() {
String xAxisColumnName = "x";
String y1ColumnName = "y1";
String fillColumnName = xAxisColumnName;
GraphType graphType = GraphType.BAR;
Map<String, List<String>> graphData = new HashMap<>();
graphData.put(xAxisColumnName, Arrays.asList("1", "1", "2"));
graphData.put(y1ColumnName, Arrays.asList("40", "50", "60"));
List<PlotlyTraceWrapper> traces = PlotlyWidget.transform(xAxisColumnName, fillColumnName, graphType, graphData);
assertEquals(2, traces.size());
PlotlyTraceWrapper a = traces.get(0).getName().equals("1") ? traces.get(0) : traces.get(1);
assertEquals(2, a.getX().length);
assertEquals("40", a.getY()[0]);
assertEquals("50", a.getY()[1]);
}
@Test
public void testInitializeHorizontalOrientation() {
boolean isHorizontal = true;
String xAxisTitle = "x";
String yAxisTitle = "y";
params.put(X_AXIS_TITLE, xAxisTitle);
params.put(Y_AXIS_TITLE, yAxisTitle);
params.put(TYPE, GraphType.BAR.toString());
params.put(BAR_MODE, BarMode.STACK.toString());
params.put(IS_HORIZONTAL, Boolean.toString(isHorizontal));
selectColumns.add(mockXColumn);
selectColumns.add(mockY1Column);
rowValues.add("1.1");
rowValues.add("2.2");
rows.add(mockRow);
when(mockQueryResultBundle.getQueryCount()).thenReturn(1L);
widget.configure(null, params, null, null);
verify(mockJobTracker).startAndTrack(eq(AsynchType.TableQuery), queryBundleRequestCaptor.capture(), eq(AsynchronousProgressWidget.WAIT_MS), jobTrackerCallbackCaptor.capture());
jobTrackerCallbackCaptor.getValue().onComplete(mockQueryResultBundle);
verify(mockView).showChart(anyString(), eq(yAxisTitle), eq(xAxisTitle), plotlyTraceArrayCaptor.capture(), anyString(), anyString(), anyString(), anyBoolean());
List traces = plotlyTraceArrayCaptor.getValue();
assertTrue(traces.size() > 0);
assertEquals(isHorizontal, ((PlotlyTraceWrapper)traces.get(0)).isHorizontal());
}
}
| add test around lazy loading plotly react js
| src/test/java/org/sagebionetworks/web/unitclient/widget/entity/renderer/PlotlyWidgetTest.java | add test around lazy loading plotly react js | <ide><path>rc/test/java/org/sagebionetworks/web/unitclient/widget/entity/renderer/PlotlyWidgetTest.java
<ide> import static org.mockito.Mockito.times;
<ide> import static org.mockito.Mockito.verify;
<ide> import static org.mockito.Mockito.when;
<del>import static org.sagebionetworks.web.client.ClientProperties.PLOTLY_JS;
<add>import static org.sagebionetworks.web.client.ClientProperties.*;
<ide> import static org.sagebionetworks.web.client.widget.entity.renderer.PlotlyWidget.ALL_PARTS_MASK;
<ide> import static org.sagebionetworks.web.client.widget.entity.renderer.PlotlyWidget.LIMIT;
<ide> import static org.sagebionetworks.web.shared.WidgetConstants.BAR_MODE;
<ide> when(mockY2Column.getName()).thenReturn(Y1_COLUMN_NAME);
<ide> when(mockRow.getValues()).thenReturn(rowValues);
<ide> when(mockResourceLoader.isLoaded(eq(PLOTLY_JS))).thenReturn(true);
<add> when(mockResourceLoader.isLoaded(eq(PLOTLY_REACT_JS))).thenReturn(true);
<ide> }
<ide>
<ide> @Test
<ide> verify(mockView, never()).showChart(anyString(), anyString(), anyString(), anyList(), anyString(), anyString(), anyString(), anyBoolean());
<ide>
<ide> when(mockResourceLoader.isLoaded(eq(PLOTLY_JS))).thenReturn(true);
<add> callback.onSuccess(null);
<add> verify(mockView).showChart(anyString(), anyString(), anyString(), anyList(), anyString(), anyString(), anyString(), eq(showLegend));
<add> }
<add>
<add> @Test
<add> public void testLazyLoadPlotlyReactJS() throws JSONObjectAdapterException {
<add> GraphType type = GraphType.SCATTER;
<add> params.put(TYPE, type.toString());
<add> boolean showLegend = true;
<add> params.put(SHOW_LEGEND, Boolean.toString(showLegend));
<add> WikiPageKey pageKey = null;
<add> when(mockResourceLoader.isLoaded(eq(PLOTLY_REACT_JS))).thenReturn(false);
<add> widget.configure(pageKey, params, null, null);
<add>
<add> verify(mockJobTracker).startAndTrack(eq(AsynchType.TableQuery), queryBundleRequestCaptor.capture(), eq(AsynchronousProgressWidget.WAIT_MS), jobTrackerCallbackCaptor.capture());
<add> jobTrackerCallbackCaptor.getValue().onComplete(mockQueryResultBundle);
<add>
<add> verify(mockView, never()).showChart(anyString(), anyString(), anyString(), anyList(), anyString(), anyString(), anyString(), anyBoolean());
<add>
<add> verify(mockResourceLoader).isLoaded(eq(PLOTLY_REACT_JS));
<add> verify(mockResourceLoader).requires(eq(PLOTLY_REACT_JS), webResourceLoadedCallbackCaptor.capture());
<add>
<add> AsyncCallback callback = webResourceLoadedCallbackCaptor.getValue();
<add> Exception ex = new Exception();
<add> callback.onFailure(ex);
<add> verify(mockSynAlert).handleException(ex);
<add> verify(mockView, never()).showChart(anyString(), anyString(), anyString(), anyList(), anyString(), anyString(), anyString(), anyBoolean());
<add>
<add> when(mockResourceLoader.isLoaded(eq(PLOTLY_REACT_JS))).thenReturn(true);
<ide> callback.onSuccess(null);
<ide> verify(mockView).showChart(anyString(), anyString(), anyString(), anyList(), anyString(), anyString(), anyString(), eq(showLegend));
<ide> } |
|
Java | mit | 4802b6347b462b457af3f11036bf8cfae3940045 | 0 | stripe/stripe-android,stripe/stripe-android,stripe/stripe-android,stripe/stripe-android,stripe/stripe-android | package com.stripe.android;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.Size;
import android.support.annotation.VisibleForTesting;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.Executor;
import com.stripe.android.model.Card;
import com.stripe.android.model.Token;
import com.stripe.android.util.StripeTextUtils;
import com.stripe.exception.AuthenticationException;
import com.stripe.net.RequestOptions;
/**
* Class that handles {@link Token} creation from charges and {@link Card} models.
*/
public class Stripe {
@VisibleForTesting
TokenCreator tokenCreator = new TokenCreator() {
@Override
public void create(
final Card card,
final String publishableKey,
final Executor executor,
final TokenCallback callback) {
AsyncTask<Void, Void, ResponseWrapper> task =
new AsyncTask<Void, Void, ResponseWrapper>() {
@Override
protected ResponseWrapper doInBackground(Void... params) {
try {
RequestOptions requestOptions = RequestOptions.builder()
.setApiKey(publishableKey).build();
com.stripe.model.Token stripeToken = com.stripe.model.Token.create(
hashMapFromCard(card), requestOptions);
com.stripe.model.Card stripeCard = stripeToken.getCard();
Card card = androidCardFromStripeCard(stripeCard);
Token token = androidTokenFromStripeToken(card, stripeToken);
return new ResponseWrapper(token, null);
} catch (Exception e) {
return new ResponseWrapper(null, e);
}
}
@Override
protected void onPostExecute(ResponseWrapper result) {
tokenTaskPostExecution(result, callback);
}
};
executeTokenTask(executor, task);
}
};
@VisibleForTesting
TokenRequester tokenRequester = new TokenRequester() {
@Override
public void request(final String tokenId, final String publishableKey,
final Executor executor, final TokenCallback callback) {
AsyncTask<Void, Void, ResponseWrapper> task = new AsyncTask<Void, Void, ResponseWrapper>() {
protected ResponseWrapper doInBackground(Void... params) {
try {
com.stripe.model.Token stripeToken = com.stripe.model.Token.retrieve(
tokenId, publishableKey);
com.stripe.model.Card stripeCard = stripeToken.getCard();
Card card = androidCardFromStripeCard(stripeCard);
Token token = androidTokenFromStripeToken(card, stripeToken);
return new ResponseWrapper(token, null);
} catch (Exception e) {
return new ResponseWrapper(null, e);
}
}
protected void onPostExecute(ResponseWrapper result) {
tokenTaskPostExecution(result, callback);
}
};
executeTokenTask(executor, task);
}
};
private String defaultPublishableKey;
/**
* A blank constructor to set the key later.
*/
public Stripe() { }
/**
* Constructor with publishable key.
*
* @param publishableKey the client's publishable key
* @throws AuthenticationException if the key is invalid
*/
public Stripe(String publishableKey) throws AuthenticationException {
setDefaultPublishableKey(publishableKey);
}
/**
* The simplest way to create a token, using a {@link Card} and {@link TokenCallback}. This
* runs on the default {@link Executor} and with the
* currently set {@link #defaultPublishableKey}.
*
* @param card the {@link Card} used to create this payment token
* @param callback a {@link TokenCallback} to receive either the token or an error
*/
public void createToken(@NonNull final Card card, @NonNull final TokenCallback callback) {
createToken(card, defaultPublishableKey, callback);
}
/**
* Call to create a {@link Token} with a specific public key.
*
* @param card the {@link Card} used for this transaction
* @param publishableKey the public key used for this transaction
* @param callback a {@link TokenCallback} to receive the result of this operation
*/
public void createToken(
@NonNull final Card card,
@NonNull final String publishableKey,
@NonNull final TokenCallback callback) {
createToken(card, publishableKey, null, callback);
}
/**
* Call to create a {@link Token} on a specific {@link Executor}.
* @param card the {@link Card} to use for this token creation
* @param executor An {@link Executor} on which to run this operation. If you don't wish to
* specify an executor, use one of the other createToken methods.
* @param callback a {@link TokenCallback} to receive the result of this operation
*/
public void createToken(
@NonNull final Card card,
@NonNull final Executor executor,
@NonNull final TokenCallback callback) {
createToken(card, defaultPublishableKey, executor, callback);
}
/**
* Call to create a {@link Token} with the publishable key and {@link Executor} specified.
*
* @param card the {@link Card} used for this payment token
* @param publishableKey the publishable key to use
* @param executor an {@link Executor} to run this operation on. If null, this is run on a
* default non-ui executor
* @param callback a {@link TokenCallback} to receive the result or error message
*/
public void createToken(
@NonNull final Card card,
@NonNull @Size(min = 1) final String publishableKey,
@Nullable final Executor executor,
@NonNull final TokenCallback callback) {
try {
if (card == null) {
throw new RuntimeException(
"Required Parameter: 'card' is required to create a token");
}
if (callback == null) {
throw new RuntimeException(
"Required Parameter: 'callback' is required to use the created " +
"token and handle errors");
}
validateKey(publishableKey);
tokenCreator.create(card, publishableKey, executor, callback);
}
catch (AuthenticationException e) {
callback.onError(e);
}
}
/**
* Retrieve a token for inspection, using the token's id.
*
* @param tokenId the id of the {@link Token} being requested
* @param callback a {@link TokenCallback} to receive the result
*
* @deprecated the requestToken endpoint is not guaranteed to work with a public key, as that
* ability has been turned off for accounts using API versions later than 2014-10-07. Secret
* keys should not be included in mobile applications.
*/
@Deprecated
public void requestToken(
@NonNull final String tokenId,
@NonNull final TokenCallback callback) {
requestToken(tokenId, defaultPublishableKey, callback);
}
/**
* Retrieve a token for inspection, using the token's id and a publishable key.
*
* @param tokenId the id of the {@link Token} being requested
* @param publishableKey the publishable key used to create this token
* @param callback a {@link TokenCallback} to receive the result
*
* @deprecated the requestToken endpoint is not guaranteed to work with a public key, as that
* ability has been turned off for accounts using API versions later than 2014-10-07. Secret
* keys should not be included in mobile applications.
*/
@Deprecated
public void requestToken(
@NonNull final String tokenId,
@NonNull @Size(min = 1) final String publishableKey,
@NonNull final TokenCallback callback) {
requestToken(tokenId, publishableKey, null, callback);
}
/**
* Retrieve a token for inspection on a specific {@link Executor}, using the token's id.
*
* @param tokenId the id of the {@link Token} being requested
* @param executor an {@link Executor} on which to run this request
* @param callback a {@link TokenCallback} to receive the result
*
* @deprecated the requestToken endpoint is not guaranteed to work with a public key, as that
* ability has been turned off for accounts using API versions later than 2014-10-07. Secret
* keys should not be included in mobile applications.
*/
@Deprecated
public void requestToken(
@NonNull final String tokenId,
@NonNull final Executor executor,
@NonNull final TokenCallback callback) {
requestToken(tokenId, defaultPublishableKey, executor, callback);
}
/**
* Retrieve a token for inspection on a specific {@link Executor}, using the publishable key
* that was used to create the token.
*
* @param tokenId the id of the token being requested
* @param publishableKey the key used to create the token
* @param executor an {@link Executor} on which to run this operation, or {@code null} to run
* on a default background executor
* @param callback a {@link TokenCallback} to receive the result
*
* @deprecated the requestToken endpoint is not guaranteed to work with a public key, as that
* ability has been turned off for accounts using API versions later than 2014-10-07. Secret
* keys should not be included in mobile applications.
*/
@Deprecated
public void requestToken(
@NonNull final String tokenId,
@NonNull @Size(min = 1) final String publishableKey,
@Nullable final Executor executor,
@NonNull final TokenCallback callback) {
try {
if (tokenId == null) {
throw new RuntimeException("Required Parameter: 'tokenId' " +
"is required to request a token");
}
if (callback == null) {
throw new RuntimeException("Required Parameter: 'callback' " +
"is required to use the requested token and handle errors");
}
validateKey(publishableKey);
tokenRequester.request(tokenId, publishableKey, executor, callback);
} catch (AuthenticationException e) {
callback.onError(e);
}
}
/**
* Set the default publishable key to use with this {@link Stripe} instance.
*
* @param publishableKey the key to be set
* @throws AuthenticationException if the key is null, empty, or a secret key
*/
public void setDefaultPublishableKey(@NonNull @Size(min = 1) String publishableKey)
throws AuthenticationException {
validateKey(publishableKey);
this.defaultPublishableKey = publishableKey;
}
/**
* Converts a stripe-java card model into a {@link Card} model.
*
* @param stripeCard the server-returned {@link com.stripe.model.Card}.
* @return an equivalent {@link Card}.
*/
@VisibleForTesting
Card androidCardFromStripeCard(com.stripe.model.Card stripeCard) {
return new Card(
null,
stripeCard.getExpMonth(),
stripeCard.getExpYear(),
null,
stripeCard.getName(),
stripeCard.getAddressLine1(),
stripeCard.getAddressLine2(),
stripeCard.getAddressCity(),
stripeCard.getAddressState(),
stripeCard.getAddressZip(),
stripeCard.getAddressCountry(),
stripeCard.getBrand(),
stripeCard.getLast4(),
stripeCard.getFingerprint(),
stripeCard.getFunding(),
stripeCard.getCountry(),
stripeCard.getCurrency());
}
private void validateKey(@NonNull @Size(min = 1) String publishableKey)
throws AuthenticationException {
if (publishableKey == null || publishableKey.length() == 0) {
throw new AuthenticationException("Invalid Publishable Key: " +
"You must use a valid publishable key to create a token. " +
"For more info, see https://stripe.com/docs/stripe.js.", null, 0);
}
if (publishableKey.startsWith("sk_")) {
throw new AuthenticationException("Invalid Publishable Key: " +
"You are using a secret key to create a token, " +
"instead of the publishable one. For more info, " +
"see https://stripe.com/docs/stripe.js", null, 0);
}
}
private Token androidTokenFromStripeToken(
Card androidCard,
com.stripe.model.Token stripeToken) {
return new Token(
stripeToken.getId(),
stripeToken.getLivemode(),
new Date(stripeToken.getCreated() * 1000),
stripeToken.getUsed(),
androidCard);
}
private void tokenTaskPostExecution(ResponseWrapper result, TokenCallback callback) {
if (result.token != null) {
callback.onSuccess(result.token);
}
else if (result.error != null) {
callback.onError(result.error);
}
else {
callback.onError(new RuntimeException(
"Somehow got neither a token response or an error response"));
}
}
private void executeTokenTask(Executor executor, AsyncTask<Void, Void, ResponseWrapper> task) {
if (executor != null && Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(executor);
} else {
task.execute();
}
}
private Map<String, Object> hashMapFromCard(Card card) {
Map<String, Object> tokenParams = new HashMap<>();
Map<String, Object> cardParams = new HashMap<>();
cardParams.put("number", StripeTextUtils.nullIfBlank(card.getNumber()));
cardParams.put("cvc", StripeTextUtils.nullIfBlank(card.getCVC()));
cardParams.put("exp_month", card.getExpMonth());
cardParams.put("exp_year", card.getExpYear());
cardParams.put("name", StripeTextUtils.nullIfBlank(card.getName()));
cardParams.put("currency", StripeTextUtils.nullIfBlank(card.getCurrency()));
cardParams.put("address_line1", StripeTextUtils.nullIfBlank(card.getAddressLine1()));
cardParams.put("address_line2", StripeTextUtils.nullIfBlank(card.getAddressLine2()));
cardParams.put("address_city", StripeTextUtils.nullIfBlank(card.getAddressCity()));
cardParams.put("address_zip", StripeTextUtils.nullIfBlank(card.getAddressZip()));
cardParams.put("address_state", StripeTextUtils.nullIfBlank(card.getAddressState()));
cardParams.put("address_country", StripeTextUtils.nullIfBlank(card.getAddressCountry()));
// Remove all null values; they cause validation errors
for (String key : new HashSet<>(cardParams.keySet())) {
if (cardParams.get(key) == null) {
cardParams.remove(key);
}
}
tokenParams.put("card", cardParams);
return tokenParams;
}
private class ResponseWrapper {
public final Token token;
public final Exception error;
private ResponseWrapper(Token token, Exception error) {
this.error = error;
this.token = token;
}
}
@VisibleForTesting
interface TokenCreator {
void create(Card card, String publishableKey, Executor executor, TokenCallback callback);
}
@VisibleForTesting
interface TokenRequester {
void request(String tokenId, String publishableKey, Executor executor, TokenCallback callback);
}
}
| stripe/src/main/java/com/stripe/android/Stripe.java | package com.stripe.android;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.Size;
import android.support.annotation.VisibleForTesting;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.Executor;
import com.stripe.android.model.Card;
import com.stripe.android.model.Token;
import com.stripe.android.util.StripeTextUtils;
import com.stripe.exception.AuthenticationException;
import com.stripe.net.RequestOptions;
/**
* Class that handles {@link Token} creation from charges and {@link Card} models.
*/
public class Stripe {
@VisibleForTesting
TokenCreator tokenCreator = new TokenCreator() {
@Override
public void create(
final Card card,
final String publishableKey,
final Executor executor,
final TokenCallback callback) {
AsyncTask<Void, Void, ResponseWrapper> task =
new AsyncTask<Void, Void, ResponseWrapper>() {
@Override
protected ResponseWrapper doInBackground(Void... params) {
try {
RequestOptions requestOptions = RequestOptions.builder()
.setApiKey(publishableKey).build();
com.stripe.model.Token stripeToken = com.stripe.model.Token.create(
hashMapFromCard(card), requestOptions);
com.stripe.model.Card stripeCard = stripeToken.getCard();
Card card = androidCardFromStripeCard(stripeCard);
Token token = androidTokenFromStripeToken(card, stripeToken);
return new ResponseWrapper(token, null);
} catch (Exception e) {
return new ResponseWrapper(null, e);
}
}
@Override
protected void onPostExecute(ResponseWrapper result) {
tokenTaskPostExecution(result, callback);
}
};
executeTokenTask(executor, task);
}
};
@VisibleForTesting
TokenRequester tokenRequester = new TokenRequester() {
@Override
public void request(final String tokenId, final String publishableKey,
final Executor executor, final TokenCallback callback) {
AsyncTask<Void, Void, ResponseWrapper> task = new AsyncTask<Void, Void, ResponseWrapper>() {
protected ResponseWrapper doInBackground(Void... params) {
try {
com.stripe.model.Token stripeToken = com.stripe.model.Token.retrieve(
tokenId, publishableKey);
com.stripe.model.Card stripeCard = stripeToken.getCard();
Card card = androidCardFromStripeCard(stripeCard);
Token token = androidTokenFromStripeToken(card, stripeToken);
return new ResponseWrapper(token, null);
} catch (Exception e) {
return new ResponseWrapper(null, e);
}
}
protected void onPostExecute(ResponseWrapper result) {
tokenTaskPostExecution(result, callback);
}
};
executeTokenTask(executor, task);
}
};
private String defaultPublishableKey;
/**
* A blank constructor to set the key later.
*/
public Stripe() { }
/**
* Constructor with publishable key.
*
* @param publishableKey the client's publishable key
* @throws AuthenticationException if the key is invalid
*/
public Stripe(String publishableKey) throws AuthenticationException {
setDefaultPublishableKey(publishableKey);
}
/**
* The simplest way to create a token, using a {@link Card} and {@link TokenCallback}. This
* runs on the default {@link Executor} and with the
* currently set {@link #defaultPublishableKey}.
*
* @param card the {@link Card} used to create this payment token
* @param callback a {@link TokenCallback} to receive either the token or an error
*/
public void createToken(@NonNull final Card card, @NonNull final TokenCallback callback) {
createToken(card, defaultPublishableKey, callback);
}
/**
* Call to create a {@link Token} with a specific public key.
*
* @param card the {@link Card} used for this transaction
* @param publishableKey the public key used for this transaction
* @param callback a {@link TokenCallback} to receive the result of this operation
*/
public void createToken(
@NonNull final Card card,
@NonNull final String publishableKey,
@NonNull final TokenCallback callback) {
createToken(card, publishableKey, null, callback);
}
/**
* Call to create a {@link Token} on a specific {@link Executor}.
* @param card the {@link Card} to use for this token creation
* @param executor An {@link Executor} on which to run this operation. If you don't wish to
* specify an executor, use one of the other createToken methods.
* @param callback a {@link TokenCallback} to receive the result of this operation
*/
public void createToken(
@NonNull final Card card,
@NonNull final Executor executor,
@NonNull final TokenCallback callback) {
createToken(card, defaultPublishableKey, executor, callback);
}
/**
* Call to create a {@link Token} with the publishable key and {@link Executor} specified.
*
* @param card the {@link Card} used for this payment token
* @param publishableKey the publishable key to use
* @param executor an {@link Executor} to run this operation on. If null, this is run on a
* default non-ui executor
* @param callback a {@link TokenCallback} to receive the result or error message
*/
public void createToken(
@NonNull final Card card,
@NonNull @Size(min = 1) final String publishableKey,
@Nullable final Executor executor,
@NonNull final TokenCallback callback) {
try {
if (card == null) {
throw new RuntimeException(
"Required Parameter: 'card' is required to create a token");
}
if (callback == null) {
throw new RuntimeException(
"Required Parameter: 'callback' is required to use the created " +
"token and handle errors");
}
validateKey(publishableKey);
tokenCreator.create(card, publishableKey, executor, callback);
}
catch (AuthenticationException e) {
callback.onError(e);
}
}
/**
* Retrieve a token for inspection, using the token's id.
*
* @param tokenId the id of the {@link Token} being requested
* @param callback a {@link TokenCallback} to receive the result
*
* @deprecated the requestToken endpoint is not guaranteed to work with a public key, as that
* ability has been turned off for accounts using API versions later than 2014-10-07. Secret
* keys should not be included in mobile applications.
*/
@Deprecated
public void requestToken(
@NonNull final String tokenId,
@NonNull final TokenCallback callback) {
requestToken(tokenId, defaultPublishableKey, callback);
}
/**
* Retrieve a token for inspection, using the token's id and a publishable key.
*
* @param tokenId the id of the {@link Token} being requested
* @param publishableKey the publishable key used to create this token
* @param callback a {@link TokenCallback} to receive the result
*
* @deprecated the requestToken endpoint is not guaranteed to work with a public key, as that
* ability has been turned off for accounts using API versions later than 2014-10-07. Secret
* keys should not be included in mobile applications.
*/
public void requestToken(
@NonNull final String tokenId,
@NonNull @Size(min = 1) final String publishableKey,
@NonNull final TokenCallback callback) {
requestToken(tokenId, publishableKey, null, callback);
}
/**
* Retrieve a token for inspection on a specific {@link Executor}, using the token's id.
*
* @param tokenId the id of the {@link Token} being requested
* @param executor an {@link Executor} on which to run this request
* @param callback a {@link TokenCallback} to receive the result
*
* @deprecated the requestToken endpoint is not guaranteed to work with a public key, as that
* ability has been turned off for accounts using API versions later than 2014-10-07. Secret
* keys should not be included in mobile applications.
*/
public void requestToken(
@NonNull final String tokenId,
@NonNull final Executor executor,
@NonNull final TokenCallback callback) {
requestToken(tokenId, defaultPublishableKey, executor, callback);
}
/**
* Retrieve a token for inspection on a specific {@link Executor}, using the publishable key
* that was used to create the token.
*
* @param tokenId the id of the token being requested
* @param publishableKey the key used to create the token
* @param executor an {@link Executor} on which to run this operation, or {@code null} to run
* on a default background executor
* @param callback a {@link TokenCallback} to receive the result
*
* @deprecated the requestToken endpoint is not guaranteed to work with a public key, as that
* ability has been turned off for accounts using API versions later than 2014-10-07. Secret
* keys should not be included in mobile applications.
*/
public void requestToken(
@NonNull final String tokenId,
@NonNull @Size(min = 1) final String publishableKey,
@Nullable final Executor executor,
@NonNull final TokenCallback callback) {
try {
if (tokenId == null) {
throw new RuntimeException("Required Parameter: 'tokenId' " +
"is required to request a token");
}
if (callback == null) {
throw new RuntimeException("Required Parameter: 'callback' " +
"is required to use the requested token and handle errors");
}
validateKey(publishableKey);
tokenRequester.request(tokenId, publishableKey, executor, callback);
} catch (AuthenticationException e) {
callback.onError(e);
}
}
/**
* Set the default publishable key to use with this {@link Stripe} instance.
*
* @param publishableKey the key to be set
* @throws AuthenticationException if the key is null, empty, or a secret key
*/
public void setDefaultPublishableKey(@NonNull @Size(min = 1) String publishableKey)
throws AuthenticationException {
validateKey(publishableKey);
this.defaultPublishableKey = publishableKey;
}
/**
* Converts a stripe-java card model into a {@link Card} model.
*
* @param stripeCard the server-returned {@link com.stripe.model.Card}.
* @return an equivalent {@link Card}.
*/
@VisibleForTesting
Card androidCardFromStripeCard(com.stripe.model.Card stripeCard) {
return new Card(
null,
stripeCard.getExpMonth(),
stripeCard.getExpYear(),
null,
stripeCard.getName(),
stripeCard.getAddressLine1(),
stripeCard.getAddressLine2(),
stripeCard.getAddressCity(),
stripeCard.getAddressState(),
stripeCard.getAddressZip(),
stripeCard.getAddressCountry(),
stripeCard.getBrand(),
stripeCard.getLast4(),
stripeCard.getFingerprint(),
stripeCard.getFunding(),
stripeCard.getCountry(),
stripeCard.getCurrency());
}
private void validateKey(@NonNull @Size(min = 1) String publishableKey)
throws AuthenticationException {
if (publishableKey == null || publishableKey.length() == 0) {
throw new AuthenticationException("Invalid Publishable Key: " +
"You must use a valid publishable key to create a token. " +
"For more info, see https://stripe.com/docs/stripe.js.", null, 0);
}
if (publishableKey.startsWith("sk_")) {
throw new AuthenticationException("Invalid Publishable Key: " +
"You are using a secret key to create a token, " +
"instead of the publishable one. For more info, " +
"see https://stripe.com/docs/stripe.js", null, 0);
}
}
private Token androidTokenFromStripeToken(
Card androidCard,
com.stripe.model.Token stripeToken) {
return new Token(
stripeToken.getId(),
stripeToken.getLivemode(),
new Date(stripeToken.getCreated() * 1000),
stripeToken.getUsed(),
androidCard);
}
private void tokenTaskPostExecution(ResponseWrapper result, TokenCallback callback) {
if (result.token != null) {
callback.onSuccess(result.token);
}
else if (result.error != null) {
callback.onError(result.error);
}
else {
callback.onError(new RuntimeException(
"Somehow got neither a token response or an error response"));
}
}
private void executeTokenTask(Executor executor, AsyncTask<Void, Void, ResponseWrapper> task) {
if (executor != null && Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(executor);
} else {
task.execute();
}
}
private Map<String, Object> hashMapFromCard(Card card) {
Map<String, Object> tokenParams = new HashMap<>();
Map<String, Object> cardParams = new HashMap<>();
cardParams.put("number", StripeTextUtils.nullIfBlank(card.getNumber()));
cardParams.put("cvc", StripeTextUtils.nullIfBlank(card.getCVC()));
cardParams.put("exp_month", card.getExpMonth());
cardParams.put("exp_year", card.getExpYear());
cardParams.put("name", StripeTextUtils.nullIfBlank(card.getName()));
cardParams.put("currency", StripeTextUtils.nullIfBlank(card.getCurrency()));
cardParams.put("address_line1", StripeTextUtils.nullIfBlank(card.getAddressLine1()));
cardParams.put("address_line2", StripeTextUtils.nullIfBlank(card.getAddressLine2()));
cardParams.put("address_city", StripeTextUtils.nullIfBlank(card.getAddressCity()));
cardParams.put("address_zip", StripeTextUtils.nullIfBlank(card.getAddressZip()));
cardParams.put("address_state", StripeTextUtils.nullIfBlank(card.getAddressState()));
cardParams.put("address_country", StripeTextUtils.nullIfBlank(card.getAddressCountry()));
// Remove all null values; they cause validation errors
for (String key : new HashSet<>(cardParams.keySet())) {
if (cardParams.get(key) == null) {
cardParams.remove(key);
}
}
tokenParams.put("card", cardParams);
return tokenParams;
}
private class ResponseWrapper {
public final Token token;
public final Exception error;
private ResponseWrapper(Token token, Exception error) {
this.error = error;
this.token = token;
}
}
@VisibleForTesting
interface TokenCreator {
void create(Card card, String publishableKey, Executor executor, TokenCallback callback);
}
@VisibleForTesting
interface TokenRequester {
void request(String tokenId, String publishableKey, Executor executor, TokenCallback callback);
}
}
| flagging the other variants of requestToken
| stripe/src/main/java/com/stripe/android/Stripe.java | flagging the other variants of requestToken | <ide><path>tripe/src/main/java/com/stripe/android/Stripe.java
<ide> * ability has been turned off for accounts using API versions later than 2014-10-07. Secret
<ide> * keys should not be included in mobile applications.
<ide> */
<add> @Deprecated
<ide> public void requestToken(
<ide> @NonNull final String tokenId,
<ide> @NonNull @Size(min = 1) final String publishableKey,
<ide> * ability has been turned off for accounts using API versions later than 2014-10-07. Secret
<ide> * keys should not be included in mobile applications.
<ide> */
<add> @Deprecated
<ide> public void requestToken(
<ide> @NonNull final String tokenId,
<ide> @NonNull final Executor executor,
<ide> * ability has been turned off for accounts using API versions later than 2014-10-07. Secret
<ide> * keys should not be included in mobile applications.
<ide> */
<add> @Deprecated
<ide> public void requestToken(
<ide> @NonNull final String tokenId,
<ide> @NonNull @Size(min = 1) final String publishableKey, |
|
JavaScript | mit | 50ecafe4a504c9056b1ef72dc8c28fb260b5e031 | 0 | pixelpicosean/phaser,TukekeSoft/phaser,mahill/phaser,englercj/phaser,GGAlanSmithee/phaser,TukekeSoft/phaser,clark-stevenson/phaser,mahill/phaser,BeanSeed/phaser,photonstorm/phaser,rblopes/phaser,clark-stevenson/phaser,GGAlanSmithee/phaser,photonstorm/phaser,spayton/phaser,TukekeSoft/phaser,clark-stevenson/phaser,BeanSeed/phaser,GGAlanSmithee/phaser,spayton/phaser | var Camera = require('../camera/Camera');
var Class = require('../utils/Class');
var GetFastValue = require('../utils/object/GetFastValue');
var KeyControl = require('../camera/KeyControl');
var RectangleContains = require('../geom/rectangle/Contains');
var SmoothedKeyControl = require('../camera/SmoothedKeyControl');
var CameraManager = new Class({
initialize:
function CameraManager (scene)
{
// The Scene that owns this plugin
this.scene = scene;
this.cameras = [];
this.cameraPool = [];
if (scene.sys.settings.cameras)
{
// We have cameras to create
this.fromJSON(scene.sys.settings.cameras);
}
else
{
// Make one
this.add();
}
// Set the default camera
this.main = this.cameras[0];
},
/*
{
cameras: [
{
name: string
x: int
y: int
width: int
height: int
zoom: float
rotation: float
roundPixels: bool
scrollX: float
scrollY: float
backgroundColor: string
bounds: {
x: int
y: int
width: int
height: int
}
}
]
}
*/
fromJSON: function (config)
{
if (!Array.isArray(config))
{
config = [ config ];
}
var gameWidth = this.scene.sys.game.config.width;
var gameHeight = this.scene.sys.game.config.height;
for (var i = 0; i < config.length; i++)
{
var cameraConfig = config[i];
var x = GetFastValue(cameraConfig, 'x', 0);
var y = GetFastValue(cameraConfig, 'y', 0);
var width = GetFastValue(cameraConfig, 'width', gameWidth);
var height = GetFastValue(cameraConfig, 'height', gameHeight);
var camera = this.add(x, y, width, height);
// Direct properties
camera.name = GetFastValue(cameraConfig, 'name', '');
camera.zoom = GetFastValue(cameraConfig, 'zoom', 1);
camera.rotation = GetFastValue(cameraConfig, 'rotation', 0);
camera.scrollX = GetFastValue(cameraConfig, 'scrollX', 0);
camera.scrollY = GetFastValue(cameraConfig, 'scrollY', 0);
camera.roundPixels = GetFastValue(cameraConfig, 'roundPixels', false);
// Background Color
var backgroundColor = GetFastValue(cameraConfig, 'backgroundColor', false);
if (backgroundColor)
{
camera.setBackgroundColor(backgroundColor);
}
// Bounds
var boundsConfig = GetFastValue(cameraConfig, 'bounds', null);
if (boundsConfig)
{
var bx = GetFastValue(boundsConfig, 'x', 0);
var by = GetFastValue(boundsConfig, 'y', 0);
var bwidth = GetFastValue(boundsConfig, 'width', gameWidth);
var bheight = GetFastValue(boundsConfig, 'height', gameHeight);
camera.setBounds(bx, by, bwidth, bheight);
}
}
return this;
},
add: function (x, y, width, height, makeMain)
{
if (x === undefined) { x = 0; }
if (y === undefined) { y = 0; }
if (width === undefined) { width = this.scene.sys.game.config.width; }
if (height === undefined) { height = this.scene.sys.game.config.height; }
if (makeMain === undefined) { makeMain = false; }
var camera = null;
if (this.cameraPool.length > 0)
{
camera = this.cameraPool.pop();
camera.setViewport(x, y, width, height);
}
else
{
camera = new Camera(x, y, width, height);
}
camera.setScene(this.scene);
this.cameras.push(camera);
if (makeMain)
{
this.main = camera;
}
return camera;
},
addKeyControl: function (config)
{
return new KeyControl(config);
},
addSmoothedKeyControl: function (config)
{
return new SmoothedKeyControl(config);
},
addReference: function (camera)
{
var index = this.cameras.indexOf(camera);
var poolIndex = this.cameraPool.indexOf(camera);
if (index < 0 && poolIndex >= 0)
{
this.cameras.push(camera);
this.cameraPool.slice(poolIndex, 1);
return camera;
}
return null;
},
remove: function (camera)
{
var cameraIndex = this.cameras.indexOf(camera);
if (cameraIndex >= 0 && this.cameras.length > 1)
{
this.cameraPool.push(this.cameras[cameraIndex]);
this.cameras.splice(cameraIndex, 1);
if (this.main === camera)
{
this.main = this.cameras[0];
}
}
},
resetAll: function ()
{
while (this.cameras.length > 0)
{
this.cameraPool.push(this.cameras.pop());
}
this.main = this.add();
return this.main;
},
update: function (timestep, delta)
{
for (var i = 0, l = this.cameras.length; i < l; ++i)
{
this.cameras[i].update(timestep, delta);
}
},
getCameraBelowPointer: function (pointer)
{
var cameras = this.cameras;
// Start from the most recently added camera (the 'top' camera)
for (var i = cameras.length - 1; i >= 0; i--)
{
var camera = cameras[i];
if (camera.inputEnabled && RectangleContains(camera, pointer.x, pointer.y))
{
return camera;
}
}
},
render: function (renderer, children, interpolation)
{
var cameras = this.cameras;
for (var i = 0, l = cameras.length; i < l; ++i)
{
var camera = cameras[i];
camera.preRender();
renderer.render(this.scene, children, interpolation, camera);
}
},
destroy: function ()
{
this.main = undefined;
for (var i = 0; i < this.cameras.length; i++)
{
this.cameras[i].destroy();
}
for (i = 0; i < this.cameraPool.length; i++)
{
this.cameraPool[i].destroy();
}
this.cameras = [];
this.cameraPool = [];
this.scene = undefined;
}
});
module.exports = CameraManager;
| v3/src/plugins/CameraManager.js | var Camera = require('../camera/Camera');
var Class = require('../utils/Class');
var GetFastValue = require('../utils/object/GetFastValue');
var KeyControl = require('../camera/KeyControl');
var RectangleContains = require('../geom/rectangle/Contains');
var SmoothedKeyControl = require('../camera/SmoothedKeyControl');
var CameraManager = new Class({
initialize:
function CameraManager (scene)
{
// The Scene that owns this plugin
this.scene = scene;
this.cameras = [];
this.cameraPool = [];
if (scene.sys.settings.cameras)
{
// We have cameras to create
this.fromJSON(scene.sys.settings.cameras);
}
else
{
// Make one
this.add();
}
// Set the default camera
this.main = this.cameras[0];
},
/*
{
cameras: [
{
name: string
x: int
y: int
width: int
height: int
zoom: float
rotation: float
roundPixels: bool
scrollX: float
scrollY: float
backgroundColor: string
bounds: {
x: int
y: int
width: int
height: int
}
}
]
}
*/
fromJSON: function (config)
{
if (!Array.isArray(config))
{
config = [ config ];
}
var gameWidth = this.scene.sys.game.config.width;
var gameHeight = this.scene.sys.game.config.height;
for (var i = 0; i < config.length; i++)
{
var cameraConfig = config[i];
var x = GetFastValue(cameraConfig, 'x', 0);
var y = GetFastValue(cameraConfig, 'y', 0);
var width = GetFastValue(cameraConfig, 'width', gameWidth);
var height = GetFastValue(cameraConfig, 'height', gameHeight);
var camera = this.add(x, y, width, height);
// Direct properties
camera.name = GetFastValue(cameraConfig, 'name', '');
camera.zoom = GetFastValue(cameraConfig, 'zoom', 1);
camera.rotation = GetFastValue(cameraConfig, 'rotation', 0);
camera.scrollX = GetFastValue(cameraConfig, 'scrollX', 0);
camera.scrollY = GetFastValue(cameraConfig, 'scrollY', 0);
camera.roundPixels = GetFastValue(cameraConfig, 'roundPixels', false);
// Background Color
var backgroundColor = GetFastValue(cameraConfig, 'backgroundColor', false);
if (backgroundColor)
{
camera.setBackgroundColor(backgroundColor);
}
// Bounds
var boundsConfig = GetFastValue(cameraConfig, 'bounds', null);
if (boundsConfig)
{
var bx = GetFastValue(boundsConfig, 'x', 0);
var by = GetFastValue(boundsConfig, 'y', 0);
var bwidth = GetFastValue(boundsConfig, 'width', gameWidth);
var bheight = GetFastValue(boundsConfig, 'height', gameHeight);
camera.setBounds(bx, by, bwidth, bheight);
}
}
return this;
},
add: function (x, y, width, height)
{
if (x === undefined) { x = 0; }
if (y === undefined) { y = 0; }
if (width === undefined) { width = this.scene.sys.game.config.width; }
if (height === undefined) { height = this.scene.sys.game.config.height; }
var camera = null;
if (this.cameraPool.length > 0)
{
camera = this.cameraPool.pop();
camera.setViewport(x, y, width, height);
}
else
{
camera = new Camera(x, y, width, height);
}
camera.setScene(this.scene);
this.cameras.push(camera);
return camera;
},
addKeyControl: function (config)
{
return new KeyControl(config);
},
addSmoothedKeyControl: function (config)
{
return new SmoothedKeyControl(config);
},
addReference: function (camera)
{
var index = this.cameras.indexOf(camera);
var poolIndex = this.cameraPool.indexOf(camera);
if (index < 0 && poolIndex >= 0)
{
this.cameras.push(camera);
this.cameraPool.slice(poolIndex, 1);
return camera;
}
return null;
},
remove: function (camera)
{
var cameraIndex = this.cameras.indexOf(camera);
if (cameraIndex >= 0)
{
this.cameraPool.push(this.cameras[cameraIndex]);
this.cameras.splice(cameraIndex, 1);
}
},
resetAll: function ()
{
while (this.cameras.length > 0)
{
this.cameraPool.push(this.cameras.pop());
}
this.main = this.add();
},
update: function (timestep, delta)
{
for (var i = 0, l = this.cameras.length; i < l; ++i)
{
this.cameras[i].update(timestep, delta);
}
},
getCameraBelowPointer: function (pointer)
{
var cameras = this.cameras;
// Start from the most recently added camera (the 'top' camera)
for (var i = cameras.length - 1; i >= 0; i--)
{
var camera = cameras[i];
if (camera.inputEnabled && RectangleContains(camera, pointer.x, pointer.y))
{
return camera;
}
}
},
render: function (renderer, children, interpolation)
{
var cameras = this.cameras;
for (var i = 0, l = cameras.length; i < l; ++i)
{
var camera = cameras[i];
camera.preRender();
renderer.render(this.scene, children, interpolation, camera);
}
},
destroy: function ()
{
this.main = undefined;
for (var i = 0; i < this.cameras.length; i++)
{
this.cameras[i].destroy();
}
for (i = 0; i < this.cameraPool.length; i++)
{
this.cameraPool[i].destroy();
}
this.cameras = [];
this.cameraPool = [];
this.scene = undefined;
}
});
module.exports = CameraManager;
| Cannot delete all cameras from a Scene. Added 'makeMain' argument to add camera.
| v3/src/plugins/CameraManager.js | Cannot delete all cameras from a Scene. Added 'makeMain' argument to add camera. | <ide><path>3/src/plugins/CameraManager.js
<ide> return this;
<ide> },
<ide>
<del> add: function (x, y, width, height)
<add> add: function (x, y, width, height, makeMain)
<ide> {
<ide> if (x === undefined) { x = 0; }
<ide> if (y === undefined) { y = 0; }
<ide> if (width === undefined) { width = this.scene.sys.game.config.width; }
<ide> if (height === undefined) { height = this.scene.sys.game.config.height; }
<add> if (makeMain === undefined) { makeMain = false; }
<ide>
<ide> var camera = null;
<ide>
<ide> camera.setScene(this.scene);
<ide>
<ide> this.cameras.push(camera);
<add>
<add> if (makeMain)
<add> {
<add> this.main = camera;
<add> }
<ide>
<ide> return camera;
<ide> },
<ide> {
<ide> var cameraIndex = this.cameras.indexOf(camera);
<ide>
<del> if (cameraIndex >= 0)
<add> if (cameraIndex >= 0 && this.cameras.length > 1)
<ide> {
<ide> this.cameraPool.push(this.cameras[cameraIndex]);
<ide> this.cameras.splice(cameraIndex, 1);
<add>
<add> if (this.main === camera)
<add> {
<add> this.main = this.cameras[0];
<add> }
<ide> }
<ide> },
<ide>
<ide> }
<ide>
<ide> this.main = this.add();
<add>
<add> return this.main;
<ide> },
<ide>
<ide> update: function (timestep, delta) |
|
Java | apache-2.0 | c39bb8fccb863fc6b87023497c53d47d94226e60 | 0 | googleinterns/step18-2020,googleinterns/step18-2020,googleinterns/step18-2020,googleinterns/step18-2020,googleinterns/step18-2020 | package com.google.launchpod.data;
import com.google.appengine.api.datastore.Entity;
import com.google.launchpod.servlets.FormHandlerServlet;
public final class UserFeed{
private final String podcastTitle;
private final String mp3Link;
private UserFeed(String podcastTitle, String mp3Link) {
this.podcastTitle = podcastTitle;
this.mp3Link = mp3Link;
}
/** Create UserFeed Object from Entity
* @param entity : entity that is being used to create user feed object
* @return UserFeed object
*/
public static UserFeed fromEntity(Entity entity){
String podcastTitle = (String) entity.getProperty(FormHandlerServlet.PODCAST_TITLE);
String mp3Link = (String) entity.getProperty(FormHandlerServlet.MP3LINK);
return new UserFeed(podcastTitle, mp3Link);
}
public String getTitle(){
return this.podcastTitle;
}
public String getLink(){
return this.mp3Link;
}
}
| launchpod/src/main/java/com/google/launchpod/data/UserFeed.java | package com.google.launchpod.data;
import com.google.appengine.api.datastore.Entity;
import com.google.launchpod.servlets.FormHandlerServlet;
public final class UserFeed{
private final String podcastTitle;
private final String mp3Link;
private final String pubDate;
private UserFeed(String podcastTitle, String mp3Link, String pubDate) {
this.podcastTitle = podcastTitle;
this.mp3Link = mp3Link;
this.pubDate = pubDate;
}
/** Create UserFeed Object from Entity
* @param entity : entity that is being used to create user feed object
* @return UserFeed object
*/
public static UserFeed fromEntity(Entity entity){
String podcastTitle = (String) entity.getProperty(FormHandlerServlet.PODCAST_TITLE);
String mp3Link = (String) entity.getProperty(FormHandlerServlet.MP3LINK);
String pubDate = (String) entity.getProperty(FormHandlerServlet.PUB_DATE);
return new UserFeed(podcastTitle, mp3Link, pubDate);
}
public String getTitle(){
return this.podcastTitle;
}
public String getLink(){
return this.mp3Link;
}
public String getPubDate(){
return this.pubDate;
}
}
| fix minor bug issue with unecessary pubdate inside of userfeed class
| launchpod/src/main/java/com/google/launchpod/data/UserFeed.java | fix minor bug issue with unecessary pubdate inside of userfeed class | <ide><path>aunchpod/src/main/java/com/google/launchpod/data/UserFeed.java
<ide>
<ide> private final String podcastTitle;
<ide> private final String mp3Link;
<del> private final String pubDate;
<ide>
<del> private UserFeed(String podcastTitle, String mp3Link, String pubDate) {
<add> private UserFeed(String podcastTitle, String mp3Link) {
<ide> this.podcastTitle = podcastTitle;
<ide> this.mp3Link = mp3Link;
<del> this.pubDate = pubDate;
<ide> }
<ide> /** Create UserFeed Object from Entity
<ide> * @param entity : entity that is being used to create user feed object
<ide> public static UserFeed fromEntity(Entity entity){
<ide> String podcastTitle = (String) entity.getProperty(FormHandlerServlet.PODCAST_TITLE);
<ide> String mp3Link = (String) entity.getProperty(FormHandlerServlet.MP3LINK);
<del> String pubDate = (String) entity.getProperty(FormHandlerServlet.PUB_DATE);
<ide>
<del> return new UserFeed(podcastTitle, mp3Link, pubDate);
<add> return new UserFeed(podcastTitle, mp3Link);
<ide> }
<ide>
<ide> public String getTitle(){
<ide> public String getLink(){
<ide> return this.mp3Link;
<ide> }
<del>
<del> public String getPubDate(){
<del> return this.pubDate;
<del> }
<ide> } |
|
Java | epl-1.0 | 09ee0502c49b46e53668b02a0e33bb559836d996 | 0 | miklossy/xtext-core,miklossy/xtext-core | /*******************************************************************************
* Copyright (c) 2018 itemis AG (http://www.itemis.eu) 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
*******************************************************************************/
package org.eclipse.xtext.util;
/**
* Reusable and customizable implementation of the methdo pair
* {@link Strings#convertToJavaString(String)} and
* {@link Strings#convertFromJavaString(String, boolean)}.
*
* @since 2.16
*/
public class JavaStringConverter {
/**
* Resolve Java control character sequences with to the actual character value.
* Optionally handle unicode escape sequences, too.
*/
public String convertFromJavaString(String string, boolean useUnicode) {
int length = string.length();
StringBuilder result = new StringBuilder(length);
return convertFromJavaString(string, useUnicode, 0, result);
}
protected String convertFromJavaString(String string, boolean useUnicode, int index, StringBuilder result) {
int length = string.length();
while(index < length) {
index = unescapeCharAndAppendTo(string, useUnicode, index, result);
}
return result.toString();
}
protected int unescapeCharAndAppendTo(String string, boolean useUnicode, int index, StringBuilder result) {
char c = string.charAt(index++);
if (c == '\\') {
index = doUnescapeCharAndAppendTo(string, useUnicode, index, result);
} else {
validateAndAppendChar(result, c);
}
return index;
}
protected void validateAndAppendChar(StringBuilder result, char c) {
if (validate(result, c)) {
result.append(c);
}
}
protected boolean validate(StringBuilder result, char c) {
return true;
}
protected int doUnescapeCharAndAppendTo(String string, boolean useUnicode, int index, StringBuilder result) {
char c = string.charAt(index++);
switch(c) {
case 'b':
c = '\b';
break;
case 't':
c = '\t';
break;
case 'n':
c = '\n';
break;
case 'f':
c = '\f';
break;
case 'r':
c = '\r';
break;
case '"':
case '\'':
case '\\':
break;
case 'u':
if (useUnicode) {
return unescapeUnicodeSequence(string, index, result);
}
// intentional fallThrough
default:
return handleUnknownEscapeSequence(string, c, useUnicode, index, result);
}
validateAndAppendChar(result, c);
return index;
}
protected int handleUnknownEscapeSequence(String string, char c, boolean useUnicode, int index, StringBuilder result) {
throw new IllegalArgumentException("Illegal escape character \\" + c);
}
protected int unescapeUnicodeSequence(String string, int index, StringBuilder result) {
try {
return doUnescapeUnicodeEscapeSequence(string, index, result);
} catch(NumberFormatException e) {
throw new IllegalArgumentException("Illegal \\uxxxx encoding in " + string);
}
}
protected int doUnescapeUnicodeEscapeSequence(String string, int index, StringBuilder result) throws NumberFormatException {
if(isInvalidUnicodeEscapeSequence(string, index))
return handleInvalidUnicodeEscapeSequnce(string, index, result);
char appendMe = (char) Integer.parseInt(string.substring(index, index + 4), 16);
validateAndAppendChar(result, appendMe);
return index + 4;
}
/**
* Return true if the chars starting at index do not appear to be a unicode
* escape sequence (without the leading backslash u}.
*/
protected boolean isInvalidUnicodeEscapeSequence(String string, int index) {
return index+4 > string.length();
}
protected int handleInvalidUnicodeEscapeSequnce(String string, int index, StringBuilder result) {
throw new IllegalArgumentException("Illegal \\uxxxx encoding in " + string + " at index " + index);
}
/**
* Escapes control characters with a preceding backslash.
* Encodes special chars as unicode escape sequence.
* The resulting string is safe to be put into a Java string literal between
* the quotes.
*/
public String convertToJavaString(String theString) {
return convertToJavaString(theString, true);
}
/**
* Escapes control characters with a preceding backslash.
* Optionally encodes special chars as unicode escape sequence.
* The resulting string is safe to be put into a Java string literal between
* the quotes.
*/
public String convertToJavaString(String input, boolean useUnicode) {
int length = input.length();
StringBuilder result = new StringBuilder(length + 4);
for (int i = 0; i < length; i++) {
escapeAndAppendTo(input.charAt(i), useUnicode, result);
}
return result.toString();
}
protected void escapeAndAppendTo(char c, boolean useUnicode, StringBuilder result) {
String appendMe;
switch (c) {
case '\b':
appendMe = "\\b";
break;
case '\t':
appendMe = "\\t";
break;
case '\n':
appendMe = "\\n";
break;
case '\f':
appendMe = "\\f";
break;
case '\r':
appendMe = "\\r";
break;
case '"':
appendMe = "\\\"";
break;
case '\'':
appendMe = "\\'";
break;
case '\\':
appendMe = "\\\\";
break;
default:
if (useUnicode && mustEncodeAsEscapeSequence(c)) {
result.append("\\u");
for (int i = 12; i >= 0; i-=4) {
result.append(toHex((c >> i) & 0xF));
}
} else {
result.append(c);
}
return;
}
result.append(appendMe);
}
protected boolean mustEncodeAsEscapeSequence(char next) {
return next < 0x0020 || next > 0x007e;
}
public char toHex(int i) {
return "0123456789ABCDEF".charAt(i & 0xF);
}
} | org.eclipse.xtext.util/src/org/eclipse/xtext/util/JavaStringConverter.java | /*******************************************************************************
* Copyright (c) 2018 itemis AG (http://www.itemis.eu) 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
*******************************************************************************/
package org.eclipse.xtext.util;
/**
* Reusable and customizable implementation of the methdo pair
* {@link Strings#convertToJavaString(String)} and
* {@link Strings#convertFromJavaString(String, boolean)}.
*
* @since 2.16
*/
public class JavaStringConverter {
/**
* Resolve Java control character sequences with to the actual character value.
* Optionally handle unicode escape sequences, too.
*/
public String convertFromJavaString(String string, boolean useUnicode) {
int length = string.length();
StringBuilder result = new StringBuilder(length);
for(int nextIndex = 0; nextIndex < length;) {
nextIndex = unescapeCharAndAppendTo(string, useUnicode, nextIndex, result);
}
return result.toString();
}
protected int unescapeCharAndAppendTo(String string, boolean useUnicode, int index, StringBuilder result) {
char c = string.charAt(index++);
if (c == '\\') {
index = doUnescapeCharAndAppendTo(string, useUnicode, index, result);
} else {
result.append(c);
}
return index;
}
protected int doUnescapeCharAndAppendTo(String string, boolean useUnicode, int index, StringBuilder result) {
char c = string.charAt(index++);
switch(c) {
case 'b':
c = '\b';
break;
case 't':
c = '\t';
break;
case 'n':
c = '\n';
break;
case 'f':
c = '\f';
break;
case 'r':
c = '\r';
break;
case '"':
case '\'':
case '\\':
break;
case 'u':
if (useUnicode) {
return unescapeUnicodeSequence(string, index, result);
}
// intentional fallThrough
default:
return handleUnknownEscapeSequence(string, c, useUnicode, index, result);
}
result.append(c);
return index;
}
protected int handleUnknownEscapeSequence(String string, char c, boolean useUnicode, int index, StringBuilder result) {
throw new IllegalArgumentException("Illegal escape character \\" + c);
}
protected int unescapeUnicodeSequence(String string, int index, StringBuilder result) {
try {
if(index+4 > string.length())
throw new IllegalArgumentException("Illegal \\uxxxx encoding in " + string);
result.append((char) Integer.parseInt(string.substring(index, index + 4), 16));
return index + 4;
} catch(NumberFormatException e) {
throw new IllegalArgumentException("Illegal \\uxxxx encoding in " + string);
}
}
/**
* Escapes control characters with a preceding backslash.
* Encodes special chars as unicode escape sequence.
* The resulting string is safe to be put into a Java string literal between
* the quotes.
*/
public String convertToJavaString(String theString) {
return convertToJavaString(theString, true);
}
/**
* Escapes control characters with a preceding backslash.
* Optionally encodes special chars as unicode escape sequence.
* The resulting string is safe to be put into a Java string literal between
* the quotes.
*/
public String convertToJavaString(String input, boolean useUnicode) {
int length = input.length();
StringBuilder result = new StringBuilder(length + 4);
for (int i = 0; i < length; i++) {
escapeAndAppendTo(input.charAt(i), useUnicode, result);
}
return result.toString();
}
protected void escapeAndAppendTo(char c, boolean useUnicode, StringBuilder result) {
String appendMe;
switch (c) {
case '\b':
appendMe = "\\b";
break;
case '\t':
appendMe = "\\t";
break;
case '\n':
appendMe = "\\n";
break;
case '\f':
appendMe = "\\f";
break;
case '\r':
appendMe = "\\r";
break;
case '"':
appendMe = "\\\"";
break;
case '\'':
appendMe = "\\'";
break;
case '\\':
appendMe = "\\\\";
break;
default:
if (useUnicode && mustEncodeAsEscapeSequence(c)) {
result.append("\\u");
for (int i = 12; i >= 0; i-=4) {
result.append(toHex((c >> i) & 0xF));
}
} else {
result.append(c);
}
return;
}
result.append(appendMe);
}
protected boolean mustEncodeAsEscapeSequence(char next) {
return next < 0x0020 || next > 0x007e;
}
public char toHex(int i) {
return "0123456789ABCDEF".charAt(i & 0xF);
}
} | Make JavaStringConverter even easier to reuse
| org.eclipse.xtext.util/src/org/eclipse/xtext/util/JavaStringConverter.java | Make JavaStringConverter even easier to reuse | <ide><path>rg.eclipse.xtext.util/src/org/eclipse/xtext/util/JavaStringConverter.java
<ide> public String convertFromJavaString(String string, boolean useUnicode) {
<ide> int length = string.length();
<ide> StringBuilder result = new StringBuilder(length);
<del> for(int nextIndex = 0; nextIndex < length;) {
<del> nextIndex = unescapeCharAndAppendTo(string, useUnicode, nextIndex, result);
<add> return convertFromJavaString(string, useUnicode, 0, result);
<add> }
<add>
<add> protected String convertFromJavaString(String string, boolean useUnicode, int index, StringBuilder result) {
<add> int length = string.length();
<add> while(index < length) {
<add> index = unescapeCharAndAppendTo(string, useUnicode, index, result);
<ide> }
<ide> return result.toString();
<ide> }
<ide> if (c == '\\') {
<ide> index = doUnescapeCharAndAppendTo(string, useUnicode, index, result);
<ide> } else {
<del> result.append(c);
<add> validateAndAppendChar(result, c);
<ide> }
<ide> return index;
<ide> }
<ide>
<add> protected void validateAndAppendChar(StringBuilder result, char c) {
<add> if (validate(result, c)) {
<add> result.append(c);
<add> }
<add> }
<add>
<add> protected boolean validate(StringBuilder result, char c) {
<add> return true;
<add> }
<add>
<ide> protected int doUnescapeCharAndAppendTo(String string, boolean useUnicode, int index, StringBuilder result) {
<ide> char c = string.charAt(index++);
<ide> switch(c) {
<ide> default:
<ide> return handleUnknownEscapeSequence(string, c, useUnicode, index, result);
<ide> }
<del> result.append(c);
<add> validateAndAppendChar(result, c);
<ide> return index;
<ide> }
<ide>
<ide>
<ide> protected int unescapeUnicodeSequence(String string, int index, StringBuilder result) {
<ide> try {
<del> if(index+4 > string.length())
<del> throw new IllegalArgumentException("Illegal \\uxxxx encoding in " + string);
<del> result.append((char) Integer.parseInt(string.substring(index, index + 4), 16));
<del> return index + 4;
<add> return doUnescapeUnicodeEscapeSequence(string, index, result);
<ide> } catch(NumberFormatException e) {
<ide> throw new IllegalArgumentException("Illegal \\uxxxx encoding in " + string);
<ide> }
<add> }
<add>
<add> protected int doUnescapeUnicodeEscapeSequence(String string, int index, StringBuilder result) throws NumberFormatException {
<add> if(isInvalidUnicodeEscapeSequence(string, index))
<add> return handleInvalidUnicodeEscapeSequnce(string, index, result);
<add> char appendMe = (char) Integer.parseInt(string.substring(index, index + 4), 16);
<add> validateAndAppendChar(result, appendMe);
<add> return index + 4;
<add> }
<add>
<add> /**
<add> * Return true if the chars starting at index do not appear to be a unicode
<add> * escape sequence (without the leading backslash u}.
<add> */
<add> protected boolean isInvalidUnicodeEscapeSequence(String string, int index) {
<add> return index+4 > string.length();
<add> }
<add>
<add> protected int handleInvalidUnicodeEscapeSequnce(String string, int index, StringBuilder result) {
<add> throw new IllegalArgumentException("Illegal \\uxxxx encoding in " + string + " at index " + index);
<ide> }
<ide>
<ide> /** |
|
JavaScript | mit | 1bd63b9b48783db010e0c2140f715126ee86470a | 0 | psu-capstone-teamD/AdminUI,psu-capstone-teamD/AdminUI,psu-capstone-teamD/AdminUI | describe('MediaAssetsControllerTests', function(){
var S3Service, mediaAssetsService, schedulerService, $scope, $q, $rootScope, MediaAssetsController;
beforeEach(angular.mock.module('adminUI'));
beforeEach(inject(function($injector, $rootScope, $controller, _$q_, _S3Service_, _schedulerService_, _mediaAssetsService_) {
$rootScope = $injector.get('$rootScope');
$scope = $rootScope;
createS3Service = function($rootScope) {
return $injector.get('S3Service');
};
createSchedulerService = function($rootScope) {
return $injector.get('schedulerService');
};
createMediaAssetsService = function($rootScope) {
return $injector.get('mediaAssetsService');
}
$q = _$q_;
S3Service = createS3Service($scope);
schedulerService = createSchedulerService($scope);
mediaAssetsService = createMediaAssetsService($scope);
createMediaAssetsController = function() {
return $controller('MediaAssetsController', {
'$scope': $scope,
'$rootScope': $rootScope,
'S3Service': S3Service,
'$q': $q,
'mediaAssetsService': mediaAssetsService,
'schedulerService': schedulerService
});
}
}));
describe('initial load tests', function() {
it('should successfully load and bind variables', function() {
MediaAssetsController = createMediaAssetsController($scope, $rootScope, S3Service, $q, mediaAssetsService, schedulerService);
expect(MediaAssetsController).toBeTruthy();
expect($scope.mediaAssets).toEqual(mediaAssetsService.mediaAssets);
expect($scope.S3Objects.length).toBe(0);
expect($scope.currentURL).toBe("");
expect($scope.currentFileName).toBe("");
});
});
describe("updateCurrentS3Video() tests", function() {
it('should correctly set the file name and URL', function() {
MediaAssetsController = createMediaAssetsController($scope, $rootScope, S3Service, $q, mediaAssetsService, schedulerService);
var fileName = "testFile";
var testURL = "www.foo.com";
$scope.updateCurrentS3Video(fileName, testURL);
expect($scope.currentFileName).toBe(fileName);
expect($scope.currentURL).toBe(testURL);
});
it('should correctly handle null values', function() {
MediaAssetsController = createMediaAssetsController($scope, $rootScope, S3Service, $q, mediaAssetsService, schedulerService);
var fileName = null;
var testURL = null;
$scope.updateCurrentS3Video(fileName, testURL);
expect($scope.currentFileName).toBe("");
expect($scope.currentURL).toBe("");
});
});
describe("addFile() tests", function() {
beforeEach(function() {
MediaAssetsController = createMediaAssetsController($scope, $rootScope, S3Service, $q, mediaAssetsService, schedulerService);
spyOn($scope, '$emit');
});
it("should broadcast the correct event and arguments", function() {
$scope.currentFileName = "test";
$scope.currentURL = "www.foo.com";
$scope.title = "test title";
$scope.category = "TV Show";
$scope.videoStartTime = new Date();
$scope.order = 1;
$scope.addFile();
expect($scope.$emit).toHaveBeenCalledWith('addS3ToPlaylist', { fileName: $scope.currentFileName, fileURL: $scope.currentURL, title: $scope.title, category: $scope.category, date: $scope.videoStartTime, order: $scope.order});
});
});
describe("resetMediaAssetForm() tests", function() {
beforeEach(function() {
MediaAssetsController = createMediaAssetsController($scope, $rootScope, S3Service, $q, mediaAssetsService, schedulerService);
$scope.title = "foo";
$scope.category = "bar";
$scope.order = 10;
$scope.uploadProgress = 100;
$scope.startTime = "123";
$scope.videoStartTime = "123";
spyOn(schedulerService, 'playlistChanged');
});
it('should correctly reset the variables when called', function() {
$scope.resetMediaAssetForm();
expect($scope.title).toBeNull();
expect($scope.category).toBe("");
expect($scope.order).toBe("");
expect($scope.uploadProgress).toBe(0);
expect($scope.startTime).toBe("");
expect($scope.videoStartTime).toBe("");
expect(schedulerService.playlistChanged).toHaveBeenCalled();
});
});
}); | js/test/MediaAssetsControllerTests.spec.js | describe('MediaAssetsControllerTests', function(){
var S3Service, mediaAssetsService, schedulerService, $scope, $q, $rootScope, MediaAssetsController;
beforeEach(angular.mock.module('adminUI'));
beforeEach(inject(function($injector, $rootScope, $controller, _$q_, _S3Service_, _schedulerService_, _mediaAssetsService_) {
$rootScope = $injector.get('$rootScope');
$scope = $rootScope;
createS3Service = function($rootScope) {
return $injector.get('S3Service');
};
createSchedulerService = function($rootScope) {
return $injector.get('schedulerService');
};
createMediaAssetsService = function($rootScope) {
return $injector.get('mediaAssetsService');
}
$q = _$q_;
S3Service = createS3Service($scope);
schedulerService = createSchedulerService($scope);
mediaAssetsService = createMediaAssetsService($scope);
createMediaAssetsController = function() {
return $controller('MediaAssetsController', {
'$scope': $scope,
'$rootScope': $rootScope,
'S3Service': S3Service,
'$q': $q,
'mediaAssetsService': mediaAssetsService,
'schedulerService': schedulerService
});
}
}));
describe('initial load tests', function() {
it('should successfully load and bind variables', function() {
MediaAssetsController = createMediaAssetsController($scope, $rootScope, S3Service, $q, mediaAssetsService, schedulerService);
expect(MediaAssetsController).toBeTruthy();
expect($scope.mediaAssets).toEqual(mediaAssetsService.mediaAssets);
expect($scope.S3Objects.length).toBe(0);
expect($scope.currentURL).toBe("");
expect($scope.currentFileName).toBe("");
});
});
describe("updateCurrentS3Video() tests", function() {
it('should correctly set the file name and URL', function() {
MediaAssetsController = createMediaAssetsController($scope, $rootScope, S3Service, $q, mediaAssetsService, schedulerService);
var fileName = "testFile";
var testURL = "www.foo.com";
$scope.updateCurrentS3Video(fileName, testURL);
expect($scope.currentFileName).toBe(fileName);
expect($scope.currentURL).toBe(testURL);
});
it('should correctly handle null values', function() {
MediaAssetsController = createMediaAssetsController($scope, $rootScope, S3Service, $q, mediaAssetsService, schedulerService);
var fileName = null;
var testURL = null;
$scope.updateCurrentS3Video(fileName, testURL);
expect($scope.currentFileName).toBe("");
expect($scope.currentURL).toBe("");
});
});
describe("addFile() tests", function() {
beforeEach(function() {
MediaAssetsController = createMediaAssetsController($scope, $rootScope, S3Service, $q, mediaAssetsService, schedulerService);
spyOn($scope, '$emit');
});
it("should broadcast the correct event and arguments", function() {
$scope.currentFileName = "test";
$scope.currentURL = "www.foo.com";
$scope.title = "test title";
$scope.category = "TV Show";
$scope.videoStartTime = new Date();
$scope.order = 1;
$scope.addFile();
expect($scope.$emit).toHaveBeenCalledWith('addS3ToPlaylist', { fileName: $scope.currentFileName, fileURL: $scope.currentURL, title: $scope.title, category: $scope.category, date: $scope.videoStartTime, order: $scope.order});
});
});
}); | reset function tested
| js/test/MediaAssetsControllerTests.spec.js | reset function tested | <ide><path>s/test/MediaAssetsControllerTests.spec.js
<ide> });
<ide>
<ide> });
<add>
<add> describe("resetMediaAssetForm() tests", function() {
<add> beforeEach(function() {
<add> MediaAssetsController = createMediaAssetsController($scope, $rootScope, S3Service, $q, mediaAssetsService, schedulerService);
<add> $scope.title = "foo";
<add> $scope.category = "bar";
<add> $scope.order = 10;
<add> $scope.uploadProgress = 100;
<add> $scope.startTime = "123";
<add> $scope.videoStartTime = "123";
<add>
<add> spyOn(schedulerService, 'playlistChanged');
<add> });
<add> it('should correctly reset the variables when called', function() {
<add> $scope.resetMediaAssetForm();
<add>
<add> expect($scope.title).toBeNull();
<add> expect($scope.category).toBe("");
<add> expect($scope.order).toBe("");
<add> expect($scope.uploadProgress).toBe(0);
<add> expect($scope.startTime).toBe("");
<add> expect($scope.videoStartTime).toBe("");
<add>
<add> expect(schedulerService.playlistChanged).toHaveBeenCalled();
<add> });
<add>
<add> });
<ide> }); |
|
Java | lgpl-2.1 | ffface63f0f028900abd57d004660ee35e63191d | 0 | soul2zimate/wildfly-core,aloubyansky/wildfly-core,yersan/wildfly-core,JiriOndrusek/wildfly-core,jamezp/wildfly-core,bstansberry/wildfly-core,luck3y/wildfly-core,aloubyansky/wildfly-core,jfdenise/wildfly-core,darranl/wildfly-core,darranl/wildfly-core,yersan/wildfly-core,luck3y/wildfly-core,luck3y/wildfly-core,aloubyansky/wildfly-core,ivassile/wildfly-core,bstansberry/wildfly-core,jamezp/wildfly-core,jfdenise/wildfly-core,JiriOndrusek/wildfly-core,soul2zimate/wildfly-core,jamezp/wildfly-core,ivassile/wildfly-core,ivassile/wildfly-core,soul2zimate/wildfly-core,JiriOndrusek/wildfly-core,darranl/wildfly-core,jfdenise/wildfly-core,bstansberry/wildfly-core,yersan/wildfly-core | /*
* Copyright (C) 2016 Red Hat, inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* 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
*/
package org.jboss.as.test.integration.domain;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.jboss.as.controller.audit.JsonAuditLogItemFormatter.USER_ID;
import static org.jboss.as.controller.audit.JsonAuditLogItemFormatter.REMOTE_ADDRESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ACCESS_MECHANISM;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ALLOWED_ORIGINS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CONFIGURATION_CHANGES;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CORE_SERVICE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DOMAIN_UUID;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MANAGEMENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATIONS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_DATE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROFILE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_GROUP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVICE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SYSTEM_PROPERTY;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.util.List;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.client.helpers.Operations;
import org.jboss.as.controller.client.helpers.domain.DomainClient;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
import org.wildfly.core.testrunner.UnsuccessfulOperationException;
/**
*
* @author <a href="mailto:[email protected]">Emmanuel Hugonnet</a> (c) 2015 Red Hat, inc.
*/
public class ConfigurationChangesTestCase extends AbstractConfigurationChangesTestCase {
private static final PathElement DEFAULT_PROFILE = PathElement.pathElement(PROFILE, "default");
private static final PathElement OTHER_PROFILE = PathElement.pathElement(PROFILE, "other");
@Test
public void testConfigurationChanges() throws Exception {
try {
createProfileConfigurationChange(DEFAULT_PROFILE, MAX_HISTORY_SIZE); // shouldn't appear on slave
createProfileConfigurationChange(OTHER_PROFILE, MAX_HISTORY_SIZE);
createConfigurationChanges(HOST_MASTER);
createConfigurationChanges(HOST_SLAVE);
checkConfigurationChanges(readConfigurationChanges(domainMasterLifecycleUtil.getDomainClient(), HOST_MASTER), 11);
checkConfigurationChanges(readConfigurationChanges(domainMasterLifecycleUtil.getDomainClient(), HOST_SLAVE), 11);
checkConfigurationChanges(readConfigurationChanges(domainSlaveLifecycleUtil.getDomainClient(), HOST_SLAVE), 11);
setConfigurationChangeMaxHistory(domainMasterLifecycleUtil.getDomainClient(), HOST_MASTER, 19);
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), 19, HOST_MASTER);
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), MAX_HISTORY_SIZE, HOST_MASTER, PathElement.pathElement(SERVER, "main-one"));
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), MAX_HISTORY_SIZE, HOST_SLAVE);
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), MAX_HISTORY_SIZE, HOST_SLAVE, PathElement.pathElement(SERVER, "other-three"));
checkMaxHistorySize(domainSlaveLifecycleUtil.getDomainClient(), MAX_HISTORY_SIZE, HOST_SLAVE);
checkMaxHistorySize(domainSlaveLifecycleUtil.getDomainClient(), MAX_HISTORY_SIZE, HOST_SLAVE, PathElement.pathElement(SERVER, "other-three"));
setConfigurationChangeMaxHistory(domainMasterLifecycleUtil.getDomainClient(), HOST_SLAVE, 20);
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), 20, HOST_SLAVE);
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), MAX_HISTORY_SIZE, HOST_SLAVE, PathElement.pathElement(SERVER, "other-three"));
checkMaxHistorySize(domainSlaveLifecycleUtil.getDomainClient(), 20, HOST_SLAVE);
checkMaxHistorySize(domainSlaveLifecycleUtil.getDomainClient(), MAX_HISTORY_SIZE, HOST_SLAVE, PathElement.pathElement(SERVER, "other-three"));
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), 19, HOST_MASTER);
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), MAX_HISTORY_SIZE, HOST_MASTER, PathElement.pathElement(SERVER, "main-one"));
setConfigurationChangeMaxHistory(domainMasterLifecycleUtil.getDomainClient(), OTHER_PROFILE, 21);
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), 20, HOST_SLAVE);
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), 21, HOST_SLAVE, PathElement.pathElement(SERVER, "other-three"));
checkMaxHistorySize(domainSlaveLifecycleUtil.getDomainClient(), 20, HOST_SLAVE);
checkMaxHistorySize(domainSlaveLifecycleUtil.getDomainClient(), 21, HOST_SLAVE, PathElement.pathElement(SERVER, "other-three"));
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), 19, HOST_MASTER);
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), MAX_HISTORY_SIZE, HOST_MASTER, PathElement.pathElement(SERVER, "main-one"));
} finally {
clearProfileConfigurationChange(OTHER_PROFILE);
clearProfileConfigurationChange(DEFAULT_PROFILE);
clearConfigurationChanges(HOST_SLAVE);
clearConfigurationChanges(HOST_MASTER);
}
}
@Test
public void testConfigurationChangesOnSlave() throws Exception {
try {
createProfileConfigurationChange(OTHER_PROFILE, 20);
createConfigurationChanges(HOST_SLAVE);
PathAddress systemPropertyAddress = PathAddress.pathAddress().append(HOST_SLAVE).append(SYSTEM_PROPERTY, "slave");
ModelNode setSystemProperty = Util.createAddOperation(systemPropertyAddress);
setSystemProperty.get(VALUE).set("slave-config");
domainSlaveLifecycleUtil.getDomainClient().execute(setSystemProperty);
systemPropertyAddress = PathAddress.pathAddress().append(SERVER_GROUP, "main-server-group").append(SYSTEM_PROPERTY, "main");
setSystemProperty = Util.createAddOperation(systemPropertyAddress);
setSystemProperty.get(VALUE).set("main-config");
domainMasterLifecycleUtil.getDomainClient().execute(setSystemProperty);
List<ModelNode> changesOnSlaveHC = readConfigurationChanges(domainSlaveLifecycleUtil.getDomainClient(), HOST_SLAVE);
List<ModelNode> changesOnSlaveDC = readConfigurationChanges(domainMasterLifecycleUtil.getDomainClient(), HOST_SLAVE);
checkSlaveConfigurationChanges(changesOnSlaveHC, 12);
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), 20, HOST_SLAVE, PathElement.pathElement(SERVER, "other-three"));
checkMaxHistorySize(domainSlaveLifecycleUtil.getDomainClient(), 20, HOST_SLAVE, PathElement.pathElement(SERVER, "other-three"));
assertThat(changesOnSlaveHC.size(), is(changesOnSlaveDC.size()));
} finally {
clearProfileConfigurationChange(OTHER_PROFILE);
clearConfigurationChanges(HOST_SLAVE);
}
}
@Test
public void testExcludeLegacyOnHost() throws Exception {
DomainClient client = domainMasterLifecycleUtil.getDomainClient();
try {
createProfileConfigurationChange(OTHER_PROFILE, 5);
createConfigurationChanges(HOST_SLAVE);
final ModelNode add = Util.createAddOperation(PathAddress.pathAddress(PathAddress.pathAddress()
.append(HOST_SLAVE)
.append(CORE_SERVICE, MANAGEMENT)
.append(SERVICE, CONFIGURATION_CHANGES)));
add.get("max-history").set(MAX_HISTORY_SIZE);
ModelNode response = client.execute(add);
Assert.assertFalse(response.toString(), Operations.isSuccessfulOutcome(response));
assertThat(Operations.getFailureDescription(response).asString(), containsString("WFLYCTL0158"));
} finally {
clearProfileConfigurationChange(OTHER_PROFILE);
clearConfigurationChanges(HOST_SLAVE);
client.execute(Util.createRemoveOperation(PathAddress.pathAddress(PathAddress.pathAddress()
.append(HOST_SLAVE)
.append(CORE_SERVICE, MANAGEMENT)
.append(SERVICE, CONFIGURATION_CHANGES))));
}
}
@Test
public void testExcludeLegacyOnManagedServers() throws Exception {
DomainClient client = domainMasterLifecycleUtil.getDomainClient();
try {
createProfileConfigurationChange(OTHER_PROFILE, 5);
createConfigurationChanges(HOST_SLAVE);
clearConfigurationChanges(HOST_SLAVE);
final ModelNode add = Util.createAddOperation(PathAddress.pathAddress(PathAddress.pathAddress()
.append(HOST_SLAVE)
.append(CORE_SERVICE, MANAGEMENT)
.append(SERVICE, CONFIGURATION_CHANGES)));
add.get("max-history").set(MAX_HISTORY_SIZE);
ModelNode response = client.execute(add);
Assert.assertFalse(response.toString(), Operations.isSuccessfulOutcome(response));
assertThat(Operations.getFailureDescription(response).asString(), containsString("WFLYCTL0158"));
} finally {
clearProfileConfigurationChange(OTHER_PROFILE);
client.execute(Util.createRemoveOperation(PathAddress.pathAddress(PathAddress.pathAddress()
.append(HOST_SLAVE)
.append(CORE_SERVICE, MANAGEMENT)
.append(SERVICE, CONFIGURATION_CHANGES))));
}
}
@Test
public void testEnablingConfigurationChangesOnHC() throws Exception {
DomainClient client = domainMasterLifecycleUtil.getDomainClient();
try {
final ModelNode add = Util.createAddOperation(PathAddress.pathAddress().append(HOST_SLAVE).append(getAddress()));
add.get("max-history").set(MAX_HISTORY_SIZE);
executeForResult(client, add);
} finally {
clearConfigurationChanges(HOST_SLAVE);
}
}
private void checkConfigurationChanges(List<ModelNode> changes, int size) throws IOException {
assertThat(changes.toString(), changes.size(), is(size));
for (ModelNode change : changes) {
assertThat(change.hasDefined(OPERATION_DATE), is(true));
assertThat(change.hasDefined(USER_ID), is(false));
assertThat(change.hasDefined(DOMAIN_UUID), is(true));
assertThat(change.hasDefined(ACCESS_MECHANISM), is(true));
assertThat(change.get(ACCESS_MECHANISM).asString(), is("NATIVE"));
assertThat(change.hasDefined(REMOTE_ADDRESS), is(true));
assertThat(change.get(OPERATIONS).asList().size(), is(1));
}
validateChanges(changes);
}
private void checkSlaveConfigurationChanges( List<ModelNode> changes, int size) throws IOException {
assertThat(changes.toString(),changes.size(), is(size));
for (ModelNode change : changes) {
assertThat(change.hasDefined(OPERATION_DATE), is(true));
assertThat(change.hasDefined(USER_ID), is(false));
assertThat(change.hasDefined(DOMAIN_UUID), is(true));
assertThat(change.hasDefined(ACCESS_MECHANISM), is(true));
assertThat(change.get(ACCESS_MECHANISM).asString(), is("NATIVE"));
assertThat(change.hasDefined(REMOTE_ADDRESS), is(true));
assertThat(change.get(OPERATIONS).asList().size(), is(1));
}
ModelNode currentChange = changes.get(0);
assertThat(currentChange.get(OUTCOME).asString(), is(SUCCESS));
ModelNode currentChangeOp = currentChange.get(OPERATIONS).asList().get(0);
assertThat(currentChangeOp.get(OP).asString(), is(ADD));
assertThat(removePrefix(currentChangeOp).toString(), is(PathAddress.pathAddress(SYSTEM_PROPERTY, "slave").toString()));
assertThat(currentChangeOp.get(VALUE).asString(), is("slave-config"));
validateChanges(changes.subList(1, changes.size() - 1));
}
private void validateChanges(List<ModelNode> changes) throws IOException {
for (ModelNode change : changes) {
assertThat(change.hasDefined(OPERATION_DATE), is(true));
assertThat(change.hasDefined(USER_ID), is(false));
assertThat(change.hasDefined(DOMAIN_UUID), is(true));
assertThat(change.hasDefined(ACCESS_MECHANISM), is(true));
assertThat(change.get(ACCESS_MECHANISM).asString(), is("NATIVE"));
assertThat(change.hasDefined(REMOTE_ADDRESS), is(true));
assertThat(change.get(OPERATIONS).asList().size(), is(1));
}
ModelNode currentChange = changes.get(0);
assertThat(currentChange.get(OUTCOME).asString(), is(SUCCESS));
ModelNode currentChangeOp = currentChange.get(OPERATIONS).asList().get(0);
assertThat(currentChangeOp.get(OP).asString(), is(REMOVE));
assertThat(removePrefix(currentChangeOp).toString(), is(IN_MEMORY_HANDLER_ADDRESS.toString()));
currentChange = changes.get(1);
assertThat(currentChange.get(OUTCOME).asString(), is(SUCCESS));
currentChangeOp = currentChange.get(OPERATIONS).asList().get(0);
assertThat(currentChangeOp.get(OP).asString(), is(WRITE_ATTRIBUTE_OPERATION));
assertThat(removePrefix(currentChangeOp).toString(), is(IN_MEMORY_HANDLER_ADDRESS.toString()));
assertThat(currentChangeOp.get(VALUE).asInt(), is(50));
currentChange = changes.get(2);
assertThat(currentChange.get(OUTCOME).asString(), is(SUCCESS));
currentChangeOp = currentChange.get(OPERATIONS).asList().get(0);
assertThat(currentChangeOp.get(OP).asString(), is(ADD));
assertThat(removePrefix(currentChangeOp).toString(), is(IN_MEMORY_HANDLER_ADDRESS.toString()));
currentChange = changes.get(3);
assertThat(currentChange.get(OUTCOME).asString(), is(SUCCESS));
currentChangeOp = currentChange.get(OPERATIONS).asList().get(0);
assertThat(currentChangeOp.get(OP).asString(), is(REMOVE));
assertThat(removePrefix(currentChangeOp).toString(), is(SYSTEM_PROPERTY_ADDRESS.toString()));
currentChange = changes.get(4);
assertThat(currentChange.get(OUTCOME).asString(), is(SUCCESS));
currentChangeOp = currentChange.get(OPERATIONS).asList().get(0);
assertThat(currentChangeOp.get(OP).asString(), is(WRITE_ATTRIBUTE_OPERATION));
assertThat(removePrefix(currentChangeOp).toString(), is(AUDIT_LOG_ADDRESS.toString()));
assertThat(currentChangeOp.get(VALUE).asBoolean(), is(true));
currentChange = changes.get(5);
assertThat(currentChange.get(OUTCOME).asString(), is(SUCCESS));
currentChangeOp = currentChange.get(OPERATIONS).asList().get(0);
assertThat(currentChangeOp.get(OP).asString(), is(UNDEFINE_ATTRIBUTE_OPERATION));
assertThat(removePrefix(currentChangeOp).toString(), is(ALLOWED_ORIGINS_ADDRESS.toString()));
assertThat(currentChangeOp.get(NAME).asString(), is(ALLOWED_ORIGINS));
currentChange = changes.get(6);
assertThat(currentChange.get(OUTCOME).asString(), is(SUCCESS));
currentChangeOp = currentChange.get(OPERATIONS).asList().get(0);
assertThat(currentChangeOp.get(OP).asString(), is(ADD));
assertThat(removePrefix(currentChangeOp).toString(), is(SYSTEM_PROPERTY_ADDRESS.toString()));
assertThat(currentChangeOp.get(VALUE).asString(), is("changeConfig"));
currentChange = changes.get(7);
assertThat(currentChange.get(OUTCOME).asString(), is(FAILED));
currentChangeOp = currentChange.get(OPERATIONS).asList().get(0);
assertThat(currentChangeOp.get(NAME).asString(), is(ALLOWED_ORIGINS));
}
private void createProfileConfigurationChange(PathElement profile, int maxHistory) throws IOException, UnsuccessfulOperationException {
DomainClient client = domainMasterLifecycleUtil.getDomainClient();
final ModelNode add = Util.createAddOperation(PathAddress.pathAddress().append(profile).append(getAddress()));
add.get("max-history").set(maxHistory);
executeForResult(client, add);
}
private void clearProfileConfigurationChange(PathElement profile) throws IOException, UnsuccessfulOperationException {
DomainClient client = domainMasterLifecycleUtil.getDomainClient();
final ModelNode remove = Util.createRemoveOperation(PathAddress.pathAddress().append(profile).append(getAddress()));
executeForResult(client, remove);
}
@Override
protected PathAddress getAddress() {
return PathAddress.pathAddress()
.append(PathElement.pathElement(SUBSYSTEM, "core-management"))
.append(PathElement.pathElement("service", "configuration-changes"));
}
}
| testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/ConfigurationChangesTestCase.java | /*
* Copyright (C) 2016 Red Hat, inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* 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
*/
package org.jboss.as.test.integration.domain;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.jboss.as.controller.audit.JsonAuditLogItemFormatter.USER_ID;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ACCESS_MECHANISM;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ALLOWED_ORIGINS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CONFIGURATION_CHANGES;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CORE_SERVICE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DOMAIN_UUID;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MANAGEMENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATIONS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_DATE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROFILE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_GROUP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVICE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SYSTEM_PROPERTY;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.util.List;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.client.helpers.Operations;
import org.jboss.as.controller.client.helpers.domain.DomainClient;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
import org.wildfly.core.testrunner.UnsuccessfulOperationException;
/**
*
* @author <a href="mailto:[email protected]">Emmanuel Hugonnet</a> (c) 2015 Red Hat, inc.
*/
public class ConfigurationChangesTestCase extends AbstractConfigurationChangesTestCase {
private static final PathElement DEFAULT_PROFILE = PathElement.pathElement(PROFILE, "default");
private static final PathElement OTHER_PROFILE = PathElement.pathElement(PROFILE, "other");
@Test
public void testConfigurationChanges() throws Exception {
try {
createProfileConfigurationChange(DEFAULT_PROFILE, MAX_HISTORY_SIZE); // shouldn't appear on slave
createProfileConfigurationChange(OTHER_PROFILE, MAX_HISTORY_SIZE);
createConfigurationChanges(HOST_MASTER);
createConfigurationChanges(HOST_SLAVE);
checkConfigurationChanges(readConfigurationChanges(domainMasterLifecycleUtil.getDomainClient(), HOST_MASTER), 11);
checkConfigurationChanges(readConfigurationChanges(domainMasterLifecycleUtil.getDomainClient(), HOST_SLAVE), 11);
checkConfigurationChanges(readConfigurationChanges(domainSlaveLifecycleUtil.getDomainClient(), HOST_SLAVE), 11);
setConfigurationChangeMaxHistory(domainMasterLifecycleUtil.getDomainClient(), HOST_MASTER, 19);
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), 19, HOST_MASTER);
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), MAX_HISTORY_SIZE, HOST_MASTER, PathElement.pathElement(SERVER, "main-one"));
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), MAX_HISTORY_SIZE, HOST_SLAVE);
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), MAX_HISTORY_SIZE, HOST_SLAVE, PathElement.pathElement(SERVER, "other-three"));
checkMaxHistorySize(domainSlaveLifecycleUtil.getDomainClient(), MAX_HISTORY_SIZE, HOST_SLAVE);
checkMaxHistorySize(domainSlaveLifecycleUtil.getDomainClient(), MAX_HISTORY_SIZE, HOST_SLAVE, PathElement.pathElement(SERVER, "other-three"));
setConfigurationChangeMaxHistory(domainMasterLifecycleUtil.getDomainClient(), HOST_SLAVE, 20);
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), 20, HOST_SLAVE);
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), MAX_HISTORY_SIZE, HOST_SLAVE, PathElement.pathElement(SERVER, "other-three"));
checkMaxHistorySize(domainSlaveLifecycleUtil.getDomainClient(), 20, HOST_SLAVE);
checkMaxHistorySize(domainSlaveLifecycleUtil.getDomainClient(), MAX_HISTORY_SIZE, HOST_SLAVE, PathElement.pathElement(SERVER, "other-three"));
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), 19, HOST_MASTER);
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), MAX_HISTORY_SIZE, HOST_MASTER, PathElement.pathElement(SERVER, "main-one"));
setConfigurationChangeMaxHistory(domainMasterLifecycleUtil.getDomainClient(), OTHER_PROFILE, 21);
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), 20, HOST_SLAVE);
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), 21, HOST_SLAVE, PathElement.pathElement(SERVER, "other-three"));
checkMaxHistorySize(domainSlaveLifecycleUtil.getDomainClient(), 20, HOST_SLAVE);
checkMaxHistorySize(domainSlaveLifecycleUtil.getDomainClient(), 21, HOST_SLAVE, PathElement.pathElement(SERVER, "other-three"));
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), 19, HOST_MASTER);
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), MAX_HISTORY_SIZE, HOST_MASTER, PathElement.pathElement(SERVER, "main-one"));
} finally {
clearProfileConfigurationChange(OTHER_PROFILE);
clearProfileConfigurationChange(DEFAULT_PROFILE);
clearConfigurationChanges(HOST_SLAVE);
clearConfigurationChanges(HOST_MASTER);
}
}
@Test
public void testConfigurationChangesOnSlave() throws Exception {
try {
createProfileConfigurationChange(OTHER_PROFILE, 20);
createConfigurationChanges(HOST_SLAVE);
PathAddress systemPropertyAddress = PathAddress.pathAddress().append(HOST_SLAVE).append(SYSTEM_PROPERTY, "slave");
ModelNode setSystemProperty = Util.createAddOperation(systemPropertyAddress);
setSystemProperty.get(VALUE).set("slave-config");
domainSlaveLifecycleUtil.getDomainClient().execute(setSystemProperty);
systemPropertyAddress = PathAddress.pathAddress().append(SERVER_GROUP, "main-server-group").append(SYSTEM_PROPERTY, "main");
setSystemProperty = Util.createAddOperation(systemPropertyAddress);
setSystemProperty.get(VALUE).set("main-config");
domainMasterLifecycleUtil.getDomainClient().execute(setSystemProperty);
List<ModelNode> changesOnSlaveHC = readConfigurationChanges(domainSlaveLifecycleUtil.getDomainClient(), HOST_SLAVE);
List<ModelNode> changesOnSlaveDC = readConfigurationChanges(domainMasterLifecycleUtil.getDomainClient(), HOST_SLAVE);
checkSlaveConfigurationChanges(changesOnSlaveHC, 12);
checkMaxHistorySize(domainMasterLifecycleUtil.getDomainClient(), 20, HOST_SLAVE, PathElement.pathElement(SERVER, "other-three"));
checkMaxHistorySize(domainSlaveLifecycleUtil.getDomainClient(), 20, HOST_SLAVE, PathElement.pathElement(SERVER, "other-three"));
assertThat(changesOnSlaveHC.size(), is(changesOnSlaveDC.size()));
} finally {
clearProfileConfigurationChange(OTHER_PROFILE);
clearConfigurationChanges(HOST_SLAVE);
}
}
@Test
public void testExcludeLegacyOnHost() throws Exception {
DomainClient client = domainMasterLifecycleUtil.getDomainClient();
try {
createProfileConfigurationChange(OTHER_PROFILE, 5);
createConfigurationChanges(HOST_SLAVE);
final ModelNode add = Util.createAddOperation(PathAddress.pathAddress(PathAddress.pathAddress()
.append(HOST_SLAVE)
.append(CORE_SERVICE, MANAGEMENT)
.append(SERVICE, CONFIGURATION_CHANGES)));
add.get("max-history").set(MAX_HISTORY_SIZE);
ModelNode response = client.execute(add);
Assert.assertFalse(response.toString(), Operations.isSuccessfulOutcome(response));
assertThat(Operations.getFailureDescription(response).asString(), containsString("WFLYCTL0158"));
} finally {
clearProfileConfigurationChange(OTHER_PROFILE);
clearConfigurationChanges(HOST_SLAVE);
client.execute(Util.createRemoveOperation(PathAddress.pathAddress(PathAddress.pathAddress()
.append(HOST_SLAVE)
.append(CORE_SERVICE, MANAGEMENT)
.append(SERVICE, CONFIGURATION_CHANGES))));
}
}
@Test
public void testExcludeLegacyOnManagedServers() throws Exception {
DomainClient client = domainMasterLifecycleUtil.getDomainClient();
try {
createProfileConfigurationChange(OTHER_PROFILE, 5);
createConfigurationChanges(HOST_SLAVE);
clearConfigurationChanges(HOST_SLAVE);
final ModelNode add = Util.createAddOperation(PathAddress.pathAddress(PathAddress.pathAddress()
.append(HOST_SLAVE)
.append(CORE_SERVICE, MANAGEMENT)
.append(SERVICE, CONFIGURATION_CHANGES)));
add.get("max-history").set(MAX_HISTORY_SIZE);
ModelNode response = client.execute(add);
Assert.assertFalse(response.toString(), Operations.isSuccessfulOutcome(response));
assertThat(Operations.getFailureDescription(response).asString(), containsString("WFLYCTL0158"));
} finally {
clearProfileConfigurationChange(OTHER_PROFILE);
client.execute(Util.createRemoveOperation(PathAddress.pathAddress(PathAddress.pathAddress()
.append(HOST_SLAVE)
.append(CORE_SERVICE, MANAGEMENT)
.append(SERVICE, CONFIGURATION_CHANGES))));
}
}
@Test
public void testEnablingConfigurationChangesOnHC() throws Exception {
DomainClient client = domainMasterLifecycleUtil.getDomainClient();
try {
final ModelNode add = Util.createAddOperation(PathAddress.pathAddress().append(HOST_SLAVE).append(getAddress()));
add.get("max-history").set(MAX_HISTORY_SIZE);
executeForResult(client, add);
} finally {
clearConfigurationChanges(HOST_SLAVE);
}
}
private void checkConfigurationChanges(List<ModelNode> changes, int size) throws IOException {
assertThat(changes.toString(), changes.size(), is(size));
for (ModelNode change : changes) {
assertThat(change.hasDefined(OPERATION_DATE), is(true));
assertThat(change.hasDefined(USER_ID), is(false));
assertThat(change.hasDefined(DOMAIN_UUID), is(true));
assertThat(change.hasDefined(ACCESS_MECHANISM), is(true));
assertThat(change.get(ACCESS_MECHANISM).asString(), is("NATIVE"));
// TODO Elytron - Restore capturing the Remote address.
//assertThat(change.hasDefined(REMOTE_ADDRESS), is(true));
assertThat(change.get(OPERATIONS).asList().size(), is(1));
}
validateChanges(changes);
}
private void checkSlaveConfigurationChanges( List<ModelNode> changes, int size) throws IOException {
assertThat(changes.toString(),changes.size(), is(size));
for (ModelNode change : changes) {
assertThat(change.hasDefined(OPERATION_DATE), is(true));
assertThat(change.hasDefined(USER_ID), is(false));
assertThat(change.hasDefined(DOMAIN_UUID), is(true));
assertThat(change.hasDefined(ACCESS_MECHANISM), is(true));
assertThat(change.get(ACCESS_MECHANISM).asString(), is("NATIVE"));
// TODO Elytron - Restore capturing the Remote address.
//assertThat(change.hasDefined(REMOTE_ADDRESS), is(true));
assertThat(change.get(OPERATIONS).asList().size(), is(1));
}
ModelNode currentChange = changes.get(0);
assertThat(currentChange.get(OUTCOME).asString(), is(SUCCESS));
ModelNode currentChangeOp = currentChange.get(OPERATIONS).asList().get(0);
assertThat(currentChangeOp.get(OP).asString(), is(ADD));
assertThat(removePrefix(currentChangeOp).toString(), is(PathAddress.pathAddress(SYSTEM_PROPERTY, "slave").toString()));
assertThat(currentChangeOp.get(VALUE).asString(), is("slave-config"));
validateChanges(changes.subList(1, changes.size() - 1));
}
private void validateChanges(List<ModelNode> changes) throws IOException {
for (ModelNode change : changes) {
assertThat(change.hasDefined(OPERATION_DATE), is(true));
assertThat(change.hasDefined(USER_ID), is(false));
assertThat(change.hasDefined(DOMAIN_UUID), is(true));
assertThat(change.hasDefined(ACCESS_MECHANISM), is(true));
assertThat(change.get(ACCESS_MECHANISM).asString(), is("NATIVE"));
// TODO Elytron - Restore capturing the Remote address.
//assertThat(change.hasDefined(REMOTE_ADDRESS), is(true));
assertThat(change.get(OPERATIONS).asList().size(), is(1));
}
ModelNode currentChange = changes.get(0);
assertThat(currentChange.get(OUTCOME).asString(), is(SUCCESS));
ModelNode currentChangeOp = currentChange.get(OPERATIONS).asList().get(0);
assertThat(currentChangeOp.get(OP).asString(), is(REMOVE));
assertThat(removePrefix(currentChangeOp).toString(), is(IN_MEMORY_HANDLER_ADDRESS.toString()));
currentChange = changes.get(1);
assertThat(currentChange.get(OUTCOME).asString(), is(SUCCESS));
currentChangeOp = currentChange.get(OPERATIONS).asList().get(0);
assertThat(currentChangeOp.get(OP).asString(), is(WRITE_ATTRIBUTE_OPERATION));
assertThat(removePrefix(currentChangeOp).toString(), is(IN_MEMORY_HANDLER_ADDRESS.toString()));
assertThat(currentChangeOp.get(VALUE).asInt(), is(50));
currentChange = changes.get(2);
assertThat(currentChange.get(OUTCOME).asString(), is(SUCCESS));
currentChangeOp = currentChange.get(OPERATIONS).asList().get(0);
assertThat(currentChangeOp.get(OP).asString(), is(ADD));
assertThat(removePrefix(currentChangeOp).toString(), is(IN_MEMORY_HANDLER_ADDRESS.toString()));
currentChange = changes.get(3);
assertThat(currentChange.get(OUTCOME).asString(), is(SUCCESS));
currentChangeOp = currentChange.get(OPERATIONS).asList().get(0);
assertThat(currentChangeOp.get(OP).asString(), is(REMOVE));
assertThat(removePrefix(currentChangeOp).toString(), is(SYSTEM_PROPERTY_ADDRESS.toString()));
currentChange = changes.get(4);
assertThat(currentChange.get(OUTCOME).asString(), is(SUCCESS));
currentChangeOp = currentChange.get(OPERATIONS).asList().get(0);
assertThat(currentChangeOp.get(OP).asString(), is(WRITE_ATTRIBUTE_OPERATION));
assertThat(removePrefix(currentChangeOp).toString(), is(AUDIT_LOG_ADDRESS.toString()));
assertThat(currentChangeOp.get(VALUE).asBoolean(), is(true));
currentChange = changes.get(5);
assertThat(currentChange.get(OUTCOME).asString(), is(SUCCESS));
currentChangeOp = currentChange.get(OPERATIONS).asList().get(0);
assertThat(currentChangeOp.get(OP).asString(), is(UNDEFINE_ATTRIBUTE_OPERATION));
assertThat(removePrefix(currentChangeOp).toString(), is(ALLOWED_ORIGINS_ADDRESS.toString()));
assertThat(currentChangeOp.get(NAME).asString(), is(ALLOWED_ORIGINS));
currentChange = changes.get(6);
assertThat(currentChange.get(OUTCOME).asString(), is(SUCCESS));
currentChangeOp = currentChange.get(OPERATIONS).asList().get(0);
assertThat(currentChangeOp.get(OP).asString(), is(ADD));
assertThat(removePrefix(currentChangeOp).toString(), is(SYSTEM_PROPERTY_ADDRESS.toString()));
assertThat(currentChangeOp.get(VALUE).asString(), is("changeConfig"));
currentChange = changes.get(7);
assertThat(currentChange.get(OUTCOME).asString(), is(FAILED));
currentChangeOp = currentChange.get(OPERATIONS).asList().get(0);
assertThat(currentChangeOp.get(NAME).asString(), is(ALLOWED_ORIGINS));
}
private void createProfileConfigurationChange(PathElement profile, int maxHistory) throws IOException, UnsuccessfulOperationException {
DomainClient client = domainMasterLifecycleUtil.getDomainClient();
final ModelNode add = Util.createAddOperation(PathAddress.pathAddress().append(profile).append(getAddress()));
add.get("max-history").set(maxHistory);
executeForResult(client, add);
}
private void clearProfileConfigurationChange(PathElement profile) throws IOException, UnsuccessfulOperationException {
DomainClient client = domainMasterLifecycleUtil.getDomainClient();
final ModelNode remove = Util.createRemoveOperation(PathAddress.pathAddress().append(profile).append(getAddress()));
executeForResult(client, remove);
}
@Override
protected PathAddress getAddress() {
return PathAddress.pathAddress()
.append(PathElement.pathElement(SUBSYSTEM, "core-management"))
.append(PathElement.pathElement("service", "configuration-changes"));
}
}
| [WFCORE-2228] Restore checking for the address within the test now it is sent between processes.
| testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/ConfigurationChangesTestCase.java | [WFCORE-2228] Restore checking for the address within the test now it is sent between processes. | <ide><path>estsuite/domain/src/test/java/org/jboss/as/test/integration/domain/ConfigurationChangesTestCase.java
<ide> import static org.hamcrest.CoreMatchers.containsString;
<ide> import static org.hamcrest.CoreMatchers.is;
<ide> import static org.jboss.as.controller.audit.JsonAuditLogItemFormatter.USER_ID;
<add>import static org.jboss.as.controller.audit.JsonAuditLogItemFormatter.REMOTE_ADDRESS;
<ide> import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ACCESS_MECHANISM;
<ide> import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
<ide> import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ALLOWED_ORIGINS;
<ide> assertThat(change.hasDefined(DOMAIN_UUID), is(true));
<ide> assertThat(change.hasDefined(ACCESS_MECHANISM), is(true));
<ide> assertThat(change.get(ACCESS_MECHANISM).asString(), is("NATIVE"));
<del> // TODO Elytron - Restore capturing the Remote address.
<del> //assertThat(change.hasDefined(REMOTE_ADDRESS), is(true));
<add> assertThat(change.hasDefined(REMOTE_ADDRESS), is(true));
<ide> assertThat(change.get(OPERATIONS).asList().size(), is(1));
<ide> }
<ide> validateChanges(changes);
<ide> assertThat(change.hasDefined(DOMAIN_UUID), is(true));
<ide> assertThat(change.hasDefined(ACCESS_MECHANISM), is(true));
<ide> assertThat(change.get(ACCESS_MECHANISM).asString(), is("NATIVE"));
<del> // TODO Elytron - Restore capturing the Remote address.
<del> //assertThat(change.hasDefined(REMOTE_ADDRESS), is(true));
<add> assertThat(change.hasDefined(REMOTE_ADDRESS), is(true));
<ide> assertThat(change.get(OPERATIONS).asList().size(), is(1));
<ide> }
<ide> ModelNode currentChange = changes.get(0);
<ide> assertThat(change.hasDefined(DOMAIN_UUID), is(true));
<ide> assertThat(change.hasDefined(ACCESS_MECHANISM), is(true));
<ide> assertThat(change.get(ACCESS_MECHANISM).asString(), is("NATIVE"));
<del> // TODO Elytron - Restore capturing the Remote address.
<del> //assertThat(change.hasDefined(REMOTE_ADDRESS), is(true));
<add> assertThat(change.hasDefined(REMOTE_ADDRESS), is(true));
<ide> assertThat(change.get(OPERATIONS).asList().size(), is(1));
<ide> }
<ide> ModelNode currentChange = changes.get(0); |
|
Java | bsd-3-clause | 01499fc1a5cc6bffe23be1d384c5bd9cc332a99e | 0 | Civcraft/MusterCull,ProgrammerDan/MusterCull,BlackXnt/MusterCull | package com.untamedears.mustercull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.EntityType;
import org.bukkit.plugin.java.JavaPlugin;
/**
* Manages the configuration for the plug-in.
*
* @author Celdecea
*
*/
public class Configuration {
/**
* Whether or not configuration data needs to be saved.
*/
private boolean dirty = false;
/**
* The amount of damage to apply to a crowded mob.
*/
private int damage = 0;
/**
* Mob limits loaded from the configuration file.
*/
private Map<EntityType, List<ConfigurationLimit>> mobLimits = new HashMap<EntityType, List<ConfigurationLimit>>();
/**
* Whether or not we have limits with CullType DAMAGE.
*
* This is used by the MusterCull class to determine if the tick laborer
* needs to be started.
*/
private boolean hasDamageLimits = false;
/**
* Whether or not we have limits with CullTypes SPAWN or SPAWNER.
*
* This is used by the MusterCull class to determine if the event listener
* needs to be registered.
*/
private boolean hasSpawnLimits = false;
/**
* Number of ticks between calls to the chunk damage laborer.
*/
private long ticksBetweenDamage = 20L;
/**
* Number of entities to damage every time the damage laborer runs.
*/
private int damageCalls = 1;
/**
* Percent chance that a mob will be damaged when crowded.
*/
private int damageChance = 75;
/**
* Hard number on mobs before the damage laborer cares to run.
*/
private int mobLimit = 1;
/**
* Percentage of mobLimit each mob must be to trigger damage culling
*/
private int mobLimitPercent = 1;
/**
* Whether or not to notify when entities have been damaged.
*/
private boolean damageNotify = false;
/**
* The hard mob limit. Also however many mobs can exist with no players.
*/
private int maxMob = 10000;
/**
* How many mobs permitted less of the maximum, per player.
*/
private int playerMultiplier = 5;
/**
* Number of ticks between calls to the living entity hard cap (HardCapLaborer).
*/
private long ticksBetweenHardCap = 40L;
/**
* Whether to perform the monster cull pass to keep them within world spawn limits.
*/
private boolean enableMonsterCullToSpawn = true;
/**
* The maximum number of monsters to cull in a monster cull pass.
*/
private int maximumMonsterCullPerPass = 30;
/**
* The maximum aggression factor for the monster cull.
*/
private int minimumMonsterCullAggression = 0;
/**
* The maximum aggression factor for the monster cull.
*/
private int maximumMonsterCullAggression = 5;
/**
* Holds a reference to the Bukkit JavaPlugin for this project
*/
private JavaPlugin pluginInstance = null;
/**
* Percent that a super-chunk must contain of total server pop in order to qualify for a penalty purge.
*/
private int hardCapCullingPriorityStrategyPenaltyMobPercent = 100;
/**
* Culling strategy for hard-cap culling. RANDOM or PRIORITY
*/
private String hardCapCullingStrategy = "RANDOM";
/**
* Constructor which stores a reference to the Bukkit JavaPlugin we are using.
* @param plugin A reference to a Bukkit JavaPlugin.
*/
Configuration(JavaPlugin plugin) {
this.pluginInstance = plugin;
}
/**
* Loads configuration values from the supplied plug-in instance.
*/
public void load() {
FileConfiguration config = this.pluginInstance.getConfig();
this.setDamage(config.getInt("damage"));
this.setDamageChance(config.getInt("damage_chance"));
this.setDamageCalls(config.getInt("damage_count"));
this.setTicksBetweenDamage(config.getInt("ticks_between_damage"));
this.setMobLimit(config.getInt("mob_limit"));
this.setMobLimitPercent(config.getInt("mob_limit_percent"));
this.setDamageNotify(config.getBoolean("damage_notify"));
this.setMaximumMonsterCullAggression(config.getInt("max_monster_cull_aggression"));
this.setMinimumMonsterCullAggression(config.getInt("min_monster_cull_aggression"));
this.setMaximumMonsterCullPerPass(config.getInt("max_monster_cull_per_pass"));
this.setEnableMonsterCullToSpawn(config.getBoolean("enable_monster_cull_to_spawn"));
this.setMaxMob(config.getInt("mob_max_mob"));
this.setPlayerMultiplier(config.getInt("mob_player_multiplier"));
this.setTicksBetweenHardCap(config.getInt("ticks_between_hard_cap"));
this.setHardCapCullingStrategy(config.getString("hard_cap_culling_strategy"));
this.setHardCapCullingPriorityStrategyPenaltyMobPercent(config.getInt("hard_cap_culling_priority_strategy_penalty_mob_percent"));
List<?> list;
list = config.getList("limits");
if (list != null) {
for (Object obj : list ) {
if (obj == null) {
this.pluginInstance.getLogger().warning("Possible bad limit in configuration file.");
continue;
}
//TODO: Figure out how to do this without suppression.
@SuppressWarnings("unchecked")
LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) obj;
EntityType type = EntityType.fromName(map.get("type").toString().trim());
if (type == null) {
this.pluginInstance.getLogger().warning("Unrecognized type '" + map.get("type").toString() + "' in configuration file.");
continue;
}
int limit = (Integer)map.get("limit");
CullType culling = CullType.fromName(map.get("culling").toString());
if (culling == null) {
this.pluginInstance.getLogger().warning("Unrecognized culling '" + map.get("culling").toString() + "' in configuration file.");
continue;
}
int range = (Integer)map.get("range");
if (range > 80) {
this.pluginInstance.getLogger().warning("range is > 80, ignoring this and setting to 80.");
range = 80;
}
setLimit(type, new ConfigurationLimit(limit, culling, range));
}
}
this.dirty = false;
}
private void setHardCapCullingPriorityStrategyPenaltyMobPercent(int perc) {
hardCapCullingPriorityStrategyPenaltyMobPercent = perc;
}
public float getHardCapCullingPriorityStrategyPenaltyMobPercent() {
return hardCapCullingPriorityStrategyPenaltyMobPercent / 100.f ;
}
/**
* Saves configuration values to the supplied plug-in instance.
*/
public void save() {
if (!this.dirty) {
return;
}
FileConfiguration config = this.pluginInstance.getConfig();
config.set("damage", this.damage);
config.set("damage_chance", this.damageChance);
config.set("damage_count", this.damageCalls);
config.set("ticks_between_damage", this.ticksBetweenDamage);
config.set("mob_limit", this.mobLimit);
config.set("mob_limit_percent", this.mobLimitPercent);
config.set("damage_notify", this.damageNotify);
config.set("enable_monster_cull_to_spawn", this.enableMonsterCullToSpawn);
config.set("max_monster_cull_aggression", this.maximumMonsterCullAggression);
config.set("min_monster_cull_aggression", this.minimumMonsterCullAggression);
config.set("max_monster_cull_per_pass", this.maximumMonsterCullPerPass);
config.set("mob_max_mob", this.maxMob);
config.set("mob_player_multiplier", this.playerMultiplier);
config.set("ticks_between_hard_cap", this.ticksBetweenHardCap);
config.set("hard_cap_culling_strategy", this.hardCapCullingStrategy);
config.set("hard_cap_culling_priority_strategy_penalty_mob_percent", this.hardCapCullingPriorityStrategyPenaltyMobPercent);
this.pluginInstance.saveConfig();
this.dirty = false;
}
/**
* Returns the amount of damage to apply to a crowded mob.
* @return The amount of damage to apply to a crowded mob.
*/
public int getDamage() {
return damage;
}
/**
* Sets the amount of damage to apply to a crowded mob.
* @param damage The amount of damage to apply to a crowded mob.
*/
public void setDamage(int damage) {
if (damage <= 0) {
this.pluginInstance.getLogger().info("Warning: damage is <= 0, possibly wasting cpu cycles.");
}
this.damage = damage;
this.dirty = true;
}
/**
* Sets the ConfigurationLimit for the specified mob type. Don't add
* limits you don't need.
*
* @param type The type of entity to set a ConfigurationLimit for.
* @param limit The limit for the entity type.
*/
public void setLimit(EntityType type, ConfigurationLimit limit) {
switch (limit.getCulling()) {
case DAMAGE:
this.hasDamageLimits = true;
break;
case SPAWN:
case SPAWNER:
this.hasSpawnLimits = true;
break;
}
if (mobLimits.containsKey(type)) {
List<ConfigurationLimit> otherLimits = mobLimits.get(type);
boolean foundOneToEdit = false;
for (ConfigurationLimit otherLimit : otherLimits) {
if (0 == otherLimit.getCulling().compareTo(limit.getCulling())) {
otherLimit.setLimit(limit.getLimit());
otherLimit.setRange(limit.getRange());
foundOneToEdit = true;
break;
}
}
if (!foundOneToEdit) {
otherLimits.add(limit);
}
}
else {
List<ConfigurationLimit> otherLimits = new ArrayList<ConfigurationLimit>();
otherLimits.add(limit);
mobLimits.put(type, otherLimits);
}
this.dirty = true;
this.pluginInstance.getLogger().info("Culling " + type.toString() + " using " + limit.getCulling().toString() + "; limit=" + limit.getLimit() + " range=" + limit.getRange());
}
/**
* Returns the ConfigurationLimits for the specified mob type.
* @param type The type of entity to get a ConfigurationLimit for.
* @return The limits for the entity type, or null.
*/
public List<ConfigurationLimit> getLimits(EntityType type) {
return mobLimits.get(type);
}
/**
* Returns whether or not we have limits with CullType SPAWN or SPAWNER.
* @return true if there are any mobs with SPAWN or SPAWNER CullTypes, otherwise false.
*/
public boolean hasSpawnLimits() {
return hasSpawnLimits;
}
/**
* Returns whether or not we have limits with CullType DAMAGE.
* @return true if there are any mobs with DAMAGE CullType, otherwise false.
*/
public boolean hasDamageLimits() {
return hasDamageLimits;
}
/**
* Returns the number of ticks between calls to the damage laborer.
* @return Number of ticks between calls to the damage laborer.
*/
public long getTicksBetweenDamage() {
return ticksBetweenDamage;
}
/**
* Sets the number of ticks between calls to the damage laborer.
* @param ticksBetweenDamage Number of ticks between calls to the damage laborer.
*/
public void setTicksBetweenDamage(long ticksBetweenDamage) {
this.pluginInstance.getLogger().info("MusterCull will damage something every " + ticksBetweenDamage + " ticks.");
if (ticksBetweenDamage < 20) {
this.pluginInstance.getLogger().info("Warning: ticks_between_damage is < 20, probably won't run that fast.");
}
this.ticksBetweenDamage = ticksBetweenDamage;
this.dirty = true;
}
/**
* Returns the number of entities to take damage each time the laborer is called.
* @return Number of entities to take damage each time the laborer is called.
*/
public int getDamageCalls() {
return damageCalls;
}
/**
* Sets the number of entities to take damage each time the laborer is called.
* @param damageCalls Number of entities to take damage each time the laborer is called.
*/
public void setDamageCalls(int damageCalls) {
if (damageCalls <= 0) {
this.pluginInstance.getLogger().info("Warning: damage_count is <= 0, possibly wasting cpu cycles.");
}
else if (damageCalls > 5) {
this.pluginInstance.getLogger().info("Notice: damage_count is > 5, possibly killing performance.");
}
this.damageCalls = damageCalls;
this.dirty = true;
}
/**
* Returns the percent chance that a mob will be damaged when crowded.
* @return Percent chance that a mob will be damaged when crowded.
*/
public int getDamageChance() {
return damageChance;
}
/**
* Sets the percent chance that a mob will be damaged when crowded.
* @param damageChance Percent chance that a mob will be damaged when crowded.
*/
public void setDamageChance(int damageChance) {
if (damageChance <= 0) {
this.pluginInstance.getLogger().info("Warning: damage_chance is <= 0, possibly wasting cpu cycles.");
}
else if (damageChance > 100) {
this.pluginInstance.getLogger().info("Notice: damage_chance is > 100 when 100 is the limit. Pedantry.");
}
this.damageChance = damageChance;
this.dirty = true;
}
/**
* Returns the limit on mobs before the damage laborer cares to act.
* @return The limit on mobs before the damage laborer cares to act.
*/
public int getMobLimit() {
return this.mobLimit;
}
/**
* Sets the limit on mobs before the damage laborer cares to act.
* @param mobLimit The limit on mobs before the damage laborer cares to act.
*/
public void setMobLimit(int mobLimit) {
if (mobLimit < 0) {
this.pluginInstance.getLogger().info("Warning: mob_limit is < 0 when 0 is the limit. Pedantry.");
}
if (mobLimit > 5000) {
this.pluginInstance.getLogger().info("Warning: mob_limit is > 5000. Damage laborer may never run.");
}
this.mobLimit = mobLimit;
this.dirty = true;
}
/**
* Returns the percent part per total before the damage laborer queues mobs.
* @return The percent part per total before the damage laborer queues mobs.
*/
public int getMobLimitPercent() {
return this.mobLimitPercent;
}
/**
* Sets the percent part per total before the damage laborer queues mobs.
* @param mobLimitPercent The percent part per total before the damage laborer queues mobs.
*/
public void setMobLimitPercent(int mobLimitPercent) {
if (mobLimitPercent < 0) {
this.pluginInstance.getLogger().info("Warning: mob_limit_percent is < 0 when 0 is the limit. Pedantry.");
}
if (mobLimitPercent > 100) {
this.pluginInstance.getLogger().info("Warning: mob_limit_percent is > 100 when 100 is the limit. Pedantry.");
}
this.mobLimitPercent = mobLimitPercent;
this.dirty = true;
}
/**
* Returns the hard mob cap.
* @return The hard mob cap.
*/
public int getMaxMob(){
return this.maxMob;
}
/**
* Sets the hard mob cap.
* @param maxMob The hard mob cap.
*/
public void setMaxMob(int maxMob) {
if (maxMob < 0) {
this.pluginInstance.getLogger().info("Warning: maxMob is < 0 when 0 is the limit. Pedantry.");
}
this.maxMob = maxMob;
this.dirty = true;
}
/**
* Returns how many mobs permitted less of the maximum, per player.
* @return How many mobs permitted less of the maximum, per player.
*/
public int getPlayerMultiplier(){
return this.playerMultiplier;
}
/**
* Sets how many mobs permitted less of the maximum, per player.
* @param playerMultiplier How many mobs permitted less of the maximum, per player.
*/
public void setPlayerMultiplier(int playerMultiplier) {
if (playerMultiplier < 0) {
this.pluginInstance.getLogger().info("Warning: playerMultiplier is < 0 when 0 is the limit. Pedantry.");
}
this.playerMultiplier = playerMultiplier;
this.dirty = true;
}
/**
* Returns number of ticks between calls to the hard cap laborer.
* @return number of ticks between calls to the hard cap laborer.
*/
public long getTicksBetweenHardCap(){
return ticksBetweenHardCap;
}
/**
* Sets the culling strategy.
* @param cullingStrategy is either RANDOM or PRIORITY to determine if we should randomize culling or cull items based on what is least likely to be missed vs most likely.
*/
public void setHardCapCullingStrategy(String cullingStrategy) {
cullingStrategy = cullingStrategy.toUpperCase();
if (!cullingStrategy.equals("RANDOM") && !cullingStrategy.equals("PRIORITY"))
{
pluginInstance.getLogger().warning("hard_cap_culling_strategy not an allowed value (needs RANDOM or PRIORITY - has " + cullingStrategy + ".");
return;
}
this.hardCapCullingStrategy = cullingStrategy;
pluginInstance.getLogger().info("MusterCull hard cap culling strategy = " + this.hardCapCullingStrategy + ".");
dirty = true;
}
public GlobalCullCullingStrategyType getHardCapCullingStrategy() {
return GlobalCullCullingStrategyType.fromName(hardCapCullingStrategy);
}
/**
* Sets the number of ticks between calls to the hard cap laborer.
* @param ticksBetween Number of ticks between calls to the damage laborer.
*/
public void setTicksBetweenHardCap(long ticksBetween) {
pluginInstance.getLogger().info("MusterCull will kill something every " + ticksBetween + " ticks.");
if (ticksBetween < 200) {
pluginInstance.getLogger().warning("ticks_between_hard_cap is < 200, ignoring this and setting to 200.");
ticksBetween = 200;
}
ticksBetweenHardCap = ticksBetween;
dirty = true;
}
/**
* Gets whether to notify when an entity is damaged by this plugin.
*/
public boolean getDamageNotify() {
return this.damageNotify;
}
/**
* Sets whether to notify when an entity is damaged by this plugin.
* @param damageNotify Whether to notify when an entity is damaged by this plugin.
*/
public void setDamageNotify(boolean damageNotify) {
this.damageNotify = damageNotify;
this.dirty = true;
}
public boolean monsterCullToSpawnEnabled() {
return enableMonsterCullToSpawn;
}
public int getMaximumMonsterCullPerPass() {
return maximumMonsterCullPerPass;
}
public int getMaximumMonsterCullAggression() {
return maximumMonsterCullAggression;
}
public int getMinimumMonsterCullAggression() {
return minimumMonsterCullAggression;
}
public void setEnableMonsterCullToSpawn(boolean enableMonsterCullToSpawn) {
this.enableMonsterCullToSpawn = enableMonsterCullToSpawn;
if (monsterCullToSpawnEnabled()) {
this.pluginInstance.getLogger().info("Monster cull: Up to " + getMaximumMonsterCullPerPass() + " mobs per run, aggression is " + getMinimumMonsterCullAggression() + " to " + getMaximumMonsterCullAggression() + ".");
}
}
public void setMaximumMonsterCullPerPass(int maximumMonsterCullPerPass) {
this.maximumMonsterCullPerPass = maximumMonsterCullPerPass;
if (monsterCullToSpawnEnabled()) {
this.pluginInstance.getLogger().info("Monster cull: Up to " + getMaximumMonsterCullPerPass() + " mobs per run, aggression is " + getMinimumMonsterCullAggression() + " to " + getMaximumMonsterCullAggression() + ".");
}
}
public void setMaximumMonsterCullAggression(int maximumMonsterCullAggression) {
this.maximumMonsterCullAggression = maximumMonsterCullAggression;
if (monsterCullToSpawnEnabled()) {
this.pluginInstance.getLogger().info("Monster cull: Up to " + getMaximumMonsterCullPerPass() + " mobs per run, aggression is " + getMinimumMonsterCullAggression() + " to " + getMaximumMonsterCullAggression() + ".");
}
}
public void setMinimumMonsterCullAggression(int minimumMonsterCullAggression) {
this.minimumMonsterCullAggression = minimumMonsterCullAggression;
if (monsterCullToSpawnEnabled()) {
this.pluginInstance.getLogger().info("Monster cull: Up to " + getMaximumMonsterCullPerPass() + " mobs per run, aggression is " + getMinimumMonsterCullAggression() + " to " + getMaximumMonsterCullAggression() + ".");
}
}
}
| MusterCull/src/com/untamedears/mustercull/Configuration.java | package com.untamedears.mustercull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.EntityType;
import org.bukkit.plugin.java.JavaPlugin;
/**
* Manages the configuration for the plug-in.
*
* @author Celdecea
*
*/
public class Configuration {
/**
* Whether or not configuration data needs to be saved.
*/
private boolean dirty = false;
/**
* The amount of damage to apply to a crowded mob.
*/
private int damage = 0;
/**
* Mob limits loaded from the configuration file.
*/
private Map<EntityType, List<ConfigurationLimit>> mobLimits = new HashMap<EntityType, List<ConfigurationLimit>>();
/**
* Whether or not we have limits with CullType DAMAGE.
*
* This is used by the MusterCull class to determine if the tick laborer
* needs to be started.
*/
private boolean hasDamageLimits = false;
/**
* Whether or not we have limits with CullTypes SPAWN or SPAWNER.
*
* This is used by the MusterCull class to determine if the event listener
* needs to be registered.
*/
private boolean hasSpawnLimits = false;
/**
* Number of ticks between calls to the chunk damage laborer.
*/
private long ticksBetweenDamage = 20L;
/**
* Number of entities to damage every time the damage laborer runs.
*/
private int damageCalls = 1;
/**
* Percent chance that a mob will be damaged when crowded.
*/
private int damageChance = 75;
/**
* Hard number on mobs before the damage laborer cares to run.
*/
private int mobLimit = 1;
/**
* Percentage of mobLimit each mob must be to trigger damage culling
*/
private int mobLimitPercent = 1;
/**
* Whether or not to notify when entities have been damaged.
*/
private boolean damageNotify = false;
/**
* The hard mob limit. Also however many mobs can exist with no players.
*/
private int maxMob = 10000;
/**
* How many mobs permitted less of the maximum, per player.
*/
private int playerMultiplier = 5;
/**
* Number of ticks between calls to the living entity hard cap (HardCapLaborer).
*/
private long ticksBetweenHardCap = 40L;
/**
* Whether to perform the monster cull pass to keep them within world spawn limits.
*/
private boolean enableMonsterCullToSpawn = true;
/**
* The maximum number of monsters to cull in a monster cull pass.
*/
private int maximumMonsterCullPerPass = 30;
/**
* The maximum aggression factor for the monster cull.
*/
private int minimumMonsterCullAggression = 0;
/**
* The maximum aggression factor for the monster cull.
*/
private int maximumMonsterCullAggression = 5;
/**
* Holds a reference to the Bukkit JavaPlugin for this project
*/
private JavaPlugin pluginInstance = null;
/**
* Percent that a super-chunk must contain of total server pop in order to qualify for a penalty purge.
*/
private int hardCapCullingPriorityStrategyPenaltyMobPercent = 100;
/**
* Culling strategy for hard-cap culling. RANDOM or PRIORITY
*/
private String hardCapCullingStrategy = "RANDOM";
/**
* Constructor which stores a reference to the Bukkit JavaPlugin we are using.
* @param plugin A reference to a Bukkit JavaPlugin.
*/
Configuration(JavaPlugin plugin) {
this.pluginInstance = plugin;
}
/**
* Loads configuration values from the supplied plug-in instance.
*/
public void load() {
FileConfiguration config = this.pluginInstance.getConfig();
this.setDamage(config.getInt("damage"));
this.setDamageChance(config.getInt("damage_chance"));
this.setDamageCalls(config.getInt("damage_count"));
this.setTicksBetweenDamage(config.getInt("ticks_between_damage"));
this.setMobLimit(config.getInt("mob_limit"));
this.setMobLimitPercent(config.getInt("mob_limit_percent"));
this.setDamageNotify(config.getBoolean("damage_notify"));
this.setMaximumMonsterCullAggression(config.getInt("max_monster_cull_aggression"));
this.setMinimumMonsterCullAggression(config.getInt("min_monster_cull_aggression"));
this.setMaximumMonsterCullPerPass(config.getInt("max_monster_cull_per_pass"));
this.setEnableMonsterCullToSpawn(config.getBoolean("enable_monster_cull_to_spawn"));
this.setMaxMob(config.getInt("mob_max_mob"));
this.setPlayerMultiplier(config.getInt("mob_player_multiplier"));
this.setTicksBetweenHardCap(config.getInt("ticks_between_hard_cap"));
this.setHardCapCullingStrategy(config.getString("hard_cap_culling_strategy"));
this.setHardCapCullingPriorityStrategyPenaltyMobPercent(config.getInt("hard_cap_culling_priority_strategy_penalty_mob_percent"));
List<?> list;
list = config.getList("limits");
if (list != null) {
for (Object obj : list ) {
if (obj == null) {
this.pluginInstance.getLogger().warning("Possible bad limit in configuration file.");
continue;
}
//TODO: Figure out how to do this without suppression.
@SuppressWarnings("unchecked")
LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) obj;
EntityType type = EntityType.fromName(map.get("type").toString().trim());
if (type == null) {
this.pluginInstance.getLogger().warning("Unrecognized type '" + map.get("type").toString() + "' in configuration file.");
continue;
}
int limit = (Integer)map.get("limit");
CullType culling = CullType.fromName(map.get("culling").toString());
if (culling == null) {
this.pluginInstance.getLogger().warning("Unrecognized culling '" + map.get("culling").toString() + "' in configuration file.");
continue;
}
int range = (Integer)map.get("range");
if (range > 80) {
this.pluginInstance.getLogger().warning("limit is > 80, ignoring this and setting to 80.");
range = 80;
}
setLimit(type, new ConfigurationLimit(limit, culling, range));
}
}
this.dirty = false;
}
private void setHardCapCullingPriorityStrategyPenaltyMobPercent(int perc) {
hardCapCullingPriorityStrategyPenaltyMobPercent = perc;
}
public float getHardCapCullingPriorityStrategyPenaltyMobPercent() {
return hardCapCullingPriorityStrategyPenaltyMobPercent / 100.f ;
}
/**
* Saves configuration values to the supplied plug-in instance.
*/
public void save() {
if (!this.dirty) {
return;
}
FileConfiguration config = this.pluginInstance.getConfig();
config.set("damage", this.damage);
config.set("damage_chance", this.damageChance);
config.set("damage_count", this.damageCalls);
config.set("ticks_between_damage", this.ticksBetweenDamage);
config.set("mob_limit", this.mobLimit);
config.set("mob_limit_percent", this.mobLimitPercent);
config.set("damage_notify", this.damageNotify);
config.set("enable_monster_cull_to_spawn", this.enableMonsterCullToSpawn);
config.set("max_monster_cull_aggression", this.maximumMonsterCullAggression);
config.set("min_monster_cull_aggression", this.minimumMonsterCullAggression);
config.set("max_monster_cull_per_pass", this.maximumMonsterCullPerPass);
config.set("mob_max_mob", this.maxMob);
config.set("mob_player_multiplier", this.playerMultiplier);
config.set("ticks_between_hard_cap", this.ticksBetweenHardCap);
config.set("hard_cap_culling_strategy", this.hardCapCullingStrategy);
config.set("hard_cap_culling_priority_strategy_penalty_mob_percent", this.hardCapCullingPriorityStrategyPenaltyMobPercent);
this.pluginInstance.saveConfig();
this.dirty = false;
}
/**
* Returns the amount of damage to apply to a crowded mob.
* @return The amount of damage to apply to a crowded mob.
*/
public int getDamage() {
return damage;
}
/**
* Sets the amount of damage to apply to a crowded mob.
* @param damage The amount of damage to apply to a crowded mob.
*/
public void setDamage(int damage) {
if (damage <= 0) {
this.pluginInstance.getLogger().info("Warning: damage is <= 0, possibly wasting cpu cycles.");
}
this.damage = damage;
this.dirty = true;
}
/**
* Sets the ConfigurationLimit for the specified mob type. Don't add
* limits you don't need.
*
* @param type The type of entity to set a ConfigurationLimit for.
* @param limit The limit for the entity type.
*/
public void setLimit(EntityType type, ConfigurationLimit limit) {
switch (limit.getCulling()) {
case DAMAGE:
this.hasDamageLimits = true;
break;
case SPAWN:
case SPAWNER:
this.hasSpawnLimits = true;
break;
}
if (mobLimits.containsKey(type)) {
List<ConfigurationLimit> otherLimits = mobLimits.get(type);
boolean foundOneToEdit = false;
for (ConfigurationLimit otherLimit : otherLimits) {
if (0 == otherLimit.getCulling().compareTo(limit.getCulling())) {
otherLimit.setLimit(limit.getLimit());
otherLimit.setRange(limit.getRange());
foundOneToEdit = true;
break;
}
}
if (!foundOneToEdit) {
otherLimits.add(limit);
}
}
else {
List<ConfigurationLimit> otherLimits = new ArrayList<ConfigurationLimit>();
otherLimits.add(limit);
mobLimits.put(type, otherLimits);
}
this.dirty = true;
this.pluginInstance.getLogger().info("Culling " + type.toString() + " using " + limit.getCulling().toString() + "; limit=" + limit.getLimit() + " range=" + limit.getRange());
}
/**
* Returns the ConfigurationLimits for the specified mob type.
* @param type The type of entity to get a ConfigurationLimit for.
* @return The limits for the entity type, or null.
*/
public List<ConfigurationLimit> getLimits(EntityType type) {
return mobLimits.get(type);
}
/**
* Returns whether or not we have limits with CullType SPAWN or SPAWNER.
* @return true if there are any mobs with SPAWN or SPAWNER CullTypes, otherwise false.
*/
public boolean hasSpawnLimits() {
return hasSpawnLimits;
}
/**
* Returns whether or not we have limits with CullType DAMAGE.
* @return true if there are any mobs with DAMAGE CullType, otherwise false.
*/
public boolean hasDamageLimits() {
return hasDamageLimits;
}
/**
* Returns the number of ticks between calls to the damage laborer.
* @return Number of ticks between calls to the damage laborer.
*/
public long getTicksBetweenDamage() {
return ticksBetweenDamage;
}
/**
* Sets the number of ticks between calls to the damage laborer.
* @param ticksBetweenDamage Number of ticks between calls to the damage laborer.
*/
public void setTicksBetweenDamage(long ticksBetweenDamage) {
this.pluginInstance.getLogger().info("MusterCull will damage something every " + ticksBetweenDamage + " ticks.");
if (ticksBetweenDamage < 20) {
this.pluginInstance.getLogger().info("Warning: ticks_between_damage is < 20, probably won't run that fast.");
}
this.ticksBetweenDamage = ticksBetweenDamage;
this.dirty = true;
}
/**
* Returns the number of entities to take damage each time the laborer is called.
* @return Number of entities to take damage each time the laborer is called.
*/
public int getDamageCalls() {
return damageCalls;
}
/**
* Sets the number of entities to take damage each time the laborer is called.
* @param damageCalls Number of entities to take damage each time the laborer is called.
*/
public void setDamageCalls(int damageCalls) {
if (damageCalls <= 0) {
this.pluginInstance.getLogger().info("Warning: damage_count is <= 0, possibly wasting cpu cycles.");
}
else if (damageCalls > 5) {
this.pluginInstance.getLogger().info("Notice: damage_count is > 5, possibly killing performance.");
}
this.damageCalls = damageCalls;
this.dirty = true;
}
/**
* Returns the percent chance that a mob will be damaged when crowded.
* @return Percent chance that a mob will be damaged when crowded.
*/
public int getDamageChance() {
return damageChance;
}
/**
* Sets the percent chance that a mob will be damaged when crowded.
* @param damageChance Percent chance that a mob will be damaged when crowded.
*/
public void setDamageChance(int damageChance) {
if (damageChance <= 0) {
this.pluginInstance.getLogger().info("Warning: damage_chance is <= 0, possibly wasting cpu cycles.");
}
else if (damageChance > 100) {
this.pluginInstance.getLogger().info("Notice: damage_chance is > 100 when 100 is the limit. Pedantry.");
}
this.damageChance = damageChance;
this.dirty = true;
}
/**
* Returns the limit on mobs before the damage laborer cares to act.
* @return The limit on mobs before the damage laborer cares to act.
*/
public int getMobLimit() {
return this.mobLimit;
}
/**
* Sets the limit on mobs before the damage laborer cares to act.
* @param mobLimit The limit on mobs before the damage laborer cares to act.
*/
public void setMobLimit(int mobLimit) {
if (mobLimit < 0) {
this.pluginInstance.getLogger().info("Warning: mob_limit is < 0 when 0 is the limit. Pedantry.");
}
if (mobLimit > 5000) {
this.pluginInstance.getLogger().info("Warning: mob_limit is > 5000. Damage laborer may never run.");
}
this.mobLimit = mobLimit;
this.dirty = true;
}
/**
* Returns the percent part per total before the damage laborer queues mobs.
* @return The percent part per total before the damage laborer queues mobs.
*/
public int getMobLimitPercent() {
return this.mobLimitPercent;
}
/**
* Sets the percent part per total before the damage laborer queues mobs.
* @param mobLimitPercent The percent part per total before the damage laborer queues mobs.
*/
public void setMobLimitPercent(int mobLimitPercent) {
if (mobLimitPercent < 0) {
this.pluginInstance.getLogger().info("Warning: mob_limit_percent is < 0 when 0 is the limit. Pedantry.");
}
if (mobLimitPercent > 100) {
this.pluginInstance.getLogger().info("Warning: mob_limit_percent is > 100 when 100 is the limit. Pedantry.");
}
this.mobLimitPercent = mobLimitPercent;
this.dirty = true;
}
/**
* Returns the hard mob cap.
* @return The hard mob cap.
*/
public int getMaxMob(){
return this.maxMob;
}
/**
* Sets the hard mob cap.
* @param maxMob The hard mob cap.
*/
public void setMaxMob(int maxMob) {
if (maxMob < 0) {
this.pluginInstance.getLogger().info("Warning: maxMob is < 0 when 0 is the limit. Pedantry.");
}
this.maxMob = maxMob;
this.dirty = true;
}
/**
* Returns how many mobs permitted less of the maximum, per player.
* @return How many mobs permitted less of the maximum, per player.
*/
public int getPlayerMultiplier(){
return this.playerMultiplier;
}
/**
* Sets how many mobs permitted less of the maximum, per player.
* @param playerMultiplier How many mobs permitted less of the maximum, per player.
*/
public void setPlayerMultiplier(int playerMultiplier) {
if (playerMultiplier < 0) {
this.pluginInstance.getLogger().info("Warning: playerMultiplier is < 0 when 0 is the limit. Pedantry.");
}
this.playerMultiplier = playerMultiplier;
this.dirty = true;
}
/**
* Returns number of ticks between calls to the hard cap laborer.
* @return number of ticks between calls to the hard cap laborer.
*/
public long getTicksBetweenHardCap(){
return ticksBetweenHardCap;
}
/**
* Sets the culling strategy.
* @param cullingStrategy is either RANDOM or PRIORITY to determine if we should randomize culling or cull items based on what is least likely to be missed vs most likely.
*/
public void setHardCapCullingStrategy(String cullingStrategy) {
cullingStrategy = cullingStrategy.toUpperCase();
if (!cullingStrategy.equals("RANDOM") && !cullingStrategy.equals("PRIORITY"))
{
pluginInstance.getLogger().warning("hard_cap_culling_strategy not an allowed value (needs RANDOM or PRIORITY - has " + cullingStrategy + ".");
return;
}
this.hardCapCullingStrategy = cullingStrategy;
pluginInstance.getLogger().info("MusterCull hard cap culling strategy = " + this.hardCapCullingStrategy + ".");
dirty = true;
}
public GlobalCullCullingStrategyType getHardCapCullingStrategy() {
return GlobalCullCullingStrategyType.fromName(hardCapCullingStrategy);
}
/**
* Sets the number of ticks between calls to the hard cap laborer.
* @param ticksBetween Number of ticks between calls to the damage laborer.
*/
public void setTicksBetweenHardCap(long ticksBetween) {
pluginInstance.getLogger().info("MusterCull will kill something every " + ticksBetween + " ticks.");
if (ticksBetween < 200) {
pluginInstance.getLogger().warning("ticks_between_hard_cap is < 200, ignoring this and setting to 200.");
ticksBetween = 200;
}
ticksBetweenHardCap = ticksBetween;
dirty = true;
}
/**
* Gets whether to notify when an entity is damaged by this plugin.
*/
public boolean getDamageNotify() {
return this.damageNotify;
}
/**
* Sets whether to notify when an entity is damaged by this plugin.
* @param damageNotify Whether to notify when an entity is damaged by this plugin.
*/
public void setDamageNotify(boolean damageNotify) {
this.damageNotify = damageNotify;
this.dirty = true;
}
public boolean monsterCullToSpawnEnabled() {
return enableMonsterCullToSpawn;
}
public int getMaximumMonsterCullPerPass() {
return maximumMonsterCullPerPass;
}
public int getMaximumMonsterCullAggression() {
return maximumMonsterCullAggression;
}
public int getMinimumMonsterCullAggression() {
return minimumMonsterCullAggression;
}
public void setEnableMonsterCullToSpawn(boolean enableMonsterCullToSpawn) {
this.enableMonsterCullToSpawn = enableMonsterCullToSpawn;
if (monsterCullToSpawnEnabled()) {
this.pluginInstance.getLogger().info("Monster cull: Up to " + getMaximumMonsterCullPerPass() + " mobs per run, aggression is " + getMinimumMonsterCullAggression() + " to " + getMaximumMonsterCullAggression() + ".");
}
}
public void setMaximumMonsterCullPerPass(int maximumMonsterCullPerPass) {
this.maximumMonsterCullPerPass = maximumMonsterCullPerPass;
if (monsterCullToSpawnEnabled()) {
this.pluginInstance.getLogger().info("Monster cull: Up to " + getMaximumMonsterCullPerPass() + " mobs per run, aggression is " + getMinimumMonsterCullAggression() + " to " + getMaximumMonsterCullAggression() + ".");
}
}
public void setMaximumMonsterCullAggression(int maximumMonsterCullAggression) {
this.maximumMonsterCullAggression = maximumMonsterCullAggression;
if (monsterCullToSpawnEnabled()) {
this.pluginInstance.getLogger().info("Monster cull: Up to " + getMaximumMonsterCullPerPass() + " mobs per run, aggression is " + getMinimumMonsterCullAggression() + " to " + getMaximumMonsterCullAggression() + ".");
}
}
public void setMinimumMonsterCullAggression(int minimumMonsterCullAggression) {
this.minimumMonsterCullAggression = minimumMonsterCullAggression;
if (monsterCullToSpawnEnabled()) {
this.pluginInstance.getLogger().info("Monster cull: Up to " + getMaximumMonsterCullPerPass() + " mobs per run, aggression is " + getMinimumMonsterCullAggression() + " to " + getMaximumMonsterCullAggression() + ".");
}
}
}
| Update Configuration.java
Just noticed a typo | MusterCull/src/com/untamedears/mustercull/Configuration.java | Update Configuration.java | <ide><path>usterCull/src/com/untamedears/mustercull/Configuration.java
<ide> int range = (Integer)map.get("range");
<ide>
<ide> if (range > 80) {
<del> this.pluginInstance.getLogger().warning("limit is > 80, ignoring this and setting to 80.");
<add> this.pluginInstance.getLogger().warning("range is > 80, ignoring this and setting to 80.");
<ide> range = 80;
<ide> }
<ide> |
|
Java | apache-2.0 | 56e34e7977a1e1ce72aefa6336cc1f5370defb37 | 0 | tristantarrant/JGroups,TarantulaTechnology/JGroups,danberindei/JGroups,slaskawi/JGroups,vjuranek/JGroups,Sanne/JGroups,deepnarsay/JGroups,pruivo/JGroups,rvansa/JGroups,rhusar/JGroups,rhusar/JGroups,slaskawi/JGroups,kedzie/JGroups,pferraro/JGroups,ligzy/JGroups,vjuranek/JGroups,rpelisse/JGroups,ibrahimshbat/JGroups,Sanne/JGroups,rvansa/JGroups,pferraro/JGroups,slaskawi/JGroups,Sanne/JGroups,tristantarrant/JGroups,dimbleby/JGroups,danberindei/JGroups,pruivo/JGroups,ibrahimshbat/JGroups,kedzie/JGroups,TarantulaTechnology/JGroups,ibrahimshbat/JGroups,belaban/JGroups,pferraro/JGroups,belaban/JGroups,rpelisse/JGroups,ligzy/JGroups,deepnarsay/JGroups,rhusar/JGroups,pruivo/JGroups,kedzie/JGroups,dimbleby/JGroups,deepnarsay/JGroups,ligzy/JGroups,ibrahimshbat/JGroups,vjuranek/JGroups,TarantulaTechnology/JGroups,danberindei/JGroups,dimbleby/JGroups,rpelisse/JGroups,belaban/JGroups | // $Id: ConnectionTableNIO.java,v 1.13 2006/05/17 08:00:08 belaban Exp $
package org.jgroups.blocks;
import EDU.oswego.cs.dl.util.concurrent.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jgroups.Address;
import org.jgroups.Version;
import org.jgroups.protocols.TCP_NIO;
import org.jgroups.stack.IpAddress;
import org.jgroups.util.Util;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
/**
* Manages incoming and outgoing TCP connections. For each outgoing message to destination P, if there
* is not yet a connection for P, one will be created. Subsequent outgoing messages will use this
* connection. For incoming messages, one server socket is created at startup. For each new incoming
* client connecting, a new thread from a thread pool is allocated and listens for incoming messages
* until the socket is closed by the peer.<br>Sockets/threads with no activity will be killed
* after some time.
* <p/>
* Incoming messages from any of the sockets can be received by setting the message listener.
*
* @author Bela Ban, Scott Marlow, Alex Fu
*/
public class ConnectionTableNIO extends ConnectionTable implements Runnable {
private ServerSocketChannel m_serverSocketChannel;
private Selector m_acceptSelector;
protected final static Log LOG = LogFactory.getLog(ConnectionTableNIO.class);
private WriteHandler[] m_writeHandlers;
private int m_nextWriteHandler = 0;
private final Object m_lockNextWriteHandler = new Object();
private ReadHandler[] m_readHandlers;
private int m_nextReadHandler = 0;
private final Object m_lockNextReadHandler = new Object();
// thread pool for processing read requests
private Executor m_requestProcessors;
/**
* @param srv_port
* @throws Exception
*/
public ConnectionTableNIO(int srv_port) throws Exception {
super(srv_port);
}
/**
* @param srv_port
* @param reaper_interval
* @param conn_expire_time
* @throws Exception
*/
public ConnectionTableNIO(int srv_port, long reaper_interval,
long conn_expire_time) throws Exception {
super(srv_port, reaper_interval, conn_expire_time);
}
/**
* @param r
* @param bind_addr
* @param external_addr
* @param srv_port
* @param max_port
* @throws Exception
*/
public ConnectionTableNIO(Receiver r, InetAddress bind_addr, InetAddress external_addr, int srv_port, int max_port
)
throws Exception
{
super(r, bind_addr, external_addr, srv_port, max_port);
}
/**
* @param r
* @param bind_addr
* @param external_addr
* @param srv_port
* @param max_port
* @param reaper_interval
* @param conn_expire_time
* @throws Exception
*/
public ConnectionTableNIO(Receiver r, InetAddress bind_addr, InetAddress external_addr, int srv_port, int max_port,
long reaper_interval, long conn_expire_time
) throws Exception
{
super(r, bind_addr, external_addr, srv_port, max_port, reaper_interval, conn_expire_time);
}
/**
* Try to obtain correct Connection (or create one if not yet existent)
*/
ConnectionTable.Connection getConnection(Address dest) throws Exception
{
Connection conn = null;
SocketChannel sock_ch;
synchronized (conns)
{
conn = (Connection) conns.get(dest);
if (conn == null)
{
InetSocketAddress destAddress = new InetSocketAddress(((IpAddress) dest).getIpAddress(),
((IpAddress) dest).getPort());
sock_ch = SocketChannel.open(destAddress);
conn = new Connection(sock_ch, dest);
conn.sendLocalAddress(local_addr);
// This outbound connection is ready
conn.getReadState().setHandShakingStatus(ConnectionReadState.HANDSHAKINGFIN);
// Set channel to be non-block only after hand shaking
try
{
sock_ch.configureBlocking(false);
} catch (IOException e)
{
// No way to handle the blocking socket
conn.destroy();
throw e;
}
try
{
if (LOG.isTraceEnabled())
LOG.trace("About to change new connection send buff size from " + sock_ch.socket().getSendBufferSize() + " bytes");
sock_ch.socket().setSendBufferSize(send_buf_size);
if (LOG.isTraceEnabled())
LOG.trace("Changed new connection send buff size to " + sock_ch.socket().getSendBufferSize() + " bytes");
}
catch (IllegalArgumentException ex)
{
if (log.isErrorEnabled()) log.error("exception setting send buffer size to " +
send_buf_size + " bytes: " + ex);
}
try
{
if (LOG.isTraceEnabled())
LOG.trace("About to change new connection receive buff size from " + sock_ch.socket().getReceiveBufferSize() + " bytes");
sock_ch.socket().setReceiveBufferSize(recv_buf_size);
if (LOG.isTraceEnabled())
LOG.trace("Changed new connection receive buff size to " + sock_ch.socket().getReceiveBufferSize() + " bytes");
}
catch (IllegalArgumentException ex)
{
if (log.isErrorEnabled()) log.error("exception setting receive buffer size to " +
send_buf_size + " bytes: " + ex);
}
int idx;
synchronized (m_lockNextWriteHandler)
{
idx = m_nextWriteHandler = (m_nextWriteHandler + 1) % m_writeHandlers.length;
}
conn.setupWriteHandler(m_writeHandlers[idx]);
// Put the new connection to the queue
try
{
synchronized (m_lockNextReadHandler)
{
idx = m_nextReadHandler = (m_nextReadHandler + 1) % m_readHandlers.length;
}
m_readHandlers[idx].add(conn);
} catch (InterruptedException e)
{
if (LOG.isWarnEnabled())
LOG.warn("Thread (" +Thread.currentThread().getName() + ") was interrupted, closing connection", e);
// What can we do? Remove it from table then.
conn.destroy();
throw e;
}
// Add connection to table
addConnection(dest, conn);
notifyConnectionOpened(dest);
if (LOG.isInfoEnabled()) LOG.info("created socket to " + dest);
}
return conn;
}
}
protected void init()
throws Exception
{
TCP_NIO NIOreceiver = (TCP_NIO)receiver;
// use directExector if max thread pool size is less than or equal to zero.
if(NIOreceiver.getProcessorMaxThreads() <= 0) {
m_requestProcessors = new DirectExecutor();
}
else
{
// Create worker thread pool for processing incoming buffers
PooledExecutor requestProcessors = new PooledExecutor(new BoundedBuffer(NIOreceiver.getProcessorQueueSize()), NIOreceiver.getProcessorMaxThreads());
requestProcessors.setThreadFactory(new ThreadFactory() {
public Thread newThread(Runnable runnable) {
return new Thread(Util.getGlobalThreadGroup(), runnable);
}
});
requestProcessors.setMinimumPoolSize(NIOreceiver.getProcessorMinThreads());
requestProcessors.setKeepAliveTime(NIOreceiver.getProcessorKeepAliveTime());
requestProcessors.waitWhenBlocked();
requestProcessors.createThreads(NIOreceiver.getProcessorThreads());
m_requestProcessors = requestProcessors;
}
m_writeHandlers = WriteHandler.create(NIOreceiver.getWriterThreads());
m_readHandlers = new ReadHandler[NIOreceiver.getReaderThreads()];
for (int i = 0; i < m_readHandlers.length; i++)
m_readHandlers[i] = new ReadHandler();
}
/**
* Closes all open sockets, the server socket and all threads waiting for incoming messages
*/
public void stop()
{
if (m_serverSocketChannel.isOpen())
{
try
{
m_serverSocketChannel.close();
}
catch (Exception eat)
{
}
}
// Stop the main selector
m_acceptSelector.wakeup();
// Stop selector threads
for (int i = 0; i < m_readHandlers.length; i++)
{
try
{
m_readHandlers[i].add(new Shutdown());
} catch (InterruptedException e)
{
LOG.error("Thread ("+Thread.currentThread().getName() +") was interrupted, failed to shutdown selector", e);
}
}
for (int i = 0; i < m_writeHandlers.length; i++)
{
try
{
m_writeHandlers[i].QUEUE.put(new Shutdown());
m_writeHandlers[i].m_selector.wakeup();
} catch (InterruptedException e)
{
LOG.error("Thread ("+Thread.currentThread().getName() +") was interrupted, failed to shutdown selector", e);
}
}
// Stop the callback thread pool
if(m_requestProcessors instanceof PooledExecutor)
((PooledExecutor)m_requestProcessors).shutdownNow();
super.stop();
}
/**
* Acceptor thread. Continuously accept new connections and assign readhandler/writehandler
* to them.
*/
public void run()
{
Connection conn = null;
while (m_serverSocketChannel.isOpen())
{
int num = 0;
try
{
num = m_acceptSelector.select();
} catch (IOException e)
{
if (LOG.isWarnEnabled())
LOG.warn("Select operation on listening socket failed", e);
continue; // Give up this time
}
if (num > 0)
{
Set readyKeys = m_acceptSelector.selectedKeys();
for (Iterator i = readyKeys.iterator(); i.hasNext();)
{
SelectionKey key = (SelectionKey) i.next();
i.remove();
// We only deal with new incoming connections
ServerSocketChannel readyChannel = (ServerSocketChannel) key.channel();
SocketChannel client_sock_ch = null;
try
{
client_sock_ch = readyChannel.accept();
} catch (IOException e)
{
if (LOG.isWarnEnabled())
LOG.warn("Attempt to accept new connection from listening socket failed" , e);
// Give up this connection
continue;
}
if (LOG.isInfoEnabled())
LOG.info("accepted connection, client_sock=" + client_sock_ch.socket());
try
{
if (LOG.isTraceEnabled())
LOG.trace("About to change new connection send buff size from " + client_sock_ch.socket().getSendBufferSize() + " bytes");
client_sock_ch.socket().setSendBufferSize(send_buf_size);
if (LOG.isTraceEnabled())
LOG.trace("Changed new connection send buff size to " + client_sock_ch.socket().getSendBufferSize() + " bytes");
}
catch (IllegalArgumentException ex)
{
if (log.isErrorEnabled()) log.error("exception setting send buffer size to " +
send_buf_size + " bytes: " ,ex);
}
catch (SocketException e)
{
if (log.isErrorEnabled()) log.error("exception setting send buffer size to " +
send_buf_size + " bytes: " , e);
}
try
{
if (LOG.isTraceEnabled())
LOG.trace("About to change new connection receive buff size from " + client_sock_ch.socket().getReceiveBufferSize() + " bytes");
client_sock_ch.socket().setReceiveBufferSize(recv_buf_size);
if (LOG.isTraceEnabled())
LOG.trace("Changed new connection receive buff size to " + client_sock_ch.socket().getReceiveBufferSize() + " bytes");
}
catch (IllegalArgumentException ex)
{
if (log.isErrorEnabled()) log.error("exception setting receive buffer size to " +
send_buf_size + " bytes: " , ex);
}
catch (SocketException e)
{
if (log.isErrorEnabled()) log.error("exception setting receive buffer size to " +
recv_buf_size + " bytes: " , e);
}
conn = new Connection(client_sock_ch, null);
// Set it to be nonblocking
try
{
client_sock_ch.configureBlocking(false);
int idx;
synchronized (m_lockNextWriteHandler)
{
idx = m_nextWriteHandler = (m_nextWriteHandler + 1) % m_writeHandlers.length;
}
conn.setupWriteHandler(m_writeHandlers[idx]);
} catch (IOException e)
{
if (LOG.isWarnEnabled())
LOG.warn("Attempt to configure accepted connection failed" , e);
// Give up this connection if we cannot set it to non-block
conn.destroy();
continue;
}
catch (InterruptedException e)
{
if (LOG.isWarnEnabled())
LOG.warn("Attempt to configure accepted connection was interrupted", e);
// Give up this connection
conn.destroy();
continue;
}
try
{
int idx;
synchronized (m_lockNextReadHandler)
{
idx = m_nextReadHandler = (m_nextReadHandler + 1) % m_readHandlers.length;
}
m_readHandlers[idx].add(conn);
} catch (InterruptedException e)
{
if (LOG.isWarnEnabled())
LOG.warn("Attempt to configure read handler for accepted connection failed" , e);
// What can we do? Remove it from table then. -- not in table yet since we moved hand shaking
conn.destroy();
}
} // end of iteration
} // end of selected key > 0
} // end of thread
if (LOG.isTraceEnabled())
LOG.trace("acceptor thread terminated");
}
/**
* Finds first available port starting at start_port and returns server socket. Sets srv_port
*/
protected ServerSocket createServerSocket(int start_port, int end_port) throws Exception
{
this.m_acceptSelector = Selector.open();
m_serverSocketChannel = ServerSocketChannel.open();
m_serverSocketChannel.configureBlocking(false);
while (true)
{
try
{
SocketAddress sockAddr;
if (bind_addr == null)
{
sockAddr=new InetSocketAddress(start_port);
m_serverSocketChannel.socket().bind(sockAddr);
}
else
{
sockAddr=new InetSocketAddress(bind_addr, start_port);
m_serverSocketChannel.socket().bind(sockAddr, backlog);
}
}
catch (BindException bind_ex)
{
if (start_port == end_port)
throw (BindException) ((new BindException("No available port to bind to")).initCause(bind_ex));
start_port++;
continue;
}
catch (SocketException bind_ex)
{
if (start_port == end_port)
throw (BindException) ((new BindException("No available port to bind to")).initCause(bind_ex));
start_port++;
continue;
}
catch (IOException io_ex)
{
if (LOG.isErrorEnabled()) LOG.error("Attempt to bind serversocket failed, port="+start_port+", bind addr=" + bind_addr ,io_ex);
throw io_ex;
}
srv_port = start_port;
break;
}
m_serverSocketChannel.register(this.m_acceptSelector, SelectionKey.OP_ACCEPT);
return m_serverSocketChannel.socket();
}
// Represents shutdown
private static class Shutdown {
}
// ReadHandler has selector to deal with read, it runs in seperated thread
private class ReadHandler implements Runnable {
private Selector m_readSelector = null;
private Thread m_th = null;
private LinkedQueue m_queueNewConns = new LinkedQueue();
public ReadHandler()
{
// Open the selector and register the pipe
try
{
m_readSelector = Selector.open();
} catch (IOException e)
{
// Should never happen
e.printStackTrace();
throw new IllegalStateException(e.getMessage());
}
// Start thread
m_th = new Thread(thread_group, this, "nioReadSelectorThread");
m_th.setDaemon(true);
m_th.start();
}
private void add(Object conn) throws InterruptedException
{
m_queueNewConns.put(conn);
wakeup();
}
private void wakeup()
{
m_readSelector.wakeup();
}
public void run()
{
while (true)
{ // m_s can be closed by the management thread
int events = 0;
try
{
events = m_readSelector.select();
} catch (IOException e)
{
if (LOG.isWarnEnabled())
LOG.warn("Select operation on socket failed", e);
continue; // Give up this time
} catch (ClosedSelectorException e)
{
if (LOG.isWarnEnabled())
LOG.warn("Select operation on socket failed" , e);
return; // Selector gets closed, thread stops
}
if (events > 0)
{ // there are read-ready channels
Set readyKeys = m_readSelector.selectedKeys();
for (Iterator i = readyKeys.iterator(); i.hasNext();)
{
SelectionKey key = (SelectionKey) i.next();
i.remove();
// Do partial read and handle call back
Connection conn = (Connection) key.attachment();
try
{
if (conn.getSocketChannel().isOpen())
readOnce(conn);
else
{ // no need to close connection or cancel key
Address peerAddr = conn.getPeerAddress();
synchronized (conns)
{
conns.remove(peerAddr);
}
notifyConnectionClosed(peerAddr);
}
} catch (IOException e)
{
if (LOG.isInfoEnabled()) LOG.info("Read operation on socket failed" , e);
// The connection must be bad, cancel the key, close socket, then
// remove it from table!
Address peerAddr = conn.getPeerAddress();
key.cancel();
conn.destroy();
synchronized (conns)
{
conns.remove(peerAddr);
}
notifyConnectionClosed(peerAddr);
}
}
}
// Now we look at the connection queue to get new job
Object o = null;
try
{
o = m_queueNewConns.poll(0); // get a job
} catch (InterruptedException e)
{
if (LOG.isInfoEnabled()) LOG.info("Thread ("+Thread.currentThread().getName() +") was interrupted while polling queue" ,e);
// We must give up
continue;
}
if (null == o)
continue;
if (o instanceof Shutdown) {
return;
}
Connection conn = (Connection) o;
SocketChannel sc = conn.getSocketChannel();
try
{
sc.register(m_readSelector, SelectionKey.OP_READ, conn);
} catch (ClosedChannelException e)
{
if (LOG.isInfoEnabled()) LOG.info("Socket channel was closed while we were trying to register it to selector" , e);
// Channel becomes bad. The connection must be bad,
// close socket, then remove it from table!
Address peerAddr = conn.getPeerAddress();
conn.destroy();
synchronized (conns)
{
conns.remove(peerAddr);
}
notifyConnectionClosed(peerAddr);
}
} // end of the for-ever loop
}
private void readOnce(Connection conn)
throws IOException
{
ConnectionReadState readState = conn.getReadState();
if (readState.getHandShakingStatus() != ConnectionReadState.HANDSHAKINGFIN) // hand shaking not finished
if (!readForHandShaking(conn))
{ // not finished yet
return;
} else
{
synchronized (conns)
{
if (conns.containsKey(conn.getPeerAddress()))
{
if (conn.getPeerAddress().equals(getLocalAddress()))
{
if (LOG.isWarnEnabled())
LOG.warn(conn.getPeerAddress() + " is myself, not put it in table twice, but still read from it");
} else
{
if (LOG.isWarnEnabled())
LOG.warn(conn.getPeerAddress() + " is already there, will terminate connection");
throw new IOException(conn.getPeerAddress() + " is already there, terminate");
}
} else
addConnection(conn.getPeerAddress(), conn);
}
notifyConnectionOpened(conn.getPeerAddress());
}
if (!readState.isHeadFinished())
{ // a brand new message coming or header is not completed
// Begin or continue to read header
int size = readHeader(conn);
if (0 == size)
{ // header is not completed
return;
}
}
// Begin or continue to read body
if (readBody(conn) > 0)
{ // not finish yet
return;
}
Address addr = conn.getPeerAddress();
ByteBuffer buf = readState.getReadBodyBuffer();
// Clear status
readState.bodyFinished();
// Assign worker thread to execute call back
try
{
m_requestProcessors.execute(new ExecuteTask(addr, buf));
} catch (InterruptedException e)
{
// Cannot do call back, what can we do?
// Give up handling the message then
LOG.error("Thread ("+Thread.currentThread().getName() +") was interrupted while assigning executor to process read request" , e);
}
}
private int read(Connection conn, ByteBuffer buf)
throws IOException
{
SocketChannel sc = conn.getSocketChannel();
int num = sc.read(buf);
if (-1 == num) // EOS
throw new IOException("Couldn't read from socket as peer closed the socket");
return buf.remaining();
}
/**
* Read data for hand shaking. It doesn't try to complete. If there is nothing in
* the channel, the method returns immediately.
*
* @param conn The connection
* @return true if handshaking passes; false if it's not finished yet (not an error!).
* @throws IOException if handshaking fails
*/
private boolean readForHandShaking(Connection conn)
throws IOException
{
ConnectionReadState readState = conn.getReadState();
int i = readState.getHandShakingStatus();
switch (i)
{
case 0:
// Step 1
ByteBuffer handBuf = readState.getHandShakingBufferFixed();
if (read(conn, handBuf) != 0) // not finished step 1 yet
return false;
readState.handShakingStep1Finished();
// Let's fall down to process step 2
case 1:
// Step 2
handBuf = readState.getHandShakingBufferDynamic();
if (read(conn, handBuf) != 0) // not finished step 2 yet
return false;
readState.handShakingStep2Finished();
// Let's fall down to process step 3
case 2:
// There is a chance that handshaking finishes in step 2
if (ConnectionReadState.HANDSHAKINGFIN == readState.getHandShakingStatus())
return true;
// Step 3
handBuf = readState.getHandShakingBufferFixed();
if (read(conn, handBuf) != 0) // not finished step 3 yet
return false;
readState.handShakingStep3Finished();
// Let's fall down to process step 4
case 3:
// Again, there is a chance that handshaking finishes in step 3
if (ConnectionReadState.HANDSHAKINGFIN == readState.getHandShakingStatus())
return true;
// Step 4
handBuf = readState.getHandShakingBufferDynamic();
if (read(conn, handBuf) != 0) // not finished step 4 yet
return false;
readState.handShakingStep4Finished(); // now all done
return true;
}
// never here
return true;
}
/**
* Read message header from channel. It doesn't try to complete. If there is nothing in
* the channel, the method returns immediately.
*
* @param conn The connection
* @return 0 if header hasn't been read completely, otherwise the size of message body
* @throws IOException
*/
private int readHeader(Connection conn)
throws IOException
{
ConnectionReadState readState = conn.getReadState();
ByteBuffer headBuf = readState.getReadHeadBuffer();
SocketChannel sc = conn.getSocketChannel();
while (headBuf.remaining() > 0)
{
int num = sc.read(headBuf);
if (-1 == num)
{// EOS
throw new IOException("Peer closed socket");
}
if (0 == num) // no more data
return 0;
}
// OK, now we get the whole header, change the status and return message size
return readState.headFinished();
}
/**
* Read message body from channel. It doesn't try to complete. If there is nothing in
* the channel, the method returns immediately.
*
* @param conn The connection
* @return remaining bytes for the message
* @throws IOException
*/
private int readBody(Connection conn)
throws IOException
{
ByteBuffer bodyBuf = conn.getReadState().getReadBodyBuffer();
SocketChannel sc = conn.getSocketChannel();
while (bodyBuf.remaining() > 0)
{
int num = sc.read(bodyBuf);
if (-1 == num) // EOS
throw new IOException("Couldn't read from socket as peer closed the socket");
if (0 == num) // no more data
return bodyBuf.remaining();
}
// OK, we finished reading the whole message! Flip it (not necessary though)
bodyBuf.flip();
return 0;
}
}
private class ExecuteTask implements Runnable {
Address m_addr = null;
ByteBuffer m_buf = null;
public ExecuteTask(Address addr, ByteBuffer buf)
{
m_addr = addr;
m_buf = buf;
}
public void run()
{
receive(m_addr, m_buf.array(), m_buf.arrayOffset(), m_buf.limit());
}
}
private class ConnectionReadState {
private final Connection m_conn;
// Status for handshaking
private int m_handShakingStatus = 0; // 0(begin), 1, 2, 3, 99(finished)
static final int HANDSHAKINGFIN = 99;
private final ByteBuffer m_handShakingBufFixed = ByteBuffer.allocate(4 + 2 + 2);
private ByteBuffer m_handShakingBufDynamic = null;
// Status 1: Cookie(4) + version(2) + IP_length(2) --> use fixed buffer
// Status 2: IP buffer(?) (4 for IPv4 but it could be IPv6)
// + Port(4) + if_addition(1) --> use dynamic buffer
// Status 3: Addition_length(4) --> use fixed buffer
// Status 99: Addition data(?) --> use dynamic buffer
// Status for receiving message
private boolean m_headFinished = false;
private ByteBuffer m_readBodyBuf = null;
private final ByteBuffer m_readHeadBuf = ByteBuffer.allocate(Connection.HEADER_SIZE);
public ConnectionReadState(Connection conn)
{
m_conn = conn;
}
private void init()
{
// Initialize the handshaking status
m_handShakingBufFixed.clear();
m_handShakingBufFixed.limit(4 + 2 + 2);
}
ByteBuffer getHandShakingBufferFixed()
{
return m_handShakingBufFixed;
}
ByteBuffer getHandShakingBufferDynamic()
{
return m_handShakingBufDynamic;
}
ByteBuffer getReadBodyBuffer()
{
return m_readBodyBuf;
}
ByteBuffer getReadHeadBuffer()
{
return m_readHeadBuf;
}
void bodyFinished()
{
m_headFinished = false;
m_readHeadBuf.clear();
m_readBodyBuf = null;
m_conn.updateLastAccessed();
}
/**
* Status change for finishing reading the message header (data already in buffer)
*
* @return message size
*/
int headFinished()
{
m_headFinished = true;
m_readHeadBuf.flip();
int messageSize = m_readHeadBuf.getInt();
m_readBodyBuf = ByteBuffer.allocate(messageSize);
m_conn.updateLastAccessed();
return messageSize;
}
boolean isHeadFinished()
{
return m_headFinished;
}
/**
* Status change for finishing hand shaking step1
*
* @throws IOException if hand shaking fails
*/
void handShakingStep1Finished()
throws IOException
{
m_handShakingStatus = 1;
InetAddress clientIP = m_conn.sock_ch.socket().getInetAddress();
int clientPort = m_conn.sock_ch.socket().getPort();
m_handShakingBufFixed.flip();
// Cookie
byte[] bytesCookie = new byte[cookie.length];
m_handShakingBufFixed.get(bytesCookie);
if (!m_conn.matchCookie(bytesCookie))
throw new SocketException("ConnectionTable.Connection.readPeerAddress(): cookie received from "
+ clientIP + ":" + clientPort
+ " does not match own cookie; terminating connection");
// Version
short ver = m_handShakingBufFixed.getShort();
if (!Version.compareTo(ver))
{
if (LOG.isWarnEnabled())
LOG.warn(new StringBuffer("packet from ").append(clientIP).append(':').append(clientPort).
append(" has different version (").append(ver).append(") from ours (").
append(Version.version).append("). This may cause problems"));
}
// Length of peer IP address, could be 0
short len = m_handShakingBufFixed.getShort();
m_handShakingBufDynamic = ByteBuffer.allocate(len + 4 + 1);
}
void handShakingStep2Finished()
throws IOException
{
m_handShakingStatus = 2;
m_handShakingBufDynamic.flip();
// IP address
byte[] ip = new byte[m_handShakingBufDynamic.remaining() - 4 - 1];
m_handShakingBufDynamic.get(ip);
InetAddress addr = InetAddress.getByAddress(ip);
// Port
int port = m_handShakingBufDynamic.getInt();
m_conn.peer_addr = new IpAddress(addr, port);
// If there is additional data
boolean ifAddition = !(m_handShakingBufDynamic.get() == 0x00);
if (!ifAddition)
{ // handshaking finishes
m_handShakingStatus = HANDSHAKINGFIN;
return;
}
m_handShakingBufFixed.clear();
m_handShakingBufFixed.limit(4);
}
void handShakingStep3Finished()
{
m_handShakingStatus = 3;
m_handShakingBufFixed.flip();
// Length of additional data
int len = m_handShakingBufFixed.getInt();
if (0 == len)
{ // handshaking finishes
m_handShakingStatus = HANDSHAKINGFIN;
return;
}
m_handShakingBufDynamic = ByteBuffer.allocate(len);
}
void handShakingStep4Finished()
{
m_handShakingStatus = HANDSHAKINGFIN; // Finishes
m_handShakingBufDynamic.flip();
// Additional data
byte[] addition = new byte[m_handShakingBufDynamic.remaining()];
m_handShakingBufDynamic.get(addition);
((IpAddress) m_conn.peer_addr).setAdditionalData(addition);
}
int getHandShakingStatus()
{
return m_handShakingStatus;
}
void setHandShakingStatus(int s)
{
m_handShakingStatus = s;
}
}
class Connection extends ConnectionTable.Connection {
private SocketChannel sock_ch = null;
private WriteHandler m_writeHandler;
private SelectorWriteHandler m_selectorWriteHandler;
private final ConnectionReadState m_readState;
private static final int HEADER_SIZE = 4;
final ByteBuffer headerBuffer = ByteBuffer.allocate(HEADER_SIZE);
Connection(SocketChannel s, Address peer_addr)
{
super(s.socket(), peer_addr);
sock_ch = s;
m_readState = new ConnectionReadState(this);
m_readState.init();
}
private ConnectionReadState getReadState()
{
return m_readState;
}
private void setupWriteHandler(WriteHandler hdlr) throws InterruptedException
{
m_writeHandler = hdlr;
m_selectorWriteHandler = hdlr.add(sock_ch);
}
void destroy()
{
closeSocket();
}
void doSend(byte[] buffie, int offset, int length) throws Exception
{
FutureResult result = new FutureResult();
m_writeHandler.write(sock_ch, ByteBuffer.wrap(buffie, offset, length), result, m_selectorWriteHandler);
Exception ex = result.getException();
if (ex != null)
{
if (LOG.isErrorEnabled())
LOG.error("failed sending message", ex);
if (ex.getCause() instanceof IOException)
throw (IOException) ex.getCause();
throw ex;
}
result.get();
}
SocketChannel getSocketChannel()
{
return sock_ch;
}
void closeSocket()
{
if (sock_ch != null)
{
try
{
if(sock_ch.isConnected()) {
sock_ch.close();
}
}
catch (Exception eat)
{
}
sock_ch = null;
}
}
}
/**
* Handle writing to non-blocking NIO connection.
*/
private static class WriteHandler implements Runnable {
// Create a queue for write requests
private final LinkedQueue QUEUE = new LinkedQueue();
private Selector m_selector;
private int m_pendingChannels; // count of the number of channels that have pending writes
// note that this variable is only accessed by one thread.
// allocate and reuse the header for all buffer write operations
private ByteBuffer m_headerBuffer = ByteBuffer.allocate(Connection.HEADER_SIZE);
/**
* create instances of WriteHandler threads for sending data.
*
* @param workerThreads is the number of threads to create.
*/
private static WriteHandler[] create(int workerThreads)
{
WriteHandler[] handlers = new WriteHandler[workerThreads];
for (int looper = 0; looper < workerThreads; looper++)
{
handlers[looper] = new WriteHandler();
try
{
handlers[looper].m_selector = SelectorProvider.provider().openSelector();
}
catch (IOException e)
{
if (LOG.isErrorEnabled()) LOG.error(e);
}
Thread thread = new Thread(handlers[looper], "nioWriteHandlerThread");
thread.setDaemon(true);
thread.start();
}
return handlers;
}
/**
* Add a new channel to be handled.
*
* @param channel
*/
private SelectorWriteHandler add(SocketChannel channel) throws InterruptedException
{
return new SelectorWriteHandler(channel, m_selector, m_headerBuffer);
}
/**
* Writes buffer to the specified socket connection. This is always performed asynchronously. If you want
* to perform a synchrounous write, call notification.`get() which will block until the write operation is complete.
* Best practice is to call notification.getException() which may return any exceptions that occured during the write
* operation.
*
* @param channel is where the buffer is written to.
* @param buffer is what we write.
* @param notification may be specified if you want to know how many bytes were written and know if an exception
* occurred.
*/
private void write(SocketChannel channel, ByteBuffer buffer, FutureResult notification, SelectorWriteHandler hdlr) throws InterruptedException
{
QUEUE.put(new WriteRequest(channel, buffer, notification, hdlr));
}
private void close(SelectorWriteHandler entry)
{
entry.cancel();
}
private void handleChannelError(Selector selector, SelectorWriteHandler entry, SelectionKey selKey, Throwable error)
{
// notify callers of the exception and drain all of the send buffers for this channel.
do
{
if (error != null)
entry.notifyError(error);
}
while (entry.next());
close(entry);
}
// process the write operation
private void processWrite(Selector selector)
{
Set keys = selector.selectedKeys();
Object arr[] = keys.toArray();
for (int looper = 0; looper < arr.length; looper++)
{
SelectionKey key = (SelectionKey) arr[looper];
SelectorWriteHandler entry = (SelectorWriteHandler) key.attachment();
boolean needToDecrementPendingChannels = false;
try
{
if (0 == entry.write())
{ // write the buffer and if the remaining bytes is zero,
// notify the caller of number of bytes written.
entry.notifyObject(new Integer(entry.getBytesWritten()));
// switch to next write buffer or clear interest bit on socket channel.
if (!entry.next())
{
needToDecrementPendingChannels = true;
}
}
}
catch (IOException e)
{
needToDecrementPendingChannels = true;
// connection must of closed
handleChannelError(selector, entry, key, e);
}
finally
{
if (needToDecrementPendingChannels)
m_pendingChannels--;
}
}
keys.clear();
}
public void run()
{
while (m_selector.isOpen())
{
try
{
WriteRequest queueEntry;
Object o;
// When there are no more commands in the Queue, we will hit the blocking code after this loop.
while (null != (o = QUEUE.poll(0)))
{
if (o instanceof Shutdown) // Stop the thread
{
return;
}
queueEntry = (WriteRequest) o;
if (queueEntry.getHandler().add(queueEntry))
{
// If the add operation returns true, than means that a buffer is available to be written to the
// corresponding channel and channel's selection key has been modified to indicate interest in the
// 'write' operation.
// If the add operation threw an exception, we will not increment m_pendingChannels which
// seems correct as long as a new buffer wasn't added to be sent.
// Another way to view this is that we don't have to protect m_pendingChannels on the increment
// side, only need to protect on the decrement side (this logic of this run() will be incorrect
// if m_pendingChannels is set incorrectly).
m_pendingChannels++;
}
try
{
// process any connections ready to be written to.
if (m_selector.selectNow() > 0)
{
processWrite(m_selector);
}
}
catch (IOException e)
{ // need to understand what causes this error so we can handle it properly
if (LOG.isErrorEnabled()) LOG.error("SelectNow operation on write selector failed, didn't expect this to occur, please report this", e);
return; // if select fails, give up so we don't go into a busy loop.
}
}
// if there isn't any pending work to do, block on queue to get next request.
if (m_pendingChannels == 0)
{
o = QUEUE.take();
if (o instanceof Shutdown){ // Stop the thread
return;
}
queueEntry = (WriteRequest) o;
if (queueEntry.getHandler().add(queueEntry))
m_pendingChannels++;
}
// otherwise do a blocking wait select operation.
else
{
try
{
if ((m_selector.select()) > 0)
{
processWrite(m_selector);
}
}
catch (IOException e)
{ // need to understand what causes this error
if (LOG.isErrorEnabled()) LOG.error("Failure while writing to socket",e);
}
}
}
catch (InterruptedException e)
{
if (LOG.isErrorEnabled()) LOG.error("Thread ("+Thread.currentThread().getName() +") was interrupted", e);
}
catch (Throwable e) // Log throwable rather than terminating this thread.
{ // We are a daemon thread so we shouldn't prevent the process from terminating if
// the controlling thread decides that should happen.
if (LOG.isErrorEnabled()) LOG.error("Thread ("+Thread.currentThread().getName() +") caught Throwable" , e);
}
}
}
}
// Wrapper class for passing Write requests. There will be an instance of this class for each socketChannel
// mapped to a Selector.
public static class SelectorWriteHandler {
private final LinkedList m_writeRequests = new LinkedList(); // Collection of writeRequests
private boolean m_headerSent = false;
private SocketChannel m_channel;
private SelectionKey m_key;
private Selector m_selector;
private int m_bytesWritten = 0;
private boolean m_enabled = false;
private ByteBuffer m_headerBuffer;
SelectorWriteHandler(SocketChannel channel, Selector selector, ByteBuffer headerBuffer)
{
m_channel = channel;
m_selector = selector;
m_headerBuffer = headerBuffer;
}
private void register(Selector selector, SocketChannel channel) throws ClosedChannelException
{
// register the channel but don't enable OP_WRITE until we have a write request.
m_key = channel.register(selector, 0, this);
}
// return true if selection key is enabled when it wasn't previous to call.
private boolean enable()
{
boolean rc = false;
try
{
if (m_key == null)
{ // register the socket on first access,
// we are the only thread using this variable, so no sync needed.
register(m_selector, m_channel);
}
}
catch (ClosedChannelException e)
{
return rc;
}
if (!m_enabled)
{
rc = true;
try
{
m_key.interestOps(SelectionKey.OP_WRITE);
}
catch (CancelledKeyException e)
{ // channel must of closed
return false;
}
m_enabled = true;
}
return rc;
}
private void disable()
{
if (m_enabled)
{
try
{
m_key.interestOps(0); // pass zero which means that we are not interested in being
// notified of anything for this channel.
}
catch (CancelledKeyException eat) // If we finished writing and didn't get an exception, then
{ // we probably don't need to throw this exception (if they try to write
// again, we will then throw an exception).
}
m_enabled = false;
}
}
private void cancel()
{
m_key.cancel();
}
boolean add(WriteRequest entry)
{
m_writeRequests.add(entry);
return enable();
}
WriteRequest getCurrentRequest()
{
return (WriteRequest) m_writeRequests.getFirst();
}
SocketChannel getChannel()
{
return m_channel;
}
ByteBuffer getBuffer()
{
return getCurrentRequest().getBuffer();
}
FutureResult getCallback()
{
return getCurrentRequest().getCallback();
}
int getBytesWritten()
{
return m_bytesWritten;
}
void notifyError(Throwable error)
{
if (getCallback() != null)
getCallback().setException(error);
}
void notifyObject(Object result)
{
if (getCallback() != null)
getCallback().set(result);
}
/**
* switch to next request or disable write interest bit if there are no more buffers.
*
* @return true if another request was found to be processed.
*/
boolean next()
{
m_headerSent = false;
m_bytesWritten = 0;
m_writeRequests.removeFirst(); // remove current entry
boolean rc = !m_writeRequests.isEmpty();
if (!rc) // disable select for this channel if no more entries
disable();
return rc;
}
/**
* @return bytes remaining to write. This function will only throw IOException, unchecked exceptions are not
* expected to be thrown from here. It is very important for the caller to know if an unchecked exception can
* be thrown in here. Please correct the following throws list to include any other exceptions and update
* caller to handle them.
* @throws IOException
*/
int write() throws IOException
{
// Send header first. Note that while we are writing the shared header buffer,
// no other threads can access the header buffer as we are the only thread that has access to it.
if (!m_headerSent)
{
m_headerSent = true;
m_headerBuffer.clear();
m_headerBuffer.putInt(getBuffer().remaining());
m_headerBuffer.flip();
do
{
getChannel().write(m_headerBuffer);
} // we should be able to handle writing the header in one action but just in case, just do a busy loop
while (m_headerBuffer.remaining() > 0);
}
m_bytesWritten += (getChannel().write(getBuffer()));
return getBuffer().remaining();
}
}
public static class WriteRequest {
private final SocketChannel m_channel;
private final ByteBuffer m_buffer;
private final FutureResult m_callback;
private final SelectorWriteHandler m_hdlr;
WriteRequest(SocketChannel channel, ByteBuffer buffer, FutureResult callback, SelectorWriteHandler hdlr)
{
m_channel = channel;
m_buffer = buffer;
m_callback = callback;
m_hdlr = hdlr;
}
SelectorWriteHandler getHandler()
{
return m_hdlr;
}
SocketChannel getChannel()
{
return m_channel;
}
ByteBuffer getBuffer()
{
return m_buffer;
}
FutureResult getCallback()
{
return m_callback;
}
}
}
| src/org/jgroups/blocks/ConnectionTableNIO.java | // $Id: ConnectionTableNIO.java,v 1.12 2006/03/01 09:12:39 belaban Exp $
package org.jgroups.blocks;
import EDU.oswego.cs.dl.util.concurrent.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jgroups.Address;
import org.jgroups.Version;
import org.jgroups.protocols.TCP_NIO;
import org.jgroups.stack.IpAddress;
import org.jgroups.util.Util;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
/**
* Manages incoming and outgoing TCP connections. For each outgoing message to destination P, if there
* is not yet a connection for P, one will be created. Subsequent outgoing messages will use this
* connection. For incoming messages, one server socket is created at startup. For each new incoming
* client connecting, a new thread from a thread pool is allocated and listens for incoming messages
* until the socket is closed by the peer.<br>Sockets/threads with no activity will be killed
* after some time.
* <p/>
* Incoming messages from any of the sockets can be received by setting the message listener.
*
* @author Bela Ban, Scott Marlow, Alex Fu
*/
public class ConnectionTableNIO extends ConnectionTable implements Runnable {
private ServerSocketChannel m_serverSocketChannel;
private Selector m_acceptSelector;
protected final static Log LOG = LogFactory.getLog(ConnectionTableNIO.class);
private WriteHandler[] m_writeHandlers;
private int m_nextWriteHandler = 0;
private final Object m_lockNextWriteHandler = new Object();
private ReadHandler[] m_readHandlers;
private int m_nextReadHandler = 0;
private final Object m_lockNextReadHandler = new Object();
// thread pool for processing read requests
private Executor m_requestProcessors;
/**
* @param srv_port
* @throws Exception
*/
public ConnectionTableNIO(int srv_port) throws Exception {
super(srv_port);
}
/**
* @param srv_port
* @param reaper_interval
* @param conn_expire_time
* @throws Exception
*/
public ConnectionTableNIO(int srv_port, long reaper_interval,
long conn_expire_time) throws Exception {
super(srv_port, reaper_interval, conn_expire_time);
}
/**
* @param r
* @param bind_addr
* @param external_addr
* @param srv_port
* @param max_port
* @throws Exception
*/
public ConnectionTableNIO(Receiver r, InetAddress bind_addr, InetAddress external_addr, int srv_port, int max_port
)
throws Exception
{
super(r, bind_addr, external_addr, srv_port, max_port);
}
/**
* @param r
* @param bind_addr
* @param external_addr
* @param srv_port
* @param max_port
* @param reaper_interval
* @param conn_expire_time
* @throws Exception
*/
public ConnectionTableNIO(Receiver r, InetAddress bind_addr, InetAddress external_addr, int srv_port, int max_port,
long reaper_interval, long conn_expire_time
) throws Exception
{
super(r, bind_addr, external_addr, srv_port, max_port, reaper_interval, conn_expire_time);
}
/**
* Try to obtain correct Connection (or create one if not yet existent)
*/
ConnectionTable.Connection getConnection(Address dest) throws Exception
{
Connection conn = null;
SocketChannel sock_ch;
synchronized (conns)
{
conn = (Connection) conns.get(dest);
if (conn == null)
{
InetSocketAddress destAddress = new InetSocketAddress(((IpAddress) dest).getIpAddress(),
((IpAddress) dest).getPort());
sock_ch = SocketChannel.open(destAddress);
conn = new Connection(sock_ch, dest);
conn.sendLocalAddress(local_addr);
// This outbound connection is ready
conn.getReadState().setHandShakingStatus(ConnectionReadState.HANDSHAKINGFIN);
// Set channel to be non-block only after hand shaking
try
{
sock_ch.configureBlocking(false);
} catch (IOException e)
{
// No way to handle the blocking socket
conn.destroy();
throw e;
}
try
{
if (LOG.isTraceEnabled())
LOG.trace("About to change new connection send buff size from " + sock_ch.socket().getSendBufferSize() + " bytes");
sock_ch.socket().setSendBufferSize(send_buf_size);
if (LOG.isTraceEnabled())
LOG.trace("Changed new connection send buff size to " + sock_ch.socket().getSendBufferSize() + " bytes");
}
catch (IllegalArgumentException ex)
{
if (log.isErrorEnabled()) log.error("exception setting send buffer size to " +
send_buf_size + " bytes: " + ex);
}
try
{
if (LOG.isTraceEnabled())
LOG.trace("About to change new connection receive buff size from " + sock_ch.socket().getReceiveBufferSize() + " bytes");
sock_ch.socket().setReceiveBufferSize(recv_buf_size);
if (LOG.isTraceEnabled())
LOG.trace("Changed new connection receive buff size to " + sock_ch.socket().getReceiveBufferSize() + " bytes");
}
catch (IllegalArgumentException ex)
{
if (log.isErrorEnabled()) log.error("exception setting receive buffer size to " +
send_buf_size + " bytes: " + ex);
}
int idx;
synchronized (m_lockNextWriteHandler)
{
idx = m_nextWriteHandler = (m_nextWriteHandler + 1) % m_writeHandlers.length;
}
conn.setupWriteHandler(m_writeHandlers[idx]);
// Put the new connection to the queue
try
{
synchronized (m_lockNextReadHandler)
{
idx = m_nextReadHandler = (m_nextReadHandler + 1) % m_readHandlers.length;
}
m_readHandlers[idx].add(conn);
} catch (InterruptedException e)
{
if (LOG.isWarnEnabled())
LOG.warn("Thread (" +Thread.currentThread().getName() + ") was interrupted, closing connection", e);
// What can we do? Remove it from table then.
conn.destroy();
throw e;
}
// Add connection to table
addConnection(dest, conn);
notifyConnectionOpened(dest);
if (LOG.isInfoEnabled()) LOG.info("created socket to " + dest);
}
return conn;
}
}
protected void init()
throws Exception
{
TCP_NIO NIOreceiver = (TCP_NIO)receiver;
// use directExector if max thread pool size is less than or equal to zero.
if(NIOreceiver.getProcessorMaxThreads() <= 0) {
m_requestProcessors = new DirectExecutor();
}
else
{
// Create worker thread pool for processing incoming buffers
PooledExecutor requestProcessors = new PooledExecutor(new BoundedBuffer(NIOreceiver.getProcessorQueueSize()), NIOreceiver.getProcessorMaxThreads());
requestProcessors.setThreadFactory(new ThreadFactory() {
public Thread newThread(Runnable runnable) {
return new Thread(Util.getGlobalThreadGroup(), runnable);
}
});
requestProcessors.setMinimumPoolSize(NIOreceiver.getProcessorMinThreads());
requestProcessors.setKeepAliveTime(NIOreceiver.getProcessorKeepAliveTime());
requestProcessors.waitWhenBlocked();
requestProcessors.createThreads(NIOreceiver.getProcessorThreads());
m_requestProcessors = requestProcessors;
}
m_writeHandlers = WriteHandler.create(NIOreceiver.getWriterThreads());
m_readHandlers = new ReadHandler[NIOreceiver.getReaderThreads()];
for (int i = 0; i < m_readHandlers.length; i++)
m_readHandlers[i] = new ReadHandler();
}
/**
* Closes all open sockets, the server socket and all threads waiting for incoming messages
*/
public void stop()
{
if (m_serverSocketChannel.isOpen())
{
try
{
m_serverSocketChannel.close();
}
catch (Exception eat)
{
}
}
// Stop the main selector
m_acceptSelector.wakeup();
// Stop selector threads
for (int i = 0; i < m_readHandlers.length; i++)
{
try
{
m_readHandlers[i].add(new Shutdown());
} catch (InterruptedException e)
{
LOG.error("Thread ("+Thread.currentThread().getName() +") was interrupted, failed to shutdown selector", e);
}
}
for (int i = 0; i < m_writeHandlers.length; i++)
{
try
{
m_writeHandlers[i].QUEUE.put(new Shutdown());
m_writeHandlers[i].m_selector.wakeup();
} catch (InterruptedException e)
{
LOG.error("Thread ("+Thread.currentThread().getName() +") was interrupted, failed to shutdown selector", e);
}
}
// Stop the callback thread pool
if(m_requestProcessors instanceof PooledExecutor)
((PooledExecutor)m_requestProcessors).shutdownNow();
super.stop();
}
/**
* Acceptor thread. Continuously accept new connections and assign readhandler/writehandler
* to them.
*/
public void run()
{
Connection conn = null;
while (m_serverSocketChannel.isOpen())
{
int num = 0;
try
{
num = m_acceptSelector.select();
} catch (IOException e)
{
if (LOG.isWarnEnabled())
LOG.warn("Select operation on listening socket failed", e);
continue; // Give up this time
}
if (num > 0)
{
Set readyKeys = m_acceptSelector.selectedKeys();
for (Iterator i = readyKeys.iterator(); i.hasNext();)
{
SelectionKey key = (SelectionKey) i.next();
i.remove();
// We only deal with new incoming connections
ServerSocketChannel readyChannel = (ServerSocketChannel) key.channel();
SocketChannel client_sock_ch = null;
try
{
client_sock_ch = readyChannel.accept();
} catch (IOException e)
{
if (LOG.isWarnEnabled())
LOG.warn("Attempt to accept new connection from listening socket failed" , e);
// Give up this connection
continue;
}
if (LOG.isInfoEnabled())
LOG.info("accepted connection, client_sock=" + client_sock_ch.socket());
try
{
if (LOG.isTraceEnabled())
LOG.trace("About to change new connection send buff size from " + client_sock_ch.socket().getSendBufferSize() + " bytes");
client_sock_ch.socket().setSendBufferSize(send_buf_size);
if (LOG.isTraceEnabled())
LOG.trace("Changed new connection send buff size to " + client_sock_ch.socket().getSendBufferSize() + " bytes");
}
catch (IllegalArgumentException ex)
{
if (log.isErrorEnabled()) log.error("exception setting send buffer size to " +
send_buf_size + " bytes: " ,ex);
}
catch (SocketException e)
{
if (log.isErrorEnabled()) log.error("exception setting send buffer size to " +
send_buf_size + " bytes: " , e);
}
try
{
if (LOG.isTraceEnabled())
LOG.trace("About to change new connection receive buff size from " + client_sock_ch.socket().getReceiveBufferSize() + " bytes");
client_sock_ch.socket().setReceiveBufferSize(recv_buf_size);
if (LOG.isTraceEnabled())
LOG.trace("Changed new connection receive buff size to " + client_sock_ch.socket().getReceiveBufferSize() + " bytes");
}
catch (IllegalArgumentException ex)
{
if (log.isErrorEnabled()) log.error("exception setting receive buffer size to " +
send_buf_size + " bytes: " , ex);
}
catch (SocketException e)
{
if (log.isErrorEnabled()) log.error("exception setting receive buffer size to " +
recv_buf_size + " bytes: " , e);
}
conn = new Connection(client_sock_ch, null);
// Set it to be nonblocking
try
{
client_sock_ch.configureBlocking(false);
int idx;
synchronized (m_lockNextWriteHandler)
{
idx = m_nextWriteHandler = (m_nextWriteHandler + 1) % m_writeHandlers.length;
}
conn.setupWriteHandler(m_writeHandlers[idx]);
} catch (IOException e)
{
if (LOG.isWarnEnabled())
LOG.warn("Attempt to configure accepted connection failed" , e);
// Give up this connection if we cannot set it to non-block
conn.destroy();
continue;
}
catch (InterruptedException e)
{
if (LOG.isWarnEnabled())
LOG.warn("Attempt to configure accepted connection was interrupted", e);
// Give up this connection
conn.destroy();
continue;
}
try
{
int idx;
synchronized (m_lockNextReadHandler)
{
idx = m_nextReadHandler = (m_nextReadHandler + 1) % m_readHandlers.length;
}
m_readHandlers[idx].add(conn);
} catch (InterruptedException e)
{
if (LOG.isWarnEnabled())
LOG.warn("Attempt to configure read handler for accepted connection failed" , e);
// What can we do? Remove it from table then. -- not in table yet since we moved hand shaking
conn.destroy();
}
} // end of iteration
} // end of selected key > 0
} // end of thread
if (LOG.isTraceEnabled())
LOG.trace("acceptor thread terminated");
}
/**
* Finds first available port starting at start_port and returns server socket. Sets srv_port
*/
protected ServerSocket createServerSocket(int start_port, int end_port) throws Exception
{
this.m_acceptSelector = Selector.open();
m_serverSocketChannel = ServerSocketChannel.open();
m_serverSocketChannel.configureBlocking(false);
while (true)
{
try
{
if (bind_addr == null)
m_serverSocketChannel.socket().bind(new InetSocketAddress(start_port));
else
m_serverSocketChannel.socket().bind(new InetSocketAddress(bind_addr, start_port), backlog);
}
catch (BindException bind_ex)
{
if (start_port == end_port)
throw (BindException) ((new BindException("No available port to bind to")).initCause(bind_ex));
start_port++;
continue;
}
catch (SocketException bind_ex)
{
if (start_port == end_port)
throw (BindException) ((new BindException("No available port to bind to")).initCause(bind_ex));
start_port++;
continue;
}
catch (IOException io_ex)
{
if (LOG.isErrorEnabled()) LOG.error("Attempt to bind serversocket failed, port="+start_port+", bind addr=" + bind_addr ,io_ex);
throw io_ex;
}
srv_port = start_port;
break;
}
m_serverSocketChannel.register(this.m_acceptSelector, SelectionKey.OP_ACCEPT);
return m_serverSocketChannel.socket();
}
// Represents shutdown
private static class Shutdown {
}
// ReadHandler has selector to deal with read, it runs in seperated thread
private class ReadHandler implements Runnable {
private Selector m_readSelector = null;
private Thread m_th = null;
private LinkedQueue m_queueNewConns = new LinkedQueue();
public ReadHandler()
{
// Open the selector and register the pipe
try
{
m_readSelector = Selector.open();
} catch (IOException e)
{
// Should never happen
e.printStackTrace();
throw new IllegalStateException(e.getMessage());
}
// Start thread
m_th = new Thread(thread_group, this, "nioReadSelectorThread");
m_th.setDaemon(true);
m_th.start();
}
private void add(Object conn) throws InterruptedException
{
m_queueNewConns.put(conn);
wakeup();
}
private void wakeup()
{
m_readSelector.wakeup();
}
public void run()
{
while (true)
{ // m_s can be closed by the management thread
int events = 0;
try
{
events = m_readSelector.select();
} catch (IOException e)
{
if (LOG.isWarnEnabled())
LOG.warn("Select operation on socket failed", e);
continue; // Give up this time
} catch (ClosedSelectorException e)
{
if (LOG.isWarnEnabled())
LOG.warn("Select operation on socket failed" , e);
return; // Selector gets closed, thread stops
}
if (events > 0)
{ // there are read-ready channels
Set readyKeys = m_readSelector.selectedKeys();
for (Iterator i = readyKeys.iterator(); i.hasNext();)
{
SelectionKey key = (SelectionKey) i.next();
i.remove();
// Do partial read and handle call back
Connection conn = (Connection) key.attachment();
try
{
if (conn.getSocketChannel().isOpen())
readOnce(conn);
else
{ // no need to close connection or cancel key
Address peerAddr = conn.getPeerAddress();
synchronized (conns)
{
conns.remove(peerAddr);
}
notifyConnectionClosed(peerAddr);
}
} catch (IOException e)
{
if (LOG.isInfoEnabled()) LOG.info("Read operation on socket failed" , e);
// The connection must be bad, cancel the key, close socket, then
// remove it from table!
Address peerAddr = conn.getPeerAddress();
key.cancel();
conn.destroy();
synchronized (conns)
{
conns.remove(peerAddr);
}
notifyConnectionClosed(peerAddr);
}
}
}
// Now we look at the connection queue to get new job
Object o = null;
try
{
o = m_queueNewConns.poll(0); // get a job
} catch (InterruptedException e)
{
if (LOG.isInfoEnabled()) LOG.info("Thread ("+Thread.currentThread().getName() +") was interrupted while polling queue" ,e);
// We must give up
continue;
}
if (null == o)
continue;
if (o instanceof Shutdown) {
return;
}
Connection conn = (Connection) o;
SocketChannel sc = conn.getSocketChannel();
try
{
sc.register(m_readSelector, SelectionKey.OP_READ, conn);
} catch (ClosedChannelException e)
{
if (LOG.isInfoEnabled()) LOG.info("Socket channel was closed while we were trying to register it to selector" , e);
// Channel becomes bad. The connection must be bad,
// close socket, then remove it from table!
Address peerAddr = conn.getPeerAddress();
conn.destroy();
synchronized (conns)
{
conns.remove(peerAddr);
}
notifyConnectionClosed(peerAddr);
}
} // end of the for-ever loop
}
private void readOnce(Connection conn)
throws IOException
{
ConnectionReadState readState = conn.getReadState();
if (readState.getHandShakingStatus() != ConnectionReadState.HANDSHAKINGFIN) // hand shaking not finished
if (!readForHandShaking(conn))
{ // not finished yet
return;
} else
{
synchronized (conns)
{
if (conns.containsKey(conn.getPeerAddress()))
{
if (conn.getPeerAddress().equals(getLocalAddress()))
{
if (LOG.isWarnEnabled())
LOG.warn(conn.getPeerAddress() + " is myself, not put it in table twice, but still read from it");
} else
{
if (LOG.isWarnEnabled())
LOG.warn(conn.getPeerAddress() + " is already there, will terminate connection");
throw new IOException(conn.getPeerAddress() + " is already there, terminate");
}
} else
addConnection(conn.getPeerAddress(), conn);
}
notifyConnectionOpened(conn.getPeerAddress());
}
if (!readState.isHeadFinished())
{ // a brand new message coming or header is not completed
// Begin or continue to read header
int size = readHeader(conn);
if (0 == size)
{ // header is not completed
return;
}
}
// Begin or continue to read body
if (readBody(conn) > 0)
{ // not finish yet
return;
}
Address addr = conn.getPeerAddress();
ByteBuffer buf = readState.getReadBodyBuffer();
// Clear status
readState.bodyFinished();
// Assign worker thread to execute call back
try
{
m_requestProcessors.execute(new ExecuteTask(addr, buf));
} catch (InterruptedException e)
{
// Cannot do call back, what can we do?
// Give up handling the message then
LOG.error("Thread ("+Thread.currentThread().getName() +") was interrupted while assigning executor to process read request" , e);
}
}
private int read(Connection conn, ByteBuffer buf)
throws IOException
{
SocketChannel sc = conn.getSocketChannel();
int num = sc.read(buf);
if (-1 == num) // EOS
throw new IOException("Couldn't read from socket as peer closed the socket");
return buf.remaining();
}
/**
* Read data for hand shaking. It doesn't try to complete. If there is nothing in
* the channel, the method returns immediately.
*
* @param conn The connection
* @return true if handshaking passes; false if it's not finished yet (not an error!).
* @throws IOException if handshaking fails
*/
private boolean readForHandShaking(Connection conn)
throws IOException
{
ConnectionReadState readState = conn.getReadState();
int i = readState.getHandShakingStatus();
switch (i)
{
case 0:
// Step 1
ByteBuffer handBuf = readState.getHandShakingBufferFixed();
if (read(conn, handBuf) != 0) // not finished step 1 yet
return false;
readState.handShakingStep1Finished();
// Let's fall down to process step 2
case 1:
// Step 2
handBuf = readState.getHandShakingBufferDynamic();
if (read(conn, handBuf) != 0) // not finished step 2 yet
return false;
readState.handShakingStep2Finished();
// Let's fall down to process step 3
case 2:
// There is a chance that handshaking finishes in step 2
if (ConnectionReadState.HANDSHAKINGFIN == readState.getHandShakingStatus())
return true;
// Step 3
handBuf = readState.getHandShakingBufferFixed();
if (read(conn, handBuf) != 0) // not finished step 3 yet
return false;
readState.handShakingStep3Finished();
// Let's fall down to process step 4
case 3:
// Again, there is a chance that handshaking finishes in step 3
if (ConnectionReadState.HANDSHAKINGFIN == readState.getHandShakingStatus())
return true;
// Step 4
handBuf = readState.getHandShakingBufferDynamic();
if (read(conn, handBuf) != 0) // not finished step 4 yet
return false;
readState.handShakingStep4Finished(); // now all done
return true;
}
// never here
return true;
}
/**
* Read message header from channel. It doesn't try to complete. If there is nothing in
* the channel, the method returns immediately.
*
* @param conn The connection
* @return 0 if header hasn't been read completely, otherwise the size of message body
* @throws IOException
*/
private int readHeader(Connection conn)
throws IOException
{
ConnectionReadState readState = conn.getReadState();
ByteBuffer headBuf = readState.getReadHeadBuffer();
SocketChannel sc = conn.getSocketChannel();
while (headBuf.remaining() > 0)
{
int num = sc.read(headBuf);
if (-1 == num)
{// EOS
throw new IOException("Peer closed socket");
}
if (0 == num) // no more data
return 0;
}
// OK, now we get the whole header, change the status and return message size
return readState.headFinished();
}
/**
* Read message body from channel. It doesn't try to complete. If there is nothing in
* the channel, the method returns immediately.
*
* @param conn The connection
* @return remaining bytes for the message
* @throws IOException
*/
private int readBody(Connection conn)
throws IOException
{
ByteBuffer bodyBuf = conn.getReadState().getReadBodyBuffer();
SocketChannel sc = conn.getSocketChannel();
while (bodyBuf.remaining() > 0)
{
int num = sc.read(bodyBuf);
if (-1 == num) // EOS
throw new IOException("Couldn't read from socket as peer closed the socket");
if (0 == num) // no more data
return bodyBuf.remaining();
}
// OK, we finished reading the whole message! Flip it (not necessary though)
bodyBuf.flip();
return 0;
}
}
private class ExecuteTask implements Runnable {
Address m_addr = null;
ByteBuffer m_buf = null;
public ExecuteTask(Address addr, ByteBuffer buf)
{
m_addr = addr;
m_buf = buf;
}
public void run()
{
receive(m_addr, m_buf.array(), m_buf.arrayOffset(), m_buf.limit());
}
}
private class ConnectionReadState {
private final Connection m_conn;
// Status for handshaking
private int m_handShakingStatus = 0; // 0(begin), 1, 2, 3, 99(finished)
static final int HANDSHAKINGFIN = 99;
private final ByteBuffer m_handShakingBufFixed = ByteBuffer.allocate(4 + 2 + 2);
private ByteBuffer m_handShakingBufDynamic = null;
// Status 1: Cookie(4) + version(2) + IP_length(2) --> use fixed buffer
// Status 2: IP buffer(?) (4 for IPv4 but it could be IPv6)
// + Port(4) + if_addition(1) --> use dynamic buffer
// Status 3: Addition_length(4) --> use fixed buffer
// Status 99: Addition data(?) --> use dynamic buffer
// Status for receiving message
private boolean m_headFinished = false;
private ByteBuffer m_readBodyBuf = null;
private final ByteBuffer m_readHeadBuf = ByteBuffer.allocate(Connection.HEADER_SIZE);
public ConnectionReadState(Connection conn)
{
m_conn = conn;
}
private void init()
{
// Initialize the handshaking status
m_handShakingBufFixed.clear();
m_handShakingBufFixed.limit(4 + 2 + 2);
}
ByteBuffer getHandShakingBufferFixed()
{
return m_handShakingBufFixed;
}
ByteBuffer getHandShakingBufferDynamic()
{
return m_handShakingBufDynamic;
}
ByteBuffer getReadBodyBuffer()
{
return m_readBodyBuf;
}
ByteBuffer getReadHeadBuffer()
{
return m_readHeadBuf;
}
void bodyFinished()
{
m_headFinished = false;
m_readHeadBuf.clear();
m_readBodyBuf = null;
m_conn.updateLastAccessed();
}
/**
* Status change for finishing reading the message header (data already in buffer)
*
* @return message size
*/
int headFinished()
{
m_headFinished = true;
m_readHeadBuf.flip();
int messageSize = m_readHeadBuf.getInt();
m_readBodyBuf = ByteBuffer.allocate(messageSize);
m_conn.updateLastAccessed();
return messageSize;
}
boolean isHeadFinished()
{
return m_headFinished;
}
/**
* Status change for finishing hand shaking step1
*
* @throws IOException if hand shaking fails
*/
void handShakingStep1Finished()
throws IOException
{
m_handShakingStatus = 1;
InetAddress clientIP = m_conn.sock_ch.socket().getInetAddress();
int clientPort = m_conn.sock_ch.socket().getPort();
m_handShakingBufFixed.flip();
// Cookie
byte[] bytesCookie = new byte[cookie.length];
m_handShakingBufFixed.get(bytesCookie);
if (!m_conn.matchCookie(bytesCookie))
throw new SocketException("ConnectionTable.Connection.readPeerAddress(): cookie received from "
+ clientIP + ":" + clientPort
+ " does not match own cookie; terminating connection");
// Version
short ver = m_handShakingBufFixed.getShort();
if (!Version.compareTo(ver))
{
if (LOG.isWarnEnabled())
LOG.warn(new StringBuffer("packet from ").append(clientIP).append(':').append(clientPort).
append(" has different version (").append(ver).append(") from ours (").
append(Version.version).append("). This may cause problems"));
}
// Length of peer IP address, could be 0
short len = m_handShakingBufFixed.getShort();
m_handShakingBufDynamic = ByteBuffer.allocate(len + 4 + 1);
}
void handShakingStep2Finished()
throws IOException
{
m_handShakingStatus = 2;
m_handShakingBufDynamic.flip();
// IP address
byte[] ip = new byte[m_handShakingBufDynamic.remaining() - 4 - 1];
m_handShakingBufDynamic.get(ip);
InetAddress addr = InetAddress.getByAddress(ip);
// Port
int port = m_handShakingBufDynamic.getInt();
m_conn.peer_addr = new IpAddress(addr, port);
// If there is additional data
boolean ifAddition = !(m_handShakingBufDynamic.get() == 0x00);
if (!ifAddition)
{ // handshaking finishes
m_handShakingStatus = HANDSHAKINGFIN;
return;
}
m_handShakingBufFixed.clear();
m_handShakingBufFixed.limit(4);
}
void handShakingStep3Finished()
{
m_handShakingStatus = 3;
m_handShakingBufFixed.flip();
// Length of additional data
int len = m_handShakingBufFixed.getInt();
if (0 == len)
{ // handshaking finishes
m_handShakingStatus = HANDSHAKINGFIN;
return;
}
m_handShakingBufDynamic = ByteBuffer.allocate(len);
}
void handShakingStep4Finished()
{
m_handShakingStatus = HANDSHAKINGFIN; // Finishes
m_handShakingBufDynamic.flip();
// Additional data
byte[] addition = new byte[m_handShakingBufDynamic.remaining()];
m_handShakingBufDynamic.get(addition);
((IpAddress) m_conn.peer_addr).setAdditionalData(addition);
}
int getHandShakingStatus()
{
return m_handShakingStatus;
}
void setHandShakingStatus(int s)
{
m_handShakingStatus = s;
}
}
class Connection extends ConnectionTable.Connection {
private SocketChannel sock_ch = null;
private WriteHandler m_writeHandler;
private SelectorWriteHandler m_selectorWriteHandler;
private final ConnectionReadState m_readState;
private static final int HEADER_SIZE = 4;
final ByteBuffer headerBuffer = ByteBuffer.allocate(HEADER_SIZE);
Connection(SocketChannel s, Address peer_addr)
{
super(s.socket(), peer_addr);
sock_ch = s;
m_readState = new ConnectionReadState(this);
m_readState.init();
}
private ConnectionReadState getReadState()
{
return m_readState;
}
private void setupWriteHandler(WriteHandler hdlr) throws InterruptedException
{
m_writeHandler = hdlr;
m_selectorWriteHandler = hdlr.add(sock_ch);
}
void destroy()
{
closeSocket();
}
void doSend(byte[] buffie, int offset, int length) throws Exception
{
FutureResult result = new FutureResult();
m_writeHandler.write(sock_ch, ByteBuffer.wrap(buffie, offset, length), result, m_selectorWriteHandler);
Exception ex = result.getException();
if (ex != null)
{
if (LOG.isErrorEnabled())
LOG.error("failed sending message", ex);
if (ex.getCause() instanceof IOException)
throw (IOException) ex.getCause();
throw ex;
}
result.get();
}
SocketChannel getSocketChannel()
{
return sock_ch;
}
void closeSocket()
{
if (sock_ch != null)
{
try
{
if(sock_ch.isConnected()) {
sock_ch.close();
}
}
catch (Exception eat)
{
}
sock_ch = null;
}
}
}
/**
* Handle writing to non-blocking NIO connection.
*/
private static class WriteHandler implements Runnable {
// Create a queue for write requests
private final LinkedQueue QUEUE = new LinkedQueue();
private Selector m_selector;
private int m_pendingChannels; // count of the number of channels that have pending writes
// note that this variable is only accessed by one thread.
// allocate and reuse the header for all buffer write operations
private ByteBuffer m_headerBuffer = ByteBuffer.allocate(Connection.HEADER_SIZE);
/**
* create instances of WriteHandler threads for sending data.
*
* @param workerThreads is the number of threads to create.
*/
private static WriteHandler[] create(int workerThreads)
{
WriteHandler[] handlers = new WriteHandler[workerThreads];
for (int looper = 0; looper < workerThreads; looper++)
{
handlers[looper] = new WriteHandler();
try
{
handlers[looper].m_selector = SelectorProvider.provider().openSelector();
}
catch (IOException e)
{
if (LOG.isErrorEnabled()) LOG.error(e);
}
Thread thread = new Thread(handlers[looper], "nioWriteHandlerThread");
thread.setDaemon(true);
thread.start();
}
return handlers;
}
/**
* Add a new channel to be handled.
*
* @param channel
*/
private SelectorWriteHandler add(SocketChannel channel) throws InterruptedException
{
return new SelectorWriteHandler(channel, m_selector, m_headerBuffer);
}
/**
* Writes buffer to the specified socket connection. This is always performed asynchronously. If you want
* to perform a synchrounous write, call notification.`get() which will block until the write operation is complete.
* Best practice is to call notification.getException() which may return any exceptions that occured during the write
* operation.
*
* @param channel is where the buffer is written to.
* @param buffer is what we write.
* @param notification may be specified if you want to know how many bytes were written and know if an exception
* occurred.
*/
private void write(SocketChannel channel, ByteBuffer buffer, FutureResult notification, SelectorWriteHandler hdlr) throws InterruptedException
{
QUEUE.put(new WriteRequest(channel, buffer, notification, hdlr));
}
private void close(SelectorWriteHandler entry)
{
entry.cancel();
}
private void handleChannelError(Selector selector, SelectorWriteHandler entry, SelectionKey selKey, Throwable error)
{
// notify callers of the exception and drain all of the send buffers for this channel.
do
{
if (error != null)
entry.notifyError(error);
}
while (entry.next());
close(entry);
}
// process the write operation
private void processWrite(Selector selector)
{
Set keys = selector.selectedKeys();
Object arr[] = keys.toArray();
for (int looper = 0; looper < arr.length; looper++)
{
SelectionKey key = (SelectionKey) arr[looper];
SelectorWriteHandler entry = (SelectorWriteHandler) key.attachment();
boolean needToDecrementPendingChannels = false;
try
{
if (0 == entry.write())
{ // write the buffer and if the remaining bytes is zero,
// notify the caller of number of bytes written.
entry.notifyObject(new Integer(entry.getBytesWritten()));
// switch to next write buffer or clear interest bit on socket channel.
if (!entry.next())
{
needToDecrementPendingChannels = true;
}
}
}
catch (IOException e)
{
needToDecrementPendingChannels = true;
// connection must of closed
handleChannelError(selector, entry, key, e);
}
finally
{
if (needToDecrementPendingChannels)
m_pendingChannels--;
}
}
keys.clear();
}
public void run()
{
while (m_selector.isOpen())
{
try
{
WriteRequest queueEntry;
Object o;
// When there are no more commands in the Queue, we will hit the blocking code after this loop.
while (null != (o = QUEUE.poll(0)))
{
if (o instanceof Shutdown) // Stop the thread
{
return;
}
queueEntry = (WriteRequest) o;
if (queueEntry.getHandler().add(queueEntry))
{
// If the add operation returns true, than means that a buffer is available to be written to the
// corresponding channel and channel's selection key has been modified to indicate interest in the
// 'write' operation.
// If the add operation threw an exception, we will not increment m_pendingChannels which
// seems correct as long as a new buffer wasn't added to be sent.
// Another way to view this is that we don't have to protect m_pendingChannels on the increment
// side, only need to protect on the decrement side (this logic of this run() will be incorrect
// if m_pendingChannels is set incorrectly).
m_pendingChannels++;
}
try
{
// process any connections ready to be written to.
if (m_selector.selectNow() > 0)
{
processWrite(m_selector);
}
}
catch (IOException e)
{ // need to understand what causes this error so we can handle it properly
if (LOG.isErrorEnabled()) LOG.error("SelectNow operation on write selector failed, didn't expect this to occur, please report this", e);
return; // if select fails, give up so we don't go into a busy loop.
}
}
// if there isn't any pending work to do, block on queue to get next request.
if (m_pendingChannels == 0)
{
o = QUEUE.take();
if (o instanceof Shutdown){ // Stop the thread
return;
}
queueEntry = (WriteRequest) o;
if (queueEntry.getHandler().add(queueEntry))
m_pendingChannels++;
}
// otherwise do a blocking wait select operation.
else
{
try
{
if ((m_selector.select()) > 0)
{
processWrite(m_selector);
}
}
catch (IOException e)
{ // need to understand what causes this error
if (LOG.isErrorEnabled()) LOG.error("Failure while writing to socket",e);
}
}
}
catch (InterruptedException e)
{
if (LOG.isErrorEnabled()) LOG.error("Thread ("+Thread.currentThread().getName() +") was interrupted", e);
}
catch (Throwable e) // Log throwable rather than terminating this thread.
{ // We are a daemon thread so we shouldn't prevent the process from terminating if
// the controlling thread decides that should happen.
if (LOG.isErrorEnabled()) LOG.error("Thread ("+Thread.currentThread().getName() +") caught Throwable" , e);
}
}
}
}
// Wrapper class for passing Write requests. There will be an instance of this class for each socketChannel
// mapped to a Selector.
public static class SelectorWriteHandler {
private final LinkedList m_writeRequests = new LinkedList(); // Collection of writeRequests
private boolean m_headerSent = false;
private SocketChannel m_channel;
private SelectionKey m_key;
private Selector m_selector;
private int m_bytesWritten = 0;
private boolean m_enabled = false;
private ByteBuffer m_headerBuffer;
SelectorWriteHandler(SocketChannel channel, Selector selector, ByteBuffer headerBuffer)
{
m_channel = channel;
m_selector = selector;
m_headerBuffer = headerBuffer;
}
private void register(Selector selector, SocketChannel channel) throws ClosedChannelException
{
// register the channel but don't enable OP_WRITE until we have a write request.
m_key = channel.register(selector, 0, this);
}
// return true if selection key is enabled when it wasn't previous to call.
private boolean enable()
{
boolean rc = false;
try
{
if (m_key == null)
{ // register the socket on first access,
// we are the only thread using this variable, so no sync needed.
register(m_selector, m_channel);
}
}
catch (ClosedChannelException e)
{
return rc;
}
if (!m_enabled)
{
rc = true;
try
{
m_key.interestOps(SelectionKey.OP_WRITE);
}
catch (CancelledKeyException e)
{ // channel must of closed
return false;
}
m_enabled = true;
}
return rc;
}
private void disable()
{
if (m_enabled)
{
try
{
m_key.interestOps(0); // pass zero which means that we are not interested in being
// notified of anything for this channel.
}
catch (CancelledKeyException eat) // If we finished writing and didn't get an exception, then
{ // we probably don't need to throw this exception (if they try to write
// again, we will then throw an exception).
}
m_enabled = false;
}
}
private void cancel()
{
m_key.cancel();
}
boolean add(WriteRequest entry)
{
m_writeRequests.add(entry);
return enable();
}
WriteRequest getCurrentRequest()
{
return (WriteRequest) m_writeRequests.getFirst();
}
SocketChannel getChannel()
{
return m_channel;
}
ByteBuffer getBuffer()
{
return getCurrentRequest().getBuffer();
}
FutureResult getCallback()
{
return getCurrentRequest().getCallback();
}
int getBytesWritten()
{
return m_bytesWritten;
}
void notifyError(Throwable error)
{
if (getCallback() != null)
getCallback().setException(error);
}
void notifyObject(Object result)
{
if (getCallback() != null)
getCallback().set(result);
}
/**
* switch to next request or disable write interest bit if there are no more buffers.
*
* @return true if another request was found to be processed.
*/
boolean next()
{
m_headerSent = false;
m_bytesWritten = 0;
m_writeRequests.removeFirst(); // remove current entry
boolean rc = !m_writeRequests.isEmpty();
if (!rc) // disable select for this channel if no more entries
disable();
return rc;
}
/**
* @return bytes remaining to write. This function will only throw IOException, unchecked exceptions are not
* expected to be thrown from here. It is very important for the caller to know if an unchecked exception can
* be thrown in here. Please correct the following throws list to include any other exceptions and update
* caller to handle them.
* @throws IOException
*/
int write() throws IOException
{
// Send header first. Note that while we are writing the shared header buffer,
// no other threads can access the header buffer as we are the only thread that has access to it.
if (!m_headerSent)
{
m_headerSent = true;
m_headerBuffer.clear();
m_headerBuffer.putInt(getBuffer().remaining());
m_headerBuffer.flip();
do
{
getChannel().write(m_headerBuffer);
} // we should be able to handle writing the header in one action but just in case, just do a busy loop
while (m_headerBuffer.remaining() > 0);
}
m_bytesWritten += (getChannel().write(getBuffer()));
return getBuffer().remaining();
}
}
public static class WriteRequest {
private final SocketChannel m_channel;
private final ByteBuffer m_buffer;
private final FutureResult m_callback;
private final SelectorWriteHandler m_hdlr;
WriteRequest(SocketChannel channel, ByteBuffer buffer, FutureResult callback, SelectorWriteHandler hdlr)
{
m_channel = channel;
m_buffer = buffer;
m_callback = callback;
m_hdlr = hdlr;
}
SelectorWriteHandler getHandler()
{
return m_hdlr;
}
SocketChannel getChannel()
{
return m_channel;
}
ByteBuffer getBuffer()
{
return m_buffer;
}
FutureResult getCallback()
{
return m_callback;
}
}
}
| no message
| src/org/jgroups/blocks/ConnectionTableNIO.java | no message | <ide><path>rc/org/jgroups/blocks/ConnectionTableNIO.java
<del>// $Id: ConnectionTableNIO.java,v 1.12 2006/03/01 09:12:39 belaban Exp $
<add>// $Id: ConnectionTableNIO.java,v 1.13 2006/05/17 08:00:08 belaban Exp $
<ide>
<ide> package org.jgroups.blocks;
<ide>
<ide> {
<ide> try
<ide> {
<add> SocketAddress sockAddr;
<ide> if (bind_addr == null)
<del> m_serverSocketChannel.socket().bind(new InetSocketAddress(start_port));
<add> {
<add> sockAddr=new InetSocketAddress(start_port);
<add> m_serverSocketChannel.socket().bind(sockAddr);
<add> }
<ide> else
<del> m_serverSocketChannel.socket().bind(new InetSocketAddress(bind_addr, start_port), backlog);
<add> {
<add> sockAddr=new InetSocketAddress(bind_addr, start_port);
<add> m_serverSocketChannel.socket().bind(sockAddr, backlog);
<add> }
<ide> }
<ide> catch (BindException bind_ex)
<ide> { |
|
Java | apache-2.0 | df20381a91ded3647efac616f61e6820e5618a0e | 0 | Darsstar/framework,Scarlethue/vaadin,mstahv/framework,udayinfy/vaadin,magi42/vaadin,oalles/vaadin,peterl1084/framework,Legioth/vaadin,oalles/vaadin,Darsstar/framework,mstahv/framework,travisfw/vaadin,Flamenco/vaadin,Legioth/vaadin,magi42/vaadin,Flamenco/vaadin,fireflyc/vaadin,oalles/vaadin,Peppe/vaadin,sitexa/vaadin,oalles/vaadin,Scarlethue/vaadin,Legioth/vaadin,Scarlethue/vaadin,magi42/vaadin,Legioth/vaadin,synes/vaadin,asashour/framework,Flamenco/vaadin,fireflyc/vaadin,jdahlstrom/vaadin.react,Darsstar/framework,mittop/vaadin,fireflyc/vaadin,carrchang/vaadin,peterl1084/framework,Darsstar/framework,synes/vaadin,shahrzadmn/vaadin,cbmeeks/vaadin,mstahv/framework,magi42/vaadin,carrchang/vaadin,mstahv/framework,sitexa/vaadin,udayinfy/vaadin,jdahlstrom/vaadin.react,cbmeeks/vaadin,asashour/framework,Peppe/vaadin,carrchang/vaadin,Peppe/vaadin,mstahv/framework,synes/vaadin,Darsstar/framework,peterl1084/framework,travisfw/vaadin,asashour/framework,Flamenco/vaadin,magi42/vaadin,kironapublic/vaadin,udayinfy/vaadin,Scarlethue/vaadin,fireflyc/vaadin,travisfw/vaadin,oalles/vaadin,Peppe/vaadin,sitexa/vaadin,mittop/vaadin,jdahlstrom/vaadin.react,bmitc/vaadin,jdahlstrom/vaadin.react,cbmeeks/vaadin,shahrzadmn/vaadin,shahrzadmn/vaadin,sitexa/vaadin,mittop/vaadin,shahrzadmn/vaadin,travisfw/vaadin,bmitc/vaadin,travisfw/vaadin,asashour/framework,kironapublic/vaadin,sitexa/vaadin,kironapublic/vaadin,Legioth/vaadin,mittop/vaadin,kironapublic/vaadin,shahrzadmn/vaadin,carrchang/vaadin,udayinfy/vaadin,bmitc/vaadin,udayinfy/vaadin,asashour/framework,fireflyc/vaadin,Scarlethue/vaadin,synes/vaadin,bmitc/vaadin,cbmeeks/vaadin,jdahlstrom/vaadin.react,peterl1084/framework,Peppe/vaadin,synes/vaadin,kironapublic/vaadin,peterl1084/framework | package com.vaadin.tests.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.apache.commons.io.IOUtils;
public class SourceFileChecker extends TestCase {
/**
* The tests are run in the build directory.
*/
public static String baseDirectory = null;
public static final String SRC_DIR = getBaseDir() + "src";
public static final String TESTBENCH_SRC_DIR = getBaseDir()
+ "tests/testbench";
public static final String SERVERSIDE_SRC_DIR = getBaseDir()
+ "tests/server-side";
public static final String CLIENTSIDE_SRC_DIR = getBaseDir()
+ "tests/client-side";
private String externalJavaFiles = "com/vaadin/external";
private String buildFiles = "build";
private Set<String> alwaysIgnore = new HashSet<String>();
{
alwaysIgnore.add(".settings");
alwaysIgnore.add("eclipse");
}
public static String getBaseDir() {
if (baseDirectory != null) {
return baseDirectory;
}
// Run in the "build" directory by build, in the project root by Eclipse
for (File f : new File(".").listFiles()) {
if (f.getName().equals("buildhelpers")) {
// We are in "build"
baseDirectory = "../";
return baseDirectory;
}
}
baseDirectory = "./";
return baseDirectory;
}
private static final String[] ALL_SRC_DIRS = new String[] { SRC_DIR,
TESTBENCH_SRC_DIR, SERVERSIDE_SRC_DIR, CLIENTSIDE_SRC_DIR };
public void testJavaFilesContainsLicense() throws IOException {
Set<String> ignore = new HashSet<String>(alwaysIgnore);
ignore.add(externalJavaFiles);
validateFiles(SRC_DIR, new LicenseChecker(), ignore,
"The following files are missing license information:\n{0}",
".java");
}
public void testNonJavaFilesUseUnixNewline() throws IOException {
Set<String> ignore = new HashSet<String>(alwaysIgnore);
ignore.add(buildFiles);
for (String suffix : new String[] { ".html", ".css", ".xml" }) {
validateFiles(getBaseDir(), new DosNewlineDetector(), ignore,
"The following files contain CRLF instead of LF:\n{0}",
suffix);
}
}
public void testJavaFilesUseUnixNewline() throws IOException {
Set<String> ignore = new HashSet<String>(alwaysIgnore);
ignore.add(externalJavaFiles);
for (String dir : ALL_SRC_DIRS) {
validateFiles(dir, new DosNewlineDetector(), ignore,
"The following files contain CRLF instead of LF:\n{0}",
".java");
}
}
public interface FileValidator {
void validateFile(File f) throws Exception;
}
private void validateFiles(String directory, FileValidator validator,
Set<String> ignore, String errorMessage, String ending) {
File srcDir = new File(directory);
HashSet<String> missing = new HashSet<String>();
validateFiles(directory, srcDir, missing, validator, ending, ignore);
if (!missing.isEmpty()) {
throw new RuntimeException(errorMessage.replace("{0}", missing
.toString().replace(',', '\n')));
}
}
private void validateFiles(String baseDirectory, File directory,
HashSet<String> missing, FileValidator validator, String suffix,
Set<String> ignores) {
Assert.assertTrue("Directory " + directory + " does not exist",
directory.exists());
File[] files = directory.listFiles();
if (files == null) {
throw new RuntimeException("Listing of directory "
+ directory.getPath() + " failed");
}
for (File f : files) {
boolean ignoreThis = false;
for (String ignore : ignores) {
if (new File(baseDirectory, ignore).equals(f)) {
ignoreThis = true;
continue;
}
}
if (ignoreThis) {
continue;
}
if (f.isDirectory()) {
validateFiles(baseDirectory, f, missing, validator, suffix,
ignores);
} else if (f.getName().endsWith(suffix)) {
try {
validator.validateFile(f);
} catch (Throwable t) {
missing.add(f.getPath());
}
}
}
}
abstract class FileContentsValidator implements FileValidator {
public void validateFile(File f) throws Exception {
FileInputStream fis = new FileInputStream(f);
String contents = IOUtils.toString(fis);
fis.close();
validateContents(f, contents);
}
protected abstract void validateContents(File f, String contents)
throws Exception;
}
class DosNewlineDetector extends FileContentsValidator {
@Override
protected void validateContents(File f, String contents)
throws Exception {
if (contents.contains("\r\n")) {
throw new IllegalArgumentException();
}
}
}
class LicenseChecker extends FileContentsValidator {
@Override
protected void validateContents(File f, String contents)
throws Exception {
if (!contents.contains("@" + "VaadinApache2LicenseForJavaFiles"
+ "@")) {
throw new IllegalArgumentException();
}
}
}
}
| tests/server-side/com/vaadin/tests/server/SourceFileChecker.java | package com.vaadin.tests.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.apache.commons.io.IOUtils;
public class SourceFileChecker extends TestCase {
/**
* The tests are run in the build directory.
*/
public static String baseDirectory = null;
public static final String SRC_DIR = getBaseDir() + "src";
public static final String TESTBENCH_SRC_DIR = getBaseDir()
+ "tests/testbench";
public static final String SERVERSIDE_SRC_DIR = getBaseDir()
+ "tests/server-side";
public static final String CLIENTSIDE_SRC_DIR = getBaseDir()
+ "tests/client-side";
private String externalJavaFiles = "com/vaadin/external";
private String buildFiles = "build";
private Set<String> alwaysIgnore = new HashSet<String>();
{
alwaysIgnore.add(".settings");
alwaysIgnore.add("eclipse");
}
public static String getBaseDir() {
if (baseDirectory != null) {
return baseDirectory;
}
// Run in the "build" directory by build, in the project root by Eclipse
for (File f : new File(".").listFiles()) {
if (f.getName().equals("buildhelpers")) {
// We are in "build"
baseDirectory = "../";
return baseDirectory;
}
}
baseDirectory = "./";
return baseDirectory;
}
private static final String[] ALL_SRC_DIRS = new String[] { SRC_DIR,
TESTBENCH_SRC_DIR, SERVERSIDE_SRC_DIR, CLIENTSIDE_SRC_DIR };
public void testJavaFilesContainsLicense() throws IOException {
Set<String> ignore = new HashSet<String>(alwaysIgnore);
ignore.add(externalJavaFiles);
validateFiles(SRC_DIR, new LicenseChecker(), ignore,
"The following files are missing license information:\n{0}",
".java");
}
public void testNonJavaFilesUseUnixNewline() throws IOException {
Set<String> ignore = new HashSet<String>(alwaysIgnore);
ignore.add(buildFiles);
for (String suffix : new String[] { ".html", ".css", ".xml" }) {
validateFiles(getBaseDir(), new DosNewlineDetector(), ignore,
"The following files contain CRLF instead of LF:\n{0}",
suffix);
}
}
public void testJavaFilesUseUnixNewline() throws IOException {
Set<String> ignore = new HashSet<String>(alwaysIgnore);
ignore.add(externalJavaFiles);
for (String dir : ALL_SRC_DIRS) {
validateFiles(dir, new DosNewlineDetector(), ignore,
"The following files contain CRLF instead of LF:\n{0}",
".java");
}
}
public interface FileValidator {
void validateFile(File f) throws Exception;
}
private void validateFiles(String directory, FileValidator validator,
Set<String> ignore, String errorMessage, String ending) {
File srcDir = new File(directory);
HashSet<String> missing = new HashSet<String>();
validateFiles(directory, srcDir, missing, validator, ending, ignore);
if (!missing.isEmpty()) {
throw new RuntimeException(errorMessage.replace("{0}", missing
.toString().replace(',', '\n')));
}
}
private void validateFiles(String baseDirectory, File directory,
HashSet<String> missing, FileValidator validator, String suffix,
Set<String> ignores) {
Assert.assertTrue("Directory " + directory + " does not exist",
directory.exists());
File[] files = directory.listFiles();
if (files == null) {
throw new RuntimeException("Listing of directory "
+ directory.getPath() + " failed");
}
for (File f : files) {
boolean ignoreThis = false;
for (String ignore : ignores) {
if (new File(baseDirectory, ignore).equals(f)) {
ignoreThis = true;
continue;
}
}
if (ignoreThis) {
continue;
}
if (f.isDirectory()) {
validateFiles(baseDirectory, f, missing, validator, suffix,
ignores);
} else if (f.getName().endsWith(suffix)) {
try {
validator.validateFile(f);
} catch (Throwable t) {
missing.add(f.getPath());
}
}
}
}
class DosNewlineDetector implements FileValidator {
public void validateFile(File f) throws Exception {
String contents = IOUtils.toString(new FileInputStream(f));
if (contents.contains("\r\n")) {
throw new IllegalArgumentException();
}
}
}
class LicenseChecker implements FileValidator {
public void validateFile(File f) throws Exception {
String contents = IOUtils.toString(new FileInputStream(f));
if (!contents.contains("@" + "VaadinApache2LicenseForJavaFiles"
+ "@")) {
throw new IllegalArgumentException();
}
}
}
}
| [merge from 6.7] Ensure that all opened FileInputStreams are closed
svn changeset:22944/svn branch:6.8
| tests/server-side/com/vaadin/tests/server/SourceFileChecker.java | [merge from 6.7] Ensure that all opened FileInputStreams are closed | <ide><path>ests/server-side/com/vaadin/tests/server/SourceFileChecker.java
<ide> }
<ide> }
<ide>
<del> class DosNewlineDetector implements FileValidator {
<add> abstract class FileContentsValidator implements FileValidator {
<add> public void validateFile(File f) throws Exception {
<add> FileInputStream fis = new FileInputStream(f);
<add> String contents = IOUtils.toString(fis);
<add> fis.close();
<add> validateContents(f, contents);
<add> }
<ide>
<del> public void validateFile(File f) throws Exception {
<del> String contents = IOUtils.toString(new FileInputStream(f));
<add> protected abstract void validateContents(File f, String contents)
<add> throws Exception;
<add>
<add> }
<add>
<add> class DosNewlineDetector extends FileContentsValidator {
<add>
<add> @Override
<add> protected void validateContents(File f, String contents)
<add> throws Exception {
<ide> if (contents.contains("\r\n")) {
<ide> throw new IllegalArgumentException();
<ide> }
<ide>
<ide> }
<add>
<ide> }
<ide>
<del> class LicenseChecker implements FileValidator {
<del> public void validateFile(File f) throws Exception {
<del> String contents = IOUtils.toString(new FileInputStream(f));
<add> class LicenseChecker extends FileContentsValidator {
<add>
<add> @Override
<add> protected void validateContents(File f, String contents)
<add> throws Exception {
<ide> if (!contents.contains("@" + "VaadinApache2LicenseForJavaFiles"
<ide> + "@")) {
<ide> throw new IllegalArgumentException(); |
|
Java | mit | error: pathspec 'faststring/benchmarks/src/main/java/de/unifrankfurt/faststring/runner/Main.java' did not match any file(s) known to git
| e5f8e3496fa7ed0d61c954454c0393b46c209876 | 1 | wondee/faststring,wondee/faststring | package de.unifrankfurt.faststring.runner;
import java.util.Map;
import com.google.common.collect.ImmutableMap;
import de.unifrankfurt.faststring.ConcatBenchmark;
import de.unifrankfurt.faststring.ReplaceCharBenchmark;
import de.unifrankfurt.faststring.ReplaceRegexBenchmark;
import de.unifrankfurt.faststring.SubstringBenchmark;
import de.unifrankfurt.faststring.yabt.BenchmarkRunner;
public class Main {
private static final Map<String, Class<?>> BENCHMARKS;
static {
BENCHMARKS = ImmutableMap.<String, Class<?>> builder()
.put("substring", SubstringBenchmark.class)
.put("concat", ConcatBenchmark.class)
.put("replaceChar", ReplaceCharBenchmark.class)
.put("replaceRegex", ReplaceRegexBenchmark.class)
.build();
}
public static void main(String[] args) {
if (args.length != 1) {
printUsage();
} else {
Class<?> benchmarkToRun = BENCHMARKS.get(args[0]);
if (benchmarkToRun != null) {
BenchmarkRunner.start(benchmarkToRun);
} else {
printUsage();
throw new IllegalArgumentException(args[0] + " not found as a benchmark");
}
}
}
private static void printUsage() {
System.out.println("only one param is allowed. Give the name of the benchmark to be runned.");
System.out.println("available benchmarks: ");
System.out.println(BENCHMARKS.keySet());
}
}
| faststring/benchmarks/src/main/java/de/unifrankfurt/faststring/runner/Main.java | added simple runner class | faststring/benchmarks/src/main/java/de/unifrankfurt/faststring/runner/Main.java | added simple runner class | <ide><path>aststring/benchmarks/src/main/java/de/unifrankfurt/faststring/runner/Main.java
<add>package de.unifrankfurt.faststring.runner;
<add>
<add>import java.util.Map;
<add>
<add>import com.google.common.collect.ImmutableMap;
<add>
<add>import de.unifrankfurt.faststring.ConcatBenchmark;
<add>import de.unifrankfurt.faststring.ReplaceCharBenchmark;
<add>import de.unifrankfurt.faststring.ReplaceRegexBenchmark;
<add>import de.unifrankfurt.faststring.SubstringBenchmark;
<add>import de.unifrankfurt.faststring.yabt.BenchmarkRunner;
<add>
<add>public class Main {
<add>
<add> private static final Map<String, Class<?>> BENCHMARKS;
<add>
<add> static {
<add> BENCHMARKS = ImmutableMap.<String, Class<?>> builder()
<add> .put("substring", SubstringBenchmark.class)
<add> .put("concat", ConcatBenchmark.class)
<add> .put("replaceChar", ReplaceCharBenchmark.class)
<add> .put("replaceRegex", ReplaceRegexBenchmark.class)
<add> .build();
<add>
<add> }
<add>
<add> public static void main(String[] args) {
<add> if (args.length != 1) {
<add> printUsage();
<add> } else {
<add> Class<?> benchmarkToRun = BENCHMARKS.get(args[0]);
<add>
<add> if (benchmarkToRun != null) {
<add> BenchmarkRunner.start(benchmarkToRun);
<add> } else {
<add> printUsage();
<add> throw new IllegalArgumentException(args[0] + " not found as a benchmark");
<add> }
<add> }
<add> }
<add>
<add> private static void printUsage() {
<add> System.out.println("only one param is allowed. Give the name of the benchmark to be runned.");
<add> System.out.println("available benchmarks: ");
<add> System.out.println(BENCHMARKS.keySet());
<add> }
<add>} |
|
Java | apache-2.0 | df71e4da8f3b940a7acb3b1cafe5ad38ad7efce1 | 0 | davinkevin/Podcast-Server,davinkevin/Podcast-Server,radut/Podcast-Server,davinkevin/Podcast-Server,radut/Podcast-Server,davinkevin/Podcast-Server,radut/Podcast-Server,davinkevin/Podcast-Server | package lan.dk.podcastserver.manager;
import lan.dk.podcastserver.business.ItemBusiness;
import lan.dk.podcastserver.entity.Item;
import lan.dk.podcastserver.manager.worker.downloader.Downloader;
import lan.dk.podcastserver.utils.WorkerUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import javax.annotation.Resource;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
@Controller
public class ItemDownloadManager implements ApplicationContextAware {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
private static final String WS_TOPIC_WAITINGLIST = "/topic/waitingList";
//Représnetation de la fils d'attente
private Queue<Item> waitingQueue = new ConcurrentLinkedQueue<Item>();
//Représentation de la fils en cours de téléchargement
private Map<Item, Downloader> downloadingQueue = new ConcurrentHashMap<Item, Downloader>();
@Resource SimpMessagingTemplate template;
@Autowired
ItemBusiness itemBusiness;
@Value("${concurrentDownload:3}")
private int limitParallelDownload;
@Value("${numberOfTry:10}")
private int numberOfTry;
@Value("${rootfolder:${catalina.home}/webapps/podcast/}")
private String rootfolder;
@Value("${serverURL:http://localhost:8080}")
private String serverURL;
@Value("${fileContainer:http://localhost:8080/podcast}")
protected String fileContainer;
@Autowired
private WorkerUtils workerUtils;
private AtomicInteger numberOfCurrentDownload = new AtomicInteger(0);
private boolean isRunning = false;
ApplicationContext context = null;
/* GETTER & SETTER */
public int getLimitParallelDownload() {
return limitParallelDownload;
}
public void setLimitParallelDownload(int limitParallelDownload) {
boolean addToDownloadList = limitParallelDownload < this.limitParallelDownload;
this.limitParallelDownload = limitParallelDownload;
if (addToDownloadList && !isRunning)
manageDownload();
}
public ItemDownloadManager() {
}
public Queue<Item> getWaitingQueue() {
return waitingQueue;
}
public Map<Item, Downloader> getDownloadingQueue() {
return downloadingQueue;
}
public void setWaitingQueue(Queue<Item> waitingQueue) {
this.waitingQueue = waitingQueue;
}
public void setDownloadingQueue(Map<Item, Downloader> downloadingQueue) {
this.downloadingQueue = downloadingQueue;
}
public ItemDownloadManager(Queue<Item> waitingQueue) {
this.waitingQueue = waitingQueue;
}
public int getNumberOfCurrentDownload() {
return numberOfCurrentDownload.get();
}
public void setNumberOfCurrentDownload(int numberOfCurrentDownload) {
this.numberOfCurrentDownload.set(numberOfCurrentDownload);
}
public String getRootfolder() {
return rootfolder;
}
public void setRootfolder(String rootfolder) {
this.rootfolder = rootfolder;
}
public String getServerURL() {
return serverURL;
}
public void setServerURL(String serverURL) {
this.serverURL = serverURL;
}
public String getFileContainer() {
return fileContainer;
}
public void setFileContainer(String fileContainer) {
this.fileContainer = fileContainer;
}
/* METHODS */
private void manageDownload() {
if (!isRunning) {
isRunning = true;
Item currentItem = null;
while (downloadingQueue.size() < this.limitParallelDownload && !waitingQueue.isEmpty()) {
currentItem = this.getWaitingQueue().poll();
if ( !"Started".equals(currentItem.getStatus()) && !"Finish".equals(currentItem.getStatus()) ) {
getDownloaderByTypeAndRun(currentItem);
}
}
isRunning = false;
}
this.convertAndSendWaitingQueue();
}
private void initDownload() {
for(Item item : itemBusiness.findAllToDownload()) {
if (!waitingQueue.contains(item)) {
waitingQueue.add(item);
}
}
}
public void launchDownload() {
this.initDownload();
this.manageDownload();
}
// Change status of all downloads :
public void stopAllDownload() {
for (Downloader downloader : downloadingQueue.values()) {
downloader.stopDownload();
}
}
public void pauseAllDownload() {
for (Downloader downloader : downloadingQueue.values()) {
downloader.pauseDownload();
}
}
public void restartAllDownload() {
for (Downloader downloader : downloadingQueue.values()) {
if (downloader.getItem().getStatus().equals("Paused")) {
getDownloaderByTypeAndRun(downloader.getItem());
}
}
}
// Change State of id identified download
public void stopDownload(int id) {
downloadingQueue.get(getItemInDownloadingQueue(id)).stopDownload();
}
public void pauseDownload(int id) {
Item item = getItemInDownloadingQueue(id);
downloadingQueue.get(item).pauseDownload();
}
public void restartDownload(int id) {
getDownloaderByTypeAndRun(downloadingQueue.get(getItemInDownloadingQueue(id)).getItem());
}
public void toogleDownload(int id) {
Item item = getItemInDownloadingQueue(id);
if (item.getStatus().equals("Paused")) {
logger.debug("restart du download");
restartDownload(id);
} else if (item.getStatus().equals("Started")) {
logger.debug("pause du download");
pauseDownload(id);
}
}
public void addItemToQueue(int id) {
this.addItemToQueue(itemBusiness.findOne(id));
//this.convertAndSendWaitingQueue();
}
public void addItemToQueue(Item item) {
if (waitingQueue.contains(item) || downloadingQueue.containsKey(item))
return;
waitingQueue.add(item);
manageDownload();
}
public void removeItemFromQueue(int id, Boolean stopItem) {
Item item = itemBusiness.findOne(id);
this.removeItemFromQueue(item);
if (stopItem)
itemBusiness.save(item.setStatus("Stopped"));
this.convertAndSendWaitingQueue();
}
public void removeItemFromQueue(Item item) {
waitingQueue.remove(item);
}
/* Helpers */
public void addACurrentDownload() {
this.numberOfCurrentDownload.incrementAndGet();
}
public void removeACurrentDownload(Item item) {
this.numberOfCurrentDownload.decrementAndGet();
this.downloadingQueue.remove(item);
if (!isRunning)
manageDownload();
}
public Item getItemInDownloadingQueue(int id) {
for (Item item : downloadingQueue.keySet()) {
if (item.getId()== id) {
return item;
}
}
return null;
}
private void getDownloaderByTypeAndRun(Item item) {
if (downloadingQueue.containsKey(item)) { // Cas ou le Worker se met en pause et reste en mémoire // dans la DownloadingQueue
Downloader downloader = downloadingQueue.get(item);
downloader.startDownload();
} else { // Cas ou le Worker se coupe pour la pause et nécessite un relancement
Downloader worker = workerUtils.getDownloaderByType(item);
if (worker != null) {
this.getDownloadingQueue().put(item, worker);
new Thread((Runnable) worker).start();
}
}
}
public void resetDownload(Item item) {
if (downloadingQueue.containsKey(item) && canBeReseted(item)) {
item.addATry();
Downloader worker = workerUtils.getDownloaderByType(item);
if (worker != null) {
this.getDownloadingQueue().put(item, worker);
new Thread((Runnable) worker).start();
}
}
}
@Override
public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
logger.debug("Initialisation du Contexte");
this.context = applicationContext;
}
public void removeItemFromQueueAndDownload(Item itemToDelete) {
//* Si le téléchargement est en cours ou en attente : *//
if (this.getDownloadingQueue().containsKey(itemToDelete)) {
this.stopDownload(itemToDelete.getId());
} else if (this.getWaitingQueue().contains(itemToDelete)) {
this.removeItemFromQueue(itemToDelete);
}
this.convertAndSendWaitingQueue();
}
protected void convertAndSendWaitingQueue() {
this.template.convertAndSend(WS_TOPIC_WAITINGLIST, this.waitingQueue);
}
public boolean canBeReseted(Item item) {
return item.getNumberOfTry()+1 <= numberOfTry;
}
}
| src/main/java/lan/dk/podcastserver/manager/ItemDownloadManager.java | package lan.dk.podcastserver.manager;
import lan.dk.podcastserver.business.ItemBusiness;
import lan.dk.podcastserver.entity.Item;
import lan.dk.podcastserver.manager.worker.downloader.Downloader;
import lan.dk.podcastserver.utils.WorkerUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import javax.annotation.Resource;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
@Controller
public class ItemDownloadManager implements ApplicationContextAware {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
private static final String WS_TOPIC_WAITINGLIST = "/topic/waitingList";
//Représnetation de la fils d'attente
private Queue<Item> waitingQueue = new ConcurrentLinkedQueue<Item>();
//Représentation de la fils en cours de téléchargement
private Map<Item, Downloader> downloadingQueue = new ConcurrentHashMap<Item, Downloader>();
@Resource SimpMessagingTemplate template;
@Autowired
ItemBusiness itemBusiness;
@Value("${concurrentDownload:3}")
private int limitParallelDownload;
@Value("${numberOfTry:10}")
private int numberOfTry;
@Value("${rootfolder:${catalina.home}/webapps/podcast/}")
private String rootfolder;
@Value("${serverURL:http://localhost:8080}")
private String serverURL;
@Value("${fileContainer:http://localhost:8080/podcast}")
protected String fileContainer;
@Autowired
private WorkerUtils workerUtils;
private AtomicInteger numberOfCurrentDownload = new AtomicInteger(0);
private boolean isRunning = false;
ApplicationContext context = null;
/* GETTER & SETTER */
public int getLimitParallelDownload() {
return limitParallelDownload;
}
public void setLimitParallelDownload(int limitParallelDownload) {
boolean addToDownloadList = limitParallelDownload < this.limitParallelDownload;
this.limitParallelDownload = limitParallelDownload;
if (addToDownloadList && !isRunning)
manageDownload();
}
public ItemDownloadManager() {
}
public Queue<Item> getWaitingQueue() {
return waitingQueue;
}
public Map<Item, Downloader> getDownloadingQueue() {
return downloadingQueue;
}
public void setWaitingQueue(Queue<Item> waitingQueue) {
this.waitingQueue = waitingQueue;
}
public void setDownloadingQueue(Map<Item, Downloader> downloadingQueue) {
this.downloadingQueue = downloadingQueue;
}
public ItemDownloadManager(Queue<Item> waitingQueue) {
this.waitingQueue = waitingQueue;
}
public int getNumberOfCurrentDownload() {
return numberOfCurrentDownload.get();
}
public void setNumberOfCurrentDownload(int numberOfCurrentDownload) {
this.numberOfCurrentDownload.set(numberOfCurrentDownload);
}
public String getRootfolder() {
return rootfolder;
}
public void setRootfolder(String rootfolder) {
this.rootfolder = rootfolder;
}
public String getServerURL() {
return serverURL;
}
public void setServerURL(String serverURL) {
this.serverURL = serverURL;
}
public String getFileContainer() {
return fileContainer;
}
public void setFileContainer(String fileContainer) {
this.fileContainer = fileContainer;
}
/* METHODS */
private void manageDownload() {
if (!isRunning) {
isRunning = true;
Item currentItem = null;
while (downloadingQueue.size() < this.limitParallelDownload && !waitingQueue.isEmpty()) {
currentItem = this.getWaitingQueue().poll();
if ( !"Started".equals(currentItem.getStatus()) && !"Finish".equals(currentItem.getStatus()) ) {
getDownloaderByTypeAndRun(currentItem);
}
}
isRunning = false;
}
this.convertAndSendWaitingQueue();
}
private void initDownload() {
for(Item item : itemBusiness.findAllToDownload()) {
if (!waitingQueue.contains(item)) {
waitingQueue.add(item);
}
}
}
public void launchDownload() {
this.initDownload();
this.manageDownload();
}
// Change status of all downloads :
public void stopAllDownload() {
for (Downloader downloader : downloadingQueue.values()) {
downloader.stopDownload();
}
}
public void pauseAllDownload() {
for (Downloader downloader : downloadingQueue.values()) {
downloader.pauseDownload();
}
}
public void restartAllDownload() {
for (Downloader downloader : downloadingQueue.values()) {
if (downloader.getItem().getStatus().equals("Paused")) {
getDownloaderByTypeAndRun(downloader.getItem());
}
}
}
// Change State of id identified download
public void stopDownload(int id) {
downloadingQueue.get(getItemInDownloadingQueue(id)).stopDownload();
}
public void pauseDownload(int id) {
Item item = getItemInDownloadingQueue(id);
downloadingQueue.get(item).pauseDownload();
}
public void restartDownload(int id) {
getDownloaderByTypeAndRun(downloadingQueue.get(getItemInDownloadingQueue(id)).getItem());
}
public void toogleDownload(int id) {
Item item = getItemInDownloadingQueue(id);
if (item.getStatus().equals("Paused")) {
logger.debug("restart du download");
restartDownload(id);
} else if (item.getStatus().equals("Started")) {
logger.debug("pause du download");
pauseDownload(id);
}
}
public void addItemToQueue(int id) {
this.addItemToQueue(itemBusiness.findOne(id));
this.convertAndSendWaitingQueue();
}
public void addItemToQueue(Item item) {
if (waitingQueue.contains(item) || downloadingQueue.containsKey(item))
return;
waitingQueue.add(item);
manageDownload();
}
public void removeItemFromQueue(int id, Boolean stopItem) {
Item item = itemBusiness.findOne(id);
this.removeItemFromQueue(item);
if (stopItem)
itemBusiness.save(item.setStatus("Stopped"));
this.convertAndSendWaitingQueue();
}
public void removeItemFromQueue(Item item) {
waitingQueue.remove(item);
}
/* Helpers */
public void addACurrentDownload() {
this.numberOfCurrentDownload.incrementAndGet();
}
public void removeACurrentDownload(Item item) {
this.numberOfCurrentDownload.decrementAndGet();
this.downloadingQueue.remove(item);
if (!isRunning)
manageDownload();
}
public Item getItemInDownloadingQueue(int id) {
for (Item item : downloadingQueue.keySet()) {
if (item.getId()== id) {
return item;
}
}
return null;
}
private void getDownloaderByTypeAndRun(Item item) {
if (downloadingQueue.containsKey(item)) { // Cas ou le Worker se met en pause et reste en mémoire // dans la DownloadingQueue
Downloader downloader = downloadingQueue.get(item);
downloader.startDownload();
} else { // Cas ou le Worker se coupe pour la pause et nécessite un relancement
Downloader worker = workerUtils.getDownloaderByType(item);
if (worker != null) {
this.getDownloadingQueue().put(item, worker);
new Thread((Runnable) worker).start();
}
}
}
public void resetDownload(Item item) {
if (downloadingQueue.containsKey(item) && canBeReseted(item)) {
item.addATry();
Downloader worker = workerUtils.getDownloaderByType(item);
if (worker != null) {
this.getDownloadingQueue().put(item, worker);
new Thread((Runnable) worker).start();
}
}
}
@Override
public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
logger.debug("Initialisation du Contexte");
this.context = applicationContext;
}
public void removeItemFromQueueAndDownload(Item itemToDelete) {
//* Si le téléchargement est en cours ou en attente : *//
if (this.getDownloadingQueue().containsKey(itemToDelete)) {
this.stopDownload(itemToDelete.getId());
} else if (this.getWaitingQueue().contains(itemToDelete)) {
this.removeItemFromQueue(itemToDelete);
}
this.convertAndSendWaitingQueue();
}
protected void convertAndSendWaitingQueue() {
this.template.convertAndSend(WS_TOPIC_WAITINGLIST, this.waitingQueue);
}
public boolean canBeReseted(Item item) {
return item.getNumberOfTry()+1 <= numberOfTry;
}
}
| Retrait de la double notification Web-Socket lors de l'ajout d'un download
| src/main/java/lan/dk/podcastserver/manager/ItemDownloadManager.java | Retrait de la double notification Web-Socket lors de l'ajout d'un download | <ide><path>rc/main/java/lan/dk/podcastserver/manager/ItemDownloadManager.java
<ide>
<ide> public void addItemToQueue(int id) {
<ide> this.addItemToQueue(itemBusiness.findOne(id));
<del> this.convertAndSendWaitingQueue();
<add> //this.convertAndSendWaitingQueue();
<ide> }
<ide>
<ide> public void addItemToQueue(Item item) { |
|
Java | apache-2.0 | 4dc304114ada4e89b3159e0ff006f113846ec37c | 0 | timp/anagram,timp/anagram,timp/anagrammer,timp/anagrammer | src/main/java/com/github/timp/anagram/Trie.java | package com.github.timp.anagram;
import java.util.HashMap;
import java.util.Map;
/**
* Derived from work Copyright (c) 2012, Brendan Conniff.
*
* An implementation of a Trie https://en.wikipedia.org/wiki/Trie
*/
public class Trie {
private final Map<Character,Trie> child = new HashMap<Character,Trie>();
private final String word;
private boolean marksEndOfWord = false;
public Trie() { this(""); }
public Trie(String w) { word = w; }
public void add(String s) {
if (s.length() > 0) {
final Character c = s.charAt(0);
Trie ch = child.get(c);
if (ch == null) {
ch = new Trie(word + c);
child.put(c, ch);
}
ch.add(s.substring(1));
} else {
setMarksEndOfWord(true);
}
}
/**
*
* @return whether this node reprsents a word end, not necessarily the last character
*/
public boolean marksEndOfWord() { return marksEndOfWord; }
/**
* @return the word
*/
public String getWord() { return word; }
/**
* @param c the node character
* @return the child trie or null
*/
public Trie getChild(char c) { return child.get(c); }
/**
* @param a whether this node in the Trie marks a word end
*/
private void setMarksEndOfWord(boolean a) { marksEndOfWord = a; }
}
| Unused
| src/main/java/com/github/timp/anagram/Trie.java | Unused | <ide><path>rc/main/java/com/github/timp/anagram/Trie.java
<del>package com.github.timp.anagram;
<del>
<del>import java.util.HashMap;
<del>import java.util.Map;
<del>
<del>/**
<del> * Derived from work Copyright (c) 2012, Brendan Conniff.
<del> *
<del> * An implementation of a Trie https://en.wikipedia.org/wiki/Trie
<del> */
<del>public class Trie {
<del>
<del> private final Map<Character,Trie> child = new HashMap<Character,Trie>();
<del> private final String word;
<del> private boolean marksEndOfWord = false;
<del>
<del> public Trie() { this(""); }
<del> public Trie(String w) { word = w; }
<del>
<del> public void add(String s) {
<del> if (s.length() > 0) {
<del> final Character c = s.charAt(0);
<del> Trie ch = child.get(c);
<del> if (ch == null) {
<del> ch = new Trie(word + c);
<del> child.put(c, ch);
<del> }
<del> ch.add(s.substring(1));
<del> } else {
<del> setMarksEndOfWord(true);
<del> }
<del> }
<del>
<del> /**
<del> *
<del> * @return whether this node reprsents a word end, not necessarily the last character
<del> */
<del> public boolean marksEndOfWord() { return marksEndOfWord; }
<del>
<del> /**
<del> * @return the word
<del> */
<del> public String getWord() { return word; }
<del>
<del> /**
<del> * @param c the node character
<del> * @return the child trie or null
<del> */
<del> public Trie getChild(char c) { return child.get(c); }
<del>
<del> /**
<del> * @param a whether this node in the Trie marks a word end
<del> */
<del> private void setMarksEndOfWord(boolean a) { marksEndOfWord = a; }
<del>
<del>} |
||
Java | apache-2.0 | b30d8f8373aa2a559d1ca63bf766ef30042de9ef | 0 | apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere | /*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
* </p>
*/
package io.shardingsphere.jdbc.orchestration.internal.config;
import com.google.common.base.Strings;
import io.shardingsphere.core.api.config.MasterSlaveRuleConfiguration;
import io.shardingsphere.core.api.config.ShardingRuleConfiguration;
import io.shardingsphere.jdbc.orchestration.internal.yaml.converter.DataSourceConverter;
import io.shardingsphere.jdbc.orchestration.internal.yaml.converter.MasterSlaveConfigurationConverter;
import io.shardingsphere.jdbc.orchestration.internal.yaml.converter.ShardingConfigurationConverter;
import io.shardingsphere.jdbc.orchestration.reg.api.RegistryCenter;
import javax.sql.DataSource;
import java.util.Map;
import java.util.Properties;
/**
* Configuration service.
*
* @author caohao
* @author zhangliang
*/
public final class ConfigurationService {
private final ConfigurationNode configNode;
private final RegistryCenter regCenter;
public ConfigurationService(final String name, final RegistryCenter regCenter) {
configNode = new ConfigurationNode(name);
this.regCenter = regCenter;
}
/**
* Persist sharding configuration.
*
* @param dataSourceMap data source map
* @param shardingRuleConfig sharding rule configuration
* @param configMap config map
* @param props sharding properties
* @param isOverwrite is overwrite registry center's configuration
*/
public void persistShardingConfiguration(
final Map<String, DataSource> dataSourceMap, final ShardingRuleConfiguration shardingRuleConfig, final Map<String, Object> configMap, final Properties props, final boolean isOverwrite) {
persistDataSourceConfiguration(dataSourceMap, isOverwrite);
persistShardingRuleConfiguration(shardingRuleConfig, isOverwrite);
persistShardingConfigMap(configMap, isOverwrite);
persistShardingProperties(props, isOverwrite);
}
/**
* Adjust has data source configuration or not in registry center.
*
* @return has data source configuration or not
*/
public boolean hasDataSourceConfiguration() {
return regCenter.isExisted(configNode.getFullPath(ConfigurationNode.DATA_SOURCE_NODE_PATH));
}
/**
* Adjust has sharding rule configuration or not in registry center.
*
* @return has sharding rule configuration or not
*/
public boolean hasShardingRuleConfiguration() {
return regCenter.isExisted(configNode.getFullPath(ConfigurationNode.SHARDING_RULE_NODE_PATH));
}
/**
* Adjust has sharding config map or not in registry center.
*
* @return has sharding config map or not
*/
public boolean hasShardingConfigMap() {
return regCenter.isExisted(configNode.getFullPath(ConfigurationNode.SHARDING_CONFIG_MAP_NODE_PATH));
}
/**
* Adjust has sharding properties or not in registry center.
*
* @return has sharding properties or not
*/
public boolean hasShardingProperties() {
return regCenter.isExisted(configNode.getFullPath(ConfigurationNode.SHARDING_PROPS_NODE_PATH));
}
private void persistDataSourceConfiguration(final Map<String, DataSource> dataSourceMap, final boolean isOverwrite) {
if (isOverwrite || !hasDataSourceConfiguration()) {
regCenter.persist(configNode.getFullPath(ConfigurationNode.DATA_SOURCE_NODE_PATH), DataSourceConverter.dataSourceMapToYaml(dataSourceMap));
}
}
private void persistShardingRuleConfiguration(final ShardingRuleConfiguration shardingRuleConfig, final boolean isOverwrite) {
if (isOverwrite || !hasShardingRuleConfiguration()) {
regCenter.persist(configNode.getFullPath(ConfigurationNode.SHARDING_RULE_NODE_PATH), ShardingConfigurationConverter.shardingRuleConfigToYaml(shardingRuleConfig));
}
}
private void persistShardingConfigMap(final Map<String, Object> configMap, final boolean isOverwrite) {
if (isOverwrite || !hasShardingConfigMap()) {
regCenter.persist(configNode.getFullPath(ConfigurationNode.SHARDING_CONFIG_MAP_NODE_PATH), ShardingConfigurationConverter.configMapToYaml(configMap));
}
}
private void persistShardingProperties(final Properties props, final boolean isOverwrite) {
if (isOverwrite || !hasShardingProperties()) {
regCenter.persist(configNode.getFullPath(ConfigurationNode.SHARDING_PROPS_NODE_PATH), ShardingConfigurationConverter.propertiesToYaml(props));
}
}
/**
* Persist master-slave configuration.
*
* @param dataSourceMap data source map
* @param masterSlaveRuleConfig master-slave rule configuration
* @param configMap config map
* @param isOverwrite is overwrite registry center's configuration
*/
public void persistMasterSlaveConfiguration(
final Map<String, DataSource> dataSourceMap, final MasterSlaveRuleConfiguration masterSlaveRuleConfig, final Map<String, Object> configMap, final boolean isOverwrite) {
persistDataSourceConfiguration(dataSourceMap, isOverwrite);
persistMasterSlaveRuleConfiguration(masterSlaveRuleConfig, isOverwrite);
persistMasterSlaveConfigMap(configMap, isOverwrite);
}
/**
* Adjust has master-slave rule configuration or not in registry center.
*
* @return has master-slave rule configuration or not
*/
public boolean hasMasterSlaveRuleConfiguration() {
return regCenter.isExisted(configNode.getFullPath(ConfigurationNode.MASTER_SLAVE_RULE_NODE_PATH));
}
/**
* Adjust has master-slave config map or not in registry center.
*
* @return has master-slave config map or not
*/
public boolean hasMasterSlaveConfigMap() {
return regCenter.isExisted(configNode.getFullPath(ConfigurationNode.MASTER_SLAVE_CONFIG_MAP_NODE_PATH));
}
private void persistMasterSlaveRuleConfiguration(final MasterSlaveRuleConfiguration masterSlaveRuleConfig, final boolean isOverwrite) {
if (isOverwrite || !hasMasterSlaveRuleConfiguration()) {
regCenter.persist(configNode.getFullPath(ConfigurationNode.MASTER_SLAVE_RULE_NODE_PATH), MasterSlaveConfigurationConverter.masterSlaveRuleConfigToYaml(masterSlaveRuleConfig));
}
}
private void persistMasterSlaveConfigMap(final Map<String, Object> configMap, final boolean isOverwrite) {
if (isOverwrite || !hasMasterSlaveConfigMap()) {
regCenter.persist(configNode.getFullPath(ConfigurationNode.MASTER_SLAVE_CONFIG_MAP_NODE_PATH), MasterSlaveConfigurationConverter.configMapToYaml(configMap));
}
}
/**
* Load data source configuration.
*
* @return data source configuration map
*/
public Map<String, DataSource> loadDataSourceMap() {
return DataSourceConverter.dataSourceMapFromYaml(regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.DATA_SOURCE_NODE_PATH)));
}
/**
* Load sharding rule configuration.
*
* @return sharding rule configuration
*/
public ShardingRuleConfiguration loadShardingRuleConfiguration() {
return ShardingConfigurationConverter.shardingRuleConfigFromYaml(regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.SHARDING_RULE_NODE_PATH)));
}
/**
* Load sharding config map.
*
* @return sharding config map
*/
@SuppressWarnings("unchecked")
public Map<String, Object> loadShardingConfigMap() {
return ShardingConfigurationConverter.configMapFromYaml(regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.SHARDING_CONFIG_MAP_NODE_PATH)));
}
/**
* Load sharding properties configuration.
*
* @return sharding properties
*/
public Properties loadShardingProperties() {
String data = regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.SHARDING_PROPS_NODE_PATH));
return Strings.isNullOrEmpty(data) ? new Properties() : ShardingConfigurationConverter.propertiesFromYaml(data);
}
/**
* Load master-slave rule configuration.
*
* @return master-slave rule configuration
*/
public MasterSlaveRuleConfiguration loadMasterSlaveRuleConfiguration() {
return MasterSlaveConfigurationConverter.masterSlaveRuleConfigFromYaml(regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.MASTER_SLAVE_RULE_NODE_PATH)));
}
/**
* Load master-slave config map.
*
* @return master-slave config map
*/
@SuppressWarnings("unchecked")
public Map<String, Object> loadMasterSlaveConfigMap() {
return MasterSlaveConfigurationConverter.configMapFromYaml(regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.MASTER_SLAVE_CONFIG_MAP_NODE_PATH)));
}
}
| sharding-jdbc-orchestration/src/main/java/io/shardingsphere/jdbc/orchestration/internal/config/ConfigurationService.java | /*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
* </p>
*/
package io.shardingsphere.jdbc.orchestration.internal.config;
import com.google.common.base.Strings;
import io.shardingsphere.core.api.config.MasterSlaveRuleConfiguration;
import io.shardingsphere.core.api.config.ShardingRuleConfiguration;
import io.shardingsphere.jdbc.orchestration.internal.json.DataSourceJsonConverter;
import io.shardingsphere.jdbc.orchestration.internal.json.GsonFactory;
import io.shardingsphere.jdbc.orchestration.internal.json.MasterSlaveRuleConfigurationConverter;
import io.shardingsphere.jdbc.orchestration.internal.json.ShardingRuleConfigurationConverter;
import io.shardingsphere.jdbc.orchestration.reg.api.RegistryCenter;
import javax.sql.DataSource;
import java.util.Map;
import java.util.Properties;
/**
* Configuration service.
*
* @author caohao
* @author zhangliang
*/
public final class ConfigurationService {
private final ConfigurationNode configNode;
private final RegistryCenter regCenter;
public ConfigurationService(final String name, final RegistryCenter regCenter) {
configNode = new ConfigurationNode(name);
this.regCenter = regCenter;
}
/**
* Persist sharding configuration.
*
* @param dataSourceMap data source map
* @param shardingRuleConfig sharding rule configuration
* @param configMap config map
* @param props sharding properties
* @param isOverwrite is overwrite registry center's configuration
*/
public void persistShardingConfiguration(
final Map<String, DataSource> dataSourceMap, final ShardingRuleConfiguration shardingRuleConfig, final Map<String, Object> configMap, final Properties props, final boolean isOverwrite) {
persistDataSourceConfiguration(dataSourceMap, isOverwrite);
persistShardingRuleConfiguration(shardingRuleConfig, isOverwrite);
persistShardingConfigMap(configMap, isOverwrite);
persistShardingProperties(props, isOverwrite);
}
/**
* Adjust has data source configuration or not in registry center.
*
* @return has data source configuration or not
*/
public boolean hasDataSourceConfiguration() {
return regCenter.isExisted(configNode.getFullPath(ConfigurationNode.DATA_SOURCE_NODE_PATH));
}
/**
* Adjust has sharding rule configuration or not in registry center.
*
* @return has sharding rule configuration or not
*/
public boolean hasShardingRuleConfiguration() {
return regCenter.isExisted(configNode.getFullPath(ConfigurationNode.SHARDING_RULE_NODE_PATH));
}
/**
* Adjust has sharding config map or not in registry center.
*
* @return has sharding config map or not
*/
public boolean hasShardingConfigMap() {
return regCenter.isExisted(configNode.getFullPath(ConfigurationNode.SHARDING_CONFIG_MAP_NODE_PATH));
}
/**
* Adjust has sharding properties or not in registry center.
*
* @return has sharding properties or not
*/
public boolean hasShardingProperties() {
return regCenter.isExisted(configNode.getFullPath(ConfigurationNode.SHARDING_PROPS_NODE_PATH));
}
private void persistDataSourceConfiguration(final Map<String, DataSource> dataSourceMap, final boolean isOverwrite) {
if (isOverwrite || !hasDataSourceConfiguration()) {
regCenter.persist(configNode.getFullPath(ConfigurationNode.DATA_SOURCE_NODE_PATH), DataSourceJsonConverter.toJson(dataSourceMap));
}
}
private void persistShardingRuleConfiguration(final ShardingRuleConfiguration shardingRuleConfig, final boolean isOverwrite) {
if (isOverwrite || !hasShardingRuleConfiguration()) {
regCenter.persist(configNode.getFullPath(ConfigurationNode.SHARDING_RULE_NODE_PATH), ShardingRuleConfigurationConverter.toJson(shardingRuleConfig));
}
}
private void persistShardingConfigMap(final Map<String, Object> configMap, final boolean isOverwrite) {
if (isOverwrite || !hasShardingConfigMap()) {
regCenter.persist(configNode.getFullPath(ConfigurationNode.SHARDING_CONFIG_MAP_NODE_PATH), GsonFactory.getGson().toJson(configMap));
}
}
private void persistShardingProperties(final Properties props, final boolean isOverwrite) {
if (isOverwrite || !hasShardingProperties()) {
regCenter.persist(configNode.getFullPath(ConfigurationNode.SHARDING_PROPS_NODE_PATH), GsonFactory.getGson().toJson(props));
}
}
/**
* Persist master-slave configuration.
*
* @param dataSourceMap data source map
* @param masterSlaveRuleConfig master-slave rule configuration
* @param configMap config map
* @param isOverwrite is overwrite registry center's configuration
*/
public void persistMasterSlaveConfiguration(
final Map<String, DataSource> dataSourceMap, final MasterSlaveRuleConfiguration masterSlaveRuleConfig, final Map<String, Object> configMap, final boolean isOverwrite) {
persistDataSourceConfiguration(dataSourceMap, isOverwrite);
persistMasterSlaveRuleConfiguration(masterSlaveRuleConfig, isOverwrite);
persistMasterSlaveConfigMap(configMap, isOverwrite);
}
/**
* Adjust has master-slave rule configuration or not in registry center.
*
* @return has master-slave rule configuration or not
*/
public boolean hasMasterSlaveRuleConfiguration() {
return regCenter.isExisted(configNode.getFullPath(ConfigurationNode.MASTER_SLAVE_RULE_NODE_PATH));
}
/**
* Adjust has master-slave config map or not in registry center.
*
* @return has master-slave config map or not
*/
public boolean hasMasterSlaveConfigMap() {
return regCenter.isExisted(configNode.getFullPath(ConfigurationNode.MASTER_SLAVE_CONFIG_MAP_NODE_PATH));
}
private void persistMasterSlaveRuleConfiguration(final MasterSlaveRuleConfiguration masterSlaveRuleConfig, final boolean isOverwrite) {
if (isOverwrite || !hasMasterSlaveRuleConfiguration()) {
regCenter.persist(configNode.getFullPath(ConfigurationNode.MASTER_SLAVE_RULE_NODE_PATH), MasterSlaveRuleConfigurationConverter.toJson(masterSlaveRuleConfig));
}
}
private void persistMasterSlaveConfigMap(final Map<String, Object> configMap, final boolean isOverwrite) {
if (isOverwrite || !hasMasterSlaveConfigMap()) {
regCenter.persist(configNode.getFullPath(ConfigurationNode.MASTER_SLAVE_CONFIG_MAP_NODE_PATH), GsonFactory.getGson().toJson(configMap));
}
}
/**
* Load data source configuration.
*
* @return data source configuration map
*/
public Map<String, DataSource> loadDataSourceMap() {
return DataSourceJsonConverter.fromJson(regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.DATA_SOURCE_NODE_PATH)));
}
/**
* Load sharding rule configuration.
*
* @return sharding rule configuration
*/
public ShardingRuleConfiguration loadShardingRuleConfiguration() {
return ShardingRuleConfigurationConverter.fromJson(regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.SHARDING_RULE_NODE_PATH)));
}
/**
* Load sharding config map.
*
* @return sharding config map
*/
@SuppressWarnings("unchecked")
public Map<String, Object> loadShardingConfigMap() {
return GsonFactory.getGson().fromJson(regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.SHARDING_CONFIG_MAP_NODE_PATH)), Map.class);
}
/**
* Load sharding properties configuration.
*
* @return sharding properties
*/
public Properties loadShardingProperties() {
String data = regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.SHARDING_PROPS_NODE_PATH));
return Strings.isNullOrEmpty(data) ? new Properties() : GsonFactory.getGson().fromJson(data, Properties.class);
}
/**
* Load master-slave rule configuration.
*
* @return master-slave rule configuration
*/
public MasterSlaveRuleConfiguration loadMasterSlaveRuleConfiguration() {
return MasterSlaveRuleConfigurationConverter.fromJson(regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.MASTER_SLAVE_RULE_NODE_PATH)));
}
/**
* Load master-slave config map.
*
* @return master-slave config map
*/
@SuppressWarnings("unchecked")
public Map<String, Object> loadMasterSlaveConfigMap() {
return GsonFactory.getGson().fromJson(regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.MASTER_SLAVE_CONFIG_MAP_NODE_PATH)), Map.class);
}
}
| using yaml instead of json to store config in registry.
| sharding-jdbc-orchestration/src/main/java/io/shardingsphere/jdbc/orchestration/internal/config/ConfigurationService.java | using yaml instead of json to store config in registry. | <ide><path>harding-jdbc-orchestration/src/main/java/io/shardingsphere/jdbc/orchestration/internal/config/ConfigurationService.java
<ide> import com.google.common.base.Strings;
<ide> import io.shardingsphere.core.api.config.MasterSlaveRuleConfiguration;
<ide> import io.shardingsphere.core.api.config.ShardingRuleConfiguration;
<del>import io.shardingsphere.jdbc.orchestration.internal.json.DataSourceJsonConverter;
<del>import io.shardingsphere.jdbc.orchestration.internal.json.GsonFactory;
<del>import io.shardingsphere.jdbc.orchestration.internal.json.MasterSlaveRuleConfigurationConverter;
<del>import io.shardingsphere.jdbc.orchestration.internal.json.ShardingRuleConfigurationConverter;
<add>import io.shardingsphere.jdbc.orchestration.internal.yaml.converter.DataSourceConverter;
<add>import io.shardingsphere.jdbc.orchestration.internal.yaml.converter.MasterSlaveConfigurationConverter;
<add>import io.shardingsphere.jdbc.orchestration.internal.yaml.converter.ShardingConfigurationConverter;
<ide> import io.shardingsphere.jdbc.orchestration.reg.api.RegistryCenter;
<ide>
<ide> import javax.sql.DataSource;
<ide>
<ide> private void persistDataSourceConfiguration(final Map<String, DataSource> dataSourceMap, final boolean isOverwrite) {
<ide> if (isOverwrite || !hasDataSourceConfiguration()) {
<del> regCenter.persist(configNode.getFullPath(ConfigurationNode.DATA_SOURCE_NODE_PATH), DataSourceJsonConverter.toJson(dataSourceMap));
<add> regCenter.persist(configNode.getFullPath(ConfigurationNode.DATA_SOURCE_NODE_PATH), DataSourceConverter.dataSourceMapToYaml(dataSourceMap));
<ide> }
<ide> }
<ide>
<ide> private void persistShardingRuleConfiguration(final ShardingRuleConfiguration shardingRuleConfig, final boolean isOverwrite) {
<ide> if (isOverwrite || !hasShardingRuleConfiguration()) {
<del> regCenter.persist(configNode.getFullPath(ConfigurationNode.SHARDING_RULE_NODE_PATH), ShardingRuleConfigurationConverter.toJson(shardingRuleConfig));
<add> regCenter.persist(configNode.getFullPath(ConfigurationNode.SHARDING_RULE_NODE_PATH), ShardingConfigurationConverter.shardingRuleConfigToYaml(shardingRuleConfig));
<ide> }
<ide> }
<ide>
<ide> private void persistShardingConfigMap(final Map<String, Object> configMap, final boolean isOverwrite) {
<ide> if (isOverwrite || !hasShardingConfigMap()) {
<del> regCenter.persist(configNode.getFullPath(ConfigurationNode.SHARDING_CONFIG_MAP_NODE_PATH), GsonFactory.getGson().toJson(configMap));
<add> regCenter.persist(configNode.getFullPath(ConfigurationNode.SHARDING_CONFIG_MAP_NODE_PATH), ShardingConfigurationConverter.configMapToYaml(configMap));
<ide> }
<ide> }
<ide>
<ide> private void persistShardingProperties(final Properties props, final boolean isOverwrite) {
<ide> if (isOverwrite || !hasShardingProperties()) {
<del> regCenter.persist(configNode.getFullPath(ConfigurationNode.SHARDING_PROPS_NODE_PATH), GsonFactory.getGson().toJson(props));
<add> regCenter.persist(configNode.getFullPath(ConfigurationNode.SHARDING_PROPS_NODE_PATH), ShardingConfigurationConverter.propertiesToYaml(props));
<ide> }
<ide> }
<ide>
<ide>
<ide> private void persistMasterSlaveRuleConfiguration(final MasterSlaveRuleConfiguration masterSlaveRuleConfig, final boolean isOverwrite) {
<ide> if (isOverwrite || !hasMasterSlaveRuleConfiguration()) {
<del> regCenter.persist(configNode.getFullPath(ConfigurationNode.MASTER_SLAVE_RULE_NODE_PATH), MasterSlaveRuleConfigurationConverter.toJson(masterSlaveRuleConfig));
<add> regCenter.persist(configNode.getFullPath(ConfigurationNode.MASTER_SLAVE_RULE_NODE_PATH), MasterSlaveConfigurationConverter.masterSlaveRuleConfigToYaml(masterSlaveRuleConfig));
<ide> }
<ide> }
<ide>
<ide> private void persistMasterSlaveConfigMap(final Map<String, Object> configMap, final boolean isOverwrite) {
<ide> if (isOverwrite || !hasMasterSlaveConfigMap()) {
<del> regCenter.persist(configNode.getFullPath(ConfigurationNode.MASTER_SLAVE_CONFIG_MAP_NODE_PATH), GsonFactory.getGson().toJson(configMap));
<add> regCenter.persist(configNode.getFullPath(ConfigurationNode.MASTER_SLAVE_CONFIG_MAP_NODE_PATH), MasterSlaveConfigurationConverter.configMapToYaml(configMap));
<ide> }
<ide> }
<ide>
<ide> * @return data source configuration map
<ide> */
<ide> public Map<String, DataSource> loadDataSourceMap() {
<del> return DataSourceJsonConverter.fromJson(regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.DATA_SOURCE_NODE_PATH)));
<add> return DataSourceConverter.dataSourceMapFromYaml(regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.DATA_SOURCE_NODE_PATH)));
<ide> }
<ide>
<ide> /**
<ide> * @return sharding rule configuration
<ide> */
<ide> public ShardingRuleConfiguration loadShardingRuleConfiguration() {
<del> return ShardingRuleConfigurationConverter.fromJson(regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.SHARDING_RULE_NODE_PATH)));
<add> return ShardingConfigurationConverter.shardingRuleConfigFromYaml(regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.SHARDING_RULE_NODE_PATH)));
<ide> }
<ide>
<ide> /**
<ide> */
<ide> @SuppressWarnings("unchecked")
<ide> public Map<String, Object> loadShardingConfigMap() {
<del> return GsonFactory.getGson().fromJson(regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.SHARDING_CONFIG_MAP_NODE_PATH)), Map.class);
<add> return ShardingConfigurationConverter.configMapFromYaml(regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.SHARDING_CONFIG_MAP_NODE_PATH)));
<ide> }
<ide>
<ide> /**
<ide> */
<ide> public Properties loadShardingProperties() {
<ide> String data = regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.SHARDING_PROPS_NODE_PATH));
<del> return Strings.isNullOrEmpty(data) ? new Properties() : GsonFactory.getGson().fromJson(data, Properties.class);
<add> return Strings.isNullOrEmpty(data) ? new Properties() : ShardingConfigurationConverter.propertiesFromYaml(data);
<ide> }
<ide>
<ide> /**
<ide> * @return master-slave rule configuration
<ide> */
<ide> public MasterSlaveRuleConfiguration loadMasterSlaveRuleConfiguration() {
<del> return MasterSlaveRuleConfigurationConverter.fromJson(regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.MASTER_SLAVE_RULE_NODE_PATH)));
<add> return MasterSlaveConfigurationConverter.masterSlaveRuleConfigFromYaml(regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.MASTER_SLAVE_RULE_NODE_PATH)));
<ide> }
<ide>
<ide> /**
<ide> */
<ide> @SuppressWarnings("unchecked")
<ide> public Map<String, Object> loadMasterSlaveConfigMap() {
<del> return GsonFactory.getGson().fromJson(regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.MASTER_SLAVE_CONFIG_MAP_NODE_PATH)), Map.class);
<add> return MasterSlaveConfigurationConverter.configMapFromYaml(regCenter.getDirectly(configNode.getFullPath(ConfigurationNode.MASTER_SLAVE_CONFIG_MAP_NODE_PATH)));
<ide> }
<ide> } |
|
Java | apache-2.0 | 622086b6cd1a3ae10a59cef2dc9c00106f07174d | 0 | Talend/components,Talend/components | // ============================================================================
//
// Copyright (C) 2006-2018 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// https://github.com/Talend/data-prep/blob/master/LICENSE
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.components.simplefileio.runtime.hadoop.excel.streaming;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.crypt.Decryptor;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.model.StylesTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.monitorjbl.xlsx.exceptions.OpenException;
import com.monitorjbl.xlsx.exceptions.ReadException;
public class StreamingWorkbookReader implements Iterable<Sheet>, AutoCloseable {
private static final Logger LOGGER = LoggerFactory.getLogger(StreamingWorkbookReader.class);
private static final QName SHEET_NAME_ATT_QNAME = new QName("name");
private final List<StreamingSheet> sheets;
private final List<String> sheetNames = new ArrayList<>();
private final StreamingReader.Builder builder;
private File tmp;
private OPCPackage pkg;
public StreamingWorkbookReader(StreamingReader.Builder builder) {
this.sheets = new ArrayList<>();
this.builder = builder;
}
private static File writeInputStreamToFile(InputStream is, int bufferSize) throws IOException {
File f = Files.createTempFile("tmp-", ".xlsx").toFile();
try (FileOutputStream fos = new FileOutputStream(f)) {
int read;
byte[] bytes = new byte[bufferSize];
while ((read = is.read(bytes)) != -1) {
fos.write(bytes, 0, read);
}
is.close();
fos.close();
return f;
}
}
public StreamingSheetReader first() {
return sheets.get(0).getReader();
}
public void init(InputStream is) {
File f = null;
try {
f = writeInputStreamToFile(is, builder.getBufferSize());
LOGGER.debug("Created temp file [{}", f.getAbsolutePath());
init(f);
tmp = f;
} catch (IOException e) {
throw new ReadException("Unable to read input stream", e);
} catch (RuntimeException e) {
FilesHelper.deleteQuietly(f);
throw e;
}
}
// to override https://bz.apache.org/bugzilla/show_bug.cgi?id=57699
public void init(File f) {
try {
if (builder.getPassword() != null) {
// Based on: https://poi.apache.org/encryption.html
POIFSFileSystem poifs = new POIFSFileSystem(f);
EncryptionInfo info = new EncryptionInfo(poifs);
Decryptor d = Decryptor.getInstance(info);
d.verifyPassword(builder.getPassword());
pkg = OPCPackage.open(d.getDataStream(poifs));
} else {
pkg = OPCPackage.open(f);
}
XSSFReader reader = new XSSFReader(pkg);
SharedStringsTable sst = reader.getSharedStringsTable();
StylesTable styles = reader.getStylesTable();
loadSheets(reader, sst, styles, builder.getRowCacheSize());
} catch (IOException e) {
throw new OpenException("Failed to open file", e);
} catch (OpenXML4JException | XMLStreamException e) {
throw new ReadException("Unable to read workbook", e);
} catch (GeneralSecurityException e) {
throw new ReadException("Unable to read workbook - Decryption failed", e);
}
}
void loadSheets(XSSFReader reader, SharedStringsTable sst, StylesTable stylesTable, int rowCacheSize)
throws IOException, InvalidFormatException, XMLStreamException {
lookupSheetNames(reader.getWorkbookData());
Iterator<InputStream> iter = reader.getSheetsData();
int i = 0;
while (iter.hasNext()) {
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
// Disable DTDs
xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
XMLEventReader parser = xmlInputFactory.createXMLEventReader(iter.next());
if(i < sheetNames.size()) {
sheets.add(new StreamingSheet(sheetNames.get(i++), new StreamingSheetReader(sst, stylesTable, parser, rowCacheSize)));
}
}
}
void lookupSheetNames(InputStream workBookData) throws IOException, InvalidFormatException, XMLStreamException {
sheetNames.clear();
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
// Disable DTDs
xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
XMLEventReader parser = xmlInputFactory.createXMLEventReader(workBookData);
boolean parsingsSheets = false;
while (parser.hasNext()) {
XMLEvent event = parser.nextEvent();
switch (event.getEventType()) {
case XMLStreamConstants.START_ELEMENT:
StartElement startElement = event.asStartElement();
String tagLocalName = startElement.getName().getLocalPart();
if ("sheets".equals(tagLocalName)) {
parsingsSheets = true;
continue;
}
if (parsingsSheets && "sheet".equals(tagLocalName)) {
Attribute attribute = startElement.getAttributeByName(SHEET_NAME_ATT_QNAME);
if (attribute != null) {
sheetNames.add(attribute.getValue());
}
}
break;
case XMLStreamConstants.END_ELEMENT:
if ("sheets".equals(event.asEndElement().getName().getLocalPart())) {
return;
}
}
}
}
int findSheetByName(String name) {
return sheetNames.indexOf(name);
}
String findSheetNameByIndex(int index) {
return sheetNames.get(index);
}
List<? extends Sheet> getSheets() {
return sheets;
}
@Override
public Iterator<Sheet> iterator() {
return new StreamingSheetIterator(sheets.iterator());
}
@Override
public void close() {
try {
for (StreamingSheet sheet : sheets) {
sheet.getReader().close();
}
pkg.revert();
} finally {
if (tmp != null) {
LOGGER.debug("Deleting tmp file [{}]", tmp.getAbsolutePath());
FilesHelper.deleteQuietly(tmp);
}
}
}
static class StreamingSheetIterator implements Iterator<Sheet> {
private final Iterator<StreamingSheet> iterator;
public StreamingSheetIterator(Iterator<StreamingSheet> iterator) {
this.iterator = iterator;
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Sheet next() {
return iterator.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException("NotSupported");
}
}
}
| components/components-fileio/simplefileio-runtime/src/main/java/org/talend/components/simplefileio/runtime/hadoop/excel/streaming/StreamingWorkbookReader.java | // ============================================================================
//
// Copyright (C) 2006-2018 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// https://github.com/Talend/data-prep/blob/master/LICENSE
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.components.simplefileio.runtime.hadoop.excel.streaming;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.crypt.Decryptor;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.model.StylesTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.monitorjbl.xlsx.exceptions.OpenException;
import com.monitorjbl.xlsx.exceptions.ReadException;
public class StreamingWorkbookReader implements Iterable<Sheet>, AutoCloseable {
private static final Logger LOGGER = LoggerFactory.getLogger(StreamingWorkbookReader.class);
private static final QName SHEET_NAME_ATT_QNAME = new QName("name");
private final List<StreamingSheet> sheets;
private final List<String> sheetNames = new ArrayList<>();
private final StreamingReader.Builder builder;
private File tmp;
private OPCPackage pkg;
public StreamingWorkbookReader(StreamingReader.Builder builder) {
this.sheets = new ArrayList<>();
this.builder = builder;
}
private static File writeInputStreamToFile(InputStream is, int bufferSize) throws IOException {
File f = Files.createTempFile("tmp-", ".xlsx").toFile();
try (FileOutputStream fos = new FileOutputStream(f)) {
int read;
byte[] bytes = new byte[bufferSize];
while ((read = is.read(bytes)) != -1) {
fos.write(bytes, 0, read);
}
is.close();
fos.close();
return f;
}
}
public StreamingSheetReader first() {
return sheets.get(0).getReader();
}
public void init(InputStream is) {
File f = null;
try {
f = writeInputStreamToFile(is, builder.getBufferSize());
LOGGER.debug("Created temp file [{}", f.getAbsolutePath());
init(f);
tmp = f;
} catch (IOException e) {
throw new ReadException("Unable to read input stream", e);
} catch (RuntimeException e) {
FilesHelper.deleteQuietly(f);
throw e;
}
}
// to override https://bz.apache.org/bugzilla/show_bug.cgi?id=57699
public void init(File f) {
try {
if (builder.getPassword() != null) {
// Based on: https://poi.apache.org/encryption.html
POIFSFileSystem poifs = new POIFSFileSystem(f);
EncryptionInfo info = new EncryptionInfo(poifs);
Decryptor d = Decryptor.getInstance(info);
d.verifyPassword(builder.getPassword());
pkg = OPCPackage.open(d.getDataStream(poifs));
} else {
pkg = OPCPackage.open(f);
}
XSSFReader reader = new XSSFReader(pkg);
SharedStringsTable sst = reader.getSharedStringsTable();
StylesTable styles = reader.getStylesTable();
loadSheets(reader, sst, styles, builder.getRowCacheSize());
} catch (IOException e) {
throw new OpenException("Failed to open file", e);
} catch (OpenXML4JException | XMLStreamException e) {
throw new ReadException("Unable to read workbook", e);
} catch (GeneralSecurityException e) {
throw new ReadException("Unable to read workbook - Decryption failed", e);
}
}
void loadSheets(XSSFReader reader, SharedStringsTable sst, StylesTable stylesTable, int rowCacheSize)
throws IOException, InvalidFormatException, XMLStreamException {
lookupSheetNames(reader.getWorkbookData());
Iterator<InputStream> iter = reader.getSheetsData();
int i = 0;
while (iter.hasNext()) {
XMLEventReader parser = XMLInputFactory.newInstance().createXMLEventReader(iter.next());
if(i < sheetNames.size()) {
sheets.add(new StreamingSheet(sheetNames.get(i++), new StreamingSheetReader(sst, stylesTable, parser, rowCacheSize)));
}
}
}
void lookupSheetNames(InputStream workBookData) throws IOException, InvalidFormatException, XMLStreamException {
sheetNames.clear();
XMLEventReader parser = XMLInputFactory.newInstance().createXMLEventReader(workBookData);
boolean parsingsSheets = false;
while (parser.hasNext()) {
XMLEvent event = parser.nextEvent();
switch (event.getEventType()) {
case XMLStreamConstants.START_ELEMENT:
StartElement startElement = event.asStartElement();
String tagLocalName = startElement.getName().getLocalPart();
if ("sheets".equals(tagLocalName)) {
parsingsSheets = true;
continue;
}
if (parsingsSheets && "sheet".equals(tagLocalName)) {
Attribute attribute = startElement.getAttributeByName(SHEET_NAME_ATT_QNAME);
if (attribute != null) {
sheetNames.add(attribute.getValue());
}
}
break;
case XMLStreamConstants.END_ELEMENT:
if ("sheets".equals(event.asEndElement().getName().getLocalPart())) {
return;
}
}
}
}
int findSheetByName(String name) {
return sheetNames.indexOf(name);
}
String findSheetNameByIndex(int index) {
return sheetNames.get(index);
}
List<? extends Sheet> getSheets() {
return sheets;
}
@Override
public Iterator<Sheet> iterator() {
return new StreamingSheetIterator(sheets.iterator());
}
@Override
public void close() {
try {
for (StreamingSheet sheet : sheets) {
sheet.getReader().close();
}
pkg.revert();
} finally {
if (tmp != null) {
LOGGER.debug("Deleting tmp file [{}]", tmp.getAbsolutePath());
FilesHelper.deleteQuietly(tmp);
}
}
}
static class StreamingSheetIterator implements Iterator<Sheet> {
private final Iterator<StreamingSheet> iterator;
public StreamingSheetIterator(Iterator<StreamingSheet> iterator) {
this.iterator = iterator;
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Sheet next() {
return iterator.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException("NotSupported");
}
}
}
| TDI-44819 - Disable DTDs when checking excel files (#1741)
| components/components-fileio/simplefileio-runtime/src/main/java/org/talend/components/simplefileio/runtime/hadoop/excel/streaming/StreamingWorkbookReader.java | TDI-44819 - Disable DTDs when checking excel files (#1741) | <ide><path>omponents/components-fileio/simplefileio-runtime/src/main/java/org/talend/components/simplefileio/runtime/hadoop/excel/streaming/StreamingWorkbookReader.java
<ide> Iterator<InputStream> iter = reader.getSheetsData();
<ide> int i = 0;
<ide> while (iter.hasNext()) {
<del> XMLEventReader parser = XMLInputFactory.newInstance().createXMLEventReader(iter.next());
<add> XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
<add> // Disable DTDs
<add> xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
<add> XMLEventReader parser = xmlInputFactory.createXMLEventReader(iter.next());
<ide> if(i < sheetNames.size()) {
<ide> sheets.add(new StreamingSheet(sheetNames.get(i++), new StreamingSheetReader(sst, stylesTable, parser, rowCacheSize)));
<ide> }
<ide> void lookupSheetNames(InputStream workBookData) throws IOException, InvalidFormatException, XMLStreamException {
<ide> sheetNames.clear();
<ide>
<del> XMLEventReader parser = XMLInputFactory.newInstance().createXMLEventReader(workBookData);
<add> XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
<add> // Disable DTDs
<add> xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
<add> XMLEventReader parser = xmlInputFactory.createXMLEventReader(workBookData);
<ide> boolean parsingsSheets = false;
<ide> while (parser.hasNext()) {
<ide> XMLEvent event = parser.nextEvent(); |
|
Java | apache-2.0 | f393ea35e5c324ec436ba5f28f609f977045c94c | 0 | n1hility/undertow,jamezp/undertow,emag/codereading-undertow,aradchykov/undertow,undertow-io/undertow,undertow-io/undertow,marschall/undertow,rhatlapa/undertow,aldaris/undertow,n1hility/undertow,Karm/undertow,baranowb/undertow,rhatlapa/undertow,rogerchina/undertow,wildfly-security-incubator/undertow,yonglehou/undertow,ctomc/undertow,baranowb/undertow,biddyweb/undertow,amannm/undertow,aradchykov/undertow,Karm/undertow,jstourac/undertow,undertow-io/undertow,grassjedi/undertow,TomasHofman/undertow,popstr/undertow,yonglehou/undertow,nkhuyu/undertow,darranl/undertow,msfm/undertow,biddyweb/undertow,darranl/undertow,wildfly-security-incubator/undertow,golovnin/undertow,jasonchaffee/undertow,yonglehou/undertow,rogerchina/undertow,jasonchaffee/undertow,pferraro/undertow,darranl/undertow,popstr/undertow,msfm/undertow,jstourac/undertow,soul2zimate/undertow,rhusar/undertow,grassjedi/undertow,soul2zimate/undertow,pferraro/undertow,marschall/undertow,jamezp/undertow,rogerchina/undertow,TomasHofman/undertow,wildfly-security-incubator/undertow,pedroigor/undertow,aldaris/undertow,Karm/undertow,jstourac/undertow,emag/codereading-undertow,n1hility/undertow,pferraro/undertow,jamezp/undertow,rhusar/undertow,amannm/undertow,baranowb/undertow,ctomc/undertow,biddyweb/undertow,rhatlapa/undertow,aradchykov/undertow,popstr/undertow,msfm/undertow,aldaris/undertow,stuartwdouglas/undertow,rhusar/undertow,marschall/undertow,stuartwdouglas/undertow,golovnin/undertow,grassjedi/undertow,nkhuyu/undertow,amannm/undertow,golovnin/undertow,nkhuyu/undertow,jasonchaffee/undertow,stuartwdouglas/undertow,ctomc/undertow,TomasHofman/undertow,soul2zimate/undertow,pedroigor/undertow,pedroigor/undertow | package io.undertow.servlet.spec;
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import io.undertow.servlet.UndertowServletMessages;
import org.xnio.ChannelListener;
import org.xnio.IoUtils;
import org.xnio.channels.Channels;
import org.xnio.channels.StreamSinkChannel;
import static org.xnio.Bits.anyAreClear;
import static org.xnio.Bits.anyAreSet;
/**
* Output stream used for upgraded requests. This is different to {@link ServletOutputStreamImpl}
* as it does no buffering, and it not tied to an exchange.
*
* @author Stuart Douglas
*/
public class UpgradeServletOutputStream extends ServletOutputStream {
private final StreamSinkChannel channel;
private WriteListener listener;
/**
* If this stream is ready for a write
*/
private static final int FLAG_READY = 1;
private static final int FLAG_CLOSED = 1 << 1;
private static final int FLAG_DELEGATE_SHUTDOWN = 1 << 2;
private int state;
/**
* The buffer that is in the process of being written out
*/
private ByteBuffer buffer;
protected UpgradeServletOutputStream(final StreamSinkChannel channel) {
this.channel = channel;
}
@Override
public void write(final byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
public void write(final byte[] b, final int off, final int len) throws IOException {
if (anyAreSet(state, FLAG_CLOSED)) {
throw UndertowServletMessages.MESSAGES.streamIsClosed();
}
if (listener == null) {
Channels.writeBlocking(channel, ByteBuffer.wrap(b, off, len));
} else {
if (anyAreClear(state, FLAG_READY)) {
throw UndertowServletMessages.MESSAGES.streamNotReady();
}
int res;
ByteBuffer buffer = ByteBuffer.wrap(b);
do {
res = channel.write(buffer);
if (res == 0) {
ByteBuffer copy = ByteBuffer.allocate(buffer.remaining());
copy.put(buffer);
copy.flip();
this.buffer = copy;
state = state & ~FLAG_READY;
channel.resumeWrites();
return;
}
} while (buffer.hasRemaining());
}
}
@Override
public void write(final int b) throws IOException {
write(new byte[]{(byte) b}, 0, 1);
}
@Override
public void flush() throws IOException {
if (anyAreSet(state, FLAG_CLOSED)) {
throw UndertowServletMessages.MESSAGES.streamIsClosed();
}
if (listener == null) {
Channels.flushBlocking(channel);
}
}
@Override
public void close() throws IOException {
state |= FLAG_CLOSED;
state &= ~FLAG_READY;
if (listener == null) {
channel.shutdownWrites();
state |= FLAG_DELEGATE_SHUTDOWN;
Channels.flushBlocking(channel);
} else {
if (buffer == null) {
channel.shutdownWrites();
state |= FLAG_DELEGATE_SHUTDOWN;
if (!channel.flush()) {
channel.resumeWrites();
}
}
}
}
void closeBlocking() throws IOException {
state |= FLAG_CLOSED;
try {
if (buffer != null) {
Channels.writeBlocking(channel, buffer);
}
channel.shutdownWrites();
Channels.flushBlocking(channel);
} finally {
channel.close();
}
}
@Override
public boolean isReady() {
if (listener == null) {
//TODO: is this the correct behaviour?
throw UndertowServletMessages.MESSAGES.streamNotInAsyncMode();
}
return anyAreSet(state, FLAG_READY);
}
@Override
public void setWriteListener(final WriteListener writeListener) {
if (writeListener == null) {
throw UndertowServletMessages.MESSAGES.paramCannotBeNull("writeListener");
}
if(listener != null) {
throw UndertowServletMessages.MESSAGES.listenerAlreadySet();
}
listener = writeListener;
channel.getWriteSetter().set(new WriteChannelListener());
state |= FLAG_READY;
channel.resumeWrites();
}
private class WriteChannelListener implements ChannelListener<StreamSinkChannel> {
@Override
public void handleEvent(final StreamSinkChannel channel) {
//flush the channel if it is closed
if (anyAreSet(state, FLAG_DELEGATE_SHUTDOWN)) {
try {
//either it will work, and the channel is closed
//or it won't, and we continue with writes resumed
channel.flush();
return;
} catch (IOException e) {
handleError(channel, e);
}
}
//if there is data still to write
if (buffer != null) {
int res;
do {
try {
res = channel.write(buffer);
if (res == 0) {
return;
}
} catch (IOException e) {
handleError(channel, e);
}
} while (buffer.hasRemaining());
buffer = null;
}
if (anyAreSet(state, FLAG_CLOSED)) {
try {
channel.shutdownWrites();
state |= FLAG_DELEGATE_SHUTDOWN;
channel.flush(); //if this does not succeed we are already resumed anyway
} catch (IOException e) {
handleError(channel, e);
}
} else {
state |= FLAG_READY;
channel.suspendWrites();
channel.getWorker().submit(new Runnable() {
@Override
public void run() {
try {
listener.onWritePossible();
} catch (IOException e) {
listener.onError(e);
}
}
});
}
}
private void handleError(final StreamSinkChannel channel, final IOException e) {
try {
listener.onError(e);
} finally {
IoUtils.safeClose(channel);
}
}
}
}
| servlet/src/main/java/io/undertow/servlet/spec/UpgradeServletOutputStream.java | package io.undertow.servlet.spec;
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import io.undertow.servlet.UndertowServletMessages;
import org.xnio.ChannelListener;
import org.xnio.IoUtils;
import org.xnio.channels.Channels;
import org.xnio.channels.StreamSinkChannel;
import static org.xnio.Bits.anyAreClear;
import static org.xnio.Bits.anyAreSet;
/**
* Output stream used for upgraded requests. This is different to {@link ServletOutputStreamImpl}
* as it does no buffering, and it not tied to an exchange.
*
* @author Stuart Douglas
*/
public class UpgradeServletOutputStream extends ServletOutputStream {
private final StreamSinkChannel channel;
private WriteListener listener;
/**
* If this stream is ready for a write
*/
private static final int FLAG_READY = 1;
private static final int FLAG_CLOSED = 1 << 1;
private static final int FLAG_DELEGATE_SHUTDOWN = 1 << 2;
private int state;
/**
* The buffer that is in the process of being written out
*/
private ByteBuffer buffer;
protected UpgradeServletOutputStream(final StreamSinkChannel channel) {
this.channel = channel;
}
@Override
public void write(final byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
public void write(final byte[] b, final int off, final int len) throws IOException {
if (anyAreSet(state, FLAG_CLOSED)) {
throw UndertowServletMessages.MESSAGES.streamIsClosed();
}
if (listener == null) {
Channels.writeBlocking(channel, ByteBuffer.wrap(b, off, len));
} else {
if (anyAreClear(state, FLAG_READY)) {
throw UndertowServletMessages.MESSAGES.streamNotReady();
}
int res;
ByteBuffer buffer = ByteBuffer.wrap(b);
do {
res = channel.write(buffer);
if (res == 0) {
ByteBuffer copy = ByteBuffer.allocate(buffer.remaining());
copy.put(buffer);
copy.flip();
this.buffer = copy;
state = state & ~FLAG_READY;
channel.resumeWrites();
return;
}
} while (buffer.hasRemaining());
}
}
@Override
public void write(final int b) throws IOException {
write(new byte[]{(byte) b}, 0, 1);
}
@Override
public void flush() throws IOException {
if (anyAreSet(state, FLAG_CLOSED)) {
throw UndertowServletMessages.MESSAGES.streamIsClosed();
}
if (listener == null) {
Channels.flushBlocking(channel);
}
}
@Override
public void close() throws IOException {
state |= FLAG_CLOSED;
state &= ~FLAG_READY;
if (listener == null) {
channel.shutdownWrites();
state |= FLAG_DELEGATE_SHUTDOWN;
Channels.flushBlocking(channel);
} else {
if (buffer == null) {
channel.shutdownWrites();
state |= FLAG_DELEGATE_SHUTDOWN;
if (!channel.flush()) {
channel.resumeWrites();
}
}
}
}
void closeBlocking() throws IOException {
state |= FLAG_CLOSED;
try {
if (buffer != null) {
Channels.writeBlocking(channel, buffer);
}
channel.shutdownWrites();
Channels.flushBlocking(channel);
} finally {
channel.close();
}
}
@Override
public boolean isReady() {
if (listener == null) {
//TODO: is this the correct behaviour?
throw UndertowServletMessages.MESSAGES.streamNotInAsyncMode();
}
return anyAreSet(state, FLAG_READY);
}
@Override
public void setWriteListener(final WriteListener writeListener) {
if (writeListener == null) {
throw UndertowServletMessages.MESSAGES.paramCannotBeNull("writeListener");
}
if(listener != null) {
throw UndertowServletMessages.MESSAGES.listenerAlreadySet();
}
listener = writeListener;
channel.getWriteSetter().set(new WriteChannelListener());
channel.resumeWrites();
}
private class WriteChannelListener implements ChannelListener<StreamSinkChannel> {
@Override
public void handleEvent(final StreamSinkChannel channel) {
//flush the channel if it is closed
if (anyAreSet(state, FLAG_DELEGATE_SHUTDOWN)) {
try {
//either it will work, and the channel is closed
//or it won't, and we continue with writes resumed
channel.flush();
return;
} catch (IOException e) {
handleError(channel, e);
}
}
//if there is data still to write
if (buffer != null) {
int res;
do {
try {
res = channel.write(buffer);
if (res == 0) {
return;
}
} catch (IOException e) {
handleError(channel, e);
}
} while (buffer.hasRemaining());
buffer = null;
}
if (anyAreSet(state, FLAG_CLOSED)) {
try {
channel.shutdownWrites();
state |= FLAG_DELEGATE_SHUTDOWN;
channel.flush(); //if this does not succeed we are already resumed anyway
} catch (IOException e) {
handleError(channel, e);
}
} else {
state |= FLAG_READY;
channel.suspendWrites();
channel.getWorker().submit(new Runnable() {
@Override
public void run() {
try {
listener.onWritePossible();
} catch (IOException e) {
listener.onError(e);
}
}
});
}
}
private void handleError(final StreamSinkChannel channel, final IOException e) {
try {
listener.onError(e);
} finally {
IoUtils.safeClose(channel);
}
}
}
}
| Mark stream as writable straight away
| servlet/src/main/java/io/undertow/servlet/spec/UpgradeServletOutputStream.java | Mark stream as writable straight away | <ide><path>ervlet/src/main/java/io/undertow/servlet/spec/UpgradeServletOutputStream.java
<ide> }
<ide> listener = writeListener;
<ide> channel.getWriteSetter().set(new WriteChannelListener());
<add> state |= FLAG_READY;
<ide> channel.resumeWrites();
<ide> }
<ide> |
|
Java | apache-2.0 | 8e8412f11467240c75120922c2fbfc693e73891b | 0 | aerobase/unifiedpush-server,aerobase/unifiedpush-server,aerobase/unifiedpush-server,C-B4/unifiedpush-server,C-B4/unifiedpush-server,C-B4/unifiedpush-server,C-B4/unifiedpush-server | package org.jboss.aerogear.unifiedpush.rest.registry.installations;
import java.net.URL;
import java.util.ArrayList;
import javax.inject.Inject;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.jboss.aerogear.unifiedpush.api.Installation;
import org.jboss.aerogear.unifiedpush.api.InstallationVerificationAttempt;
import org.jboss.aerogear.unifiedpush.api.PushApplication;
import org.jboss.aerogear.unifiedpush.api.Variant;
import org.jboss.aerogear.unifiedpush.rest.RestApplication;
import org.jboss.aerogear.unifiedpush.rest.RestEndpointTest;
import org.jboss.aerogear.unifiedpush.rest.util.Authenticator;
import org.jboss.aerogear.unifiedpush.rest.util.ClientAuthHelper;
import org.jboss.aerogear.unifiedpush.rest.util.HttpBasicHelper;
import org.jboss.aerogear.unifiedpush.service.AliasService;
import org.jboss.aerogear.unifiedpush.service.ClientInstallationService;
import org.jboss.aerogear.unifiedpush.service.Configuration;
import org.jboss.aerogear.unifiedpush.service.GenericVariantService;
import org.jboss.aerogear.unifiedpush.service.PropertyPlaceholderConfigurer;
import org.jboss.aerogear.unifiedpush.service.PushApplicationService;
import org.jboss.aerogear.unifiedpush.service.VerificationService;
import org.jboss.aerogear.unifiedpush.service.VerificationService.VerificationResult;
import org.jboss.aerogear.unifiedpush.test.archive.UnifiedPushServiceArchive;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.arquillian.transaction.api.annotation.TransactionMode;
import org.jboss.arquillian.transaction.api.annotation.Transactional;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.jboss.resteasy.plugins.providers.RegisterBuiltin;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
public class InstallationRegistrationEndpointTest extends RestEndpointTest {
private static final String RESOURCE_PREFIX = RestApplication.class.getAnnotation(ApplicationPath.class).value().substring(1);
@Deployment
public static WebArchive archive() {
return UnifiedPushServiceArchive.forTestClass(InstallationRegistrationEndpointTest.class)
.addMavenDependencies("org.jboss.aerogear.unifiedpush:unifiedpush-service")
.addAsLibrary("org.jboss.aerogear.unifiedpush:unifiedpush-model-jpa", new String[]{"META-INF/persistence.xml",
"test-data.sql"}, new String[] {"META-INF/test-persistence.xml", "META-INF/test-data.sql"})
.addPackage(RestApplication.class.getPackage())
.addPackage(InstallationRegistrationEndpoint.class.getPackage())
.addPackage(InstallationRegistrationEndpoint.class.getPackage())
.addClasses(RestEndpointTest.class, InstallationRegistrationEndpoint.class, RestApplication.class,
HttpBasicHelper.class, Authenticator.class, ClientAuthHelper.class)
.addAsWebInfResource("META-INF/test-ds.xml", "test-ds.xml")
.addAsResource("test.properties", "default.properties")
.as(WebArchive.class);
}
@BeforeClass
public static void initResteasyClient() {
RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
}
@Test
@RunAsClient
public void unAuthorizedDeviceTest(@ArquillianResource URL deploymentUrl) {
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target(deploymentUrl.toString() + RESOURCE_PREFIX + "/registry/device");
Response response = target.request().post(Entity.entity(new Installation(), MediaType.APPLICATION_JSON_TYPE));
Assert.assertTrue(response.getStatus() == 401);
}
@Test
@RunAsClient
public void registerDeviceTest(@ArquillianResource URL deploymentUrl) {
// Prepare installation
Installation iosInstallation = getDefaultInstallation();
ResteasyClient client = new ResteasyClientBuilder().register(new Authenticator(DEFAULT_VARIENT_ID, DEFAULT_VARIENT_PASS)).build();
try{
ResteasyWebTarget target = client.target(deploymentUrl.toString() + RESOURCE_PREFIX + "/registry/device");
Response response = target.request().post(Entity.entity(iosInstallation, MediaType.APPLICATION_JSON_TYPE));
Installation newInstallation = response.readEntity(Installation.class);
Assert.assertTrue(response.getStatus() == 200);
Assert.assertTrue(newInstallation.isEnabled());
} catch (Throwable e){
Assert.fail(e.getMessage());
}
}
@Inject
private Configuration configuration;
@Inject
private GenericVariantService genericVariantService;
@Inject
private ClientInstallationService installationService;
@Inject
private PushApplicationService applicationService;
@Inject
private VerificationService verificationService;
@Inject
private AliasService aliasService;
@Test
@Transactional(TransactionMode.ROLLBACK)
public void enableDeviceTest() {
// Prepare installation
Installation iosInstallation = getDefaultInstallation();
// Also check case sensitive aliases
iosInstallation.setAlias("[email protected]");
try {
configuration.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);
System.setProperty(Configuration.PROP_ENABLE_VERIFICATION, "true");
Variant variant = genericVariantService.findByVariantID(DEFAULT_VARIENT_ID);
Assert.assertTrue(variant.getVariantID().equals(DEFAULT_VARIENT_ID));
installationService.addInstallationSynchronously(variant, iosInstallation);
Installation inst = installationService.findById(iosInstallation.getId());
Assert.assertTrue(inst != null && inst.isEnabled() == false);
// Register alias
PushApplication app = applicationService.findByVariantID(variant.getVariantID());
ArrayList<String> aliases = new ArrayList<String>();
aliases.add("[email protected]");
aliasService.updateAliasesAndInstallations(app, aliases, false);
// ReEnable device
String code = verificationService.initiateDeviceVerification(inst, variant);
VerificationResult results = verificationService.verifyDevice(inst, variant, new InstallationVerificationAttempt(code, inst.getDeviceToken()));
Assert.assertTrue(results != null && results.equals(VerificationResult.SUCCESS));
Variant var = installationService.associateInstallation(inst, variant);
Assert.assertTrue(var != null);
} catch (Throwable e) {
Assert.fail(e.getMessage());
}finally{
// Rest system property to false
System.setProperty(Configuration.PROP_ENABLE_VERIFICATION, "false");
}
}
} | jaxrs/src/test/java/org/jboss/aerogear/unifiedpush/rest/registry/installations/InstallationRegistrationEndpointTest.java | package org.jboss.aerogear.unifiedpush.rest.registry.installations;
import java.net.URL;
import java.util.ArrayList;
import javax.inject.Inject;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.jboss.aerogear.unifiedpush.api.Installation;
import org.jboss.aerogear.unifiedpush.api.InstallationVerificationAttempt;
import org.jboss.aerogear.unifiedpush.api.PushApplication;
import org.jboss.aerogear.unifiedpush.api.Variant;
import org.jboss.aerogear.unifiedpush.rest.RestApplication;
import org.jboss.aerogear.unifiedpush.rest.RestEndpointTest;
import org.jboss.aerogear.unifiedpush.rest.util.Authenticator;
import org.jboss.aerogear.unifiedpush.rest.util.HttpBasicHelper;
import org.jboss.aerogear.unifiedpush.service.AliasService;
import org.jboss.aerogear.unifiedpush.service.ClientInstallationService;
import org.jboss.aerogear.unifiedpush.service.Configuration;
import org.jboss.aerogear.unifiedpush.service.GenericVariantService;
import org.jboss.aerogear.unifiedpush.service.PropertyPlaceholderConfigurer;
import org.jboss.aerogear.unifiedpush.service.PushApplicationService;
import org.jboss.aerogear.unifiedpush.service.VerificationService;
import org.jboss.aerogear.unifiedpush.service.VerificationService.VerificationResult;
import org.jboss.aerogear.unifiedpush.test.archive.UnifiedPushServiceArchive;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.arquillian.transaction.api.annotation.TransactionMode;
import org.jboss.arquillian.transaction.api.annotation.Transactional;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.jboss.resteasy.plugins.providers.RegisterBuiltin;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
public class InstallationRegistrationEndpointTest extends RestEndpointTest {
private static final String RESOURCE_PREFIX = RestApplication.class.getAnnotation(ApplicationPath.class).value().substring(1);
@Deployment
public static WebArchive archive() {
return UnifiedPushServiceArchive.forTestClass(InstallationRegistrationEndpointTest.class)
.addMavenDependencies("org.jboss.aerogear.unifiedpush:unifiedpush-service")
.addAsLibrary("org.jboss.aerogear.unifiedpush:unifiedpush-model-jpa", new String[]{"META-INF/persistence.xml",
"test-data.sql"}, new String[] {"META-INF/test-persistence.xml", "META-INF/test-data.sql"})
.addPackage(RestApplication.class.getPackage())
.addPackage(InstallationRegistrationEndpoint.class.getPackage())
.addClasses(RestEndpointTest.class, InstallationRegistrationEndpoint.class, RestApplication.class, HttpBasicHelper.class, Authenticator.class)
.addAsWebInfResource("META-INF/test-ds.xml", "test-ds.xml")
.addAsResource("test.properties", "default.properties")
.as(WebArchive.class);
}
@BeforeClass
public static void initResteasyClient() {
RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
}
@Test
@RunAsClient
public void unAuthorizedDeviceTest(@ArquillianResource URL deploymentUrl) {
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target(deploymentUrl.toString() + RESOURCE_PREFIX + "/registry/device");
Response response = target.request().post(Entity.entity(new Installation(), MediaType.APPLICATION_JSON_TYPE));
Assert.assertTrue(response.getStatus() == 401);
}
@Test
@RunAsClient
public void registerDeviceTest(@ArquillianResource URL deploymentUrl) {
// Prepare installation
Installation iosInstallation = getDefaultInstallation();
ResteasyClient client = new ResteasyClientBuilder().register(new Authenticator(DEFAULT_VARIENT_ID, DEFAULT_VARIENT_PASS)).build();
try{
ResteasyWebTarget target = client.target(deploymentUrl.toString() + RESOURCE_PREFIX + "/registry/device");
Response response = target.request().post(Entity.entity(iosInstallation, MediaType.APPLICATION_JSON_TYPE));
Installation newInstallation = response.readEntity(Installation.class);
Assert.assertTrue(response.getStatus() == 200);
Assert.assertTrue(newInstallation.isEnabled());
} catch (Throwable e){
Assert.fail(e.getMessage());
}
}
@Inject
private Configuration configuration;
@Inject
private GenericVariantService genericVariantService;
@Inject
private ClientInstallationService installationService;
@Inject
private PushApplicationService applicationService;
@Inject
private VerificationService verificationService;
@Inject
private AliasService aliasService;
@Test
@Transactional(TransactionMode.ROLLBACK)
public void enableDeviceTest() {
// Prepare installation
Installation iosInstallation = getDefaultInstallation();
// Also check case sensitive aliases
iosInstallation.setAlias("[email protected]");
try {
configuration.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);
System.setProperty(Configuration.PROP_ENABLE_VERIFICATION, "true");
Variant variant = genericVariantService.findByVariantID(DEFAULT_VARIENT_ID);
Assert.assertTrue(variant.getVariantID().equals(DEFAULT_VARIENT_ID));
installationService.addInstallationSynchronously(variant, iosInstallation);
Installation inst = installationService.findById(iosInstallation.getId());
Assert.assertTrue(inst != null && inst.isEnabled() == false);
// Register alias
PushApplication app = applicationService.findByVariantID(variant.getVariantID());
ArrayList<String> aliases = new ArrayList<String>();
aliases.add("[email protected]");
aliasService.updateAliasesAndInstallations(app, aliases, false);
// ReEnable device
String code = verificationService.initiateDeviceVerification(inst, variant);
VerificationResult results = verificationService.verifyDevice(inst, variant, new InstallationVerificationAttempt(code, inst.getDeviceToken()));
Assert.assertTrue(results != null && results.equals(VerificationResult.SUCCESS));
Variant var = installationService.associateInstallation(inst, variant);
Assert.assertTrue(var != null);
} catch (Throwable e) {
Assert.fail(e.getMessage());
}finally{
// Rest system property to false
System.setProperty(Configuration.PROP_ENABLE_VERIFICATION, "false");
}
}
} | Fix junit test failure due to previous commit
| jaxrs/src/test/java/org/jboss/aerogear/unifiedpush/rest/registry/installations/InstallationRegistrationEndpointTest.java | Fix junit test failure due to previous commit | <ide><path>axrs/src/test/java/org/jboss/aerogear/unifiedpush/rest/registry/installations/InstallationRegistrationEndpointTest.java
<ide> import org.jboss.aerogear.unifiedpush.rest.RestApplication;
<ide> import org.jboss.aerogear.unifiedpush.rest.RestEndpointTest;
<ide> import org.jboss.aerogear.unifiedpush.rest.util.Authenticator;
<add>import org.jboss.aerogear.unifiedpush.rest.util.ClientAuthHelper;
<ide> import org.jboss.aerogear.unifiedpush.rest.util.HttpBasicHelper;
<ide> import org.jboss.aerogear.unifiedpush.service.AliasService;
<ide> import org.jboss.aerogear.unifiedpush.service.ClientInstallationService;
<ide> "test-data.sql"}, new String[] {"META-INF/test-persistence.xml", "META-INF/test-data.sql"})
<ide> .addPackage(RestApplication.class.getPackage())
<ide> .addPackage(InstallationRegistrationEndpoint.class.getPackage())
<del> .addClasses(RestEndpointTest.class, InstallationRegistrationEndpoint.class, RestApplication.class, HttpBasicHelper.class, Authenticator.class)
<add> .addPackage(InstallationRegistrationEndpoint.class.getPackage())
<add> .addClasses(RestEndpointTest.class, InstallationRegistrationEndpoint.class, RestApplication.class,
<add> HttpBasicHelper.class, Authenticator.class, ClientAuthHelper.class)
<ide> .addAsWebInfResource("META-INF/test-ds.xml", "test-ds.xml")
<ide> .addAsResource("test.properties", "default.properties")
<ide> .as(WebArchive.class); |
|
JavaScript | mit | 1b0ae6504f2be314d4152ac80b63918c100f9646 | 0 | kunruch/mmcss,kunruch/mmcss | var config = require('./config.json');
var package = require('./../package.json')
var gulp = require('gulp');
var jade = require('gulp-jade');
/**
* Generate HTML
*/
gulp.task('html', function () {
return gulp.src(config.html.SRC)
.pipe(jade({
pretty: true,
data: {
package: package
}
}))
.pipe(gulp.dest(config.html.DEST))
});
/**
* Generate Minified HTML
*/
gulp.task('html-min', function () {
return gulp.src(config.html.SRC)
.pipe(jade({
pretty: false,
data: {
package: package
}
}))
.pipe(gulp.dest(config.html.DEST))
}); | tasks/html.js | var config = require('./config.json');
var package = require('./../package.json')
var gulp = require('gulp');
var jade = require('gulp-jade');
/**
* Generate HTML
*/
gulp.task('html', function () {
return gulp.src(config.html.SRC)
.pipe(jade({
pretty: true,
locals: {
package: package
}
}))
.pipe(gulp.dest(config.html.DEST))
});
/**
* Generate Minified HTML
*/
gulp.task('html-min', function () {
return gulp.src(config.html.SRC)
.pipe(jade({ pretty: false}))
.pipe(gulp.dest(config.html.DEST))
}); | Fixing build break
| tasks/html.js | Fixing build break | <ide><path>asks/html.js
<ide> return gulp.src(config.html.SRC)
<ide> .pipe(jade({
<ide> pretty: true,
<del> locals: {
<add> data: {
<ide> package: package
<ide> }
<ide> }))
<ide> */
<ide> gulp.task('html-min', function () {
<ide> return gulp.src(config.html.SRC)
<del> .pipe(jade({ pretty: false}))
<add> .pipe(jade({
<add> pretty: false,
<add> data: {
<add> package: package
<add> }
<add> }))
<ide> .pipe(gulp.dest(config.html.DEST))
<ide> }); |
|
Java | apache-2.0 | 41cc8351cfecf0a11e92f8d99023014189936cd3 | 0 | liduanw/bitherj,liduanw/bitherj,bither/bitherj,bither/bitherj | /*
* Copyright 2014 http://Bither.net
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.bither.bitherj.core;
import net.bither.bitherj.db.TxProvider;
import net.bither.bitherj.exception.ProtocolException;
import net.bither.bitherj.exception.ScriptException;
import net.bither.bitherj.message.Message;
import net.bither.bitherj.script.Script;
import net.bither.bitherj.utils.Utils;
import net.bither.bitherj.utils.VarInt;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import javax.annotation.Nullable;
public class In extends Message {
public static final int OUTPOINT_MESSAGE_LENGTH = 36;
public static final long NO_SEQUENCE = 0xFFFFFFFFL;
private byte[] txHash;
private int inSn;
private byte[] prevTxHash;
private int prevOutSn;
private byte[] inSignature;
private byte[] prevOutScript;
private long inSequence;
private Tx tx;
private transient Out connectedOut;
public byte[] getTxHash() {
return txHash;
}
public void setTxHash(byte[] txHash) {
this.txHash = txHash;
}
public int getInSn() {
return inSn;
}
public void setInSn(int inSn) {
this.inSn = inSn;
}
public byte[] getPrevTxHash() {
return prevTxHash;
}
public void setPrevTxHash(byte[] prevTxHash) {
this.prevTxHash = prevTxHash;
}
public int getPrevOutSn() {
return prevOutSn;
}
public void setPrevOutSn(int prevOutSn) {
this.prevOutSn = prevOutSn;
}
public byte[] getInSignature() {
return inSignature;
}
public void setInSignature(byte[] inSignature) {
this.inSignature = inSignature;
}
public byte[] getPrevOutScript() {
return prevOutScript;
}
public void setPrevOutScript(byte[] prevOutScript) {
this.prevOutScript = prevOutScript;
}
public long getInSequence() {
return inSequence;
}
public void setInSequence(long inSequence) {
this.inSequence = inSequence;
}
public OutPoint getOutpoint(){
return new OutPoint(this.prevTxHash, this.prevOutSn);
}
public Tx getTx() {
return tx;
}
public void setTx(Tx tx) {
this.tx = tx;
this.txHash = tx.getTxHash();
}
@Override
public boolean equals(Object o) {
if (o instanceof In) {
In inItem = (In) o;
return getInSn() == inItem.getInSn() &&
Arrays.equals(getPrevTxHash(), inItem.getPrevTxHash()) &&
getPrevOutSn() == inItem.getPrevOutSn() &&
Arrays.equals(getTxHash(), inItem.getTxHash()) &&
getInSequence() == inItem.getInSequence() &&
Arrays.equals(getInSignature(), inItem.getInSignature());
} else {
return false;
}
}
public In() {
this.inSequence = NO_SEQUENCE;
}
public In(Tx tx, byte[] msg, int offset) {
super(msg, offset);
this.tx = tx;
this.txHash = tx.getTxHash();
}
public In(Tx tx, Out out) {
this.tx = tx;
this.txHash = tx.getTxHash();
prevTxHash = out.getTxHash();
prevOutSn = out.getOutSn();
prevOutScript = out.getOutScript();
this.inSequence = NO_SEQUENCE;
}
public In(@Nullable Tx parentTransaction, byte[] scriptBytes,
Out outpoint) {
super();
this.inSignature = scriptBytes;
this.prevTxHash = outpoint.getTxHash();
this.prevOutSn = outpoint.getOutSn();
this.prevOutScript = outpoint.getOutScript();
this.inSequence = NO_SEQUENCE;
this.tx = parentTransaction;
this.txHash = this.tx.getTxHash();
length = 40 + (scriptBytes == null ? 1 : VarInt.sizeOf(scriptBytes.length) + scriptBytes.length);
}
protected void parse() throws ProtocolException {
int curs = cursor;
int scriptLen = (int) readVarInt(36);
length = cursor - offset + scriptLen + 4;
cursor = curs;
prevTxHash = readHash();
prevOutSn = (int) readUint32();
scriptLen = (int) readVarInt();
inSignature = readBytes(scriptLen);
inSequence = readUint32();
}
@Override
protected void bitcoinSerializeToStream(OutputStream stream) throws IOException {
stream.write(prevTxHash);
Utils.uint32ToByteStreamLE(prevOutSn, stream);
stream.write(new VarInt(inSignature.length).encode());
stream.write(inSignature);
Utils.uint32ToByteStreamLE(inSequence, stream);
}
/**
* Coinbase transactions have special inputs with hashes of zero. If this is such an input, returns true.
*/
public boolean isCoinBase() {
return Arrays.equals(prevTxHash, new byte[32]) &&
(prevOutSn & 0xFFFFFFFFL) == 0xFFFFFFFFL; // -1 but all is serialized to the wire as unsigned int.
}
/**
* @return true if this transaction's sequence number is set (ie it may be a part of a time-locked transaction)
*/
public boolean hasSequence() {
return inSequence != NO_SEQUENCE;
}
public Out getConnectedOut(){
if(connectedOut == null){
Tx preTx = TxProvider.getInstance().getTxDetailByTxHash(getPrevTxHash());
if(preTx == null){
return null;
}
if(getPrevOutSn() >=0 && getPrevOutSn() < preTx.getOuts().size()){
connectedOut = preTx.getOuts().get(getPrevOutSn());
}
}
return connectedOut;
}
public String getFromAddress(){
if(getConnectedOut() != null){
return getConnectedOut().getOutAddress();
} else if (this.getInSignature() != null){
Script script = new Script(this.getInSignature());
if (script.getChunks().size() == 2) {
try {
return script.getFromAddress();
} catch (ScriptException ex) {
ex.printStackTrace();
}
}
}
return null;
}
public long getValue(){
if(getConnectedOut() != null){
return getConnectedOut().getOutValue();
}
return 0;
}
}
| bitherj/src/main/java/net/bither/bitherj/core/In.java | /*
* Copyright 2014 http://Bither.net
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.bither.bitherj.core;
import net.bither.bitherj.db.TxProvider;
import net.bither.bitherj.exception.ProtocolException;
import net.bither.bitherj.exception.ScriptException;
import net.bither.bitherj.message.Message;
import net.bither.bitherj.script.Script;
import net.bither.bitherj.utils.Utils;
import net.bither.bitherj.utils.VarInt;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import javax.annotation.Nullable;
public class In extends Message {
public static final int OUTPOINT_MESSAGE_LENGTH = 36;
public static final long NO_SEQUENCE = 0xFFFFFFFFL;
private byte[] txHash;
private int inSn;
private byte[] prevTxHash;
private int prevOutSn;
private byte[] inSignature;
private byte[] prevOutScript;
private long inSequence;
private Tx tx;
private transient Out connectedOut;
public byte[] getTxHash() {
return txHash;
}
public void setTxHash(byte[] txHash) {
this.txHash = txHash;
}
public int getInSn() {
return inSn;
}
public void setInSn(int inSn) {
this.inSn = inSn;
}
public byte[] getPrevTxHash() {
return prevTxHash;
}
public void setPrevTxHash(byte[] prevTxHash) {
this.prevTxHash = prevTxHash;
}
public int getPrevOutSn() {
return prevOutSn;
}
public void setPrevOutSn(int prevOutSn) {
this.prevOutSn = prevOutSn;
}
public byte[] getInSignature() {
return inSignature;
}
public void setInSignature(byte[] inSignature) {
this.inSignature = inSignature;
}
public byte[] getPrevOutScript() {
return prevOutScript;
}
public void setPrevOutScript(byte[] prevOutScript) {
this.prevOutScript = prevOutScript;
}
public long getInSequence() {
return inSequence;
}
public void setInSequence(long inSequence) {
this.inSequence = inSequence;
}
public OutPoint getOutpoint(){
return new OutPoint(this.prevTxHash, this.prevOutSn);
}
public Tx getTx() {
return tx;
}
public void setTx(Tx tx) {
this.tx = tx;
this.txHash = tx.getTxHash();
}
@Override
public boolean equals(Object o) {
if (o instanceof In) {
In inItem = (In) o;
return getInSn() == inItem.getInSn() &&
Arrays.equals(getPrevTxHash(), inItem.getPrevTxHash()) &&
getPrevOutSn() == inItem.getPrevOutSn() &&
Arrays.equals(getTxHash(), inItem.getTxHash()) &&
getInSequence() == inItem.getInSequence() &&
Arrays.equals(getInSignature(), inItem.getInSignature());
} else {
return false;
}
}
public In() {
this.inSequence = NO_SEQUENCE;
}
public In(Tx tx, byte[] msg, int offset) {
super(msg, offset);
this.tx = tx;
this.txHash = tx.getTxHash();
}
public In(Tx tx, Out out) {
this.tx = tx;
this.txHash = tx.getTxHash();
prevTxHash = out.getTxHash();
prevOutSn = out.getOutSn();
prevOutScript = out.getOutScript();
this.inSequence = NO_SEQUENCE;
}
public In(@Nullable Tx parentTransaction, byte[] scriptBytes,
Out outpoint) {
super();
this.inSignature = scriptBytes;
this.prevTxHash = outpoint.getTxHash();
this.prevOutSn = outpoint.getOutSn();
this.prevOutScript = outpoint.getOutScript();
this.inSequence = NO_SEQUENCE;
this.tx = parentTransaction;
this.txHash = this.tx.getTxHash();
length = 40 + (scriptBytes == null ? 1 : VarInt.sizeOf(scriptBytes.length) + scriptBytes.length);
}
protected void parse() throws ProtocolException {
int curs = cursor;
int scriptLen = (int) readVarInt(36);
length = cursor - offset + scriptLen + 4;
cursor = curs;
prevTxHash = readHash();
prevOutSn = (int) readUint32();
scriptLen = (int) readVarInt();
inSignature = readBytes(scriptLen);
inSequence = readUint32();
}
@Override
protected void bitcoinSerializeToStream(OutputStream stream) throws IOException {
stream.write(prevTxHash);
Utils.uint32ToByteStreamLE(prevOutSn, stream);
stream.write(new VarInt(inSignature.length).encode());
stream.write(inSignature);
Utils.uint32ToByteStreamLE(inSequence, stream);
}
/**
* Coinbase transactions have special inputs with hashes of zero. If this is such an input, returns true.
*/
public boolean isCoinBase() {
return Arrays.equals(prevTxHash, new byte[32]) &&
(prevOutSn & 0xFFFFFFFFL) == 0xFFFFFFFFL; // -1 but all is serialized to the wire as unsigned int.
}
/**
* @return true if this transaction's sequence number is set (ie it may be a part of a time-locked transaction)
*/
public boolean hasSequence() {
return inSequence != NO_SEQUENCE;
}
public Out getConnectedOut(){
if(connectedOut == null){
Tx preTx = TxProvider.getInstance().getTxDetailByTxHash(getPrevTxHash());
if(preTx == null){
return null;
}
if(getPrevOutSn() >=0 && getPrevOutSn() < preTx.getOuts().size()){
connectedOut = preTx.getOuts().get(getPrevOutSn());
}
}
return connectedOut;
}
public String getFromAddress(){
if(getConnectedOut() != null){
return getConnectedOut().getOutAddress();
} else {
Script script = new Script(this.getInSignature());
if (script.getChunks().size() == 2) {
try {
return script.getFromAddress();
} catch (ScriptException ex) {
ex.printStackTrace();
}
}
}
return null;
}
public long getValue(){
if(getConnectedOut() != null){
return getConnectedOut().getOutValue();
}
return 0;
}
}
| fix: in 's signature may be null
| bitherj/src/main/java/net/bither/bitherj/core/In.java | fix: in 's signature may be null | <ide><path>itherj/src/main/java/net/bither/bitherj/core/In.java
<ide> public String getFromAddress(){
<ide> if(getConnectedOut() != null){
<ide> return getConnectedOut().getOutAddress();
<del> } else {
<add> } else if (this.getInSignature() != null){
<ide> Script script = new Script(this.getInSignature());
<ide> if (script.getChunks().size() == 2) {
<ide> try { |
|
JavaScript | mit | 26c6071d49a33159342d262581dd80f9b2d3147d | 0 | jourdanrodrigues/controk-frontend-web,jourdanrodrigues/controk-frontend-web | 'use strict';
let spawn = require("child_process").spawn,
exitHandler = function (code) {
// Exit handler thought: http://stackoverflow.com/a/14032965
spawn("pkill", ["-TERM", "-P", process.pid]);
process.exit(code);
};
process.on("exit", exitHandler);
process.on("close", exitHandler);
process.on("SIGINT", exitHandler.bind(1));
let emitMessage = (message) => {
console.log("\x1b[36m", message, "\x1b[0m");
};
// Synchronously check if ".env" exists before import
let fs = require("fs");
if (fs.existsSync(".env")) {
require("dotenv").config();
}
// Imports
let gulp = require("gulp"),
gulpIf = require("gulp-if");
let testing = process.argv.indexOf("test") >= 0,
port = process.env.PORT || "8888";
// Environment Variables
if (testing) { // Execute tests without debug
process.env["DEBUG"] = "0";
}
let debug = process.env.DEBUG == "1",
apiURL = process.env.API_URL || "",
socketHost = process.env.SOCKET_HOST || "";
// Tasks definitions
gulp.task("jshint", function() {
let jshint = require("gulp-jshint");
return gulp.src(["**/*.js", "!{assets,dist,node_modules,coverage}/**", "!app/app.module.js"])
.pipe(jshint())
.pipe(jshint.reporter("default"));
});
gulp.task("compile", function() {
let rename = require("gulp-rename"),
replace = require("gulp-replace"),
sass = require("gulp-sass");
return gulp
.src(["**/*.{src.html,src.js,src.json,scss}", "!node_modules/**"])
// Define path (and name if ".src")
.pipe(rename((path) => { path.basename = path.basename.replace(".src", "") }))
// Performs the operations for each file
.pipe(gulpIf("*.js", replace("***apiURL***", apiURL)))
.pipe(gulpIf("*.json", replace("***apiURL***", apiURL)))
.pipe(gulpIf("*.js", replace("***socketHost***", socketHost)))
.pipe(gulpIf("*.js", replace("***codeCoverage***", testing.toString())))
.pipe(gulpIf("*.scss", sass.sync().on("error", sass.logError)))
.pipe(gulp.dest(""));
});
// Last task before connection
gulp.task("build", ["compile"], function() {
let useref = require("gulp-useref"),
uglify = require("gulp-uglify"),
cleanCss = require("gulp-clean-css"),
htmlMin = require("gulp-htmlmin"),
img64 = require("gulp-img64");
return gulp
.src(["**/*.{html,ico}", "!{coverage,dist,node_modules}/**"])
.pipe(gulpIf("index.html", useref()))
.pipe(gulpIf("*.js", uglify()))
.pipe(gulpIf("*.css", cleanCss({removeComments: true})))
.pipe(gulpIf("*.html", htmlMin({collapseWhitespace: true})))
.pipe(gulpIf("*.html", img64()))
.pipe(gulp.dest("dist"));
});
let fileHandlerTask = ((debug || testing) ? "compile" : "build");
gulp.task("connect", function() {
let express = require('express'),
app = express(),
im = require('istanbul-middleware');
if (testing) {
im.hookLoader(".");
app.use("/coverage", im.createHandler());
app.use(im.createClientHandler(__dirname));
}
app.use(express.static(`${__dirname}/${debug || testing ? "" : "dist"}`));
app.listen(port, function () {
emitMessage(`Server started at "http://0.0.0.0:${port}/".`);
});
});
gulp.task("watch", function() {
gulp.watch(
["**/*.{js,html,scss}", "!app/app.module.js", "!{assets,dist,node_modules,tests}/**",
"!{protractor.conf,gulpfile}.js"],
[fileHandlerTask]
);
});
// Standalone mode
let standaloneTaskDependencies = [fileHandlerTask, "connect"];
if (!testing) {
standaloneTaskDependencies.push("watch");
}
gulp.task("standalone", standaloneTaskDependencies, function() {
let webservicePath = "tests/webservice/",
jsonServer = spawn(
"node_modules/.bin/json-server", [
`${webservicePath}database.json`,
"--routes", `${webservicePath}routes.json`,
"--port", process.env.API_PORT
]
);
jsonServer.stderr.on("data", (data) => { process.stderr.write(data.toString()) });
});
gulp.task("test", ["standalone"], function() {
let request = require("request"),
updateWebDriver = spawn("node_modules/.bin/webdriver-manager", ["update"]);
emitMessage("Forget the message ahead. The \"webdriver\" is being updated...");
updateWebDriver.on("close", function (code) {
if (code != 0) {
process.exit(code);
}
emitMessage("To the tests...");
let protractor = spawn("node_modules/.bin/protractor");
protractor.stdout.on("data", (data) => { process.stdout.write(data.toString()) });
protractor.on("close", function (code) {
//noinspection JSCheckFunctionSignatures
request(`http://localhost:${port}/coverage/download`)
.pipe(fs.createWriteStream("coverage.zip"))
.on("close", function () {
let zip = new (require("adm-zip"))("./coverage.zip");
//noinspection JSUnresolvedFunction
zip.extractAllTo("coverage", true);
process.exit(code);
});
});
});
});
gulp.task("default", [fileHandlerTask, "connect", "watch"]);
| gulpfile.js | 'use strict';
let spawn = require("child_process").spawn,
exitHandler = function (code) {
// Exit handler thought: http://stackoverflow.com/a/14032965
spawn("pkill", ["-TERM", "-P", process.pid]);
process.exit(code);
};
process.on("exit", exitHandler);
process.on("close", exitHandler);
process.on("SIGINT", exitHandler.bind(1));
let emitMessage = (message) => {
console.log("\x1b[36m", message, "\x1b[0m");
};
// Synchronously check if ".env" exists before import
let fs = require("fs");
if (fs.existsSync(".env")) {
require("dotenv").config();
}
// Imports
let gulp = require("gulp"),
gulpIf = require("gulp-if");
let testing = process.argv.indexOf("test") >= 0,
port = process.env.PORT || "8888";
// Environment Variables
if (testing) { // Execute tests without debug
process.env["DEBUG"] = "0";
}
let debug = process.env.DEBUG == "1",
apiURL = process.env.API_URL || "",
socketHost = process.env.SOCKET_HOST || "";
// Tasks definitions
gulp.task("jshint", function() {
let jshint = require("gulp-jshint");
return gulp.src(["**/*.js", "!{assets,dist,node_modules,coverage}/**", "!app/app.module.js"])
.pipe(jshint())
.pipe(jshint.reporter("default"));
});
gulp.task("compile", ["jshint"], function() {
let rename = require("gulp-rename"),
replace = require("gulp-replace"),
sass = require("gulp-sass");
return gulp
.src(["**/*.{src.html,src.js,src.json,scss}", "!node_modules/**"])
// Define path (and name if ".src")
.pipe(rename((path) => { path.basename = path.basename.replace(".src", "") }))
// Performs the operations for each file
.pipe(gulpIf("*.js", replace("***apiURL***", apiURL)))
.pipe(gulpIf("*.json", replace("***apiURL***", apiURL)))
.pipe(gulpIf("*.js", replace("***socketHost***", socketHost)))
.pipe(gulpIf("*.js", replace("***codeCoverage***", testing.toString())))
.pipe(gulpIf("*.scss", sass.sync().on("error", sass.logError)))
.pipe(gulp.dest(""));
});
// Last task before connection
gulp.task("build", ["compile"], function() {
let useref = require("gulp-useref"),
uglify = require("gulp-uglify"),
cleanCss = require("gulp-clean-css"),
htmlMin = require("gulp-htmlmin"),
img64 = require("gulp-img64");
return gulp
.src(["**/*.{html,ico}", "!{coverage,dist,node_modules}/**"])
.pipe(gulpIf("index.html", useref()))
.pipe(gulpIf("*.js", uglify()))
.pipe(gulpIf("*.css", cleanCss({removeComments: true})))
.pipe(gulpIf("*.html", htmlMin({collapseWhitespace: true})))
.pipe(gulpIf("*.html", img64()))
.pipe(gulp.dest("dist"));
});
let fileHandlerTask = ((debug || testing) ? "compile" : "build");
gulp.task("connect", function() {
let express = require('express'),
app = express(),
im = require('istanbul-middleware');
if (testing) {
im.hookLoader(".");
app.use("/coverage", im.createHandler());
app.use(im.createClientHandler(__dirname));
}
app.use(express.static(`${__dirname}/${debug || testing ? "" : "dist"}`));
app.listen(port, function () {
emitMessage(`Server started at "http://0.0.0.0:${port}/".`);
});
});
gulp.task("watch", function() {
gulp.watch(
["**/*.{js,html,scss}", "!app/app.module.js", "!{assets,dist,node_modules,tests}/**",
"!{protractor.conf,gulpfile}.js"],
[fileHandlerTask]
);
});
// Standalone mode
let standaloneTaskDependencies = [fileHandlerTask, "connect"];
if (!testing) {
standaloneTaskDependencies.push("watch");
}
gulp.task("standalone", standaloneTaskDependencies, function() {
let webservicePath = "tests/webservice/",
jsonServer = spawn(
"node_modules/.bin/json-server", [
`${webservicePath}database.json`,
"--routes", `${webservicePath}routes.json`,
"--port", process.env.API_PORT
]
);
jsonServer.stderr.on("data", (data) => { process.stderr.write(data.toString()) });
});
gulp.task("test", ["standalone"], function() {
let request = require("request"),
updateWebDriver = spawn("node_modules/.bin/webdriver-manager", ["update"]);
emitMessage("Forget the message ahead. The \"webdriver\" is being updated...");
updateWebDriver.on("close", function (code) {
if (code != 0) {
process.exit(code);
}
emitMessage("To the tests...");
let protractor = spawn("node_modules/.bin/protractor");
protractor.stdout.on("data", (data) => { process.stdout.write(data.toString()) });
protractor.on("close", function (code) {
//noinspection JSCheckFunctionSignatures
request(`http://localhost:${port}/coverage/download`)
.pipe(fs.createWriteStream("coverage.zip"))
.on("close", function () {
let zip = new (require("adm-zip"))("./coverage.zip");
//noinspection JSUnresolvedFunction
zip.extractAllTo("coverage", true);
process.exit(code);
});
});
});
});
gulp.task("default", [fileHandlerTask, "connect", "watch"]);
| :fire: Removes JSHint from task cause is annoying.
| gulpfile.js | :fire: Removes JSHint from task cause is annoying. | <ide><path>ulpfile.js
<ide> .pipe(jshint.reporter("default"));
<ide> });
<ide>
<del>gulp.task("compile", ["jshint"], function() {
<add>gulp.task("compile", function() {
<ide> let rename = require("gulp-rename"),
<ide> replace = require("gulp-replace"),
<ide> sass = require("gulp-sass"); |
|
Java | apache-2.0 | 51cb1bbdbcac7d1de9a31aaa73c622ca03658d5b | 0 | allurefw/allure2-model | package io.qameta.allure;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.qameta.allure.model.Allure2ModelJackson;
import io.qameta.allure.model.TestResult;
import io.qameta.allure.model.TestResultContainer;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
import static io.qameta.allure.AllureUtils.generateTestResultContainerName;
import static io.qameta.allure.AllureUtils.generateTestResultName;
/**
* @author charlie (Dmitry Baev).
*/
public class FileSystemResultsWriter implements AllureResultsWriter {
private final Path outputDirectory;
private final ObjectMapper mapper;
public FileSystemResultsWriter(Path outputDirectory) {
this.outputDirectory = outputDirectory;
this.mapper = Allure2ModelJackson.createMapper();
}
@Override
public void write(TestResult testResult) {
final String testResultName = Objects.isNull(testResult.getUuid())
? generateTestResultName()
: generateTestResultName(testResult.getUuid());
createDirectories(outputDirectory);
Path file = outputDirectory.resolve(testResultName);
try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file.toFile()))) {
mapper.writeValue(os, testResult);
} catch (IOException e) {
throw new AllureResultsWriteException("Could not write Allure test result", e);
}
}
@Override
public void write(TestResultContainer testResultContainer) {
final String testResultContainerName = Objects.isNull(testResultContainer.getUuid())
? generateTestResultContainerName()
: generateTestResultContainerName(testResultContainer.getUuid());
createDirectories(outputDirectory);
Path file = outputDirectory.resolve(testResultContainerName);
try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file.toFile()))) {
mapper.writeValue(os, testResultContainer);
} catch (IOException e) {
throw new AllureResultsWriteException("Could not write Allure test result container", e);
}
}
@Override
public void write(String source, InputStream attachment) {
createDirectories(outputDirectory);
Path file = outputDirectory.resolve(source);
try (InputStream is = attachment) {
Files.copy(is, file);
} catch (IOException e) {
throw new AllureResultsWriteException("Could not write Allure attachment", e);
}
}
private void createDirectories(Path directory) {
try {
Files.createDirectories(directory);
} catch (IOException e) {
throw new AllureResultsWriteException("Could not create Allure results directory", e);
}
}
}
| allure2-model-api/src/main/java/io/qameta/allure/FileSystemResultsWriter.java | package io.qameta.allure;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.qameta.allure.model.Allure2ModelJackson;
import io.qameta.allure.model.TestResult;
import io.qameta.allure.model.TestResultContainer;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
import static io.qameta.allure.AllureUtils.generateTestResultContainerName;
import static io.qameta.allure.AllureUtils.generateTestResultName;
import static java.nio.file.StandardOpenOption.CREATE_NEW;
/**
* @author charlie (Dmitry Baev).
*/
public class FileSystemResultsWriter implements AllureResultsWriter {
private final Path outputDirectory;
private final ObjectMapper mapper;
public FileSystemResultsWriter(Path outputDirectory) {
this.outputDirectory = outputDirectory;
this.mapper = Allure2ModelJackson.createMapper();
}
@Override
public void write(TestResult testResult) {
final String testResultName = Objects.isNull(testResult.getUuid())
? generateTestResultName()
: generateTestResultName(testResult.getUuid());
createDirectories(outputDirectory);
Path file = outputDirectory.resolve(testResultName);
try (OutputStream os = Files.newOutputStream(file, CREATE_NEW)) {
mapper.writeValue(os, testResult);
} catch (IOException e) {
throw new AllureResultsWriteException("Could not write Allure test result", e);
}
}
@Override
public void write(TestResultContainer testResultContainer) {
final String testResultContainerName = Objects.isNull(testResultContainer.getUuid())
? generateTestResultContainerName()
: generateTestResultContainerName(testResultContainer.getUuid());
createDirectories(outputDirectory);
Path file = outputDirectory.resolve(testResultContainerName);
try (OutputStream os = Files.newOutputStream(file, CREATE_NEW)) {
mapper.writeValue(os, testResultContainer);
} catch (IOException e) {
throw new AllureResultsWriteException("Could not write Allure test result container", e);
}
}
@Override
public void write(String source, InputStream attachment) {
createDirectories(outputDirectory);
Path file = outputDirectory.resolve(source);
try (InputStream is = attachment) {
Files.copy(is, file);
} catch (IOException e) {
throw new AllureResultsWriteException("Could not write Allure attachment", e);
}
}
private void createDirectories(Path directory) {
try {
Files.createDirectories(directory);
} catch (IOException e) {
throw new AllureResultsWriteException("Could not create Allure results directory", e);
}
}
}
| use blocking io instead of nio (via #16)
| allure2-model-api/src/main/java/io/qameta/allure/FileSystemResultsWriter.java | use blocking io instead of nio (via #16) | <ide><path>llure2-model-api/src/main/java/io/qameta/allure/FileSystemResultsWriter.java
<ide> import io.qameta.allure.model.TestResult;
<ide> import io.qameta.allure.model.TestResultContainer;
<ide>
<del>import java.io.IOException;
<del>import java.io.InputStream;
<del>import java.io.OutputStream;
<add>import java.io.*;
<ide> import java.nio.file.Files;
<ide> import java.nio.file.Path;
<ide> import java.util.Objects;
<ide>
<ide> import static io.qameta.allure.AllureUtils.generateTestResultContainerName;
<ide> import static io.qameta.allure.AllureUtils.generateTestResultName;
<del>import static java.nio.file.StandardOpenOption.CREATE_NEW;
<ide>
<ide> /**
<ide> * @author charlie (Dmitry Baev).
<ide> : generateTestResultName(testResult.getUuid());
<ide> createDirectories(outputDirectory);
<ide> Path file = outputDirectory.resolve(testResultName);
<del> try (OutputStream os = Files.newOutputStream(file, CREATE_NEW)) {
<add> try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file.toFile()))) {
<ide> mapper.writeValue(os, testResult);
<ide> } catch (IOException e) {
<ide> throw new AllureResultsWriteException("Could not write Allure test result", e);
<ide> : generateTestResultContainerName(testResultContainer.getUuid());
<ide> createDirectories(outputDirectory);
<ide> Path file = outputDirectory.resolve(testResultContainerName);
<del> try (OutputStream os = Files.newOutputStream(file, CREATE_NEW)) {
<add> try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file.toFile()))) {
<ide> mapper.writeValue(os, testResultContainer);
<ide> } catch (IOException e) {
<ide> throw new AllureResultsWriteException("Could not write Allure test result container", e); |
|
Java | apache-2.0 | 9b3f6287e2eb0dd80e486860d4a39984d2e2164d | 0 | izonder/intellij-community,tmpgit/intellij-community,caot/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,semonte/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,amith01994/intellij-community,semonte/intellij-community,semonte/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,semonte/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,caot/intellij-community,fnouama/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,signed/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,kdwink/intellij-community,clumsy/intellij-community,caot/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,dslomov/intellij-community,FHannes/intellij-community,semonte/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,allotria/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,xfournet/intellij-community,semonte/intellij-community,supersven/intellij-community,jagguli/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,da1z/intellij-community,da1z/intellij-community,retomerz/intellij-community,fnouama/intellij-community,supersven/intellij-community,allotria/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,samthor/intellij-community,nicolargo/intellij-community,caot/intellij-community,xfournet/intellij-community,ibinti/intellij-community,vladmm/intellij-community,apixandru/intellij-community,retomerz/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,semonte/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,ibinti/intellij-community,izonder/intellij-community,allotria/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,clumsy/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,slisson/intellij-community,vladmm/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,caot/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,kool79/intellij-community,hurricup/intellij-community,blademainer/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,signed/intellij-community,tmpgit/intellij-community,supersven/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,samthor/intellij-community,FHannes/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,da1z/intellij-community,da1z/intellij-community,kdwink/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,dslomov/intellij-community,FHannes/intellij-community,amith01994/intellij-community,supersven/intellij-community,retomerz/intellij-community,izonder/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,caot/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,signed/intellij-community,clumsy/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,ibinti/intellij-community,asedunov/intellij-community,slisson/intellij-community,jagguli/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,semonte/intellij-community,allotria/intellij-community,izonder/intellij-community,kdwink/intellij-community,kool79/intellij-community,dslomov/intellij-community,slisson/intellij-community,ibinti/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,izonder/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,allotria/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,caot/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,signed/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,supersven/intellij-community,clumsy/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,supersven/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,slisson/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,fnouama/intellij-community,allotria/intellij-community,fitermay/intellij-community,slisson/intellij-community,semonte/intellij-community,fitermay/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,apixandru/intellij-community,amith01994/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,kool79/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,signed/intellij-community,jagguli/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,supersven/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,xfournet/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,caot/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,da1z/intellij-community,izonder/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,blademainer/intellij-community,amith01994/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,suncycheng/intellij-community,slisson/intellij-community,signed/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,fitermay/intellij-community,izonder/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,dslomov/intellij-community,semonte/intellij-community,samthor/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,asedunov/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,apixandru/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,dslomov/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,ahb0327/intellij-community,samthor/intellij-community,jagguli/intellij-community,asedunov/intellij-community,FHannes/intellij-community,apixandru/intellij-community,da1z/intellij-community,kool79/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,asedunov/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,blademainer/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,tmpgit/intellij-community | /*
* Copyright 2000-2009 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.psi.impl.light;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
public class LightClassReference extends LightElement implements PsiJavaCodeReferenceElement {
private final String myText;
private final String myClassName;
private final PsiElement myContext;
private final GlobalSearchScope myResolveScope;
private final PsiClass myRefClass;
private final PsiSubstitutor mySubstitutor;
private LightReferenceParameterList myParameterList;
private LightClassReference(@NotNull PsiManager manager, @NotNull @NonNls String text, @NotNull @NonNls String className, PsiSubstitutor substitutor, @NotNull GlobalSearchScope resolveScope) {
super(manager, JavaLanguage.INSTANCE);
myText = text;
myClassName = className;
myResolveScope = resolveScope;
myContext = null;
myRefClass = null;
mySubstitutor = substitutor;
}
public LightClassReference(@NotNull PsiManager manager, @NotNull @NonNls String text, @NotNull @NonNls String className, @NotNull GlobalSearchScope resolveScope) {
this (manager, text, className, null, resolveScope);
}
public LightClassReference(@NotNull PsiManager manager, @NotNull @NonNls String text, @NotNull @NonNls String className, PsiSubstitutor substitutor, PsiElement context) {
super(manager, JavaLanguage.INSTANCE);
myText = text;
myClassName = className;
mySubstitutor = substitutor;
myContext = context;
myResolveScope = null;
myRefClass = null;
}
public LightClassReference(@NotNull PsiManager manager, @NotNull @NonNls String text, @NotNull PsiClass refClass) {
this(manager, text, refClass, null);
}
public LightClassReference(@NotNull PsiManager manager, @NotNull @NonNls String text, @NotNull PsiClass refClass, PsiSubstitutor substitutor) {
super(manager, JavaLanguage.INSTANCE);
myText = text;
myRefClass = refClass;
myResolveScope = null;
myClassName = null;
myContext = null;
mySubstitutor = substitutor;
}
@Override
public PsiElement resolve() {
if (myClassName != null) {
final JavaPsiFacade facade = JavaPsiFacade.getInstance(getProject());
if (myContext != null) {
return facade.getResolveHelper().resolveReferencedClass(myClassName, myContext);
}
else {
return facade.findClass(myClassName, myResolveScope);
}
}
else {
return myRefClass;
}
}
@Override
@NotNull
public JavaResolveResult advancedResolve(boolean incompleteCode){
final PsiElement resolved = resolve();
if (resolved == null) {
return JavaResolveResult.EMPTY;
}
PsiSubstitutor substitutor = mySubstitutor;
if (substitutor == null) {
if (resolved instanceof PsiClass) {
substitutor = JavaPsiFacade.getInstance(myManager.getProject()).getElementFactory().createRawSubstitutor((PsiClass) resolved);
} else {
substitutor = PsiSubstitutor.EMPTY;
}
}
return new CandidateInfo(resolved, substitutor);
}
@Override
@NotNull
public JavaResolveResult[] multiResolve(boolean incompleteCode){
final JavaResolveResult result = advancedResolve(incompleteCode);
if(result != JavaResolveResult.EMPTY) return new JavaResolveResult[]{result};
return JavaResolveResult.EMPTY_ARRAY;
}
@Override
public void processVariants(@NotNull PsiScopeProcessor processor){
throw new RuntimeException("Variants are not available for light references");
}
@Override
public PsiElement getReferenceNameElement() {
return null;
}
@Override
public PsiReferenceParameterList getParameterList() {
if (myParameterList == null) {
myParameterList = new LightReferenceParameterList(myManager, PsiTypeElement.EMPTY_ARRAY);
}
return myParameterList;
}
@Override
public String getQualifiedName() {
if (myClassName != null) {
if (myContext != null) {
PsiClass psiClass = (PsiClass)resolve();
if (psiClass != null) {
return psiClass.getQualifiedName();
}
}
return myClassName;
}
return myRefClass.getQualifiedName();
}
@Override
public String getReferenceName() {
if (myClassName != null){
return PsiNameHelper.getShortClassName(myClassName);
}
else{
if (myRefClass instanceof PsiAnonymousClass){
return ((PsiAnonymousClass)myRefClass).getBaseClassReference().getReferenceName();
}
else{
return myRefClass.getName();
}
}
}
@Override
public String getText() {
return myText;
}
@Override
public PsiReference getReference() {
return this;
}
@Override
@NotNull
public String getCanonicalText() {
String name = getQualifiedName();
if (name == null) return null;
PsiType[] types = getTypeParameters();
if (types.length == 0) return name;
StringBuffer buf = new StringBuffer();
buf.append(name);
buf.append('<');
for (int i = 0; i < types.length; i++) {
if (i > 0) buf.append(',');
buf.append(types[i].getCanonicalText());
}
buf.append('>');
return buf.toString();
}
@Override
public PsiElement copy() {
if (myClassName != null) {
if (myContext != null) {
return new LightClassReference(myManager, myText, myClassName, mySubstitutor, myContext);
}
else{
return new LightClassReference(myManager, myText, myClassName, mySubstitutor, myResolveScope);
}
}
else {
return new LightClassReference(myManager, myText, myRefClass, mySubstitutor);
}
}
@Override
public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
//TODO?
throw new UnsupportedOperationException();
}
@Override
public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException {
//TODO?
throw new UnsupportedOperationException();
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof JavaElementVisitor) {
((JavaElementVisitor)visitor).visitReferenceElement(this);
}
else {
visitor.visitElement(this);
}
}
public String toString() {
return "LightClassReference:" + myText;
}
@Override
public boolean isReferenceTo(PsiElement element) {
return element instanceof PsiClass && getManager().areElementsEquivalent(resolve(), element);
}
@Override
@NotNull
public Object[] getVariants() {
throw new RuntimeException("Variants are not available for light references");
}
@Override
public boolean isSoft(){
return false;
}
@Override
public TextRange getRangeInElement() {
return new TextRange(0, getTextLength());
}
@Override
public PsiElement getElement() {
return this;
}
@Override
public boolean isValid() {
return myRefClass == null || myRefClass.isValid();
}
@Override
@NotNull
public PsiType[] getTypeParameters() {
return PsiType.EMPTY_ARRAY;
}
@Override
public PsiElement getQualifier() {
return null;
}
@Override
public boolean isQualified() {
return false;
}
@NotNull
@Override
public GlobalSearchScope getResolveScope() {
return myResolveScope;
}
}
| java/java-psi-impl/src/com/intellij/psi/impl/light/LightClassReference.java | /*
* Copyright 2000-2009 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.psi.impl.light;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
public class LightClassReference extends LightElement implements PsiJavaCodeReferenceElement {
private final String myText;
private final String myClassName;
private final PsiElement myContext;
private final GlobalSearchScope myResolveScope;
private final PsiClass myRefClass;
private final PsiSubstitutor mySubstitutor;
private LightReferenceParameterList myParameterList;
private LightClassReference(@NotNull PsiManager manager, @NotNull @NonNls String text, @NotNull @NonNls String className, PsiSubstitutor substitutor, @NotNull GlobalSearchScope resolveScope) {
super(manager, JavaLanguage.INSTANCE);
myText = text;
myClassName = className;
myResolveScope = resolveScope;
myContext = null;
myRefClass = null;
mySubstitutor = substitutor;
}
public LightClassReference(@NotNull PsiManager manager, @NotNull @NonNls String text, @NotNull @NonNls String className, @NotNull GlobalSearchScope resolveScope) {
this (manager, text, className, null, resolveScope);
}
public LightClassReference(@NotNull PsiManager manager, @NotNull @NonNls String text, @NotNull @NonNls String className, PsiSubstitutor substitutor, PsiElement context) {
super(manager, JavaLanguage.INSTANCE);
myText = text;
myClassName = className;
mySubstitutor = substitutor;
myContext = context;
myResolveScope = null;
myRefClass = null;
}
public LightClassReference(@NotNull PsiManager manager, @NotNull @NonNls String text, @NotNull PsiClass refClass) {
this(manager, text, refClass, null);
}
public LightClassReference(@NotNull PsiManager manager, @NotNull @NonNls String text, @NotNull PsiClass refClass, PsiSubstitutor substitutor) {
super(manager, JavaLanguage.INSTANCE);
myText = text;
myRefClass = refClass;
myResolveScope = null;
myClassName = null;
myContext = null;
mySubstitutor = substitutor;
}
@Override
public PsiElement resolve() {
if (myClassName != null) {
final JavaPsiFacade facade = JavaPsiFacade.getInstance(getProject());
if (myContext != null) {
return facade.getResolveHelper().resolveReferencedClass(myClassName, myContext);
}
else {
return facade.findClass(myClassName, myResolveScope);
}
}
else {
return myRefClass;
}
}
@Override
@NotNull
public JavaResolveResult advancedResolve(boolean incompleteCode){
final PsiElement resolved = resolve();
if (resolved == null) {
return JavaResolveResult.EMPTY;
}
PsiSubstitutor substitutor = mySubstitutor;
if (substitutor == null) {
if (resolved instanceof PsiClass) {
substitutor = JavaPsiFacade.getInstance(myManager.getProject()).getElementFactory().createRawSubstitutor((PsiClass) resolved);
} else {
substitutor = PsiSubstitutor.EMPTY;
}
}
return new CandidateInfo(resolved, substitutor);
}
@Override
@NotNull
public JavaResolveResult[] multiResolve(boolean incompleteCode){
final JavaResolveResult result = advancedResolve(incompleteCode);
if(result != JavaResolveResult.EMPTY) return new JavaResolveResult[]{result};
return JavaResolveResult.EMPTY_ARRAY;
}
@Override
public void processVariants(@NotNull PsiScopeProcessor processor){
throw new RuntimeException("Variants are not available for light references");
}
@Override
public PsiElement getReferenceNameElement() {
return null;
}
@Override
public PsiReferenceParameterList getParameterList() {
if (myParameterList == null) {
myParameterList = new LightReferenceParameterList(myManager, PsiTypeElement.EMPTY_ARRAY);
}
return myParameterList;
}
@Override
public String getQualifiedName() {
if (myClassName != null) {
if (myContext != null) {
PsiClass psiClass = (PsiClass)resolve();
if (psiClass != null) {
return psiClass.getQualifiedName();
}
}
return myClassName;
}
return myRefClass.getQualifiedName();
}
@Override
public String getReferenceName() {
if (myClassName != null){
return PsiNameHelper.getShortClassName(myClassName);
}
else{
if (myRefClass instanceof PsiAnonymousClass){
return ((PsiAnonymousClass)myRefClass).getBaseClassReference().getReferenceName();
}
else{
return myRefClass.getName();
}
}
}
@Override
public String getText() {
return myText;
}
@Override
public PsiReference getReference() {
return this;
}
@Override
@NotNull
public String getCanonicalText() {
String name = getQualifiedName();
if (name == null) return null;
PsiType[] types = getTypeParameters();
if (types.length == 0) return name;
StringBuffer buf = new StringBuffer();
buf.append(name);
buf.append('<');
for (int i = 0; i < types.length; i++) {
if (i > 0) buf.append(',');
buf.append(types[i].getCanonicalText());
}
buf.append('>');
return buf.toString();
}
@Override
public PsiElement copy() {
if (myClassName != null) {
if (myContext != null) {
return new LightClassReference(myManager, myText, myClassName, mySubstitutor, myContext);
}
else{
return new LightClassReference(myManager, myText, myClassName, mySubstitutor, myResolveScope);
}
}
else {
return new LightClassReference(myManager, myText, myRefClass, mySubstitutor);
}
}
@Override
public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
//TODO?
throw new UnsupportedOperationException();
}
@Override
public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException {
//TODO?
throw new UnsupportedOperationException();
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof JavaElementVisitor) {
((JavaElementVisitor)visitor).visitReferenceElement(this);
}
else {
visitor.visitElement(this);
}
}
public String toString() {
return "LightClassReference:" + myText;
}
@Override
public boolean isReferenceTo(PsiElement element) {
return element instanceof PsiClass && getManager().areElementsEquivalent(resolve(), element);
}
@Override
@NotNull
public Object[] getVariants() {
throw new RuntimeException("Variants are not available for light references");
}
@Override
public boolean isSoft(){
return false;
}
@Override
public TextRange getRangeInElement() {
return new TextRange(0, getTextLength());
}
@Override
public PsiElement getElement() {
return this;
}
@Override
public boolean isValid() {
return myRefClass == null || myRefClass.isValid();
}
@Override
@NotNull
public PsiType[] getTypeParameters() {
return PsiType.EMPTY_ARRAY;
}
@Override
public PsiElement getQualifier() {
return null;
}
@Override
public boolean isQualified() {
return false;
}
}
| LightClassReference.resolveScope should not be allScope
in IDEA-126629 that leads to all same-named classes being found and the first of them selected by chance, sometimes causing wrong Closeable/AutoCloseable warning
| java/java-psi-impl/src/com/intellij/psi/impl/light/LightClassReference.java | LightClassReference.resolveScope should not be allScope | <ide><path>ava/java-psi-impl/src/com/intellij/psi/impl/light/LightClassReference.java
<ide> public boolean isQualified() {
<ide> return false;
<ide> }
<add>
<add> @NotNull
<add> @Override
<add> public GlobalSearchScope getResolveScope() {
<add> return myResolveScope;
<add> }
<ide> } |
|
Java | bsd-3-clause | 5306e487dfb39cfe0d19a28c7bce582b4ed1bfa3 | 0 | voodoodyne/subetha,msoftware/subetha,msoftware/subetha,voodoodyne/subetha,msoftware/subetha,voodoodyne/subetha,msoftware/subetha,voodoodyne/subetha | /*
* $Id$
* $URL$
*/
package org.subethamail.entity;
import java.io.Serializable;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapKey;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.OrderBy;
import javax.persistence.QueryHint;
import javax.persistence.Transient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Sort;
import org.hibernate.annotations.SortType;
import org.hibernate.validator.Email;
import org.subethamail.common.Permission;
import org.subethamail.common.PermissionException;
import org.subethamail.common.valid.Validator;
/**
* Entity for a single mailing list
*
* @author Jeff Schnitzer
*/
@NamedQueries({
@NamedQuery(
name="MailingListByEmail",
query="from MailingList l where l.email = :email",
hints={
@QueryHint(name="org.hibernate.readOnly", value="true"),
@QueryHint(name="org.hibernate.cacheable", value="true")
}
),
@NamedQuery(
name="MailingListByUrl",
query="from MailingList l where l.url = :url",
hints={
@QueryHint(name="org.hibernate.readOnly", value="true"),
@QueryHint(name="org.hibernate.cacheable", value="true")
}
),
@NamedQuery(
name="AllMailingLists",
query="from MailingList l",
hints={
@QueryHint(name="org.hibernate.readOnly", value="true"),
@QueryHint(name="org.hibernate.cacheable", value="true")
}
)
})
@Entity
@Cache(usage=CacheConcurrencyStrategy.TRANSACTIONAL)
@SuppressWarnings("serial")
public class MailingList implements Serializable, Comparable
{
/** */
@Transient private static Log log = LogFactory.getLog(MailingList.class);
/**
* TreeSet requires a weird comparator because it uses the comparator
* instead of equals(). When we return 0, it means the objects must
* really be equal.
*/
public static class SubscriptionComparator implements Comparator<Subscription>
{
public int compare(Subscription s1, Subscription s2)
{
if(s1 == null || s2 == null)
return 0;
int result = s1.getPerson().compareTo(s2.getPerson());
if (result == 0)
return s1.getPerson().getId().compareTo(s2.getPerson().getId());
else
return result;
}
};
/** */
@Id
@GeneratedValue
Long id;
/** */
@Column(nullable=false, length=Validator.MAX_LIST_EMAIL)
@Email
String email;
@Column(nullable=false, length=Validator.MAX_LIST_NAME)
String name;
/** */
@Column(nullable=false, length=Validator.MAX_LIST_URL)
String url;
@Column(nullable=false, length=Validator.MAX_LIST_DESCRIPTION)
String description;
/** Hold subs for moderator approval */
@Column(nullable=false)
boolean subscriptionHeld;
//
// TODO: set these two columns back to nullable=false when
// this hibernate bug is fixed:
// http://opensource.atlassian.com/projects/hibernate/browse/HHH-1654
// Also, this affects the creation sequence for mailing lists
//
/** The default role for new subscribers */
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="defaultRoleId", nullable=true)
Role defaultRole;
/** The role to consider anonymous (not subscribed) people */
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="anonymousRoleId", nullable=true)
Role anonymousRole;
/** */
@OneToMany(cascade=CascadeType.ALL, mappedBy="list")
@Sort(type=SortType.COMPARATOR, comparator=SubscriptionComparator.class)
@Cache(usage=CacheConcurrencyStrategy.TRANSACTIONAL)
SortedSet<Subscription> subscriptions;
/** */
@OneToMany(cascade=CascadeType.ALL, mappedBy="list")
@OrderBy(value="dateCreated")
//@Cache(usage=CacheConcurrencyStrategy.TRANSACTIONAL) // caching unnecessary
Set<SubscriptionHold> subscriptionHolds;
/** */
@OneToMany(cascade=CascadeType.ALL, mappedBy="list")
@Cache(usage=CacheConcurrencyStrategy.TRANSACTIONAL)
@MapKey(name="className")
Map<String, EnabledFilter> enabledFilters;
/** */
@OneToMany(cascade=CascadeType.ALL, mappedBy="list")
@Cache(usage=CacheConcurrencyStrategy.TRANSACTIONAL)
@OrderBy(value="name")
Set<Role> roles;
/**
*/
public MailingList() {}
/**
*/
public MailingList(String email, String name, String url, String description)
{
if (log.isDebugEnabled())
log.debug("Creating new mailing list");
// These are validated normally.
this.setEmail(email);
this.setName(name);
this.setUrl(url);
this.setDescription(description);
// Make sure collections start empty
this.subscriptions = new TreeSet<Subscription>();
this.enabledFilters = new HashMap<String, EnabledFilter>();
this.roles = new HashSet<Role>();
this.subscriptionHolds = new HashSet<SubscriptionHold>();
// We have to start with one role, the owner role
Role owner = new Role(this);
this.roles.add(owner);
// TODO: restore this code when hibernate bug fixed. In the mean time,
// the creator MUST persist the MailingList *then* set these values.
// http://opensource.atlassian.com/projects/hibernate/browse/HHH-1654
// this.defaultRole = owner;
// this.anonymousRole = owner;
}
/** */
public Long getId() { return this.id; }
/**
*/
public String getEmail() { return this.email; }
/**
*/
public void setEmail(String value)
{
if (log.isDebugEnabled())
log.debug("Setting email of " + this + " to " + value);
this.email = value;
}
/**
*/
public String getName() { return this.name; }
/**
*/
public void setName(String value)
{
if (log.isDebugEnabled())
log.debug("Setting name of " + this + " to " + value);
this.name = value;
}
/**
*/
public String getUrl() { return this.url; }
/**
*/
public void setUrl(String value)
{
if (value == null || value.length() > Validator.MAX_LIST_URL)
throw new IllegalArgumentException("Invalid url");
if (log.isDebugEnabled())
log.debug("Setting url of " + this + " to " + value);
this.url = value;
}
/**
*/
public String getDescription() { return this.description; }
/**
*/
public void setDescription(String value)
{
if (log.isDebugEnabled())
log.debug("Setting description of " + this + " to " + value);
this.description = value;
}
/**
*/
public boolean isSubscriptionHeld() { return this.subscriptionHeld; }
public void setSubscriptionHeld(boolean value)
{
this.subscriptionHeld = value;
}
/**
* @return all the subscriptions associated with this list
*/
public Set<Subscription> getSubscriptions() { return this.subscriptions; }
/**
* @return all the held subscriptions
*/
public Set<SubscriptionHold> getSubscriptionHolds() { return this.subscriptionHolds; }
/**
* @return all plugins enabled on this list
*/
public Map<String, EnabledFilter> getEnabledFilters() { return this.enabledFilters; }
/**
* Convenience method.
*/
public void addEnabledFilter(EnabledFilter filt)
{
this.enabledFilters.put(filt.getClassName(), filt);
}
/**
* @return all roles available for this list
*/
public Set<Role> getRoles() { return this.roles; }
/**
* @return true if role is valid for this list
*/
public boolean isValidRole(Role role)
{
return this.roles.contains(role);
}
/** */
public Role getDefaultRole() { return this.defaultRole; }
public void setDefaultRole(Role value)
{
if (!this.isValidRole(value))
throw new IllegalArgumentException("Role belongs to some other list");
this.defaultRole = value;
}
/** */
public Role getAnonymousRole() { return this.anonymousRole; }
public void setAnonymousRole(Role value)
{
if (!this.isValidRole(value))
throw new IllegalArgumentException("Role belongs to some other list");
this.anonymousRole = value;
}
/**
* Figures out which role is the owner and returns it
*/
public Role getOwnerRole()
{
for (Role check: this.roles)
if (check.isOwner())
return check;
throw new IllegalStateException("Missing owner role");
}
/**
* Figures out the role for a person. If pers is null,
* returns the anonymous role.
*/
public Role getRoleFor(Person pers)
{
if (pers == null)
return this.anonymousRole;
else
return pers.getRoleIn(this);
}
/**
* Figures out the permissions for a person. Very
* similar to getRoleFor() but takes into account
* site adminstrators which always have permission.
*/
public Set<Permission> getPermissionsFor(Person pers)
{
if (pers == null)
return this.anonymousRole.getPermissions();
else
return pers.getPermissionsIn(this);
}
/**
* @param pers can be null to indicate anonymous person. Site admins have all permissions.
* @throws PermissionException if person doesn't have the permission
*/
public void checkPermission(Person pers, Permission check) throws PermissionException
{
if (! this.getPermissionsFor(pers).contains(check))
throw new PermissionException(check);
}
/**
* @return the context root of the SubEtha web application, determined
* from the main URL. Does not include trailing /.
*/
public String getUrlBase()
{
//TODO: make this a constant somewhere
int pos = this.url.indexOf("/se/list/");
if (pos < 0)
throw new IllegalStateException("Malformed list url");
return this.url.substring(0, pos + "/se".length());
}
/**
* @return the owner email address for this list
*/
public String getOwnerEmail()
{
int atIndex = this.email.indexOf('@');
String box = this.email.substring(0, atIndex);
String remainder = this.email.substring(atIndex);
return box + "-owner" + remainder;
}
/** */
public String toString()
{
return this.getClass() + " {id=" + this.id + ", address=" + this.email + "}";
}
/**
* Natural sort order is based on email address
*/
public int compareTo(Object arg0)
{
MailingList other = (MailingList)arg0;
return this.email.compareTo(other.getEmail());
}
}
| entity/src/org/subethamail/entity/MailingList.java | /*
* $Id$
* $URL$
*/
package org.subethamail.entity;
import java.io.Serializable;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapKey;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.OrderBy;
import javax.persistence.QueryHint;
import javax.persistence.Transient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Sort;
import org.hibernate.annotations.SortType;
import org.hibernate.validator.Email;
import org.subethamail.common.Permission;
import org.subethamail.common.PermissionException;
import org.subethamail.common.valid.Validator;
/**
* Entity for a single mailing list
*
* @author Jeff Schnitzer
*/
@NamedQueries({
@NamedQuery(
name="MailingListByEmail",
query="from MailingList l where l.email = :email",
hints={
@QueryHint(name="org.hibernate.readOnly", value="true"),
@QueryHint(name="org.hibernate.cacheable", value="true")
}
),
@NamedQuery(
name="MailingListByUrl",
query="from MailingList l where l.url = :url",
hints={
@QueryHint(name="org.hibernate.readOnly", value="true"),
@QueryHint(name="org.hibernate.cacheable", value="true")
}
),
@NamedQuery(
name="AllMailingLists",
query="from MailingList l",
hints={
@QueryHint(name="org.hibernate.readOnly", value="true"),
@QueryHint(name="org.hibernate.cacheable", value="true")
}
)
})
@Entity
@Cache(usage=CacheConcurrencyStrategy.TRANSACTIONAL)
@SuppressWarnings("serial")
public class MailingList implements Serializable, Comparable
{
/** */
@Transient private static Log log = LogFactory.getLog(MailingList.class);
/**
* TreeSet requires a weird comparator because it uses the comparator
* instead of equals(). When we return 0, it means the objects must
* really be equal.
*/
public static class SubscriptionComparator implements Comparator<Subscription>
{
public int compare(Subscription s1, Subscription s2)
{
int result = s1.getPerson().compareTo(s2.getPerson());
if (result == 0)
return s1.getPerson().getId().compareTo(s2.getPerson().getId());
else
return result;
}
};
/** */
@Id
@GeneratedValue
Long id;
/** */
@Column(nullable=false, length=Validator.MAX_LIST_EMAIL)
@Email
String email;
@Column(nullable=false, length=Validator.MAX_LIST_NAME)
String name;
/** */
@Column(nullable=false, length=Validator.MAX_LIST_URL)
String url;
@Column(nullable=false, length=Validator.MAX_LIST_DESCRIPTION)
String description;
/** Hold subs for moderator approval */
@Column(nullable=false)
boolean subscriptionHeld;
//
// TODO: set these two columns back to nullable=false when
// this hibernate bug is fixed:
// http://opensource.atlassian.com/projects/hibernate/browse/HHH-1654
// Also, this affects the creation sequence for mailing lists
//
/** The default role for new subscribers */
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="defaultRoleId", nullable=true)
Role defaultRole;
/** The role to consider anonymous (not subscribed) people */
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="anonymousRoleId", nullable=true)
Role anonymousRole;
/** */
@OneToMany(cascade=CascadeType.ALL, mappedBy="list")
@Sort(type=SortType.COMPARATOR, comparator=SubscriptionComparator.class)
@Cache(usage=CacheConcurrencyStrategy.TRANSACTIONAL)
SortedSet<Subscription> subscriptions;
/** */
@OneToMany(cascade=CascadeType.ALL, mappedBy="list")
@OrderBy(value="dateCreated")
//@Cache(usage=CacheConcurrencyStrategy.TRANSACTIONAL) // caching unnecessary
Set<SubscriptionHold> subscriptionHolds;
/** */
@OneToMany(cascade=CascadeType.ALL, mappedBy="list")
@Cache(usage=CacheConcurrencyStrategy.TRANSACTIONAL)
@MapKey(name="className")
Map<String, EnabledFilter> enabledFilters;
/** */
@OneToMany(cascade=CascadeType.ALL, mappedBy="list")
@Cache(usage=CacheConcurrencyStrategy.TRANSACTIONAL)
@OrderBy(value="name")
Set<Role> roles;
/**
*/
public MailingList() {}
/**
*/
public MailingList(String email, String name, String url, String description)
{
if (log.isDebugEnabled())
log.debug("Creating new mailing list");
// These are validated normally.
this.setEmail(email);
this.setName(name);
this.setUrl(url);
this.setDescription(description);
// Make sure collections start empty
this.subscriptions = new TreeSet<Subscription>();
this.enabledFilters = new HashMap<String, EnabledFilter>();
this.roles = new HashSet<Role>();
this.subscriptionHolds = new HashSet<SubscriptionHold>();
// We have to start with one role, the owner role
Role owner = new Role(this);
this.roles.add(owner);
// TODO: restore this code when hibernate bug fixed. In the mean time,
// the creator MUST persist the MailingList *then* set these values.
// http://opensource.atlassian.com/projects/hibernate/browse/HHH-1654
// this.defaultRole = owner;
// this.anonymousRole = owner;
}
/** */
public Long getId() { return this.id; }
/**
*/
public String getEmail() { return this.email; }
/**
*/
public void setEmail(String value)
{
if (log.isDebugEnabled())
log.debug("Setting email of " + this + " to " + value);
this.email = value;
}
/**
*/
public String getName() { return this.name; }
/**
*/
public void setName(String value)
{
if (log.isDebugEnabled())
log.debug("Setting name of " + this + " to " + value);
this.name = value;
}
/**
*/
public String getUrl() { return this.url; }
/**
*/
public void setUrl(String value)
{
if (value == null || value.length() > Validator.MAX_LIST_URL)
throw new IllegalArgumentException("Invalid url");
if (log.isDebugEnabled())
log.debug("Setting url of " + this + " to " + value);
this.url = value;
}
/**
*/
public String getDescription() { return this.description; }
/**
*/
public void setDescription(String value)
{
if (log.isDebugEnabled())
log.debug("Setting description of " + this + " to " + value);
this.description = value;
}
/**
*/
public boolean isSubscriptionHeld() { return this.subscriptionHeld; }
public void setSubscriptionHeld(boolean value)
{
this.subscriptionHeld = value;
}
/**
* @return all the subscriptions associated with this list
*/
public Set<Subscription> getSubscriptions() { return this.subscriptions; }
/**
* @return all the held subscriptions
*/
public Set<SubscriptionHold> getSubscriptionHolds() { return this.subscriptionHolds; }
/**
* @return all plugins enabled on this list
*/
public Map<String, EnabledFilter> getEnabledFilters() { return this.enabledFilters; }
/**
* Convenience method.
*/
public void addEnabledFilter(EnabledFilter filt)
{
this.enabledFilters.put(filt.getClassName(), filt);
}
/**
* @return all roles available for this list
*/
public Set<Role> getRoles() { return this.roles; }
/**
* @return true if role is valid for this list
*/
public boolean isValidRole(Role role)
{
return this.roles.contains(role);
}
/** */
public Role getDefaultRole() { return this.defaultRole; }
public void setDefaultRole(Role value)
{
if (!this.isValidRole(value))
throw new IllegalArgumentException("Role belongs to some other list");
this.defaultRole = value;
}
/** */
public Role getAnonymousRole() { return this.anonymousRole; }
public void setAnonymousRole(Role value)
{
if (!this.isValidRole(value))
throw new IllegalArgumentException("Role belongs to some other list");
this.anonymousRole = value;
}
/**
* Figures out which role is the owner and returns it
*/
public Role getOwnerRole()
{
for (Role check: this.roles)
if (check.isOwner())
return check;
throw new IllegalStateException("Missing owner role");
}
/**
* Figures out the role for a person. If pers is null,
* returns the anonymous role.
*/
public Role getRoleFor(Person pers)
{
if (pers == null)
return this.anonymousRole;
else
return pers.getRoleIn(this);
}
/**
* Figures out the permissions for a person. Very
* similar to getRoleFor() but takes into account
* site adminstrators which always have permission.
*/
public Set<Permission> getPermissionsFor(Person pers)
{
if (pers == null)
return this.anonymousRole.getPermissions();
else
return pers.getPermissionsIn(this);
}
/**
* @param pers can be null to indicate anonymous person. Site admins have all permissions.
* @throws PermissionException if person doesn't have the permission
*/
public void checkPermission(Person pers, Permission check) throws PermissionException
{
if (! this.getPermissionsFor(pers).contains(check))
throw new PermissionException(check);
}
/**
* @return the context root of the SubEtha web application, determined
* from the main URL. Does not include trailing /.
*/
public String getUrlBase()
{
//TODO: make this a constant somewhere
int pos = this.url.indexOf("/se/list/");
if (pos < 0)
throw new IllegalStateException("Malformed list url");
return this.url.substring(0, pos + "/se".length());
}
/**
* @return the owner email address for this list
*/
public String getOwnerEmail()
{
int atIndex = this.email.indexOf('@');
String box = this.email.substring(0, atIndex);
String remainder = this.email.substring(atIndex);
return box + "-owner" + remainder;
}
/** */
public String toString()
{
return this.getClass() + " {id=" + this.id + ", address=" + this.email + "}";
}
/**
* Natural sort order is based on email address
*/
public int compareTo(Object arg0)
{
MailingList other = (MailingList)arg0;
return this.email.compareTo(other.getEmail());
}
}
| checks for null arguments first.
git-svn-id: 60dcf9651b07bc729a3db0984941a1a33fd6e0f2@362 68df8246-1725-11de-bcda-2bb9902f8029
| entity/src/org/subethamail/entity/MailingList.java | checks for null arguments first. | <ide><path>ntity/src/org/subethamail/entity/MailingList.java
<ide> {
<ide> public int compare(Subscription s1, Subscription s2)
<ide> {
<add> if(s1 == null || s2 == null)
<add> return 0;
<add>
<ide> int result = s1.getPerson().compareTo(s2.getPerson());
<ide>
<ide> if (result == 0) |
|
Java | bsd-2-clause | 193c87c0800502929799e396cecdf75da34a17d0 | 0 | scijava/scijava-common | /*
* #%L
* SciJava Common shared library for SciJava software.
* %%
* Copyright (C) 2009 - 2013 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
package org.scijava.util;
import java.io.File;
import java.net.URL;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Useful methods for obtaining details of the SciJava application environment.
*
* @author Johannes Schindelin
* @author Curtis Rueden
*/
public final class AppUtils {
private static final Class<?> mainClass;
static {
// Get the class whose main method launched the application. The heuristic
// will fail if the main thread has terminated before this class loads.
final Map<Thread, StackTraceElement[]> traceMap =
Thread.getAllStackTraces();
String className = null;
for (final Thread thread : traceMap.keySet()) {
if (!"main".equals(thread.getName())) continue;
final StackTraceElement[] trace = traceMap.get(thread);
if (trace == null || trace.length == 0) continue;
final StackTraceElement element = trace[trace.length - 1];
className = element.getClassName();
break;
}
mainClass = className == null ? null : ClassUtils.loadClass(className);
}
private AppUtils() {
// prevent instantiation of utility class
}
/**
* Gets the class whose main method launched the application.
*
* @return The launching class, or null if the main method terminated before
* the {@code AppUtils} class was loaded.
*/
public static Class<?> getMainClass() {
return mainClass;
}
/**
* Gets the application root directory. If the given system property is set,
* it is used. Otherwise, we scan up the tree from the given class for a
* suitable directory.
*
* @param sysProp System property which may point at the root directory. If
* this is set to a valid directory, it is used.
* @param c The class from which the base directory should be derived.
* @param baseSubdirectory A hint for what to expect for a directory structure
* beneath the application base directory. If this value is null
* (i.e., no hint is given), the heuristic scans up the directory
* tree looking for the topmost pom.xml file.
* @see AppUtils#getBaseDirectory(File, String)
*/
public static File getBaseDirectory(final String sysProp, final Class<?> c,
final String baseSubdirectory)
{
final String property = System.getProperty(sysProp);
if (property != null) {
final File dir = new File(property);
if (dir.isDirectory()) return dir;
}
// look for valid base directory relative to this class
final File basePath = AppUtils.getBaseDirectory(c, baseSubdirectory);
if (basePath != null) return basePath;
// NB: Look for valid base directory relative to the main class which
// launched this environment. We will reach this logic, e.g., if the
// application is running via "mvn exec:exec". In this case, most classes
// (including this one) will be located in JARs in the local Maven
// repository cache (~/.m2/repository), so the corePath will be null.
// However, the classes of the launching project will be located in
// target/classes, so we search up the tree from one of those.
final File appPath = AppUtils.getBaseDirectory(AppUtils.getMainClass());
if (appPath != null) return appPath;
// last resort: use current working directory
return new File(".").getAbsoluteFile();
}
/**
* Gets the base file system directory containing the given class file.
*
* @param c The class from which the base directory should be derived.
* @see #getBaseDirectory(File, String)
*/
public static File getBaseDirectory(final Class<?> c) {
return getBaseDirectory(c, null);
}
/**
* Gets the base file system directory containing the given class file.
*
* @param c The class from which the base directory should be derived.
* @param baseSubdirectory A hint for what to expect for a directory structure
* beneath the application base directory.
* @see #getBaseDirectory(File, String)
*/
public static File getBaseDirectory(final Class<?> c,
final String baseSubdirectory)
{
final URL location = ClassUtils.getLocation(c);
final File baseFile = FileUtils.urlToFile(location);
return getBaseDirectory(baseFile, baseSubdirectory);
}
/**
* Gets the base file system directory from the given known class location.
* <p>
* This method uses heuristics to find the base directory in a variety of
* situations. Depending on your execution environment, the class may be
* located in one of several different places:
* </p>
* <ol>
* <li><b>In the Maven build directory.</b> Typically this is the
* {@code target/classes} folder of a given component. In this case, the class
* files reside directly on the file system (not in a JAR file). The base
* directory is defined as the toplevel Maven directory for the multi-module
* project. For example, if you have checked out {@code scijava-common.git} to
* {@code ~/sjc}, the {@code org.scijava.Context} class will be located at
* {@code ~/sjc/scijava-common/target/classes/org/scijava/Context.class}.
* Asking for the base directory for that class will yield
* {@code ~/sjc/scijava-common}, as long as you correctly specify
* {@code scijava-common} for the {@code baseSubdirectory}.</li>
* <li><b>Within a JAR file in the Maven local repository cache.</b> Typically
* this cache is located in {@code ~/.m2/repository}. The location will be
* {@code groupId/artifactId/version/artifactId-version.jar} where
* {@code groupId}, {@code artifactId} and {@code version} are the <a
* href="http://maven.apache.org/pom.html#Maven_Coordinates">Maven GAV
* coordinates</a>. Note that in this case, no base directory with respect to
* the given class can be found, and this method will return null.</li>
* <li><b>Within a JAR file beneath the base directory.</b> Common cases
* include running the application from a standalone application bundle (e.g.,
* the JARs may all be located within a {@code jars} folder of the application
* distribution archive) or using a JAR packaged by Maven and residing in the
* Maven build folder (typically {@code target/artifactId-version.jar}).
* However, this could potentially be anywhere beneath the base directory.
* This method assumes the JAR will be nested exactly one level deep; i.e., it
* computes the base directory as the parent directory of the one containing
* the JAR file.</li>
* </ol>
* <p>
* As you can see, it is quite complicated to find the base directory properly
* in all cases. The specific execution environments we have tested include:
* </p>
* <ol>
* <li><b>Running from Eclipse.</b> How Eclipse structures the classpath
* depends on which dependencies are open (i.e., project dependencies) versus
* closed (i.e., JAR dependencies). Each project dependency has a classpath
* entry <b>in its Maven build directory</b>. Each JAR dependency has a
* classpath entry <b>within a JAR file in the Maven local repository
* cache</b>.</li>
* <li><b>Running via Maven.</b> If you execute the application using Maven
* (e.g., {@code mvn exec:exec}, or with a fully Maven-compatible IDE such as
* NetBeans or IntelliJ IDEA) then all dependencies will reside <b>within JAR
* files in the local Maven repository cache</b>. But the executed project
* itself will reside <b>in its Maven build directory</b>. So as long as you
* ask for the base directory relative to a class
* <em>of the executed project</em> it will be found.</li>
* <li><b>Running as an application bundle (e.g., ImageJ).</b> Typically this
* means downloading ImageJ from the web site, unpacking it and running the
* ImageJ launcher (double-clicking ImageJ-win32.exe on Windows,
* double-clicking the {@code ImageJ.app} on OS X, etc.). In this case, all
* components reside in the {@code jars} folder of the application bundle, and
* the base directory will be found one level above that.</li>
* </ol>
*
* @param classLocation The location from which the base directory should be
* derived.
* @param baseSubdirectory A hint for what to expect for a directory structure
* beneath the application base directory. If this value is null
* (i.e., no hint is given), the heuristic scans up the directory
* tree looking for the topmost pom.xml file.
*/
public static File getBaseDirectory(final File classLocation,
final String baseSubdirectory)
{
if (classLocation == null) return null;
String path = FileUtils.getPath(classLocation).replace('\\', '/');
if (path.contains("/.m2/repository/")) {
// NB: The class is in a JAR in the Maven repository cache.
// We cannot find the application base directory relative to this path.
return null;
}
// check whether the class is in a Maven build directory
String basePrefix = "/";
if (baseSubdirectory != null) basePrefix += baseSubdirectory + "/";
final String targetClassesSuffix = basePrefix + "target/classes";
if (path.endsWith(targetClassesSuffix)) {
// NB: The class is a file beneath the Maven build directory
// ("target/classes").
path = path.substring(0, path.length() - targetClassesSuffix.length());
File dir = new File(path);
if (baseSubdirectory == null) {
// NB: There is no hint as to the directory structure.
// So we scan up the tree to find the topmost pom.xml file.
while (dir.getParentFile() != null &&
new File(dir.getParentFile(), "pom.xml").exists())
{
dir = dir.getParentFile();
}
}
return dir;
}
final Pattern pattern =
Pattern.compile(".*(" + Pattern.quote(basePrefix + "target/") +
"[^/]*\\.jar)");
final Matcher matcher = pattern.matcher(path);
if (matcher.matches()) {
// NB: The class is in the Maven build directory inside a JAR file
// ("target/[something].jar").
final int index = matcher.start(1);
path = path.substring(0, index);
return new File(path);
}
if (path.endsWith(".jar")) {
final File jarDirectory = classLocation.getParentFile();
// NB: The class is in a JAR file, which we assume is nested one level
// deep (i.e., directly beneath the application base directory).
return jarDirectory.getParentFile();
}
// NB: As a last resort, we use the class location directly.
return classLocation;
}
}
| src/main/java/org/scijava/util/AppUtils.java | /*
* #%L
* SciJava Common shared library for SciJava software.
* %%
* Copyright (C) 2009 - 2013 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
package org.scijava.util;
import java.io.File;
import java.net.URL;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Useful methods for obtaining details of the SciJava application environment.
*
* @author Johannes Schindelin
* @author Curtis Rueden
*/
public final class AppUtils {
private static final Class<?> mainClass;
static {
// Get the class whose main method launched the application. The heuristic
// will fail if the main thread has terminated before this class loads.
final Map<Thread, StackTraceElement[]> traceMap =
Thread.getAllStackTraces();
String className = null;
for (final Thread thread : traceMap.keySet()) {
if (!"main".equals(thread.getName())) continue;
final StackTraceElement[] trace = traceMap.get(thread);
if (trace == null || trace.length == 0) continue;
final StackTraceElement element = trace[trace.length - 1];
className = element.getClassName();
break;
}
mainClass = className == null ? null : ClassUtils.loadClass(className);
}
private AppUtils() {
// prevent instantiation of utility class
}
/**
* Gets the class whose main method launched the application.
*
* @return The launching class, or null if the main method terminated before
* the {@code AppUtils} class was loaded.
*/
public static Class<?> getMainClass() {
return mainClass;
}
/**
* Gets the application root directory. If the given system property is set,
* it is used. Otherwise, we scan up the tree from the given class for a
* suitable directory.
*
* @param sysProp System property which may point at the root directory. If
* this is set to a valid directory, it is used.
* @param c The class from which the base directory should be derived.
* @param baseSubdirectory A hint for what to expect for a directory structure
* beneath the application base directory. If this value is null
* (i.e., no hint is given), the heuristic scans up the directory
* tree looking for the topmost pom.xml file.
* @see AppUtils#getBaseDirectory(File, String)
*/
public static File getBaseDirectory(final String sysProp, final Class<?> c,
final String baseSubdirectory)
{
final String property = System.getProperty(sysProp);
if (property != null) {
final File dir = new File(property);
if (dir.isDirectory()) return dir;
}
// look for valid base directory relative to this class
final File basePath = AppUtils.getBaseDirectory(c, baseSubdirectory);
if (basePath != null) return basePath;
// NB: Look for valid base directory relative to the main class which
// launched this environment. We will reach this logic, e.g., if the
// application is running via "mvn exec:exec". In this case, most classes
// (including this one) will be located in JARs in the local Maven
// repository cache (~/.m2/repository), so the corePath will be null.
// However, the classes of the launching project will be located in
// target/classes, so we search up the tree from one of those.
final File appPath = AppUtils.getBaseDirectory(AppUtils.getMainClass());
if (appPath != null) return appPath;
// last resort: use current working directory
return new File(".").getAbsoluteFile();
}
/**
* Gets the base file system directory containing the given class file.
*
* @param c The class from which the base directory should be derived.
* @see #getBaseDirectory(File, String)
*/
public static File getBaseDirectory(final Class<?> c) {
return getBaseDirectory(c, null);
}
/**
* Gets the base file system directory containing the given class file.
*
* @param c The class from which the base directory should be derived.
* @param baseSubdirectory A hint for what to expect for a directory structure
* beneath the application base directory.
* @see #getBaseDirectory(File, String)
*/
public static File getBaseDirectory(final Class<?> c,
final String baseSubdirectory)
{
final URL location = ClassUtils.getLocation(c);
final File baseFile = FileUtils.urlToFile(location);
return getBaseDirectory(baseFile, baseSubdirectory);
}
/**
* Gets the base file system directory from the given known class location.
* <p>
* This method uses heuristics to find the base directory in a variety of
* situations. Depending on your execution environment, the class may be
* located in one of several different places:
* </p>
* <ol>
* <li><b>In the Maven build directory.</b> Typically this is the
* {@code target/classes} folder of a given component. In this case, the class
* files reside directly on the file system (not in a JAR file). The base
* directory is defined as the toplevel Maven directory for the multi-module
* project. For example, if you have checked out {@code scijava-common.git} to
* {@code ~/sjc}, the {@code org.scijava.Context} class will be located at
* {@code ~/sjc/scijava-common/target/classes/org/scijava/Context.class}.
* Asking for the base directory for that class will yield
* {@code ~/sjc/scijava-common}, as long as you correctly specify
* {@code scijava-common} for the {@code baseSubdirectory}.</li>
* <li><b>Within a JAR file in the Maven local repository cache.</b> Typically
* this cache is located in {@code ~/.m2/repository}. The location will be
* {@code groupId/artifactId/version/artifactId-version.jar} where
* {@code groupId}, {@code artifactId} and {@code version} are the <a
* href="http://maven.apache.org/pom.html#Maven_Coordinates">Maven GAV
* coordinates</a>. Note that in this case, no base directory with respect to
* the given class can be found, and this method will return null.</li>
* <li><b>Within a JAR file beneath the base directory.</b> Common cases
* include running the application from a standalone application bundle (e.g.,
* the JARs may all be located within a {@code jars} folder of the application
* distribution archive) or using a JAR packaged by Maven and residing in the
* Maven build folder (typically {@code target/artifactId-version.jar}).
* However, this could potentially be anywhere beneath the base directory.
* This method assumes the JAR will be nested exactly one level deep; i.e., it
* computes the base directory as the parent directory of the one containing
* the JAR file.</li>
* </ol>
* <p>
* As you can see, it is quite complicated to find the base directory properly
* in all cases. The specific execution environments we have tested include:
* </p>
* <ol>
* <li><b>Running from Eclipse.</b> How Eclipse structures the classpath
* depends on which dependencies are open (i.e., project dependencies) versus
* closed (i.e., JAR dependencies). Each project dependency has a classpath
* entry <b>in its Maven build directory</b>. Each JAR dependency has a
* classpath entry <b>within a JAR file in the Maven local repository
* cache</b>.</li>
* <li><b>Running via Maven.</b> If you execute the application using Maven
* (e.g., {@code mvn exec:exec}, or with a fully Maven-compatible IDE such as
* NetBeans or IntelliJ IDEA) then all dependencies will reside <b>within JAR
* files in the local Maven repository cache</b>. But the executed project
* itself will reside <b>in its Maven build directory</b>. So as long as you
* ask for the base directory relative to a class
* <em>of the executed project</em> it will be found.</li>
* <li><b>Running as an application bundle (e.g., ImageJ).</b> Typically this
* means downloading ImageJ from the web site, unpacking it and running the
* ImageJ launcher (double-clicking ImageJ-win32.exe on Windows,
* double-clicking the {@code ImageJ.app} on OS X, etc.). In this case, all
* components reside in the {@code jars} folder of the application bundle, and
* the base directory will be found one level above that.</li>
* </ol>
*
* @param classLocation The location from which the base directory should be
* derived.
* @param baseSubdirectory A hint for what to expect for a directory structure
* beneath the application base directory. If this value is null
* (i.e., no hint is given), the heuristic scans up the directory
* tree looking for the topmost pom.xml file.
*/
public static File getBaseDirectory(final File classLocation,
final String baseSubdirectory)
{
if (classLocation == null) return null;
String path = FileUtils.getPath(classLocation);
if (path.contains("/.m2/repository/")) {
// NB: The class is in a JAR in the Maven repository cache.
// We cannot find the application base directory relative to this path.
return null;
}
// check whether the class is in a Maven build directory
String basePrefix = "/";
if (baseSubdirectory != null) basePrefix += baseSubdirectory + "/";
final String targetClassesSuffix = basePrefix + "target/classes";
if (path.endsWith(targetClassesSuffix)) {
// NB: The class is a file beneath the Maven build directory
// ("target/classes").
path = path.substring(0, path.length() - targetClassesSuffix.length());
File dir = new File(path);
if (baseSubdirectory == null) {
// NB: There is no hint as to the directory structure.
// So we scan up the tree to find the topmost pom.xml file.
while (dir.getParentFile() != null &&
new File(dir.getParentFile(), "pom.xml").exists())
{
dir = dir.getParentFile();
}
}
return dir;
}
final Pattern pattern =
Pattern.compile(".*(" + Pattern.quote(basePrefix + "target/") +
"[^/]*\\.jar)");
final Matcher matcher = pattern.matcher(path);
if (matcher.matches()) {
// NB: The class is in the Maven build directory inside a JAR file
// ("target/[something].jar").
final int index = matcher.start(1);
path = path.substring(0, index);
return new File(path);
}
if (path.endsWith(".jar")) {
final File jarDirectory = classLocation.getParentFile();
// NB: The class is in a JAR file, which we assume is nested one level
// deep (i.e., directly beneath the application base directory).
return jarDirectory.getParentFile();
}
// NB: As a last resort, we use the class location directly.
return classLocation;
}
}
| AppUtils#getBaseDirectory: handle DOS-style paths
Oh well. And here I was, thinking that we lived in the 21st century.
Signed-off-by: Johannes Schindelin <[email protected]>
| src/main/java/org/scijava/util/AppUtils.java | AppUtils#getBaseDirectory: handle DOS-style paths | <ide><path>rc/main/java/org/scijava/util/AppUtils.java
<ide> final String baseSubdirectory)
<ide> {
<ide> if (classLocation == null) return null;
<del> String path = FileUtils.getPath(classLocation);
<add> String path = FileUtils.getPath(classLocation).replace('\\', '/');
<ide>
<ide> if (path.contains("/.m2/repository/")) {
<ide> // NB: The class is in a JAR in the Maven repository cache. |
|
Java | bsd-2-clause | b6ffa3f4b745c66e832b26a8ff262a82b9f7a05a | 0 | chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio | /*
* Copyright (c) 2003-2006 jMonkeyEngine
* 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 'jMonkeyEngine' 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 com.jme.util;
import java.io.IOException;
import java.net.URL;
import com.jme.image.Image;
import com.jme.util.export.InputCapsule;
import com.jme.util.export.JMEExporter;
import com.jme.util.export.JMEImporter;
import com.jme.util.export.OutputCapsule;
import com.jme.util.export.Savable;
/**
*
* <code>TextureKey</code> provides a way for the TextureManager to cache and
* retrieve <code>Texture</code> objects.
*
* @author Joshua Slack
* @version $Id: TextureKey.java,v 1.18 2006-07-07 20:42:13 nca Exp $
*/
final public class TextureKey implements Savable {
public interface LocationOverride {
public URL getLocation(String file);
}
protected URL m_location = null;
protected int m_minFilter, m_maxFilter;
protected float m_anisoLevel;
protected boolean m_flipped;
protected int code = Integer.MAX_VALUE;
protected int imageType = Image.GUESS_FORMAT;
protected String fileType;
private static LocationOverride locationOverride;
public TextureKey() {
}
public TextureKey(URL location, int minFilter, int maxFilter,
float anisoLevel, boolean flipped, int imageType) {
m_location = location;
m_minFilter = minFilter;
m_maxFilter = maxFilter;
m_flipped = flipped;
m_anisoLevel = anisoLevel;
this.imageType = imageType;
}
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof TextureKey)) {
return false;
}
TextureKey that = (TextureKey) other;
if (this.m_location == null) {
if (that.m_location != null)
return false;
}
else if (!this.m_location.equals(that.m_location))
return false;
if (this.m_minFilter != that.m_minFilter)
return false;
if (this.m_maxFilter != that.m_maxFilter)
return false;
if (this.m_anisoLevel != that.m_anisoLevel)
return false;
if (this.m_flipped != that.m_flipped)
return false;
if (this.imageType != that.imageType)
return false;
return true;
}
// TODO: make this better?
public int hashCode() {
if (code == Integer.MAX_VALUE) {
if(m_location != null) {
code = m_location.hashCode();
}
code += (int) (m_anisoLevel * 100);
code += m_maxFilter;
code += m_minFilter;
code += imageType;
code += (m_flipped ? 1 : 0);
}
return code;
}
public void resetHashCode() {
code = Integer.MAX_VALUE;
}
public void write(JMEExporter e) throws IOException {
OutputCapsule capsule = e.getCapsule(this);
capsule.write(m_location.getProtocol(), "protocol", null);
capsule.write(m_location.getHost(), "host", null);
capsule.write(m_location.getFile(), "file", null);
capsule.write(m_minFilter, "minFilter", 0);
capsule.write(m_maxFilter, "maxFilter", 0);
capsule.write(m_anisoLevel, "anisoLevel", 0);
capsule.write(m_flipped, "flipped", false);
capsule.write(imageType, "imageType", Image.GUESS_FORMAT);
capsule.write(fileType, "fileType", null);
}
public void read(JMEImporter e) throws IOException {
InputCapsule capsule = e.getCapsule(this);
String protocol = capsule.readString("protocol", null);
String host = capsule.readString("host", null);
String file = capsule.readString("file", null);
if(locationOverride != null && "file".equals(protocol)) {
int index = file.lastIndexOf('/');
if(index == -1) {
index = file.lastIndexOf('\\');
}
index+=1;
file = file.substring(index);
m_location = new URL(locationOverride.getLocation(file), file);
} else {
m_location = new URL(protocol, host, file);
}
m_minFilter = capsule.readInt("minFilter", 0);
m_maxFilter = capsule.readInt("maxFilter", 0);
m_anisoLevel = capsule.readFloat("anisoLevel", 0);
m_flipped = capsule.readBoolean("flipped", false);
imageType = capsule.readInt("imageType", Image.GUESS_FORMAT);
fileType = capsule.readString("fileType", null);
}
public int getImageType() {
return imageType;
}
public void setImageType(int imageType) {
this.imageType = imageType;
}
public static LocationOverride getLocationOverride() {
return locationOverride;
}
public static void setLocationOverride(LocationOverride locationOverride) {
TextureKey.locationOverride = locationOverride;
}
public static void setOverridingLocation(final URL overridingLocation) {
setLocationOverride(new LocationOverride() {
public URL getLocation(String file) {
return overridingLocation;
}
});
}
public Class getClassTag() {
return this.getClass();
}
/**
* @return Returns the anisoLevel.
*/
public float getAnisoLevel() {
return m_anisoLevel;
}
/**
* @param level The anisoLevel to set.
*/
public void setAnisoLevel(float level) {
m_anisoLevel = level;
}
/**
* @return Returns the flipped.
*/
public boolean isFlipped() {
return m_flipped;
}
/**
* @param flipped The flipped to set.
*/
public void setFlipped(boolean flipped) {
this.m_flipped = flipped;
}
/**
* @return Returns the location.
*/
public URL getLocation() {
return m_location;
}
/**
* @param location The location to set.
*/
public void setLocation(URL location) {
this.m_location = location;
}
/**
* @return Returns the maxFilter.
*/
public int getMaxFilter() {
return m_maxFilter;
}
/**
* @param filter The maxFilter to set.
*/
public void setMaxFilter(int filter) {
m_maxFilter = filter;
}
/**
* @return Returns the minFilter.
*/
public int getMinFilter() {
return m_minFilter;
}
/**
* @param filter The minFilter to set.
*/
public void setMinFilter(int filter) {
m_minFilter = filter;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
}
| src/com/jme/util/TextureKey.java | /*
* Copyright (c) 2003-2006 jMonkeyEngine
* 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 'jMonkeyEngine' 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 com.jme.util;
import java.io.IOException;
import java.net.URL;
import com.jme.image.Image;
import com.jme.util.export.InputCapsule;
import com.jme.util.export.JMEExporter;
import com.jme.util.export.JMEImporter;
import com.jme.util.export.OutputCapsule;
import com.jme.util.export.Savable;
/**
*
* <code>TextureKey</code> provides a way for the TextureManager to cache and
* retrieve <code>Texture</code> objects.
*
* @author Joshua Slack
* @version $Id: TextureKey.java,v 1.17 2006-06-19 22:39:42 nca Exp $
*/
final public class TextureKey implements Savable {
protected URL m_location = null;
protected int m_minFilter, m_maxFilter;
protected float m_anisoLevel;
protected boolean m_flipped;
protected int code = Integer.MAX_VALUE;
protected int imageType = Image.GUESS_FORMAT;
protected String fileType;
private static URL overridingLocation;
public TextureKey() {
}
public TextureKey(URL location, int minFilter, int maxFilter,
float anisoLevel, boolean flipped, int imageType) {
m_location = location;
m_minFilter = minFilter;
m_maxFilter = maxFilter;
m_flipped = flipped;
m_anisoLevel = anisoLevel;
this.imageType = imageType;
}
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof TextureKey)) {
return false;
}
TextureKey that = (TextureKey) other;
if (this.m_location == null) {
if (that.m_location != null)
return false;
}
else if (!this.m_location.equals(that.m_location))
return false;
if (this.m_minFilter != that.m_minFilter)
return false;
if (this.m_maxFilter != that.m_maxFilter)
return false;
if (this.m_anisoLevel != that.m_anisoLevel)
return false;
if (this.m_flipped != that.m_flipped)
return false;
if (this.imageType != that.imageType)
return false;
return true;
}
// TODO: make this better?
public int hashCode() {
if (code == Integer.MAX_VALUE) {
if(m_location != null) {
code = m_location.hashCode();
}
code += (int) (m_anisoLevel * 100);
code += m_maxFilter;
code += m_minFilter;
code += imageType;
code += (m_flipped ? 1 : 0);
}
return code;
}
public void resetHashCode() {
code = Integer.MAX_VALUE;
}
public void write(JMEExporter e) throws IOException {
OutputCapsule capsule = e.getCapsule(this);
capsule.write(m_location.getProtocol(), "protocol", null);
capsule.write(m_location.getHost(), "host", null);
capsule.write(m_location.getFile(), "file", null);
capsule.write(m_minFilter, "minFilter", 0);
capsule.write(m_maxFilter, "maxFilter", 0);
capsule.write(m_anisoLevel, "anisoLevel", 0);
capsule.write(m_flipped, "flipped", false);
capsule.write(imageType, "imageType", Image.GUESS_FORMAT);
capsule.write(fileType, "fileType", null);
}
public void read(JMEImporter e) throws IOException {
InputCapsule capsule = e.getCapsule(this);
String protocol = capsule.readString("protocol", null);
String host = capsule.readString("host", null);
String file = capsule.readString("file", null);
if(overridingLocation != null && "file".equals(protocol)) {
int index = file.lastIndexOf('/');
if(index == -1) {
index = file.lastIndexOf('\\');
}
index+=1;
String loc = file.substring(0, index);
if(!overridingLocation.equals(loc)) {
file = file.substring(index);
m_location = new URL(overridingLocation, file);
} else {
m_location = new URL(protocol, host, file);
}
} else {
m_location = new URL(protocol, host, file);
}
m_minFilter = capsule.readInt("minFilter", 0);
m_maxFilter = capsule.readInt("maxFilter", 0);
m_anisoLevel = capsule.readFloat("anisoLevel", 0);
m_flipped = capsule.readBoolean("flipped", false);
imageType = capsule.readInt("imageType", Image.GUESS_FORMAT);
fileType = capsule.readString("fileType", null);
}
public int getImageType() {
return imageType;
}
public void setImageType(int imageType) {
this.imageType = imageType;
}
public static URL getOverridingLocation() {
return overridingLocation;
}
public static void setOverridingLocation(URL overridingLocation) {
TextureKey.overridingLocation = overridingLocation;
}
public Class getClassTag() {
return this.getClass();
}
/**
* @return Returns the anisoLevel.
*/
public float getAnisoLevel() {
return m_anisoLevel;
}
/**
* @param level The anisoLevel to set.
*/
public void setAnisoLevel(float level) {
m_anisoLevel = level;
}
/**
* @return Returns the flipped.
*/
public boolean isFlipped() {
return m_flipped;
}
/**
* @param flipped The flipped to set.
*/
public void setFlipped(boolean flipped) {
this.m_flipped = flipped;
}
/**
* @return Returns the location.
*/
public URL getLocation() {
return m_location;
}
/**
* @param location The location to set.
*/
public void setLocation(URL location) {
this.m_location = location;
}
/**
* @return Returns the maxFilter.
*/
public int getMaxFilter() {
return m_maxFilter;
}
/**
* @param filter The maxFilter to set.
*/
public void setMaxFilter(int filter) {
m_maxFilter = filter;
}
/**
* @return Returns the minFilter.
*/
public int getMinFilter() {
return m_minFilter;
}
/**
* @param filter The minFilter to set.
*/
public void setMinFilter(int filter) {
m_minFilter = filter;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
}
| ISSUE: MINOR
Add an optional interface for the setting of location override.
git-svn-id: 5afc437a751a4ff2ced778146f5faadda0b504ab@3080 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
| src/com/jme/util/TextureKey.java | ISSUE: MINOR | <ide><path>rc/com/jme/util/TextureKey.java
<ide> * retrieve <code>Texture</code> objects.
<ide> *
<ide> * @author Joshua Slack
<del> * @version $Id: TextureKey.java,v 1.17 2006-06-19 22:39:42 nca Exp $
<add> * @version $Id: TextureKey.java,v 1.18 2006-07-07 20:42:13 nca Exp $
<ide> */
<ide> final public class TextureKey implements Savable {
<add>
<add> public interface LocationOverride {
<add> public URL getLocation(String file);
<add> }
<add>
<ide> protected URL m_location = null;
<ide> protected int m_minFilter, m_maxFilter;
<ide> protected float m_anisoLevel;
<ide> protected int imageType = Image.GUESS_FORMAT;
<ide> protected String fileType;
<ide>
<del> private static URL overridingLocation;
<add> private static LocationOverride locationOverride;
<ide>
<ide> public TextureKey() {
<ide>
<ide> String protocol = capsule.readString("protocol", null);
<ide> String host = capsule.readString("host", null);
<ide> String file = capsule.readString("file", null);
<del> if(overridingLocation != null && "file".equals(protocol)) {
<add> if(locationOverride != null && "file".equals(protocol)) {
<ide> int index = file.lastIndexOf('/');
<ide> if(index == -1) {
<ide> index = file.lastIndexOf('\\');
<ide> }
<ide> index+=1;
<ide>
<del> String loc = file.substring(0, index);
<del> if(!overridingLocation.equals(loc)) {
<del> file = file.substring(index);
<del> m_location = new URL(overridingLocation, file);
<del> } else {
<del> m_location = new URL(protocol, host, file);
<del> }
<add> file = file.substring(index);
<add> m_location = new URL(locationOverride.getLocation(file), file);
<ide> } else {
<ide> m_location = new URL(protocol, host, file);
<ide> }
<ide> this.imageType = imageType;
<ide> }
<ide>
<del> public static URL getOverridingLocation() {
<del> return overridingLocation;
<del> }
<del>
<del> public static void setOverridingLocation(URL overridingLocation) {
<del> TextureKey.overridingLocation = overridingLocation;
<add> public static LocationOverride getLocationOverride() {
<add> return locationOverride;
<add> }
<add>
<add> public static void setLocationOverride(LocationOverride locationOverride) {
<add> TextureKey.locationOverride = locationOverride;
<add> }
<add>
<add> public static void setOverridingLocation(final URL overridingLocation) {
<add> setLocationOverride(new LocationOverride() {
<add> public URL getLocation(String file) {
<add> return overridingLocation;
<add> }
<add> });
<ide> }
<ide>
<ide> public Class getClassTag() { |
|
Java | apache-2.0 | 64704cb4309052c0bf8a63631c4b17a5c54bba61 | 0 | fengbaicanhe/intellij-community,orekyuu/intellij-community,consulo/consulo,ftomassetti/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,xfournet/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,retomerz/intellij-community,dslomov/intellij-community,allotria/intellij-community,xfournet/intellij-community,consulo/consulo,robovm/robovm-studio,SerCeMan/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,ryano144/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,da1z/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,apixandru/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,da1z/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,fnouama/intellij-community,izonder/intellij-community,kdwink/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,apixandru/intellij-community,izonder/intellij-community,clumsy/intellij-community,samthor/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,amith01994/intellij-community,allotria/intellij-community,retomerz/intellij-community,FHannes/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,ryano144/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,supersven/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,apixandru/intellij-community,kool79/intellij-community,akosyakov/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,da1z/intellij-community,adedayo/intellij-community,amith01994/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,semonte/intellij-community,caot/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,signed/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,fnouama/intellij-community,robovm/robovm-studio,fitermay/intellij-community,caot/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,caot/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,petteyg/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,samthor/intellij-community,youdonghai/intellij-community,samthor/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,allotria/intellij-community,slisson/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,da1z/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,xfournet/intellij-community,diorcety/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,robovm/robovm-studio,consulo/consulo,blademainer/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,slisson/intellij-community,ryano144/intellij-community,allotria/intellij-community,adedayo/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,holmes/intellij-community,supersven/intellij-community,apixandru/intellij-community,ibinti/intellij-community,jagguli/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,robovm/robovm-studio,retomerz/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,kool79/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,caot/intellij-community,fitermay/intellij-community,retomerz/intellij-community,da1z/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,caot/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,holmes/intellij-community,diorcety/intellij-community,supersven/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,supersven/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,amith01994/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,vladmm/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,allotria/intellij-community,samthor/intellij-community,izonder/intellij-community,petteyg/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,signed/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,signed/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,izonder/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,ahb0327/intellij-community,caot/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,youdonghai/intellij-community,izonder/intellij-community,apixandru/intellij-community,fnouama/intellij-community,hurricup/intellij-community,caot/intellij-community,holmes/intellij-community,asedunov/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,supersven/intellij-community,slisson/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,ernestp/consulo,izonder/intellij-community,slisson/intellij-community,fitermay/intellij-community,semonte/intellij-community,fitermay/intellij-community,ernestp/consulo,mglukhikh/intellij-community,petteyg/intellij-community,kool79/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,samthor/intellij-community,xfournet/intellij-community,petteyg/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,consulo/consulo,allotria/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,amith01994/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,ernestp/consulo,kool79/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,amith01994/intellij-community,kdwink/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,holmes/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,fnouama/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,ryano144/intellij-community,FHannes/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,robovm/robovm-studio,tmpgit/intellij-community,ernestp/consulo,fnouama/intellij-community,petteyg/intellij-community,FHannes/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,consulo/consulo,caot/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,semonte/intellij-community,semonte/intellij-community,consulo/consulo,robovm/robovm-studio,orekyuu/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,semonte/intellij-community,slisson/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,blademainer/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,signed/intellij-community,clumsy/intellij-community,adedayo/intellij-community,diorcety/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,ernestp/consulo,da1z/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,slisson/intellij-community,vladmm/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,kool79/intellij-community,vladmm/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,xfournet/intellij-community,diorcety/intellij-community,semonte/intellij-community,allotria/intellij-community,suncycheng/intellij-community,signed/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,allotria/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,samthor/intellij-community,youdonghai/intellij-community,signed/intellij-community,signed/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,apixandru/intellij-community,caot/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,kool79/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,retomerz/intellij-community,dslomov/intellij-community,xfournet/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,robovm/robovm-studio,signed/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,caot/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,semonte/intellij-community,xfournet/intellij-community,ibinti/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,ernestp/consulo,clumsy/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,holmes/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,kool79/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,diorcety/intellij-community,da1z/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,signed/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,dslomov/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,slisson/intellij-community,jagguli/intellij-community,adedayo/intellij-community,diorcety/intellij-community,signed/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,blademainer/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,kdwink/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,hurricup/intellij-community | /*
* Copyright 2000-2009 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.codeInsight.daemon.impl;
import com.intellij.codeHighlighting.Pass;
import com.intellij.codeInsight.daemon.DaemonBundle;
import com.intellij.codeInsight.daemon.HighlightDisplayKey;
import com.intellij.codeInsight.daemon.impl.analysis.HighlightLevelUtil;
import com.intellij.codeInsight.daemon.impl.quickfix.QuickFixAction;
import com.intellij.codeInsight.intention.EmptyIntentionAction;
import com.intellij.codeInspection.*;
import com.intellij.codeInspection.ex.*;
import com.intellij.codeInspection.ui.ProblemDescriptionNode;
import com.intellij.concurrency.JobUtil;
import com.intellij.injected.editor.DocumentWindow;
import com.intellij.lang.Language;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.colors.CodeInsightColors;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.keymap.Keymap;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.Trinity;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.profile.codeInspection.SeverityProvider;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.util.ConcurrencyUtil;
import com.intellij.util.Function;
import com.intellij.util.Processor;
import com.intellij.util.containers.ConcurrentHashMap;
import com.intellij.util.containers.TransferToEDTQueue;
import com.intellij.xml.util.XmlStringUtil;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
/**
* @author max
*/
public class LocalInspectionsPass extends ProgressableTextEditorHighlightingPass implements DumbAware {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.LocalInspectionsPass");
public static final TextRange EMPTY_PRIORITY_RANGE = TextRange.EMPTY_RANGE;
private final int myStartOffset;
private final int myEndOffset;
private final TextRange myPriorityRange;
private final boolean myIgnoreSuppressed;
private final ConcurrentMap<PsiFile, List<InspectionResult>> result = new ConcurrentHashMap<PsiFile, List<InspectionResult>>();
private static final String PRESENTABLE_NAME = DaemonBundle.message("pass.inspection");
private volatile List<HighlightInfo> myInfos = Collections.emptyList();
private final String myShortcutText;
private final SeverityRegistrar mySeverityRegistrar;
private final InspectionProfileWrapper myProfileWrapper;
private boolean myFailFastOnAcquireReadAction;
public LocalInspectionsPass(@NotNull PsiFile file,
@Nullable Document document,
int startOffset,
int endOffset,
@NotNull TextRange priorityRange,
boolean ignoreSuppressed) {
super(file.getProject(), document, PRESENTABLE_NAME, file, true);
myStartOffset = startOffset;
myEndOffset = endOffset;
myPriorityRange = priorityRange;
myIgnoreSuppressed = ignoreSuppressed;
setId(Pass.LOCAL_INSPECTIONS);
final KeymapManager keymapManager = KeymapManager.getInstance();
if (keymapManager != null) {
final Keymap keymap = keymapManager.getActiveKeymap();
myShortcutText = keymap == null ? "" : "(" + KeymapUtil.getShortcutsText(keymap.getShortcuts(IdeActions.ACTION_SHOW_ERROR_DESCRIPTION)) + ")";
}
else {
myShortcutText = "";
}
InspectionProfileWrapper profileToUse = InspectionProjectProfileManager.getInstance(myProject).getProfileWrapper();
Function<InspectionProfileWrapper,InspectionProfileWrapper> custom = file.getUserData(InspectionProfileWrapper.CUSTOMIZATION_KEY);
if (custom != null) {
profileToUse = custom.fun(profileToUse);
}
myProfileWrapper = profileToUse;
mySeverityRegistrar = ((SeverityProvider)myProfileWrapper.getInspectionProfile().getProfileManager()).getSeverityRegistrar();
LOG.assertTrue(mySeverityRegistrar != null);
// initial guess
setProgressLimit(300 * 2);
}
protected void collectInformationWithProgress(@NotNull ProgressIndicator progress) {
try {
if (!HighlightLevelUtil.shouldInspect(myFile)) return;
final InspectionManagerEx iManager = (InspectionManagerEx)InspectionManager.getInstance(myProject);
final InspectionProfileWrapper profile = myProfileWrapper;
final List<LocalInspectionTool> tools = DumbService.getInstance(myProject).filterByDumbAwareness(getInspectionTools(profile));
inspect(tools, iManager, true, true, progress);
}
finally {
disposeDescriptors();
}
}
private void disposeDescriptors() {
result.clear();
}
public void doInspectInBatch(@NotNull InspectionManagerEx iManager, @NotNull List<InspectionProfileEntry> toolWrappers) {
Map<LocalInspectionTool, LocalInspectionToolWrapper> tool2Wrapper = new THashMap<LocalInspectionTool, LocalInspectionToolWrapper>(toolWrappers.size());
for (InspectionProfileEntry toolWrapper : toolWrappers) {
tool2Wrapper.put(((LocalInspectionToolWrapper)toolWrapper).getTool(), (LocalInspectionToolWrapper)toolWrapper);
}
List<LocalInspectionTool> tools = new ArrayList<LocalInspectionTool>(tool2Wrapper.keySet());
ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
inspect(tools, iManager, false, false, progress);
addDescriptorsFromInjectedResults(tool2Wrapper, iManager);
List<InspectionResult> resultList = result.get(myFile);
if (resultList == null) return;
for (InspectionResult inspectionResult : resultList) {
LocalInspectionTool tool = inspectionResult.tool;
LocalInspectionToolWrapper toolWrapper = tool2Wrapper.get(tool);
if (toolWrapper == null) continue;
for (ProblemDescriptor descriptor : inspectionResult.foundProblems) {
toolWrapper.addProblemDescriptors(Collections.singletonList(descriptor), myIgnoreSuppressed);
}
}
}
private void addDescriptorsFromInjectedResults(Map<LocalInspectionTool, LocalInspectionToolWrapper> tool2Wrapper, InspectionManagerEx iManager) {
Set<TextRange> emptyActionRegistered = new THashSet<TextRange>();
InspectionProfile inspectionProfile = InspectionProjectProfileManager.getInstance(myProject).getInspectionProfile();
InjectedLanguageManager ilManager = InjectedLanguageManager.getInstance(myProject);
PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
for (Map.Entry<PsiFile, List<InspectionResult>> entry : result.entrySet()) {
PsiFile file = entry.getKey();
if (file == myFile) continue; // not injected
DocumentWindow documentRange = (DocumentWindow)documentManager.getDocument(file);
List<InspectionResult> resultList = entry.getValue();
for (InspectionResult inspectionResult : resultList) {
LocalInspectionTool tool = inspectionResult.tool;
HighlightSeverity severity = inspectionProfile.getErrorLevel(HighlightDisplayKey.find(tool.getShortName()), myFile).getSeverity();
for (ProblemDescriptor descriptor : inspectionResult.foundProblems) {
PsiElement psiElement = descriptor.getPsiElement();
if (psiElement == null) continue;
if (InspectionManagerEx.inspectionResultSuppressed(psiElement, tool)) continue;
HighlightInfoType level = highlightTypeFromDescriptor(descriptor, severity);
HighlightInfo info = createHighlightInfo(descriptor, tool, level,emptyActionRegistered, psiElement);
if (info == null) continue;
List<TextRange> editables = ilManager.intersectWithAllEditableFragments(file, new TextRange(info.startOffset, info.endOffset));
for (TextRange editable : editables) {
TextRange hostRange = documentRange.injectedToHost(editable);
QuickFix[] fixes = descriptor.getFixes();
LocalQuickFix[] localFixes = null;
if (fixes != null) {
localFixes = new LocalQuickFix[fixes.length];
for (int k = 0; k < fixes.length; k++) {
QuickFix fix = fixes[k];
localFixes[k] = (LocalQuickFix)fix;
}
}
ProblemDescriptor patchedDescriptor = iManager.createProblemDescriptor(myFile, hostRange, descriptor.getDescriptionTemplate(),
descriptor.getHighlightType(), true, localFixes);
LocalInspectionToolWrapper toolWrapper = tool2Wrapper.get(tool);
toolWrapper.addProblemDescriptors(Collections.singletonList(patchedDescriptor), true);
}
}
}
}
}
private void inspect(@NotNull final List<LocalInspectionTool> tools,
@NotNull final InspectionManagerEx iManager,
final boolean isOnTheFly,
boolean failFastOnAcquireReadAction,
@NotNull final ProgressIndicator indicator) {
myFailFastOnAcquireReadAction = failFastOnAcquireReadAction;
if (tools.isEmpty()) return;
List<PsiElement> inside = new ArrayList<PsiElement>();
List<PsiElement> outside = new ArrayList<PsiElement>();
Divider.divideInsideAndOutside(myFile, myStartOffset, myEndOffset, myPriorityRange, inside, outside,
HighlightLevelUtil.AnalysisLevel.HIGHLIGHT_AND_INSPECT,true);
setProgressLimit(1L * tools.size() * 2);
final LocalInspectionToolSession session = new LocalInspectionToolSession(myFile, myStartOffset, myEndOffset);
List<Trinity<LocalInspectionTool, ProblemsHolder, PsiElementVisitor>> init = new ArrayList<Trinity<LocalInspectionTool, ProblemsHolder, PsiElementVisitor>>();
visitPriorityElementsAndInit(tools, iManager, isOnTheFly, indicator, inside, session, init);
visitRestElementsAndCleanup(tools,iManager,isOnTheFly, indicator, outside, session, init);
indicator.checkCanceled();
myInfos = new ArrayList<HighlightInfo>();
addHighlightsFromResults(myInfos, indicator);
}
private void visitPriorityElementsAndInit(@NotNull List<LocalInspectionTool> tools,
@NotNull final InspectionManagerEx iManager,
final boolean isOnTheFly,
@NotNull final ProgressIndicator indicator,
@NotNull final List<PsiElement> elements,
@NotNull final LocalInspectionToolSession session,
@NotNull final List<Trinity<LocalInspectionTool, ProblemsHolder, PsiElementVisitor>> init) {
boolean result = JobUtil.invokeConcurrentlyUnderProgress(tools, new Processor<LocalInspectionTool>() {
public boolean process(final LocalInspectionTool tool) {
indicator.checkCanceled();
ApplicationManager.getApplication().assertReadAccessAllowed();
final boolean[] applyIncrementally = {isOnTheFly};
ProblemsHolder holder = new ProblemsHolder(iManager, myFile, isOnTheFly) {
@Override
public void registerProblem(@NotNull ProblemDescriptor descriptor) {
super.registerProblem(descriptor);
if (applyIncrementally[0]) {
addDescriptorIncrementally(descriptor, tool, indicator);
}
}
};
PsiElementVisitor visitor = createVisitorAndAcceptElements(tool, holder, isOnTheFly, session, elements);
synchronized (init) {
init.add(Trinity.create(tool, holder, visitor));
}
advanceProgress(1);
if (holder.hasResults()) {
appendDescriptors(myFile, holder.getResults(), tool);
}
applyIncrementally[0] = false; // do not apply incrementally outside visible range
return true;
}
}, myFailFastOnAcquireReadAction, indicator);
if (!result) throw new ProcessCanceledException();
inspectInjectedPsi(elements, tools, isOnTheFly, indicator, iManager, true);
}
private static PsiElementVisitor createVisitorAndAcceptElements(@NotNull LocalInspectionTool tool,
@NotNull ProblemsHolder holder,
boolean isOnTheFly,
@NotNull LocalInspectionToolSession session,
@NotNull List<PsiElement> elements) {
PsiElementVisitor visitor = tool.buildVisitor(holder, isOnTheFly, session);
//noinspection ConstantConditions
if(visitor == null) {
LOG.error("Tool " + tool + " must not return null from the buildVisitor() method");
}
assert !(visitor instanceof PsiRecursiveElementVisitor || visitor instanceof PsiRecursiveElementWalkingVisitor)
: "The visitor returned from LocalInspectionTool.buildVisitor() must not be recursive. "+tool;
tool.inspectionStarted(session, isOnTheFly);
acceptElements(elements, visitor);
return visitor;
}
private void visitRestElementsAndCleanup(@NotNull List<LocalInspectionTool> tools,
@NotNull final InspectionManagerEx iManager,
final boolean isOnTheFly,
@NotNull final ProgressIndicator indicator,
@NotNull final List<PsiElement> elements,
@NotNull final LocalInspectionToolSession session,
@NotNull List<Trinity<LocalInspectionTool, ProblemsHolder, PsiElementVisitor>> init) {
Processor<Trinity<LocalInspectionTool, ProblemsHolder, PsiElementVisitor>> processor =
new Processor<Trinity<LocalInspectionTool, ProblemsHolder, PsiElementVisitor>>() {
@Override
public boolean process(Trinity<LocalInspectionTool, ProblemsHolder, PsiElementVisitor> trinity) {
LocalInspectionTool tool = trinity.first;
indicator.checkCanceled();
ApplicationManager.getApplication().assertReadAccessAllowed();
ProblemsHolder holder = trinity.second;
PsiElementVisitor elementVisitor = trinity.third;
acceptElements(elements, elementVisitor);
advanceProgress(1);
tool.inspectionFinished(session, holder);
if (holder.hasResults()) {
appendDescriptors(myFile, holder.getResults(), tool);
}
return true;
}
};
boolean result = JobUtil.invokeConcurrentlyUnderProgress(init, processor, myFailFastOnAcquireReadAction, indicator);
if (!result) {
throw new ProcessCanceledException();
}
inspectInjectedPsi(elements, tools, isOnTheFly, indicator, iManager, false);
}
private static void acceptElements(@NotNull List<PsiElement> elements,
@NotNull PsiElementVisitor elementVisitor) {
for (int i = 0, elementsSize = elements.size(); i < elementsSize; i++) {
PsiElement element = elements.get(i);
element.accept(elementVisitor);
ProgressManager.checkCanceled();
}
}
private void inspectInjectedPsi(@NotNull final List<PsiElement> elements,
@NotNull final List<LocalInspectionTool> tools,
final boolean onTheFly,
@NotNull final ProgressIndicator indicator,
@NotNull final InspectionManagerEx iManager,
final boolean inVisibleRange) {
final Set<PsiFile> injected = new THashSet<PsiFile>();
for (PsiElement element : elements) {
InjectedLanguageUtil.enumerate(element, myFile, new PsiLanguageInjectionHost.InjectedPsiVisitor() {
public void visit(@NotNull PsiFile injectedPsi, @NotNull List<PsiLanguageInjectionHost.Shred> places) {
injected.add(injectedPsi);
}
}, false);
}
if (injected.isEmpty()) return;
if (!JobUtil.invokeConcurrentlyUnderProgress(new ArrayList<PsiFile>(injected), new Processor<PsiFile>() {
public boolean process(final PsiFile injectedPsi) {
doInspectInjectedPsi(injectedPsi, tools, onTheFly, indicator, iManager, inVisibleRange);
return true;
}
}, myFailFastOnAcquireReadAction, indicator)) throw new ProcessCanceledException();
}
@Nullable
private HighlightInfo highlightInfoFromDescriptor(@NotNull ProblemDescriptor problemDescriptor,
@NotNull HighlightInfoType highlightInfoType,
@NotNull String message,
String toolTip, PsiElement psiElement) {
TextRange textRange = ((ProblemDescriptorImpl)problemDescriptor).getTextRange();
if (textRange == null || psiElement == null) return null;
boolean isFileLevel = psiElement instanceof PsiFile && textRange.equals(psiElement.getTextRange());
final HighlightSeverity severity = highlightInfoType.getSeverity(psiElement);
TextAttributes attributes = mySeverityRegistrar.getTextAttributesBySeverity(severity);
return new HighlightInfo(attributes, highlightInfoType, textRange.getStartOffset(),
textRange.getEndOffset(), message, toolTip,
severity, problemDescriptor.isAfterEndOfLine(), null, isFileLevel);
}
private final TransferToEDTQueue<Trinity<ProblemDescriptor, LocalInspectionTool,ProgressIndicator>> myTransferToEDTQueue
= new TransferToEDTQueue<Trinity<ProblemDescriptor, LocalInspectionTool,ProgressIndicator>>("Apply inspection results", new Processor<Trinity<ProblemDescriptor, LocalInspectionTool,ProgressIndicator>>() {
private final InspectionProfile inspectionProfile = InspectionProjectProfileManager.getInstance(myProject).getInspectionProfile();
private final InjectedLanguageManager ilManager = InjectedLanguageManager.getInstance(myProject);
private final List<HighlightInfo> infos = new ArrayList<HighlightInfo>(2);
private final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
@Override
public boolean process(Trinity<ProblemDescriptor, LocalInspectionTool,ProgressIndicator> trinity) {
ProgressIndicator indicator = trinity.getThird();
if (indicator.isCanceled()) {
return false;
}
ProblemDescriptor descriptor = trinity.first;
LocalInspectionTool tool = trinity.second;
PsiElement psiElement = descriptor.getPsiElement();
if (psiElement == null) return true;
PsiFile file = psiElement.getContainingFile();
Document thisDocument = documentManager.getDocument(file);
HighlightSeverity severity = inspectionProfile.getErrorLevel(HighlightDisplayKey.find(tool.getShortName()), file).getSeverity();
infos.clear();
createHighlightsForDescriptor(infos, emptyActionRegistered, ilManager, file, thisDocument, tool, severity, descriptor, psiElement);
for (HighlightInfo info : infos) {
final EditorColorsScheme colorsScheme = getColorsScheme();
UpdateHighlightersUtil.addHighlighterToEditorIncrementally(myProject, myDocument, myFile, myStartOffset, myEndOffset,
info, colorsScheme, getId());
}
return true;
}
}, myProject.getDisposed(), 200);
private final Set<TextRange> emptyActionRegistered = Collections.synchronizedSet(new HashSet<TextRange>());
private void addDescriptorIncrementally(@NotNull final ProblemDescriptor descriptor,
@NotNull final LocalInspectionTool tool,
@NotNull final ProgressIndicator indicator) {
if (myIgnoreSuppressed && InspectionManagerEx.inspectionResultSuppressed(descriptor.getPsiElement(), tool)) {
return;
}
myTransferToEDTQueue.offer(Trinity.create(descriptor, tool, indicator));
}
private void appendDescriptors(PsiFile file, List<ProblemDescriptor> descriptors, LocalInspectionTool tool) {
for (ProblemDescriptor descriptor : descriptors) {
if (descriptor == null) {
LOG.error("null descriptor. all descriptors(" + descriptors.size() +"): " +
descriptors + "; file: " + file + " (" + file.getVirtualFile() +"); tool: " + tool);
}
}
InspectionResult res = new InspectionResult(tool, descriptors);
appendResult(file, res);
}
private void appendResult(PsiFile file, InspectionResult res) {
List<InspectionResult> resultList = result.get(file);
if (resultList == null) {
resultList = ConcurrencyUtil.cacheOrGet(result, file, new ArrayList<InspectionResult>());
}
synchronized (resultList) {
resultList.add(res);
}
}
@NotNull
private HighlightInfoType highlightTypeFromDescriptor(final ProblemDescriptor problemDescriptor, final HighlightSeverity severity) {
final ProblemHighlightType highlightType = problemDescriptor.getHighlightType();
switch (highlightType) {
case GENERIC_ERROR_OR_WARNING:
return mySeverityRegistrar.getHighlightInfoTypeBySeverity(severity);
case LIKE_DEPRECATED:
return new HighlightInfoType.HighlightInfoTypeImpl(severity, HighlightInfoType.DEPRECATED.getAttributesKey());
case LIKE_UNKNOWN_SYMBOL:
if (severity == HighlightSeverity.ERROR) {
return new HighlightInfoType.HighlightInfoTypeImpl(severity, HighlightInfoType.WRONG_REF.getAttributesKey());
}
else if (severity == HighlightSeverity.WARNING) {
return new HighlightInfoType.HighlightInfoTypeImpl(severity, CodeInsightColors.WEAK_WARNING_ATTRIBUTES);
}
else {
return mySeverityRegistrar.getHighlightInfoTypeBySeverity(severity);
}
case LIKE_UNUSED_SYMBOL:
return new HighlightInfoType.HighlightInfoTypeImpl(severity, HighlightInfoType.UNUSED_SYMBOL.getAttributesKey());
case INFO:
return HighlightInfoType.INFO;
case WEAK_WARNING:
return HighlightInfoType.WEAK_WARNING;
case ERROR:
return HighlightInfoType.WRONG_REF;
case GENERIC_ERROR:
return HighlightInfoType.ERROR;
case INFORMATION:
final TextAttributesKey attributes = ((ProblemDescriptorImpl)problemDescriptor).getEnforcedTextAttributes();
if (attributes != null) {
return new HighlightInfoType.HighlightInfoTypeImpl(HighlightSeverity.INFORMATION, attributes);
}
return HighlightInfoType.INFORMATION;
}
throw new RuntimeException("Cannot map " + highlightType);
}
protected void applyInformationWithProgress() {
UpdateHighlightersUtil.setHighlightersToEditor(myProject, myDocument, myStartOffset, myEndOffset, myInfos, getColorsScheme(), getId());
}
private void addHighlightsFromResults(@NotNull List<HighlightInfo> outInfos, @NotNull ProgressIndicator indicator) {
InspectionProfile inspectionProfile = InspectionProjectProfileManager.getInstance(myProject).getInspectionProfile();
PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
InjectedLanguageManager ilManager = InjectedLanguageManager.getInstance(myProject);
Set<TextRange> emptyActionRegistered = new THashSet<TextRange>();
for (Map.Entry<PsiFile, List<InspectionResult>> entry : result.entrySet()) {
indicator.checkCanceled();
PsiFile file = entry.getKey();
Document documentRange = documentManager.getDocument(file);
if (documentRange == null) continue;
List<InspectionResult> resultList = entry.getValue();
for (InspectionResult inspectionResult : resultList) {
indicator.checkCanceled();
LocalInspectionTool tool = inspectionResult.tool;
HighlightSeverity severity = inspectionProfile.getErrorLevel(HighlightDisplayKey.find(tool.getShortName()), file).getSeverity();
for (ProblemDescriptor descriptor : inspectionResult.foundProblems) {
indicator.checkCanceled();
PsiElement element = descriptor.getPsiElement();
createHighlightsForDescriptor(outInfos, emptyActionRegistered, ilManager, file, documentRange, tool, severity, descriptor, element);
}
}
}
}
private void createHighlightsForDescriptor(List<HighlightInfo> outInfos,
Set<TextRange> emptyActionRegistered,
InjectedLanguageManager ilManager,
PsiFile file,
Document documentRange,
LocalInspectionTool tool,
HighlightSeverity severity,
ProblemDescriptor descriptor,
PsiElement element) {
if (element == null) return;
if (myIgnoreSuppressed && InspectionManagerEx.inspectionResultSuppressed(element, tool)) return;
HighlightInfoType level = highlightTypeFromDescriptor(descriptor, severity);
HighlightInfo info = createHighlightInfo(descriptor, tool, level, emptyActionRegistered, element);
if (info == null) return;
if (file == myFile) {
// not injected
outInfos.add(info);
return;
}
// todo we got to separate our "internal" prefixes/suffixes from user-defined ones
// todo in the latter case the errors should be highlighted, otherwise not
List<TextRange> editables = ilManager.intersectWithAllEditableFragments(file, new TextRange(info.startOffset, info.endOffset));
for (TextRange editable : editables) {
TextRange hostRange = ((DocumentWindow)documentRange).injectedToHost(editable);
HighlightInfo patched = HighlightInfo.createHighlightInfo(info.type, element, hostRange.getStartOffset(),
hostRange.getEndOffset(), info.description, info.toolTip);
if (patched != null) {
registerQuickFixes(tool, descriptor, patched, emptyActionRegistered);
outInfos.add(patched);
}
}
}
@Nullable
private HighlightInfo createHighlightInfo(@NotNull ProblemDescriptor descriptor,
@NotNull LocalInspectionTool tool,
@NotNull HighlightInfoType level,
@NotNull Set<TextRange> emptyActionRegistered,
@NotNull PsiElement element) {
@NonNls String message = ProblemDescriptionNode.renderDescriptionMessage(descriptor, element);
final HighlightDisplayKey key = HighlightDisplayKey.find(tool.getShortName());
final InspectionProfile inspectionProfile = myProfileWrapper.getInspectionProfile();
if (!inspectionProfile.isToolEnabled(key, myFile)) return null;
HighlightInfoType type = new HighlightInfoType.HighlightInfoTypeImpl(level.getSeverity(element), level.getAttributesKey());
final String plainMessage = message.startsWith("<html>") ? StringUtil.unescapeXml(message.replaceAll("<[^>]*>", "")) : message;
@NonNls final String link = "<a href=\"#inspection/" + tool.getShortName() + "\"> " + DaemonBundle.message("inspection.extended.description") +
"</a>" + myShortcutText;
@NonNls String tooltip = null;
if (descriptor.showTooltip()) {
if (message.startsWith("<html>")) {
tooltip = message.contains("</body>") ? message.replace("</body>", link + "</body>") : message.replace("</html>", link + "</html>");
}
else {
tooltip = "<html><body>" + XmlStringUtil.escapeString(message) + link + "</body></html>";
}
}
HighlightInfo highlightInfo = highlightInfoFromDescriptor(descriptor, type, plainMessage, tooltip,element);
if (highlightInfo != null) {
registerQuickFixes(tool, descriptor, highlightInfo, emptyActionRegistered);
}
return highlightInfo;
}
private static void registerQuickFixes(final LocalInspectionTool tool,
final ProblemDescriptor descriptor,
@NotNull HighlightInfo highlightInfo,
final Set<TextRange> emptyActionRegistered) {
final HighlightDisplayKey key = HighlightDisplayKey.find(tool.getShortName());
boolean needEmptyAction = true;
final QuickFix[] fixes = descriptor.getFixes();
if (fixes != null && fixes.length > 0) {
for (int k = 0; k < fixes.length; k++) {
if (fixes[k] != null) { // prevent null fixes from var args
QuickFixAction.registerQuickFixAction(highlightInfo, QuickFixWrapper.wrap(descriptor, k), key);
needEmptyAction = false;
}
}
}
HintAction hintAction = ((ProblemDescriptorImpl)descriptor).getHintAction();
if (hintAction != null) {
QuickFixAction.registerQuickFixAction(highlightInfo, hintAction, key);
needEmptyAction = false;
}
if (((ProblemDescriptorImpl)descriptor).getEnforcedTextAttributes() != null) {
needEmptyAction = false;
}
if (needEmptyAction && emptyActionRegistered.add(new TextRange(highlightInfo.fixStartOffset, highlightInfo.fixEndOffset))) {
EmptyIntentionAction emptyIntentionAction = new EmptyIntentionAction(tool.getDisplayName());
QuickFixAction.registerQuickFixAction(highlightInfo, emptyIntentionAction, key);
}
}
private static List<PsiElement> getElementsFrom(PsiFile file) {
final FileViewProvider viewProvider = file.getViewProvider();
final Set<PsiElement> result = new LinkedHashSet<PsiElement>();
final PsiElementVisitor visitor = new PsiRecursiveElementVisitor() {
@Override public void visitElement(PsiElement element) {
ProgressManager.checkCanceled();
PsiElement child = element.getFirstChild();
if (child == null) {
// leaf element
}
else {
// composite element
while (child != null) {
child.accept(this);
result.add(child);
child = child.getNextSibling();
}
}
}
};
for (Language language : viewProvider.getLanguages()) {
final PsiFile psiRoot = viewProvider.getPsi(language);
if (!HighlightLevelUtil.shouldInspect(psiRoot)) {
continue;
}
psiRoot.accept(visitor);
result.add(psiRoot);
}
return new ArrayList<PsiElement>(result);
}
List<LocalInspectionTool> getInspectionTools(InspectionProfileWrapper profile) {
return profile.getHighlightingLocalInspectionTools(myFile);
}
private void doInspectInjectedPsi(@NotNull PsiFile injectedPsi,
@NotNull List<LocalInspectionTool> tools,
final boolean isOnTheFly,
@NotNull final ProgressIndicator indicator,
@NotNull InspectionManagerEx iManager,
final boolean inVisibleRange) {
final PsiElement host = injectedPsi.getContext();
final List<PsiElement> elements = getElementsFrom(injectedPsi);
if (elements.isEmpty()) {
return;
}
for (final LocalInspectionTool tool : tools) {
indicator.checkCanceled();
if (host != null && myIgnoreSuppressed && InspectionManagerEx.inspectionResultSuppressed(host, tool)) {
continue;
}
ProblemsHolder holder = new ProblemsHolder(iManager, injectedPsi, isOnTheFly) {
@Override
public void registerProblem(@NotNull ProblemDescriptor descriptor) {
super.registerProblem(descriptor);
if (isOnTheFly && inVisibleRange) {
addDescriptorIncrementally(descriptor, tool, indicator);
}
}
};
LocalInspectionToolSession injSession = new LocalInspectionToolSession(injectedPsi, 0, injectedPsi.getTextLength());
createVisitorAndAcceptElements(tool, holder, isOnTheFly, injSession, elements);
tool.inspectionFinished(injSession,holder);
List<ProblemDescriptor> problems = holder.getResults();
if (problems != null && !problems.isEmpty()) {
appendDescriptors(injectedPsi, problems, tool);
}
}
}
@NotNull
public List<HighlightInfo> getInfos() {
return myInfos;
}
private static class InspectionResult {
public final LocalInspectionTool tool;
public final List<ProblemDescriptor> foundProblems;
private InspectionResult(@NotNull LocalInspectionTool tool, @NotNull List<ProblemDescriptor> foundProblems) {
this.tool = tool;
this.foundProblems = foundProblems;
}
}
}
| platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java | /*
* Copyright 2000-2009 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.codeInsight.daemon.impl;
import com.intellij.codeHighlighting.Pass;
import com.intellij.codeInsight.daemon.DaemonBundle;
import com.intellij.codeInsight.daemon.HighlightDisplayKey;
import com.intellij.codeInsight.daemon.impl.analysis.HighlightLevelUtil;
import com.intellij.codeInsight.daemon.impl.quickfix.QuickFixAction;
import com.intellij.codeInsight.intention.EmptyIntentionAction;
import com.intellij.codeInspection.*;
import com.intellij.codeInspection.ex.*;
import com.intellij.codeInspection.ui.ProblemDescriptionNode;
import com.intellij.concurrency.JobUtil;
import com.intellij.injected.editor.DocumentWindow;
import com.intellij.lang.Language;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.colors.CodeInsightColors;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.keymap.Keymap;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.Trinity;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.profile.codeInspection.SeverityProvider;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.util.ConcurrencyUtil;
import com.intellij.util.Function;
import com.intellij.util.Processor;
import com.intellij.util.containers.ConcurrentHashMap;
import com.intellij.util.containers.TransferToEDTQueue;
import com.intellij.xml.util.XmlStringUtil;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
/**
* @author max
*/
public class LocalInspectionsPass extends ProgressableTextEditorHighlightingPass implements DumbAware {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.LocalInspectionsPass");
private static final int NUM_ELEMENTS_PER_CHECK_CANCELLED = 5;
public static final TextRange EMPTY_PRIORITY_RANGE = TextRange.EMPTY_RANGE;
private final int myStartOffset;
private final int myEndOffset;
private final TextRange myPriorityRange;
private final boolean myIgnoreSuppressed;
private final ConcurrentMap<PsiFile, List<InspectionResult>> result = new ConcurrentHashMap<PsiFile, List<InspectionResult>>();
private static final String PRESENTABLE_NAME = DaemonBundle.message("pass.inspection");
private volatile List<HighlightInfo> myInfos = Collections.emptyList();
private final String myShortcutText;
private final SeverityRegistrar mySeverityRegistrar;
private final InspectionProfileWrapper myProfileWrapper;
private boolean myFailFastOnAcquireReadAction;
public LocalInspectionsPass(@NotNull PsiFile file,
@Nullable Document document,
int startOffset,
int endOffset,
@NotNull TextRange priorityRange,
boolean ignoreSuppressed) {
super(file.getProject(), document, PRESENTABLE_NAME, file, true);
myStartOffset = startOffset;
myEndOffset = endOffset;
myPriorityRange = priorityRange;
myIgnoreSuppressed = ignoreSuppressed;
setId(Pass.LOCAL_INSPECTIONS);
final KeymapManager keymapManager = KeymapManager.getInstance();
if (keymapManager != null) {
final Keymap keymap = keymapManager.getActiveKeymap();
myShortcutText = keymap == null ? "" : "(" + KeymapUtil.getShortcutsText(keymap.getShortcuts(IdeActions.ACTION_SHOW_ERROR_DESCRIPTION)) + ")";
}
else {
myShortcutText = "";
}
InspectionProfileWrapper profileToUse = InspectionProjectProfileManager.getInstance(myProject).getProfileWrapper();
Function<InspectionProfileWrapper,InspectionProfileWrapper> custom = file.getUserData(InspectionProfileWrapper.CUSTOMIZATION_KEY);
if (custom != null) {
profileToUse = custom.fun(profileToUse);
}
myProfileWrapper = profileToUse;
mySeverityRegistrar = ((SeverityProvider)myProfileWrapper.getInspectionProfile().getProfileManager()).getSeverityRegistrar();
LOG.assertTrue(mySeverityRegistrar != null);
// initial guess
setProgressLimit(300 * 2);
}
protected void collectInformationWithProgress(@NotNull ProgressIndicator progress) {
try {
if (!HighlightLevelUtil.shouldInspect(myFile)) return;
final InspectionManagerEx iManager = (InspectionManagerEx)InspectionManager.getInstance(myProject);
final InspectionProfileWrapper profile = myProfileWrapper;
final List<LocalInspectionTool> tools = DumbService.getInstance(myProject).filterByDumbAwareness(getInspectionTools(profile));
inspect(tools, iManager, true, true, progress);
}
finally {
disposeDescriptors();
}
}
private void disposeDescriptors() {
result.clear();
}
public void doInspectInBatch(@NotNull InspectionManagerEx iManager, @NotNull List<InspectionProfileEntry> toolWrappers) {
Map<LocalInspectionTool, LocalInspectionToolWrapper> tool2Wrapper = new THashMap<LocalInspectionTool, LocalInspectionToolWrapper>(toolWrappers.size());
for (InspectionProfileEntry toolWrapper : toolWrappers) {
tool2Wrapper.put(((LocalInspectionToolWrapper)toolWrapper).getTool(), (LocalInspectionToolWrapper)toolWrapper);
}
List<LocalInspectionTool> tools = new ArrayList<LocalInspectionTool>(tool2Wrapper.keySet());
ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
inspect(tools, iManager, false, false, progress);
addDescriptorsFromInjectedResults(tool2Wrapper, iManager);
List<InspectionResult> resultList = result.get(myFile);
if (resultList == null) return;
for (InspectionResult inspectionResult : resultList) {
LocalInspectionTool tool = inspectionResult.tool;
LocalInspectionToolWrapper toolWrapper = tool2Wrapper.get(tool);
if (toolWrapper == null) continue;
for (ProblemDescriptor descriptor : inspectionResult.foundProblems) {
toolWrapper.addProblemDescriptors(Collections.singletonList(descriptor), myIgnoreSuppressed);
}
}
}
private void addDescriptorsFromInjectedResults(Map<LocalInspectionTool, LocalInspectionToolWrapper> tool2Wrapper, InspectionManagerEx iManager) {
Set<TextRange> emptyActionRegistered = new THashSet<TextRange>();
InspectionProfile inspectionProfile = InspectionProjectProfileManager.getInstance(myProject).getInspectionProfile();
InjectedLanguageManager ilManager = InjectedLanguageManager.getInstance(myProject);
PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
for (Map.Entry<PsiFile, List<InspectionResult>> entry : result.entrySet()) {
PsiFile file = entry.getKey();
if (file == myFile) continue; // not injected
DocumentWindow documentRange = (DocumentWindow)documentManager.getDocument(file);
List<InspectionResult> resultList = entry.getValue();
for (InspectionResult inspectionResult : resultList) {
LocalInspectionTool tool = inspectionResult.tool;
HighlightSeverity severity = inspectionProfile.getErrorLevel(HighlightDisplayKey.find(tool.getShortName()), myFile).getSeverity();
for (ProblemDescriptor descriptor : inspectionResult.foundProblems) {
PsiElement psiElement = descriptor.getPsiElement();
if (psiElement == null) continue;
if (InspectionManagerEx.inspectionResultSuppressed(psiElement, tool)) continue;
HighlightInfoType level = highlightTypeFromDescriptor(descriptor, severity);
HighlightInfo info = createHighlightInfo(descriptor, tool, level,emptyActionRegistered, psiElement);
if (info == null) continue;
List<TextRange> editables = ilManager.intersectWithAllEditableFragments(file, new TextRange(info.startOffset, info.endOffset));
for (TextRange editable : editables) {
TextRange hostRange = documentRange.injectedToHost(editable);
QuickFix[] fixes = descriptor.getFixes();
LocalQuickFix[] localFixes = null;
if (fixes != null) {
localFixes = new LocalQuickFix[fixes.length];
for (int k = 0; k < fixes.length; k++) {
QuickFix fix = fixes[k];
localFixes[k] = (LocalQuickFix)fix;
}
}
ProblemDescriptor patchedDescriptor = iManager.createProblemDescriptor(myFile, hostRange, descriptor.getDescriptionTemplate(),
descriptor.getHighlightType(), true, localFixes);
LocalInspectionToolWrapper toolWrapper = tool2Wrapper.get(tool);
toolWrapper.addProblemDescriptors(Collections.singletonList(patchedDescriptor), true);
}
}
}
}
}
private void inspect(@NotNull final List<LocalInspectionTool> tools,
@NotNull final InspectionManagerEx iManager,
final boolean isOnTheFly,
boolean failFastOnAcquireReadAction,
@NotNull final ProgressIndicator indicator) {
myFailFastOnAcquireReadAction = failFastOnAcquireReadAction;
if (tools.isEmpty()) return;
List<PsiElement> inside = new ArrayList<PsiElement>();
List<PsiElement> outside = new ArrayList<PsiElement>();
Divider.divideInsideAndOutside(myFile, myStartOffset, myEndOffset, myPriorityRange, inside, outside,
HighlightLevelUtil.AnalysisLevel.HIGHLIGHT_AND_INSPECT,true);
setProgressLimit(1L * tools.size() * 2);
final LocalInspectionToolSession session = new LocalInspectionToolSession(myFile, myStartOffset, myEndOffset);
List<Trinity<LocalInspectionTool, ProblemsHolder, PsiElementVisitor>> init = new ArrayList<Trinity<LocalInspectionTool, ProblemsHolder, PsiElementVisitor>>();
visitPriorityElementsAndInit(tools, iManager, isOnTheFly, indicator, inside, session, init);
visitRestElementsAndCleanup(tools,iManager,isOnTheFly, indicator, outside, session, init);
indicator.checkCanceled();
myInfos = new ArrayList<HighlightInfo>();
addHighlightsFromResults(myInfos, indicator);
}
private void visitPriorityElementsAndInit(@NotNull List<LocalInspectionTool> tools,
@NotNull final InspectionManagerEx iManager,
final boolean isOnTheFly,
@NotNull final ProgressIndicator indicator,
@NotNull final List<PsiElement> elements,
@NotNull final LocalInspectionToolSession session,
@NotNull final List<Trinity<LocalInspectionTool, ProblemsHolder, PsiElementVisitor>> init) {
boolean result = JobUtil.invokeConcurrentlyUnderProgress(tools, new Processor<LocalInspectionTool>() {
public boolean process(final LocalInspectionTool tool) {
indicator.checkCanceled();
ApplicationManager.getApplication().assertReadAccessAllowed();
final boolean[] applyIncrementally = {isOnTheFly};
ProblemsHolder holder = new ProblemsHolder(iManager, myFile, isOnTheFly) {
@Override
public void registerProblem(@NotNull ProblemDescriptor descriptor) {
super.registerProblem(descriptor);
if (applyIncrementally[0]) {
addDescriptorIncrementally(descriptor, tool, indicator);
}
}
};
PsiElementVisitor visitor = createVisitorAndAcceptElements(tool, holder, isOnTheFly, session, elements, indicator);
synchronized (init) {
init.add(Trinity.create(tool, holder, visitor));
}
advanceProgress(1);
if (holder.hasResults()) {
appendDescriptors(myFile, holder.getResults(), tool);
}
applyIncrementally[0] = false; // do not apply incrementally outside visible range
return true;
}
}, myFailFastOnAcquireReadAction, indicator);
if (!result) throw new ProcessCanceledException();
inspectInjectedPsi(elements, tools, isOnTheFly, indicator, iManager, true);
}
private static PsiElementVisitor createVisitorAndAcceptElements(@NotNull LocalInspectionTool tool,
@NotNull ProblemsHolder holder,
boolean isOnTheFly,
@NotNull LocalInspectionToolSession session,
@NotNull List<PsiElement> elements,
@NotNull ProgressIndicator indicator) {
PsiElementVisitor visitor = tool.buildVisitor(holder, isOnTheFly, session);
//noinspection ConstantConditions
if(visitor == null) {
LOG.error("Tool " + tool + " must not return null from the buildVisitor() method");
}
assert !(visitor instanceof PsiRecursiveElementVisitor || visitor instanceof PsiRecursiveElementWalkingVisitor)
: "The visitor returned from LocalInspectionTool.buildVisitor() must not be recursive. "+tool;
tool.inspectionStarted(session, isOnTheFly);
acceptElements(elements, visitor, indicator);
return visitor;
}
private void visitRestElementsAndCleanup(@NotNull List<LocalInspectionTool> tools,
@NotNull final InspectionManagerEx iManager,
final boolean isOnTheFly,
@NotNull final ProgressIndicator indicator,
@NotNull final List<PsiElement> elements,
@NotNull final LocalInspectionToolSession session,
@NotNull List<Trinity<LocalInspectionTool, ProblemsHolder, PsiElementVisitor>> init) {
Processor<Trinity<LocalInspectionTool, ProblemsHolder, PsiElementVisitor>> processor =
new Processor<Trinity<LocalInspectionTool, ProblemsHolder, PsiElementVisitor>>() {
@Override
public boolean process(Trinity<LocalInspectionTool, ProblemsHolder, PsiElementVisitor> trinity) {
LocalInspectionTool tool = trinity.first;
indicator.checkCanceled();
ApplicationManager.getApplication().assertReadAccessAllowed();
ProblemsHolder holder = trinity.second;
PsiElementVisitor elementVisitor = trinity.third;
acceptElements(elements, elementVisitor, indicator);
advanceProgress(1);
tool.inspectionFinished(session, holder);
if (holder.hasResults()) {
appendDescriptors(myFile, holder.getResults(), tool);
}
return true;
}
};
boolean result = JobUtil.invokeConcurrentlyUnderProgress(init, processor, myFailFastOnAcquireReadAction, indicator);
if (!result) {
throw new ProcessCanceledException();
}
inspectInjectedPsi(elements, tools, isOnTheFly, indicator, iManager, false);
}
private static void acceptElements(@NotNull List<PsiElement> elements, @NotNull PsiElementVisitor elementVisitor, @NotNull ProgressIndicator indicator) {
for (int i = 0, elementsSize = elements.size(); i < elementsSize; i++) {
PsiElement element = elements.get(i);
element.accept(elementVisitor);
if (i % NUM_ELEMENTS_PER_CHECK_CANCELLED == 0) indicator.checkCanceled();
}
}
private void inspectInjectedPsi(@NotNull final List<PsiElement> elements,
@NotNull final List<LocalInspectionTool> tools,
final boolean onTheFly,
@NotNull final ProgressIndicator indicator,
@NotNull final InspectionManagerEx iManager,
final boolean inVisibleRange) {
final Set<PsiFile> injected = new THashSet<PsiFile>();
for (PsiElement element : elements) {
InjectedLanguageUtil.enumerate(element, myFile, new PsiLanguageInjectionHost.InjectedPsiVisitor() {
public void visit(@NotNull PsiFile injectedPsi, @NotNull List<PsiLanguageInjectionHost.Shred> places) {
injected.add(injectedPsi);
}
}, false);
}
if (injected.isEmpty()) return;
if (!JobUtil.invokeConcurrentlyUnderProgress(new ArrayList<PsiFile>(injected), new Processor<PsiFile>() {
public boolean process(final PsiFile injectedPsi) {
doInspectInjectedPsi(injectedPsi, tools, onTheFly, indicator, iManager, inVisibleRange);
return true;
}
}, myFailFastOnAcquireReadAction, indicator)) throw new ProcessCanceledException();
}
@Nullable
private HighlightInfo highlightInfoFromDescriptor(@NotNull ProblemDescriptor problemDescriptor,
@NotNull HighlightInfoType highlightInfoType,
@NotNull String message,
String toolTip, PsiElement psiElement) {
TextRange textRange = ((ProblemDescriptorImpl)problemDescriptor).getTextRange();
if (textRange == null || psiElement == null) return null;
boolean isFileLevel = psiElement instanceof PsiFile && textRange.equals(psiElement.getTextRange());
final HighlightSeverity severity = highlightInfoType.getSeverity(psiElement);
TextAttributes attributes = mySeverityRegistrar.getTextAttributesBySeverity(severity);
return new HighlightInfo(attributes, highlightInfoType, textRange.getStartOffset(),
textRange.getEndOffset(), message, toolTip,
severity, problemDescriptor.isAfterEndOfLine(), null, isFileLevel);
}
private final TransferToEDTQueue<Trinity<ProblemDescriptor, LocalInspectionTool,ProgressIndicator>> myTransferToEDTQueue
= new TransferToEDTQueue<Trinity<ProblemDescriptor, LocalInspectionTool,ProgressIndicator>>("Apply inspection results", new Processor<Trinity<ProblemDescriptor, LocalInspectionTool,ProgressIndicator>>() {
private final InspectionProfile inspectionProfile = InspectionProjectProfileManager.getInstance(myProject).getInspectionProfile();
private final InjectedLanguageManager ilManager = InjectedLanguageManager.getInstance(myProject);
private final List<HighlightInfo> infos = new ArrayList<HighlightInfo>(2);
private final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
@Override
public boolean process(Trinity<ProblemDescriptor, LocalInspectionTool,ProgressIndicator> trinity) {
ProgressIndicator indicator = trinity.getThird();
if (indicator.isCanceled()) {
return false;
}
ProblemDescriptor descriptor = trinity.first;
LocalInspectionTool tool = trinity.second;
PsiElement psiElement = descriptor.getPsiElement();
if (psiElement == null) return true;
PsiFile file = psiElement.getContainingFile();
Document thisDocument = documentManager.getDocument(file);
HighlightSeverity severity = inspectionProfile.getErrorLevel(HighlightDisplayKey.find(tool.getShortName()), file).getSeverity();
infos.clear();
createHighlightsForDescriptor(infos, emptyActionRegistered, ilManager, file, thisDocument, tool, severity, descriptor, psiElement);
for (HighlightInfo info : infos) {
final EditorColorsScheme colorsScheme = getColorsScheme();
UpdateHighlightersUtil.addHighlighterToEditorIncrementally(myProject, myDocument, myFile, myStartOffset, myEndOffset,
info, colorsScheme, getId());
}
return true;
}
}, myProject.getDisposed(), 200);
private final Set<TextRange> emptyActionRegistered = Collections.synchronizedSet(new HashSet<TextRange>());
private void addDescriptorIncrementally(@NotNull final ProblemDescriptor descriptor,
@NotNull final LocalInspectionTool tool,
@NotNull final ProgressIndicator indicator) {
if (myIgnoreSuppressed && InspectionManagerEx.inspectionResultSuppressed(descriptor.getPsiElement(), tool)) {
return;
}
myTransferToEDTQueue.offer(Trinity.create(descriptor, tool, indicator));
}
private void appendDescriptors(PsiFile file, List<ProblemDescriptor> descriptors, LocalInspectionTool tool) {
for (ProblemDescriptor descriptor : descriptors) {
if (descriptor == null) {
LOG.error("null descriptor. all descriptors(" + descriptors.size() +"): " +
descriptors + "; file: " + file + " (" + file.getVirtualFile() +"); tool: " + tool);
}
}
InspectionResult res = new InspectionResult(tool, descriptors);
appendResult(file, res);
}
private void appendResult(PsiFile file, InspectionResult res) {
List<InspectionResult> resultList = result.get(file);
if (resultList == null) {
resultList = ConcurrencyUtil.cacheOrGet(result, file, new ArrayList<InspectionResult>());
}
synchronized (resultList) {
resultList.add(res);
}
}
@NotNull
private HighlightInfoType highlightTypeFromDescriptor(final ProblemDescriptor problemDescriptor, final HighlightSeverity severity) {
final ProblemHighlightType highlightType = problemDescriptor.getHighlightType();
switch (highlightType) {
case GENERIC_ERROR_OR_WARNING:
return mySeverityRegistrar.getHighlightInfoTypeBySeverity(severity);
case LIKE_DEPRECATED:
return new HighlightInfoType.HighlightInfoTypeImpl(severity, HighlightInfoType.DEPRECATED.getAttributesKey());
case LIKE_UNKNOWN_SYMBOL:
if (severity == HighlightSeverity.ERROR) {
return new HighlightInfoType.HighlightInfoTypeImpl(severity, HighlightInfoType.WRONG_REF.getAttributesKey());
}
else if (severity == HighlightSeverity.WARNING) {
return new HighlightInfoType.HighlightInfoTypeImpl(severity, CodeInsightColors.WEAK_WARNING_ATTRIBUTES);
}
else {
return mySeverityRegistrar.getHighlightInfoTypeBySeverity(severity);
}
case LIKE_UNUSED_SYMBOL:
return new HighlightInfoType.HighlightInfoTypeImpl(severity, HighlightInfoType.UNUSED_SYMBOL.getAttributesKey());
case INFO:
return HighlightInfoType.INFO;
case WEAK_WARNING:
return HighlightInfoType.WEAK_WARNING;
case ERROR:
return HighlightInfoType.WRONG_REF;
case GENERIC_ERROR:
return HighlightInfoType.ERROR;
case INFORMATION:
final TextAttributesKey attributes = ((ProblemDescriptorImpl)problemDescriptor).getEnforcedTextAttributes();
if (attributes != null) {
return new HighlightInfoType.HighlightInfoTypeImpl(HighlightSeverity.INFORMATION, attributes);
}
return HighlightInfoType.INFORMATION;
}
throw new RuntimeException("Cannot map " + highlightType);
}
protected void applyInformationWithProgress() {
UpdateHighlightersUtil.setHighlightersToEditor(myProject, myDocument, myStartOffset, myEndOffset, myInfos, getColorsScheme(), getId());
}
private void addHighlightsFromResults(@NotNull List<HighlightInfo> outInfos, @NotNull ProgressIndicator indicator) {
InspectionProfile inspectionProfile = InspectionProjectProfileManager.getInstance(myProject).getInspectionProfile();
PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
InjectedLanguageManager ilManager = InjectedLanguageManager.getInstance(myProject);
Set<TextRange> emptyActionRegistered = new THashSet<TextRange>();
for (Map.Entry<PsiFile, List<InspectionResult>> entry : result.entrySet()) {
indicator.checkCanceled();
PsiFile file = entry.getKey();
Document documentRange = documentManager.getDocument(file);
if (documentRange == null) continue;
List<InspectionResult> resultList = entry.getValue();
for (InspectionResult inspectionResult : resultList) {
indicator.checkCanceled();
LocalInspectionTool tool = inspectionResult.tool;
HighlightSeverity severity = inspectionProfile.getErrorLevel(HighlightDisplayKey.find(tool.getShortName()), file).getSeverity();
for (ProblemDescriptor descriptor : inspectionResult.foundProblems) {
indicator.checkCanceled();
PsiElement element = descriptor.getPsiElement();
createHighlightsForDescriptor(outInfos, emptyActionRegistered, ilManager, file, documentRange, tool, severity, descriptor, element);
}
}
}
}
private void createHighlightsForDescriptor(List<HighlightInfo> outInfos,
Set<TextRange> emptyActionRegistered,
InjectedLanguageManager ilManager,
PsiFile file,
Document documentRange,
LocalInspectionTool tool,
HighlightSeverity severity,
ProblemDescriptor descriptor,
PsiElement element) {
if (element == null) return;
if (myIgnoreSuppressed && InspectionManagerEx.inspectionResultSuppressed(element, tool)) return;
HighlightInfoType level = highlightTypeFromDescriptor(descriptor, severity);
HighlightInfo info = createHighlightInfo(descriptor, tool, level, emptyActionRegistered, element);
if (info == null) return;
if (file == myFile) {
// not injected
outInfos.add(info);
return;
}
// todo we got to separate our "internal" prefixes/suffixes from user-defined ones
// todo in the latter case the errors should be highlighted, otherwise not
List<TextRange> editables = ilManager.intersectWithAllEditableFragments(file, new TextRange(info.startOffset, info.endOffset));
for (TextRange editable : editables) {
TextRange hostRange = ((DocumentWindow)documentRange).injectedToHost(editable);
HighlightInfo patched = HighlightInfo.createHighlightInfo(info.type, element, hostRange.getStartOffset(),
hostRange.getEndOffset(), info.description, info.toolTip);
if (patched != null) {
registerQuickFixes(tool, descriptor, patched, emptyActionRegistered);
outInfos.add(patched);
}
}
}
@Nullable
private HighlightInfo createHighlightInfo(@NotNull ProblemDescriptor descriptor,
@NotNull LocalInspectionTool tool,
@NotNull HighlightInfoType level,
@NotNull Set<TextRange> emptyActionRegistered,
@NotNull PsiElement element) {
@NonNls String message = ProblemDescriptionNode.renderDescriptionMessage(descriptor, element);
final HighlightDisplayKey key = HighlightDisplayKey.find(tool.getShortName());
final InspectionProfile inspectionProfile = myProfileWrapper.getInspectionProfile();
if (!inspectionProfile.isToolEnabled(key, myFile)) return null;
HighlightInfoType type = new HighlightInfoType.HighlightInfoTypeImpl(level.getSeverity(element), level.getAttributesKey());
final String plainMessage = message.startsWith("<html>") ? StringUtil.unescapeXml(message.replaceAll("<[^>]*>", "")) : message;
@NonNls final String link = "<a href=\"#inspection/" + tool.getShortName() + "\"> " + DaemonBundle.message("inspection.extended.description") +
"</a>" + myShortcutText;
@NonNls String tooltip = null;
if (descriptor.showTooltip()) {
if (message.startsWith("<html>")) {
tooltip = message.contains("</body>") ? message.replace("</body>", link + "</body>") : message.replace("</html>", link + "</html>");
}
else {
tooltip = "<html><body>" + XmlStringUtil.escapeString(message) + link + "</body></html>";
}
}
HighlightInfo highlightInfo = highlightInfoFromDescriptor(descriptor, type, plainMessage, tooltip,element);
if (highlightInfo != null) {
registerQuickFixes(tool, descriptor, highlightInfo, emptyActionRegistered);
}
return highlightInfo;
}
private static void registerQuickFixes(final LocalInspectionTool tool,
final ProblemDescriptor descriptor,
@NotNull HighlightInfo highlightInfo,
final Set<TextRange> emptyActionRegistered) {
final HighlightDisplayKey key = HighlightDisplayKey.find(tool.getShortName());
boolean needEmptyAction = true;
final QuickFix[] fixes = descriptor.getFixes();
if (fixes != null && fixes.length > 0) {
for (int k = 0; k < fixes.length; k++) {
if (fixes[k] != null) { // prevent null fixes from var args
QuickFixAction.registerQuickFixAction(highlightInfo, QuickFixWrapper.wrap(descriptor, k), key);
needEmptyAction = false;
}
}
}
HintAction hintAction = ((ProblemDescriptorImpl)descriptor).getHintAction();
if (hintAction != null) {
QuickFixAction.registerQuickFixAction(highlightInfo, hintAction, key);
needEmptyAction = false;
}
if (((ProblemDescriptorImpl)descriptor).getEnforcedTextAttributes() != null) {
needEmptyAction = false;
}
if (needEmptyAction && emptyActionRegistered.add(new TextRange(highlightInfo.fixStartOffset, highlightInfo.fixEndOffset))) {
EmptyIntentionAction emptyIntentionAction = new EmptyIntentionAction(tool.getDisplayName());
QuickFixAction.registerQuickFixAction(highlightInfo, emptyIntentionAction, key);
}
}
private static List<PsiElement> getElementsFrom(PsiFile file) {
final FileViewProvider viewProvider = file.getViewProvider();
final Set<PsiElement> result = new LinkedHashSet<PsiElement>();
final PsiElementVisitor visitor = new PsiRecursiveElementVisitor() {
@Override public void visitElement(PsiElement element) {
ProgressManager.checkCanceled();
PsiElement child = element.getFirstChild();
if (child == null) {
// leaf element
}
else {
// composite element
while (child != null) {
child.accept(this);
result.add(child);
child = child.getNextSibling();
}
}
}
};
for (Language language : viewProvider.getLanguages()) {
final PsiFile psiRoot = viewProvider.getPsi(language);
if (!HighlightLevelUtil.shouldInspect(psiRoot)) {
continue;
}
psiRoot.accept(visitor);
result.add(psiRoot);
}
return new ArrayList<PsiElement>(result);
}
List<LocalInspectionTool> getInspectionTools(InspectionProfileWrapper profile) {
return profile.getHighlightingLocalInspectionTools(myFile);
}
private void doInspectInjectedPsi(@NotNull PsiFile injectedPsi,
@NotNull List<LocalInspectionTool> tools,
final boolean isOnTheFly,
@NotNull final ProgressIndicator indicator,
@NotNull InspectionManagerEx iManager,
final boolean inVisibleRange) {
final PsiElement host = injectedPsi.getContext();
final List<PsiElement> elements = getElementsFrom(injectedPsi);
if (elements.isEmpty()) {
return;
}
for (final LocalInspectionTool tool : tools) {
indicator.checkCanceled();
if (host != null && myIgnoreSuppressed && InspectionManagerEx.inspectionResultSuppressed(host, tool)) {
continue;
}
ProblemsHolder holder = new ProblemsHolder(iManager, injectedPsi, isOnTheFly) {
@Override
public void registerProblem(@NotNull ProblemDescriptor descriptor) {
super.registerProblem(descriptor);
if (isOnTheFly && inVisibleRange) {
addDescriptorIncrementally(descriptor, tool, indicator);
}
}
};
LocalInspectionToolSession injSession = new LocalInspectionToolSession(injectedPsi, 0, injectedPsi.getTextLength());
createVisitorAndAcceptElements(tool, holder, isOnTheFly, injSession, elements, indicator);
tool.inspectionFinished(injSession,holder);
List<ProblemDescriptor> problems = holder.getResults();
if (problems != null && !problems.isEmpty()) {
appendDescriptors(injectedPsi, problems, tool);
}
}
}
@NotNull
public List<HighlightInfo> getInfos() {
return myInfos;
}
private static class InspectionResult {
public final LocalInspectionTool tool;
public final List<ProblemDescriptor> foundProblems;
private InspectionResult(@NotNull LocalInspectionTool tool, @NotNull List<ProblemDescriptor> foundProblems) {
this.tool = tool;
this.foundProblems = foundProblems;
}
}
}
| less often isCancelled check (one time in 10ms in ProgressManager)
| platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java | less often isCancelled check (one time in 10ms in ProgressManager) | <ide><path>latform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java
<ide> */
<ide> public class LocalInspectionsPass extends ProgressableTextEditorHighlightingPass implements DumbAware {
<ide> private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.LocalInspectionsPass");
<del> private static final int NUM_ELEMENTS_PER_CHECK_CANCELLED = 5;
<ide> public static final TextRange EMPTY_PRIORITY_RANGE = TextRange.EMPTY_RANGE;
<ide> private final int myStartOffset;
<ide> private final int myEndOffset;
<ide> }
<ide> }
<ide> };
<del> PsiElementVisitor visitor = createVisitorAndAcceptElements(tool, holder, isOnTheFly, session, elements, indicator);
<add> PsiElementVisitor visitor = createVisitorAndAcceptElements(tool, holder, isOnTheFly, session, elements);
<ide>
<ide> synchronized (init) {
<ide> init.add(Trinity.create(tool, holder, visitor));
<ide> @NotNull ProblemsHolder holder,
<ide> boolean isOnTheFly,
<ide> @NotNull LocalInspectionToolSession session,
<del> @NotNull List<PsiElement> elements,
<del> @NotNull ProgressIndicator indicator) {
<add> @NotNull List<PsiElement> elements) {
<ide> PsiElementVisitor visitor = tool.buildVisitor(holder, isOnTheFly, session);
<ide> //noinspection ConstantConditions
<ide> if(visitor == null) {
<ide> : "The visitor returned from LocalInspectionTool.buildVisitor() must not be recursive. "+tool;
<ide>
<ide> tool.inspectionStarted(session, isOnTheFly);
<del> acceptElements(elements, visitor, indicator);
<add> acceptElements(elements, visitor);
<ide> return visitor;
<ide> }
<ide>
<ide>
<ide> ProblemsHolder holder = trinity.second;
<ide> PsiElementVisitor elementVisitor = trinity.third;
<del> acceptElements(elements, elementVisitor, indicator);
<add> acceptElements(elements, elementVisitor);
<ide>
<ide> advanceProgress(1);
<ide>
<ide> inspectInjectedPsi(elements, tools, isOnTheFly, indicator, iManager, false);
<ide> }
<ide>
<del> private static void acceptElements(@NotNull List<PsiElement> elements, @NotNull PsiElementVisitor elementVisitor, @NotNull ProgressIndicator indicator) {
<add> private static void acceptElements(@NotNull List<PsiElement> elements,
<add> @NotNull PsiElementVisitor elementVisitor) {
<ide> for (int i = 0, elementsSize = elements.size(); i < elementsSize; i++) {
<ide> PsiElement element = elements.get(i);
<ide> element.accept(elementVisitor);
<del> if (i % NUM_ELEMENTS_PER_CHECK_CANCELLED == 0) indicator.checkCanceled();
<add> ProgressManager.checkCanceled();
<ide> }
<ide> }
<ide>
<ide> };
<ide>
<ide> LocalInspectionToolSession injSession = new LocalInspectionToolSession(injectedPsi, 0, injectedPsi.getTextLength());
<del> createVisitorAndAcceptElements(tool, holder, isOnTheFly, injSession, elements, indicator);
<add> createVisitorAndAcceptElements(tool, holder, isOnTheFly, injSession, elements);
<ide> tool.inspectionFinished(injSession,holder);
<ide> List<ProblemDescriptor> problems = holder.getResults();
<ide> if (problems != null && !problems.isEmpty()) { |
|
Java | apache-2.0 | ab8676d59af53a79a6d73007563c739472f3565e | 0 | fitermay/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,vladmm/intellij-community,apixandru/intellij-community,kdwink/intellij-community,ibinti/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,supersven/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,samthor/intellij-community,slisson/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,ibinti/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,petteyg/intellij-community,retomerz/intellij-community,izonder/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,adedayo/intellij-community,semonte/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,signed/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,hurricup/intellij-community,slisson/intellij-community,adedayo/intellij-community,caot/intellij-community,clumsy/intellij-community,blademainer/intellij-community,fnouama/intellij-community,ibinti/intellij-community,caot/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,caot/intellij-community,apixandru/intellij-community,FHannes/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,blademainer/intellij-community,supersven/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,jagguli/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,supersven/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,kool79/intellij-community,signed/intellij-community,signed/intellij-community,samthor/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,allotria/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,izonder/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,ibinti/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,clumsy/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,samthor/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,caot/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,signed/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,kool79/intellij-community,tmpgit/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,da1z/intellij-community,diorcety/intellij-community,vladmm/intellij-community,supersven/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,signed/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,retomerz/intellij-community,da1z/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,slisson/intellij-community,ryano144/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,samthor/intellij-community,youdonghai/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,izonder/intellij-community,ryano144/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,fitermay/intellij-community,blademainer/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,kdwink/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,da1z/intellij-community,Lekanich/intellij-community,izonder/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,supersven/intellij-community,semonte/intellij-community,da1z/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,allotria/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,signed/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,jagguli/intellij-community,allotria/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,holmes/intellij-community,kool79/intellij-community,allotria/intellij-community,petteyg/intellij-community,slisson/intellij-community,youdonghai/intellij-community,supersven/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,da1z/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,clumsy/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,izonder/intellij-community,caot/intellij-community,hurricup/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,semonte/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,slisson/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,fnouama/intellij-community,asedunov/intellij-community,adedayo/intellij-community,kdwink/intellij-community,fitermay/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,fnouama/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,supersven/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,slisson/intellij-community,jagguli/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,diorcety/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,signed/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,diorcety/intellij-community,holmes/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,kool79/intellij-community,clumsy/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,diorcety/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,kool79/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,adedayo/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,blademainer/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,samthor/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,caot/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,holmes/intellij-community,slisson/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,caot/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,asedunov/intellij-community,caot/intellij-community,holmes/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,da1z/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,dslomov/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,petteyg/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,semonte/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,fitermay/intellij-community,samthor/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,holmes/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,holmes/intellij-community,kdwink/intellij-community,fitermay/intellij-community,signed/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,samthor/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,da1z/intellij-community,clumsy/intellij-community,kdwink/intellij-community,retomerz/intellij-community,caot/intellij-community,xfournet/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,kool79/intellij-community,kdwink/intellij-community,allotria/intellij-community,fnouama/intellij-community,caot/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,semonte/intellij-community,caot/intellij-community,orekyuu/intellij-community,semonte/intellij-community,FHannes/intellij-community,vladmm/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,ibinti/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,fnouama/intellij-community,holmes/intellij-community,da1z/intellij-community,signed/intellij-community,kool79/intellij-community,ibinti/intellij-community,da1z/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,allotria/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,kool79/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,holmes/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,robovm/robovm-studio,asedunov/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,da1z/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,ryano144/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,samthor/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,supersven/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,allotria/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,samthor/intellij-community,signed/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,retomerz/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,semonte/intellij-community,pwoodworth/intellij-community | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.changes.shelf;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vcs.AbstractVcsHelper;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.Consumer;
import java.util.ArrayList;
import java.util.List;
/**
* @author irengrig
* Date: 2/25/11
* Time: 2:23 PM
*/
public class ImportIntoShelfAction extends DumbAwareAction {
public ImportIntoShelfAction() {
super("Import Patches...", "Copies a patch file to the shelf", null);
}
@Override
public void update(AnActionEvent e) {
final Project project = CommonDataKeys.PROJECT.getData(e.getDataContext());
e.getPresentation().setEnabled(project != null);
}
@Override
public void actionPerformed(AnActionEvent e) {
final Project project = CommonDataKeys.PROJECT.getData(e.getDataContext());
if (project == null) return;
final FileChooserDescriptor descriptor = new FileChooserDescriptor(true, true, false, false, false, true);
FileChooser.chooseFiles(descriptor, project, null, new Consumer<List<VirtualFile>>() {
@Override
public void consume(final List<VirtualFile> files) {
//gatherPatchFiles
final ProgressManager pm = ProgressManager.getInstance();
final ShelveChangesManager shelveChangesManager = ShelveChangesManager.getInstance(project);
final List<VirtualFile> patchTypeFiles = new ArrayList<VirtualFile>();
final boolean filesFound = pm.runProcessWithProgressSynchronously(new Runnable() {
@Override
public void run() {
patchTypeFiles.addAll(shelveChangesManager.gatherPatchFiles(files));
}
}, "Looking for patch files...", true, project);
if (!filesFound || patchTypeFiles.isEmpty()) return;
if (!patchTypeFiles.equals(files)) {
final String message = "Found " + (patchTypeFiles.size() == 1 ?
"one patch file (" + patchTypeFiles.get(0).getPath() + ")." :
(patchTypeFiles.size() + " patch files.")) +
"\nContinue with import?";
final int toImport = Messages.showYesNoDialog(project, message, "Import Patches", Messages.getQuestionIcon());
if (Messages.NO == toImport) return;
}
pm.runProcessWithProgressSynchronously(new Runnable() {
@Override
public void run() {
final List<VcsException> exceptions = new ArrayList<VcsException>();
final List<ShelvedChangeList> lists =
shelveChangesManager.importChangeLists(patchTypeFiles, new Consumer<VcsException>() {
@Override
public void consume(VcsException e) {
exceptions.add(e);
}
});
if (!lists.isEmpty()) {
ShelvedChangesViewManager.getInstance(project).activateView(lists.get(lists.size() - 1));
}
if (!exceptions.isEmpty()) {
AbstractVcsHelper.getInstance(project).showErrors(exceptions, "Import patches into shelf");
}
if (lists.isEmpty() && exceptions.isEmpty()) {
VcsBalloonProblemNotifier.showOverChangesView(project, "No patches found", MessageType.WARNING);
}
}
}, "Import patches into shelf", true, project);
}
});
}
}
| platform/vcs-impl/src/com/intellij/openapi/vcs/changes/shelf/ImportIntoShelfAction.java | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.changes.shelf;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vcs.AbstractVcsHelper;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.Consumer;
import java.util.ArrayList;
import java.util.List;
/**
* @author irengrig
* Date: 2/25/11
* Time: 2:23 PM
*/
public class ImportIntoShelfAction extends DumbAwareAction {
public ImportIntoShelfAction() {
super("Import patches...", "Copies patch file to shelf", null);
}
@Override
public void update(AnActionEvent e) {
final Project project = CommonDataKeys.PROJECT.getData(e.getDataContext());
e.getPresentation().setEnabled(project != null);
}
@Override
public void actionPerformed(AnActionEvent e) {
final Project project = CommonDataKeys.PROJECT.getData(e.getDataContext());
if (project == null) return;
final FileChooserDescriptor descriptor = new FileChooserDescriptor(true, true, false, false, false, true);
FileChooser.chooseFiles(descriptor, project, null, new Consumer<List<VirtualFile>>() {
@Override
public void consume(final List<VirtualFile> files) {
//gatherPatchFiles
final ProgressManager pm = ProgressManager.getInstance();
final ShelveChangesManager shelveChangesManager = ShelveChangesManager.getInstance(project);
final List<VirtualFile> patchTypeFiles = new ArrayList<VirtualFile>();
final boolean filesFound = pm.runProcessWithProgressSynchronously(new Runnable() {
@Override
public void run() {
patchTypeFiles.addAll(shelveChangesManager.gatherPatchFiles(files));
}
}, "Looking for patch files...", true, project);
if (!filesFound || patchTypeFiles.isEmpty()) return;
if (!patchTypeFiles.equals(files)) {
final String message = "Found " + (patchTypeFiles.size() == 1 ?
"one patch file (" + patchTypeFiles.get(0).getPath() + ")." :
(patchTypeFiles.size() + " patch files.")) +
"\nContinue with import?";
final int toImport = Messages.showYesNoDialog(project, message, "Import Patches", Messages.getQuestionIcon());
if (Messages.NO == toImport) return;
}
pm.runProcessWithProgressSynchronously(new Runnable() {
@Override
public void run() {
final List<VcsException> exceptions = new ArrayList<VcsException>();
final List<ShelvedChangeList> lists =
shelveChangesManager.importChangeLists(patchTypeFiles, new Consumer<VcsException>() {
@Override
public void consume(VcsException e) {
exceptions.add(e);
}
});
if (!lists.isEmpty()) {
ShelvedChangesViewManager.getInstance(project).activateView(lists.get(lists.size() - 1));
}
if (!exceptions.isEmpty()) {
AbstractVcsHelper.getInstance(project).showErrors(exceptions, "Import patches into shelf");
}
if (lists.isEmpty() && exceptions.isEmpty()) {
VcsBalloonProblemNotifier.showOverChangesView(project, "No patches found", MessageType.WARNING);
}
}
}, "Import patches into shelf", true, project);
}
});
}
}
| title case for action name
| platform/vcs-impl/src/com/intellij/openapi/vcs/changes/shelf/ImportIntoShelfAction.java | title case for action name | <ide><path>latform/vcs-impl/src/com/intellij/openapi/vcs/changes/shelf/ImportIntoShelfAction.java
<ide> */
<ide> public class ImportIntoShelfAction extends DumbAwareAction {
<ide> public ImportIntoShelfAction() {
<del> super("Import patches...", "Copies patch file to shelf", null);
<add> super("Import Patches...", "Copies a patch file to the shelf", null);
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | a64a5a1e06002e4fd199d6f0c91c3d971ca28dde | 0 | pvik/WhdApi | package com.whd;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.mashape.unirest.request.HttpRequestWithBody;
import com.whd.autogen.CustomFieldDefinition;
import com.whd.autogen.LocationDefinition;
import com.whd.autogen.PriorityTypeDefinition;
import com.whd.autogen.RequestTypeDefinition;
import com.whd.autogen.StatusTypeDefinition;
import com.whd.autogen.note.Jobticket;
import com.whd.autogen.note.WhdNote;
import com.whd.autogen.note.response.WhdNoteResponse;
import com.whd.autogen.ticket.CustomField;
import com.whd.autogen.ticket.Location;
import com.whd.autogen.ticket.TicketCustomField;
import com.whd.autogen.ticket.WhdTicket;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WhdApi {
private static final Logger log = LoggerFactory.getLogger(WhdApi.class);
public static WhdTicket createUpdateTicket(WhdAuth auth, WhdTicket ticket) throws WhdException {
log.trace("moving ticketCustomFields to customFields");
if(ticket.getTicketCustomFields() != null && ticket.getTicketCustomFields().size() > 0) {
ticket.setCustomFields(new ArrayList<>());
for (TicketCustomField tcf : ticket.getTicketCustomFields()) {
if(tcf.getRestValue() != null) {
CustomField cf = new CustomField();
cf.setDefinitionId(tcf.getDefinitionId());
cf.setRestValue(tcf.getRestValue());
cf.setType(tcf.getType());
ticket.getCustomFields().add(cf);
}
}
ticket.setTicketCustomFields(null);
}
log.trace("Ticket: {}", ReflectionToStringBuilder.toString(ticket));
log.debug("createUpdateTicket(WhdTicket)");
if (ticket.getId() == null) {
return createTicket(auth, ticket);
} else {
updateTicket(auth, ticket);
return ticket;
}
}
public static WhdTicket createTicket(WhdAuth auth, WhdTicket ticket) throws WhdException {
log.debug("createTicket(WhdTicket)");
WhdTicket respTicket = null;
try {
String jsonTicketStream = Util.jsonMapper
.writer()
.without(SerializationFeature.WRAP_ROOT_VALUE)
.writeValueAsString(ticket);
HttpResponse<String> resp = Unirest.post(auth.getWhdUrl())
.header("accept", "application/json")
.header("Content-Type", "application/json")
.routeParam("resource_type", "Ticket")
.queryString(auth.generateAuthUrlParams())
.body(jsonTicketStream)
.asString();
log.trace("response status: {}", resp.getStatusText());
log.trace("response: {}", resp.getBody());
Util.processResponseForException(resp);
respTicket = Util.jsonMapper.readValue(resp.getBody(), WhdTicket.class);
} catch (UnirestException e) {
throw new WhdException("Error Creating Ticket: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
return respTicket;
}
public static void updateTicket(WhdAuth auth, WhdTicket ticket) throws WhdException {
log.debug("updateTicket(WhdTicket)");
String ticketId = String.format("%d", ticket.getId());
try {
String jsonTicketStream = Util.jsonMapper.writer().without(SerializationFeature.WRAP_ROOT_VALUE).writeValueAsString(ticket);
log.trace("Json stream: {}", jsonTicketStream);
HttpRequestWithBody httpRequest = Unirest.put(auth.getWhdUrl() + "/{ticket_id}")
.header("accept", "application/json")
.header("Content-Type", "application/json")
.routeParam("resource_type", "Tickets")
.routeParam("ticket_id", ticketId)
.queryString(auth.generateAuthUrlParams());
HttpResponse<String> resp = httpRequest
.body(jsonTicketStream)
.asString();
log.debug("Sending PUT Message to: {}", httpRequest.getUrl());
Util.processResponseForException(resp);
} catch (UnirestException e) {
throw new WhdException("Error Updating Ticket: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
}
public static WhdTicket getTicket(WhdAuth auth, Integer ticketId) throws WhdException {
try {
HttpResponse<String> resp = Unirest.get(auth.getWhdUrl() + "/{ticket_id}")
.header("accept", "application/json")
.routeParam("resource_type", "Ticket")
.routeParam("ticket_id", String.format("%d", ticketId))
.queryString(auth.generateAuthUrlParams())
.asString();
log.trace("response status: {}", resp.getStatusText());
log.trace("response: {}", resp.getBody());
Util.processResponseForException(resp);
return Util.jsonMapper.readValue(resp.getBody(), WhdTicket.class);
} catch (UnirestException e) {
throw new WhdException("Error getting Ticket: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
}
public static List<WhdTicket> getTickets(WhdAuth auth, String qualifier) throws WhdException {
List<WhdTicket> tickets = new ArrayList<>();
try {
HttpResponse<String> resp = Unirest.get(auth.getWhdUrl())
.header("accept", "application/json")
.routeParam("resource_type", "Tickets")
.queryString(auth.generateAuthUrlParams())
.queryString("qualifier", qualifier)
.asString();
Util.processResponseForException(resp);
// The Tickets resource returns only partial info about Ticket
List<WhdTicket> tmpTicketList = Util.jsonMapper.readValue(resp.getBody(),
Util.jsonMapper.getTypeFactory().constructCollectionType(List.class, WhdTicket.class));
// Loop through the List and get complete ticket details for each ticket
for (WhdTicket t : tmpTicketList) {
tickets.add(getTicket(auth, t.getId()));
}
return tickets;
} catch (UnirestException e) {
throw new WhdException("Error getting Ticket: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
}
/**
* @param auth
* @param id - This is attachment id
* @return
* @throws WhdException
*/
public static byte[] getAttachment(WhdAuth auth, Integer id) throws WhdException {
try {
HttpResponse<String> resp = Unirest.get(auth.getWhdUrl() + "/{attachment_id}")
.header("accept", "application/octet")
.routeParam("resource_type", "TicketAttachments")
.routeParam("attachment_id", String.format("%d", id))
.queryString(auth.generateAuthUrlParams())
.asString();
return resp.getBody().getBytes();
} catch (UnirestException e) {
throw new WhdException("Error getting Ticket: " + e.getMessage(), e);
}
}
public static Integer addAttachment(WhdAuth auth, Integer ticketId, String filePath) throws WhdException {
try {
HttpResponse<String> strResponse = Unirest.get(auth.getWhdUrl())
.header("accept", "application/json")
.header("Set-Cookie", "http-only")
.routeParam("resource_type", "Session")
.queryString(auth.generateAuthUrlParams())
.asString();
log.debug("whdUrl: {}", auth.getWhdUrl());
log.debug("authUrlParam: {}", auth.generateAuthUrlParams());
log.debug("httpResponse headers: {}", strResponse.getHeaders());
log.debug("httpResponse status: {}", strResponse.getStatus());
log.debug("httpResponse statusText: {}", strResponse.getStatusText());
log.debug("httpResponse rawbody: {}", strResponse.getRawBody());
log.debug("httpResponse body: {}", strResponse.getBody());
String cookies = strResponse.getHeaders().get("Set-Cookie").stream()
.collect(Collectors.joining("; "));
HttpResponse<JsonNode> jsonResponse = Unirest.get(auth.getWhdUrl())
.header("accept", "application/json")
.routeParam("resource_type", "Session")
.queryString(auth.generateAuthUrlParams())
.asJson();
String wosid;
try {
wosid = jsonResponse.getBody().getObject().getString("sessionKey");
} catch (JSONException e) {
throw new WhdException("Unable to upload attachment " +
filePath + " to WHD ticket " +
ticketId + "\nInvalid REST SessionID received");
}
cookies = cookies + "; wosid="+wosid;
HttpResponse<JsonNode> jsonResponseFileUpload = Unirest.post(auth.getWhdUri()+
"/helpdesk/attachment/upload?type=jobTicket&entityId={ticket_id}")
.header("accept", "application/json")
.header("Cookie", cookies)
.header("Connection", "keep-alive")
.header("Pragma", "no-cache")
.routeParam("ticket_id", ticketId.toString())
.field("file", new File(filePath))
.asJson();
log.debug("Response for uploading attachment: {}", jsonResponseFileUpload.getBody());
//Integer attId = Integer.parseInt(jsonResponseFileUpload.getBody().getObject().getString("id"));
Integer attId = jsonResponseFileUpload.getBody().getObject().getInt("id");
log.debug("Attachment ID created: {}", attId);
return attId;
} catch (UnirestException e) {
throw new WhdException("Error uploading attachment to Ticket: " + e.getMessage(), e);
} catch (Exception e) {
throw new WhdException("Unknow Exception uploading attachment to Ticket: " + e.getMessage(), e);
}
}
public static Integer addNote(WhdAuth auth, Integer ticketId, String noteText) throws WhdException {
try {
WhdNote note = new WhdNote();
Jobticket jt = new Jobticket();
jt.setId(ticketId);
jt.setType("JobTicket");
note.setJobticket(jt);
note.setNoteText(noteText);
String jsonNoteStream = Util.jsonMapper.writer().without(SerializationFeature.WRAP_ROOT_VALUE).writeValueAsString(note);
HttpResponse<String> resp = Unirest.post(auth.getWhdUrl())
.header("accept", "application/json")
.header("Content-Type", "application/json")
.routeParam("resource_type", "TechNotes")
.queryString(auth.generateAuthUrlParams())
.body(jsonNoteStream)
.asString();
//Util.jsonMapper.reader().readValue(resp);
Util.processResponseForException(resp);
log.debug("Response for creating Note {}", resp.getBody());
WhdNoteResponse jsonResponse = Util.jsonMapper.readValue(resp.getBody(), WhdNoteResponse.class);
return jsonResponse.getId();
} catch (UnirestException e) {
throw new WhdException("Error getting Ticket: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
}
public static void populateLocationObject(WhdTicket ticket) {
if (ticket.getLocationId() != null) {
Location loc = new Location();
loc.setType("Location");
loc.setId(ticket.getLocationId());
ticket.setLocation(loc);
}
}
public static List<RequestTypeDefinition> getRequestTypeDefinitions(WhdAuth auth) throws WhdException {
List<RequestTypeDefinition> requestTypeDefinitions = null;
try {
HttpResponse<String> resp = Unirest.get(auth.getWhdUrl())
.header("accept", "application/json")
.routeParam("resource_type", "RequestTypes")
.queryString(auth.generateAuthUrlParams())
.queryString("list", "all")
.asString();
Util.processResponseForException(resp);
requestTypeDefinitions = Util.jsonMapper.readValue(resp.getBody(),
Util.jsonMapper.getTypeFactory().constructCollectionType(List.class, RequestTypeDefinition.class));
log.debug("Retreived Request Types");
} catch (UnirestException e) {
throw new WhdException("Error getting Request Type Definitions: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
return requestTypeDefinitions;
}
public static List<StatusTypeDefinition> getStatusTypeDefinitions(WhdAuth auth) throws WhdException {
List<StatusTypeDefinition> defs = null;
try {
HttpResponse<String> resp = Unirest.get(auth.getWhdUrl())
.header("accept", "application/json")
.routeParam("resource_type", "StatusTypes")
.queryString(auth.generateAuthUrlParams())
.queryString("list", "all")
.asString();
Util.processResponseForException(resp);
defs = Util.jsonMapper.readValue(resp.getBody(),
Util.jsonMapper.getTypeFactory().constructCollectionType(List.class, StatusTypeDefinition.class));
log.debug("Retreived Status Types");
} catch (UnirestException e) {
throw new WhdException("Error getting Request Type Definitions: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
return defs;
}
public static List<PriorityTypeDefinition> getPriorityTypeDefinitions(WhdAuth auth) throws WhdException {
List<PriorityTypeDefinition> defs = null;
try {
HttpResponse<String> resp = Unirest.get(auth.getWhdUrl())
.header("accept", "application/json")
.routeParam("resource_type", "PriorityTypes")
.queryString(auth.generateAuthUrlParams())
.queryString("list", "all")
.asString();
Util.processResponseForException(resp);
defs = Util.jsonMapper.readValue(resp.getBody(),
Util.jsonMapper.getTypeFactory().constructCollectionType(List.class, PriorityTypeDefinition.class));
log.debug("Retreived Priority Types");
} catch (UnirestException e) {
throw new WhdException("Error getting Request Type Definitions: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
return defs;
}
public static List<CustomFieldDefinition> getCustomFieldDefinitions(WhdAuth auth) throws WhdException {
List<CustomFieldDefinition> defs = null;
try {
HttpResponse<String> resp = Unirest.get(auth.getWhdUrl())
.header("accept", "application/json")
.routeParam("resource_type", "CustomFieldDefinitions")
.queryString(auth.generateAuthUrlParams())
.queryString("list", "all")
.asString();
Util.processResponseForException(resp);
defs = Util.jsonMapper.readValue(resp.getBody(),
Util.jsonMapper.getTypeFactory().constructCollectionType(List.class, CustomFieldDefinition.class));
log.debug("Retreived Custom Field Definitions");
} catch (UnirestException e) {
throw new WhdException("Error getting Request Type Definitions: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
return defs;
}
// Location related functions
public static LocationDefinition createLocation(WhdAuth auth, LocationDefinition location) throws WhdException {
log.debug("createLocation(LocationDefinition)");
LocationDefinition newLoc = null;
try {
String jsonTicketStream = Util.jsonMapper.writer().without(SerializationFeature.WRAP_ROOT_VALUE).writeValueAsString(location);
HttpResponse<String> resp = Unirest.put(auth.getWhdUrl() + "/{ticket_id}")
.header("accept", "application/json")
.header("Content-Type", "application/json")
.routeParam("resource_type", "Locations")
.queryString(auth.generateAuthUrlParams())
.body(jsonTicketStream)
.asString();
Util.processResponseForException(resp);
newLoc = Util.jsonMapper.readValue(resp.getBody(), LocationDefinition.class);
} catch (UnirestException e) {
throw new WhdException("Error Updating Ticket: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
return newLoc;
}
public static List<LocationDefinition> getLocationList(WhdAuth auth) throws WhdException {
List<LocationDefinition> defs = null;
try {
Unirest.setTimeouts(0,0);
HttpResponse<String> resp = Unirest.get(auth.getWhdUrl())
.header("accept", "application/json")
.routeParam("resource_type", "Locations")
.queryString(auth.generateAuthUrlParams())
.queryString("list", "all")
.asString();
Util.processResponseForException(resp);
defs = Util.jsonMapper.readValue(resp.getBody(),
Util.jsonMapper.getTypeFactory().constructCollectionType(List.class, LocationDefinition.class));
log.debug("Retreived Locations");
} catch (UnirestException e) {
throw new WhdException("Error Location Type Definitions: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
return defs;
}
public static LocationDefinition getLocation(WhdAuth auth, int locationId) throws WhdException {
LocationDefinition defs = null;
try {
HttpResponse<String> resp = Unirest.get(auth.getWhdUrl() + "/{location_id}")
.header("accept", "application/json")
.routeParam("resource_type", "Locations")
.routeParam("location_id", String.format("%d", locationId))
.queryString(auth.generateAuthUrlParams())
.queryString("list", "all")
.asString();
Util.processResponseForException(resp);
defs = Util.jsonMapper.readValue(resp.getBody(), LocationDefinition.class);
;
log.debug("Retreived Locations");
} catch (UnirestException e) {
throw new WhdException("Error getting Location Definition: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
return defs;
}
public static List<LocationDefinition> searchLocations(WhdAuth auth, String qualifier) throws WhdException {
List<LocationDefinition> defs = null;
try {
HttpResponse<String> resp = Unirest.get(auth.getWhdUrl())
.header("accept", "application/json")
.routeParam("resource_type", "Locations")
.queryString(auth.generateAuthUrlParams())
.queryString("qualifier", qualifier)
.asString();
Util.processResponseForException(resp);
defs = Util.jsonMapper.readValue(resp.getBody(),
Util.jsonMapper.getTypeFactory().constructCollectionType(List.class, LocationDefinition.class));
log.debug("Retreived Locations");
} catch (UnirestException e) {
throw new WhdException("Error getting Request Type Definitions: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
return defs;
}
public static List<LocationDefinition> searchLocations(WhdAuth auth, String qualifier, boolean includeDeleted) throws WhdException {
if (includeDeleted) {
qualifier = "(((deleted %3D null) or (deleted %3D 0) or (deleted %3D 1)) and " + qualifier + ")";
}
return searchLocations(auth, qualifier);
}
public static List<LocationDefinition> searchLocationsIncludeDeleted(WhdAuth auth, String qualifier) throws WhdException {
return searchLocations(auth, qualifier, true);
}
public static List<LocationDefinition> searchLocationsExcludeDeleted(WhdAuth auth, String qualifier) throws WhdException {
return searchLocations(auth, qualifier, false);
}
public static void updateLocation(WhdAuth auth, LocationDefinition location) throws WhdException {
try {
String locationId = String.format("%d", location.getId());
log.debug("updateLocation(<LocationDefinition;id={}>)", locationId);
String jsonLocationStream = Util.jsonMapper.writer().without(SerializationFeature.WRAP_ROOT_VALUE).writeValueAsString(location);
HttpResponse<String> resp = Unirest.put(auth.getWhdUrl() + "/{location_id}")
.header("accept", "application/json")
.header("Content-Type", "application/json")
.routeParam("resource_type", "Locations")
.routeParam("location_id", locationId)
.queryString(auth.generateAuthUrlParams())
.body(jsonLocationStream)
.asString();
Util.processResponseForException(resp);
} catch (UnirestException e) {
throw new WhdException("Error Creating Ticket: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
}
public static void deleteLocation(WhdAuth auth, LocationDefinition location) throws WhdException {
try {
String locationId = String.format("%d", location.getId());
log.debug("updateLocation(<LocationDefinition;id={}>)", locationId);
String jsonLocationStream = Util.jsonMapper.writer().without(SerializationFeature.WRAP_ROOT_VALUE).writeValueAsString(location);
HttpResponse<String> resp = Unirest.delete(auth.getWhdUrl() + "/{location_id}")
.header("accept", "application/json")
.routeParam("resource_type", "Locations")
.routeParam("location_id", locationId)
.queryString(auth.generateAuthUrlParams())
.asString();
Util.processResponseForException(resp);
LocationDefinition loc = Util.jsonMapper.readValue(resp.getBody(), LocationDefinition.class);
if (!Objects.equals(loc.getId(), location.getId())) {
throw new WhdException("Did not receive confirmation for Location Deletion from WHD");
}
} catch (UnirestException e) {
throw new WhdException("Error Creating Ticket: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
}
}
| src/main/java/com/whd/WhdApi.java | package com.whd;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.mashape.unirest.request.HttpRequestWithBody;
import com.whd.autogen.CustomFieldDefinition;
import com.whd.autogen.LocationDefinition;
import com.whd.autogen.PriorityTypeDefinition;
import com.whd.autogen.RequestTypeDefinition;
import com.whd.autogen.StatusTypeDefinition;
import com.whd.autogen.note.Jobticket;
import com.whd.autogen.note.WhdNote;
import com.whd.autogen.note.response.WhdNoteResponse;
import com.whd.autogen.ticket.CustomField;
import com.whd.autogen.ticket.Location;
import com.whd.autogen.ticket.TicketCustomField;
import com.whd.autogen.ticket.WhdTicket;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WhdApi {
private static final Logger log = LoggerFactory.getLogger(WhdApi.class);
public static WhdTicket createUpdateTicket(WhdAuth auth, WhdTicket ticket) throws WhdException {
log.trace("moving ticketCustomFields to customFields");
if(ticket.getTicketCustomFields() != null && ticket.getTicketCustomFields().size() > 0) {
ticket.setCustomFields(new ArrayList<>());
for (TicketCustomField tcf : ticket.getTicketCustomFields()) {
if(tcf.getRestValue() != null) {
CustomField cf = new CustomField();
cf.setDefinitionId(tcf.getDefinitionId());
cf.setRestValue(tcf.getRestValue());
cf.setType(tcf.getType());
ticket.getCustomFields().add(cf);
}
}
ticket.setTicketCustomFields(null);
}
log.trace("Ticket: {}", ReflectionToStringBuilder.toString(ticket));
log.debug("createUpdateTicket(WhdTicket)");
if (ticket.getId() == null) {
return createTicket(auth, ticket);
} else {
updateTicket(auth, ticket);
return ticket;
}
}
public static WhdTicket createTicket(WhdAuth auth, WhdTicket ticket) throws WhdException {
log.debug("createTicket(WhdTicket)");
WhdTicket respTicket = null;
try {
String jsonTicketStream = Util.jsonMapper
.writer()
.without(SerializationFeature.WRAP_ROOT_VALUE)
.writeValueAsString(ticket);
HttpResponse<String> resp = Unirest.post(auth.getWhdUrl())
.header("accept", "application/json")
.header("Content-Type", "application/json")
.routeParam("resource_type", "Ticket")
.queryString(auth.generateAuthUrlParams())
.body(jsonTicketStream)
.asString();
log.trace("response status: {}", resp.getStatusText());
log.trace("response: {}", resp.getBody());
Util.processResponseForException(resp);
respTicket = Util.jsonMapper.readValue(resp.getBody(), WhdTicket.class);
} catch (UnirestException e) {
throw new WhdException("Error Creating Ticket: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
return respTicket;
}
public static void updateTicket(WhdAuth auth, WhdTicket ticket) throws WhdException {
log.debug("updateTicket(WhdTicket)");
String ticketId = String.format("%d", ticket.getId());
try {
String jsonTicketStream = Util.jsonMapper.writer().without(SerializationFeature.WRAP_ROOT_VALUE).writeValueAsString(ticket);
log.trace("Json stream: {}", jsonTicketStream);
HttpRequestWithBody httpRequest = Unirest.put(auth.getWhdUrl() + "/{ticket_id}")
.header("accept", "application/json")
.header("Content-Type", "application/json")
.routeParam("resource_type", "Tickets")
.routeParam("ticket_id", ticketId)
.queryString(auth.generateAuthUrlParams());
HttpResponse<String> resp = httpRequest
.body(jsonTicketStream)
.asString();
log.debug("Sending PUT Message to: {}", httpRequest.getUrl());
Util.processResponseForException(resp);
} catch (UnirestException e) {
throw new WhdException("Error Updating Ticket: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
}
public static WhdTicket getTicket(WhdAuth auth, Integer ticketId) throws WhdException {
try {
HttpResponse<String> resp = Unirest.get(auth.getWhdUrl() + "/{ticket_id}")
.header("accept", "application/json")
.routeParam("resource_type", "Ticket")
.routeParam("ticket_id", String.format("%d", ticketId))
.queryString(auth.generateAuthUrlParams())
.asString();
log.trace("response status: {}", resp.getStatusText());
log.trace("response: {}", resp.getBody());
Util.processResponseForException(resp);
return Util.jsonMapper.readValue(resp.getBody(), WhdTicket.class);
} catch (UnirestException e) {
throw new WhdException("Error getting Ticket: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
}
public static List<WhdTicket> getTickets(WhdAuth auth, String qualifier) throws WhdException {
List<WhdTicket> tickets = new ArrayList<>();
try {
HttpResponse<String> resp = Unirest.get(auth.getWhdUrl())
.header("accept", "application/json")
.routeParam("resource_type", "Tickets")
.queryString(auth.generateAuthUrlParams())
.queryString("qualifier", qualifier)
.asString();
Util.processResponseForException(resp);
// The Tickets resource returns only partial info about Ticket
List<WhdTicket> tmpTicketList = Util.jsonMapper.readValue(resp.getBody(),
Util.jsonMapper.getTypeFactory().constructCollectionType(List.class, WhdTicket.class));
// Loop through the List and get complete ticket details for each ticket
for (WhdTicket t : tmpTicketList) {
tickets.add(getTicket(auth, t.getId()));
}
return tickets;
} catch (UnirestException e) {
throw new WhdException("Error getting Ticket: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
}
/**
* @param auth
* @param id - This is attachment id
* @return
* @throws WhdException
*/
public static byte[] getAttachment(WhdAuth auth, Integer id) throws WhdException {
try {
HttpResponse<String> resp = Unirest.get(auth.getWhdUrl() + "/{attachment_id}")
.header("accept", "application/octet")
.routeParam("resource_type", "TicketAttachments")
.routeParam("attachment_id", String.format("%d", id))
.queryString(auth.generateAuthUrlParams())
.asString();
return resp.getBody().getBytes();
} catch (UnirestException e) {
throw new WhdException("Error getting Ticket: " + e.getMessage(), e);
}
}
public static Integer addAttachment(WhdAuth auth, Integer ticketId, String filePath) throws WhdException {
try {
HttpResponse<JsonNode> jsonResponse = Unirest.get(auth.getWhdUrl())
.header("accept", "application/json")
.routeParam("resource_type", "Session")
.queryString(auth.generateAuthUrlParams())
.asJson();
String cookies = jsonResponse.getHeaders().get("Set-Cookie").stream()
.collect(Collectors.joining("; "));
String wosid;
try {
wosid = jsonResponse.getBody().getObject().getString("sessionKey");
} catch (JSONException e) {
throw new WhdException("Unable to upload attachment " +
filePath + " to WHD ticket " +
ticketId + "\nInvalid REST SessionID received");
}
cookies = cookies + "; wosid="+wosid;
HttpResponse<JsonNode> jsonResponseFileUpload = Unirest.post(auth.getWhdUri()+
"/helpdesk/attachment/upload?type=jobTicket&entityId={ticket_id}")
.header("accept", "application/json")
.header("Cookie", cookies)
.header("Connection", "keep-alive")
.header("Pragma", "no-cache")
.routeParam("ticket_id", ticketId.toString())
.field("file", new File(filePath))
.asJson();
log.debug("Response for uploading attachment: {}", jsonResponseFileUpload.getBody());
Integer attId = Integer.parseInt(jsonResponseFileUpload.getBody().getObject().getString("id"));
log.debug("Attachment ID created: {}", attId);
return attId;
} catch (UnirestException e) {
throw new WhdException("Error uploading attachment to Ticket: " + e.getMessage(), e);
}
}
public static Integer addNote(WhdAuth auth, Integer ticketId, String noteText) throws WhdException {
try {
WhdNote note = new WhdNote();
Jobticket jt = new Jobticket();
jt.setId(ticketId);
jt.setType("JobTicket");
note.setJobticket(jt);
note.setNoteText(noteText);
String jsonNoteStream = Util.jsonMapper.writer().without(SerializationFeature.WRAP_ROOT_VALUE).writeValueAsString(note);
HttpResponse<String> resp = Unirest.post(auth.getWhdUrl())
.header("accept", "application/json")
.header("Content-Type", "application/json")
.routeParam("resource_type", "TechNotes")
.queryString(auth.generateAuthUrlParams())
.body(jsonNoteStream)
.asString();
//Util.jsonMapper.reader().readValue(resp);
Util.processResponseForException(resp);
log.debug("Response for creating Note {}", resp.getBody());
WhdNoteResponse jsonResponse = Util.jsonMapper.readValue(resp.getBody(), WhdNoteResponse.class);
return jsonResponse.getId();
} catch (UnirestException e) {
throw new WhdException("Error getting Ticket: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
}
public static void populateLocationObject(WhdTicket ticket) {
if (ticket.getLocationId() != null) {
Location loc = new Location();
loc.setType("Location");
loc.setId(ticket.getLocationId());
ticket.setLocation(loc);
}
}
public static List<RequestTypeDefinition> getRequestTypeDefinitions(WhdAuth auth) throws WhdException {
List<RequestTypeDefinition> requestTypeDefinitions = null;
try {
HttpResponse<String> resp = Unirest.get(auth.getWhdUrl())
.header("accept", "application/json")
.routeParam("resource_type", "RequestTypes")
.queryString(auth.generateAuthUrlParams())
.queryString("list", "all")
.asString();
Util.processResponseForException(resp);
requestTypeDefinitions = Util.jsonMapper.readValue(resp.getBody(),
Util.jsonMapper.getTypeFactory().constructCollectionType(List.class, RequestTypeDefinition.class));
log.debug("Retreived Request Types");
} catch (UnirestException e) {
throw new WhdException("Error getting Request Type Definitions: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
return requestTypeDefinitions;
}
public static List<StatusTypeDefinition> getStatusTypeDefinitions(WhdAuth auth) throws WhdException {
List<StatusTypeDefinition> defs = null;
try {
HttpResponse<String> resp = Unirest.get(auth.getWhdUrl())
.header("accept", "application/json")
.routeParam("resource_type", "StatusTypes")
.queryString(auth.generateAuthUrlParams())
.queryString("list", "all")
.asString();
Util.processResponseForException(resp);
defs = Util.jsonMapper.readValue(resp.getBody(),
Util.jsonMapper.getTypeFactory().constructCollectionType(List.class, StatusTypeDefinition.class));
log.debug("Retreived Status Types");
} catch (UnirestException e) {
throw new WhdException("Error getting Request Type Definitions: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
return defs;
}
public static List<PriorityTypeDefinition> getPriorityTypeDefinitions(WhdAuth auth) throws WhdException {
List<PriorityTypeDefinition> defs = null;
try {
HttpResponse<String> resp = Unirest.get(auth.getWhdUrl())
.header("accept", "application/json")
.routeParam("resource_type", "PriorityTypes")
.queryString(auth.generateAuthUrlParams())
.queryString("list", "all")
.asString();
Util.processResponseForException(resp);
defs = Util.jsonMapper.readValue(resp.getBody(),
Util.jsonMapper.getTypeFactory().constructCollectionType(List.class, PriorityTypeDefinition.class));
log.debug("Retreived Priority Types");
} catch (UnirestException e) {
throw new WhdException("Error getting Request Type Definitions: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
return defs;
}
public static List<CustomFieldDefinition> getCustomFieldDefinitions(WhdAuth auth) throws WhdException {
List<CustomFieldDefinition> defs = null;
try {
HttpResponse<String> resp = Unirest.get(auth.getWhdUrl())
.header("accept", "application/json")
.routeParam("resource_type", "CustomFieldDefinitions")
.queryString(auth.generateAuthUrlParams())
.queryString("list", "all")
.asString();
Util.processResponseForException(resp);
defs = Util.jsonMapper.readValue(resp.getBody(),
Util.jsonMapper.getTypeFactory().constructCollectionType(List.class, CustomFieldDefinition.class));
log.debug("Retreived Custom Field Definitions");
} catch (UnirestException e) {
throw new WhdException("Error getting Request Type Definitions: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
return defs;
}
// Location related functions
public static LocationDefinition createLocation(WhdAuth auth, LocationDefinition location) throws WhdException {
log.debug("createLocation(LocationDefinition)");
LocationDefinition newLoc = null;
try {
String jsonTicketStream = Util.jsonMapper.writer().without(SerializationFeature.WRAP_ROOT_VALUE).writeValueAsString(location);
HttpResponse<String> resp = Unirest.put(auth.getWhdUrl() + "/{ticket_id}")
.header("accept", "application/json")
.header("Content-Type", "application/json")
.routeParam("resource_type", "Locations")
.queryString(auth.generateAuthUrlParams())
.body(jsonTicketStream)
.asString();
Util.processResponseForException(resp);
newLoc = Util.jsonMapper.readValue(resp.getBody(), LocationDefinition.class);
} catch (UnirestException e) {
throw new WhdException("Error Updating Ticket: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
return newLoc;
}
public static List<LocationDefinition> getLocationList(WhdAuth auth) throws WhdException {
List<LocationDefinition> defs = null;
try {
Unirest.setTimeouts(0,0);
HttpResponse<String> resp = Unirest.get(auth.getWhdUrl())
.header("accept", "application/json")
.routeParam("resource_type", "Locations")
.queryString(auth.generateAuthUrlParams())
.queryString("list", "all")
.asString();
Util.processResponseForException(resp);
defs = Util.jsonMapper.readValue(resp.getBody(),
Util.jsonMapper.getTypeFactory().constructCollectionType(List.class, LocationDefinition.class));
log.debug("Retreived Locations");
} catch (UnirestException e) {
throw new WhdException("Error Location Type Definitions: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
return defs;
}
public static LocationDefinition getLocation(WhdAuth auth, int locationId) throws WhdException {
LocationDefinition defs = null;
try {
HttpResponse<String> resp = Unirest.get(auth.getWhdUrl() + "/{location_id}")
.header("accept", "application/json")
.routeParam("resource_type", "Locations")
.routeParam("location_id", String.format("%d", locationId))
.queryString(auth.generateAuthUrlParams())
.queryString("list", "all")
.asString();
Util.processResponseForException(resp);
defs = Util.jsonMapper.readValue(resp.getBody(), LocationDefinition.class);
;
log.debug("Retreived Locations");
} catch (UnirestException e) {
throw new WhdException("Error getting Location Definition: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
return defs;
}
public static List<LocationDefinition> searchLocations(WhdAuth auth, String qualifier) throws WhdException {
List<LocationDefinition> defs = null;
try {
HttpResponse<String> resp = Unirest.get(auth.getWhdUrl())
.header("accept", "application/json")
.routeParam("resource_type", "Locations")
.queryString(auth.generateAuthUrlParams())
.queryString("qualifier", qualifier)
.asString();
Util.processResponseForException(resp);
defs = Util.jsonMapper.readValue(resp.getBody(),
Util.jsonMapper.getTypeFactory().constructCollectionType(List.class, LocationDefinition.class));
log.debug("Retreived Locations");
} catch (UnirestException e) {
throw new WhdException("Error getting Request Type Definitions: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
return defs;
}
public static List<LocationDefinition> searchLocations(WhdAuth auth, String qualifier, boolean includeDeleted) throws WhdException {
if (includeDeleted) {
qualifier = "(((deleted %3D null) or (deleted %3D 0) or (deleted %3D 1)) and " + qualifier + ")";
}
return searchLocations(auth, qualifier);
}
public static List<LocationDefinition> searchLocationsIncludeDeleted(WhdAuth auth, String qualifier) throws WhdException {
return searchLocations(auth, qualifier, true);
}
public static List<LocationDefinition> searchLocationsExcludeDeleted(WhdAuth auth, String qualifier) throws WhdException {
return searchLocations(auth, qualifier, false);
}
public static void updateLocation(WhdAuth auth, LocationDefinition location) throws WhdException {
try {
String locationId = String.format("%d", location.getId());
log.debug("updateLocation(<LocationDefinition;id={}>)", locationId);
String jsonLocationStream = Util.jsonMapper.writer().without(SerializationFeature.WRAP_ROOT_VALUE).writeValueAsString(location);
HttpResponse<String> resp = Unirest.put(auth.getWhdUrl() + "/{location_id}")
.header("accept", "application/json")
.header("Content-Type", "application/json")
.routeParam("resource_type", "Locations")
.routeParam("location_id", locationId)
.queryString(auth.generateAuthUrlParams())
.body(jsonLocationStream)
.asString();
Util.processResponseForException(resp);
} catch (UnirestException e) {
throw new WhdException("Error Creating Ticket: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
}
public static void deleteLocation(WhdAuth auth, LocationDefinition location) throws WhdException {
try {
String locationId = String.format("%d", location.getId());
log.debug("updateLocation(<LocationDefinition;id={}>)", locationId);
String jsonLocationStream = Util.jsonMapper.writer().without(SerializationFeature.WRAP_ROOT_VALUE).writeValueAsString(location);
HttpResponse<String> resp = Unirest.delete(auth.getWhdUrl() + "/{location_id}")
.header("accept", "application/json")
.routeParam("resource_type", "Locations")
.routeParam("location_id", locationId)
.queryString(auth.generateAuthUrlParams())
.asString();
Util.processResponseForException(resp);
LocationDefinition loc = Util.jsonMapper.readValue(resp.getBody(), LocationDefinition.class);
if (!Objects.equals(loc.getId(), location.getId())) {
throw new WhdException("Did not receive confirmation for Location Deletion from WHD");
}
} catch (UnirestException e) {
throw new WhdException("Error Creating Ticket: " + e.getMessage(), e);
} catch (IOException e) {
throw Util.processJsonMapperIOException(e);
}
}
}
| making changes to handle attachments
| src/main/java/com/whd/WhdApi.java | making changes to handle attachments | <ide><path>rc/main/java/com/whd/WhdApi.java
<ide> import org.slf4j.LoggerFactory;
<ide>
<ide> public class WhdApi {
<add>
<ide> private static final Logger log = LoggerFactory.getLogger(WhdApi.class);
<ide>
<ide> public static WhdTicket createUpdateTicket(WhdAuth auth, WhdTicket ticket) throws WhdException {
<ide>
<ide> public static Integer addAttachment(WhdAuth auth, Integer ticketId, String filePath) throws WhdException {
<ide> try {
<add>
<add>
<add> HttpResponse<String> strResponse = Unirest.get(auth.getWhdUrl())
<add> .header("accept", "application/json")
<add> .header("Set-Cookie", "http-only")
<add> .routeParam("resource_type", "Session")
<add> .queryString(auth.generateAuthUrlParams())
<add> .asString();
<add>
<add> log.debug("whdUrl: {}", auth.getWhdUrl());
<add> log.debug("authUrlParam: {}", auth.generateAuthUrlParams());
<add> log.debug("httpResponse headers: {}", strResponse.getHeaders());
<add> log.debug("httpResponse status: {}", strResponse.getStatus());
<add> log.debug("httpResponse statusText: {}", strResponse.getStatusText());
<add> log.debug("httpResponse rawbody: {}", strResponse.getRawBody());
<add> log.debug("httpResponse body: {}", strResponse.getBody());
<add>
<add> String cookies = strResponse.getHeaders().get("Set-Cookie").stream()
<add> .collect(Collectors.joining("; "));
<add>
<ide> HttpResponse<JsonNode> jsonResponse = Unirest.get(auth.getWhdUrl())
<ide> .header("accept", "application/json")
<ide> .routeParam("resource_type", "Session")
<ide> .queryString(auth.generateAuthUrlParams())
<ide> .asJson();
<del>
<del> String cookies = jsonResponse.getHeaders().get("Set-Cookie").stream()
<del> .collect(Collectors.joining("; "));
<ide>
<ide> String wosid;
<ide> try {
<ide> .asJson();
<ide>
<ide> log.debug("Response for uploading attachment: {}", jsonResponseFileUpload.getBody());
<del> Integer attId = Integer.parseInt(jsonResponseFileUpload.getBody().getObject().getString("id"));
<add> //Integer attId = Integer.parseInt(jsonResponseFileUpload.getBody().getObject().getString("id"));
<add> Integer attId = jsonResponseFileUpload.getBody().getObject().getInt("id");
<ide> log.debug("Attachment ID created: {}", attId);
<ide>
<ide> return attId;
<ide> } catch (UnirestException e) {
<ide> throw new WhdException("Error uploading attachment to Ticket: " + e.getMessage(), e);
<add> } catch (Exception e) {
<add> throw new WhdException("Unknow Exception uploading attachment to Ticket: " + e.getMessage(), e);
<ide> }
<ide> }
<ide> |
|
JavaScript | mit | f628b17877646e0c6a129b52ef603dd6e11b64ce | 0 | angular/dev-infra,angular/dev-infra,angular/dev-infra,angular/dev-infra | module.exports = {
branchPrefix: 'ng-renovate/',
gitAuthor: 'Angular Robot <[email protected]>',
platform: 'github',
forkMode: true,
onboarding: false,
repositories: [
'angular/angular',
'angular/dev-infra',
'angular/components',
'angular/angular-cli',
'angular/universal',
'angular/vscode-ng-language-service',
],
productLinks: {
documentation: 'https://docs.renovatebot.com/',
help: 'https://github.com/angular/dev-infra',
homepage: 'https://github.com/angular/dev-infra',
},
};
| .github/ng-renovate/runner-config.js | module.exports = {
branchPrefix: 'ng-renovate/',
gitAuthor: 'Angular Robot <[email protected]>',
platform: 'github',
forkMode: true,
onboarding: false,
repositories: [
'angular/dev-infra',
'angular/components',
'angular/angular-cli',
'angular/universal',
'angular/vscode-ng-language-service',
],
productLinks: {
documentation: 'https://docs.renovatebot.com/',
help: 'https://github.com/angular/dev-infra',
homepage: 'https://github.com/angular/dev-infra',
},
};
| build: enable self-hosted angular renovate runner
| .github/ng-renovate/runner-config.js | build: enable self-hosted angular renovate runner | <ide><path>github/ng-renovate/runner-config.js
<ide> forkMode: true,
<ide> onboarding: false,
<ide> repositories: [
<add> 'angular/angular',
<ide> 'angular/dev-infra',
<ide> 'angular/components',
<ide> 'angular/angular-cli', |
|
Java | bsd-3-clause | 802d2e3335457893e8aab1e79ed6c368875d1506 | 0 | NUBIC/psc-mirror,NUBIC/psc-mirror,NUBIC/psc-mirror,NUBIC/psc-mirror | package edu.northwestern.bioinformatics.studycalendar.security.plugin;
import edu.northwestern.bioinformatics.studycalendar.StudyCalendarUserException;
import edu.northwestern.bioinformatics.studycalendar.StudyCalendarValidationException;
import gov.nih.nci.cabig.ctms.tools.configuration.Configuration;
import gov.nih.nci.cabig.ctms.tools.configuration.ConfigurationProperty;
import org.acegisecurity.AuthenticationManager;
import org.acegisecurity.ui.AuthenticationEntryPoint;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import javax.servlet.Filter;
import java.util.Collection;
/**
* Template base class for implementors of {@link AuthenticationSystem}.
*
* @author Rhett Sutphin
*/
public abstract class AbstractAuthenticationSystem implements AuthenticationSystem {
private final Logger log = LoggerFactory.getLogger(getClass());
private ApplicationContext applicationContext;
private Configuration configuration;
private AuthenticationManager authenticationManager;
private AuthenticationEntryPoint entryPoint;
private Filter filter, logoutFilter;
protected ApplicationContext getApplicationContext() {
return applicationContext;
}
protected Configuration getConfiguration() {
return configuration;
}
public String name() {
return getClass().getSimpleName().replaceAll("AuthenticationSystem", "");
}
/**
* Initializes this authentication system using the values provided by the template methods.
* <p>
* When using this base class, you should generally <em>not</em> override this method, but
* rather the individual template methods.
*
* @param parent the system application context
* @param config
* @throws AuthenticationSystemInitializationFailure
* @throws StudyCalendarValidationException
*/
public void initialize(
ApplicationContext parent, Configuration config
) throws AuthenticationSystemInitializationFailure, StudyCalendarValidationException {
try {
this.applicationContext = parent;
this.configuration = config;
validateRequiredConfigurationProperties();
initBeforeCreate();
this.authenticationManager = createAuthenticationManager();
this.entryPoint = createEntryPoint();
this.filter = createFilter();
this.logoutFilter = createLogoutFilter();
initAfterCreate();
} catch (StudyCalendarUserException scue) {
throw scue; // don't wrap properly typed exceptions
} catch (RuntimeException re) {
log.info("Initialization failed with runtime exception", re);
throw new AuthenticationSystemInitializationFailure(re.getMessage(), re);
}
AuthenticationSystemValidator.validateRequiredElementsCreated(this);
}
/**
* Template method to specify some configuration properties as required.
* If any of the specified properties are null, initialization will stop before
* any of the other initialization template methods are called.
*/
protected Collection<ConfigurationProperty<?>> requiredConfigurationProperties() {
return null;
}
/**
* Template method for initialization. {@link #getApplicationContext()} and
* {@link #getConfiguration()} will be available. All the <code>create*</code>
* template methods will be called after this one.
*/
protected void initBeforeCreate() { }
/**
* Template method for initializing the value returned by {@link #authenticationManager()}.
* Alternatively, you could use {@link #initAfterCreate()}. If you take the latter
* route, be sure to override {@link #authenticationManager()}, too.
*
* @see AuthenticationSystemTools#createProviderManager
*/
protected AuthenticationManager createAuthenticationManager() {
return null;
}
/**
* Template method for initializing the value returned by {@link #entryPoint()}.
* Alternatively, you could use {@link #initAfterCreate()}. If you take the latter
* route, be sure to override {@link #entryPoint()}, too.
*/
protected AuthenticationEntryPoint createEntryPoint() {
return null;
}
/**
* Template method for initializing the value returned by {@link #filter()}.
* Alternatively, you could use {@link #initAfterCreate()}. If you take the latter
* route, be sure to override {@link #filter()}, too.
*/
protected Filter createFilter() {
return null;
}
/**
* Template method for initializing the value returned by {@link #filter()}.
* Alternatively, you could use {@link #initAfterCreate()}. If you take the latter
* route, be sure to override {@link #logoutFilter()}, too.
* <p>
* Defaults to the bean <code>defaultLogoutFilter</code> from the application context
* provided to {@link #initialize}.
*/
protected Filter createLogoutFilter() {
return (Filter) getApplicationContext().getBean("defaultLogoutFilter");
}
/**
* Template method for initialization. {@link #getApplicationContext()} and
* {@link #getConfiguration()} will be available. All the <code>create*</code>
* template methods will be called before this one.
*/
protected void initAfterCreate() { }
public AuthenticationManager authenticationManager() { return authenticationManager; }
public AuthenticationEntryPoint entryPoint() { return entryPoint; }
public Filter filter() { return filter; }
public Filter logoutFilter() { return logoutFilter; }
public boolean usesLocalPasswords() {
return false;
}
private void validateRequiredConfigurationProperties() {
if (requiredConfigurationProperties() != null) {
for (ConfigurationProperty<?> prop : requiredConfigurationProperties()) {
Object value = getConfiguration().get(prop);
boolean isNull = value == null;
boolean isBlank = (value instanceof String) && StringUtils.isBlank((String) value);
if (isNull || isBlank) {
throw new StudyCalendarValidationException("%s is required for the selected authentication system",
prop.getName());
}
}
}
}
}
| authentication/plugin-api/src/main/java/edu/northwestern/bioinformatics/studycalendar/security/plugin/AbstractAuthenticationSystem.java | package edu.northwestern.bioinformatics.studycalendar.security.plugin;
import edu.northwestern.bioinformatics.studycalendar.StudyCalendarUserException;
import edu.northwestern.bioinformatics.studycalendar.StudyCalendarValidationException;
import gov.nih.nci.cabig.ctms.tools.configuration.Configuration;
import gov.nih.nci.cabig.ctms.tools.configuration.ConfigurationProperty;
import org.acegisecurity.AuthenticationManager;
import org.acegisecurity.ui.AuthenticationEntryPoint;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import javax.servlet.Filter;
import java.util.Collection;
/**
* Template base class for implementors of {@link AuthenticationSystem}.
*
* @author Rhett Sutphin
*/
public abstract class AbstractAuthenticationSystem implements AuthenticationSystem {
private final Logger log = LoggerFactory.getLogger(getClass());
private ApplicationContext applicationContext;
private Configuration configuration;
private AuthenticationManager authenticationManager;
private AuthenticationEntryPoint entryPoint;
private Filter filter, logoutFilter;
protected ApplicationContext getApplicationContext() {
return applicationContext;
}
protected Configuration getConfiguration() {
return configuration;
}
public String name() {
return getClass().getSimpleName().replaceAll("AuthenticationSystem", "");
}
public final void initialize(
ApplicationContext parent, Configuration config
) throws AuthenticationSystemInitializationFailure, StudyCalendarValidationException {
try {
this.applicationContext = parent;
this.configuration = config;
validateRequiredConfigurationProperties();
initBeforeCreate();
this.authenticationManager = createAuthenticationManager();
this.entryPoint = createEntryPoint();
this.filter = createFilter();
this.logoutFilter = createLogoutFilter();
initAfterCreate();
} catch (StudyCalendarUserException scue) {
throw scue; // don't wrap properly typed exceptions
} catch (RuntimeException re) {
log.info("Initialization failed with runtime exception", re);
throw new AuthenticationSystemInitializationFailure(re.getMessage(), re);
}
AuthenticationSystemValidator.validateRequiredElementsCreated(this);
}
/**
* Template method to specify some configuration properties as required.
* If any of the specified properties are null, initialization will stop before
* any of the other initialization template methods are called.
*/
protected Collection<ConfigurationProperty<?>> requiredConfigurationProperties() {
return null;
}
/**
* Template method for initialization. {@link #getApplicationContext()} and
* {@link #getConfiguration()} will be available. All the <code>create*</code>
* template methods will be called after this one.
*/
protected void initBeforeCreate() { }
/**
* Template method for initializing the value returned by {@link #authenticationManager()}.
* Alternatively, you could use {@link #initAfterCreate()}. If you take the latter
* route, be sure to override {@link #authenticationManager()}, too.
*
* @see AuthenticationSystemTools#createProviderManager
*/
protected AuthenticationManager createAuthenticationManager() {
return null;
}
/**
* Template method for initializing the value returned by {@link #entryPoint()}.
* Alternatively, you could use {@link #initAfterCreate()}. If you take the latter
* route, be sure to override {@link #entryPoint()}, too.
*/
protected AuthenticationEntryPoint createEntryPoint() {
return null;
}
/**
* Template method for initializing the value returned by {@link #filter()}.
* Alternatively, you could use {@link #initAfterCreate()}. If you take the latter
* route, be sure to override {@link #filter()}, too.
*/
protected Filter createFilter() {
return null;
}
/**
* Template method for initializing the value returned by {@link #filter()}.
* Alternatively, you could use {@link #initAfterCreate()}. If you take the latter
* route, be sure to override {@link #logoutFilter()}, too.
* <p>
* Defaults to the bean <code>defaultLogoutFilter</code> from the application context
* provided to {@link #initialize}.
*/
protected Filter createLogoutFilter() {
return (Filter) getApplicationContext().getBean("defaultLogoutFilter");
}
/**
* Template method for initialization. {@link #getApplicationContext()} and
* {@link #getConfiguration()} will be available. All the <code>create*</code>
* template methods will be called before this one.
*/
protected void initAfterCreate() { }
public AuthenticationManager authenticationManager() { return authenticationManager; }
public AuthenticationEntryPoint entryPoint() { return entryPoint; }
public Filter filter() { return filter; }
public Filter logoutFilter() { return logoutFilter; }
public boolean usesLocalPasswords() {
return false;
}
private void validateRequiredConfigurationProperties() {
if (requiredConfigurationProperties() != null) {
for (ConfigurationProperty<?> prop : requiredConfigurationProperties()) {
Object value = getConfiguration().get(prop);
boolean isNull = value == null;
boolean isBlank = (value instanceof String) && StringUtils.isBlank((String) value);
if (isNull || isBlank) {
throw new StudyCalendarValidationException("%s is required for the selected authentication system",
prop.getName());
}
}
}
}
}
| Make AbstractAuthenticationSystem#initialize non-final so that it may be proxied by CGLIB. #597.
git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@3720 0d517254-b314-0410-acde-c619094fa49f
| authentication/plugin-api/src/main/java/edu/northwestern/bioinformatics/studycalendar/security/plugin/AbstractAuthenticationSystem.java | Make AbstractAuthenticationSystem#initialize non-final so that it may be proxied by CGLIB. #597. | <ide><path>uthentication/plugin-api/src/main/java/edu/northwestern/bioinformatics/studycalendar/security/plugin/AbstractAuthenticationSystem.java
<ide> return getClass().getSimpleName().replaceAll("AuthenticationSystem", "");
<ide> }
<ide>
<del> public final void initialize(
<add> /**
<add> * Initializes this authentication system using the values provided by the template methods.
<add> * <p>
<add> * When using this base class, you should generally <em>not</em> override this method, but
<add> * rather the individual template methods.
<add> *
<add> * @param parent the system application context
<add> * @param config
<add> * @throws AuthenticationSystemInitializationFailure
<add> * @throws StudyCalendarValidationException
<add> */
<add> public void initialize(
<ide> ApplicationContext parent, Configuration config
<ide> ) throws AuthenticationSystemInitializationFailure, StudyCalendarValidationException {
<ide> try { |
|
JavaScript | mit | ea487af011c49851a5034fc2ddd44202ce2a12c4 | 0 | dennischiangb/XMPApp,dennischiangb/XMPApp | const lib = require('lib')({token: process.env.STDLIB_TOKEN});
const GoogleSpreadsheet = require('google-spreadsheet');
const creds = require('../../sheetsAPI/client_secret.json');
const team = {
dennis: 'U0545PDQ3',
rodrigo: 'U0DU10LAU',
roger: 'U75RRPETH',
alejandro: 'U0408Q8R0',
amec: 'U707X17U3',
emily: 'U6XAQ854Y'
};
/**
* /hello
*
* Basic "Hello World" command.
* All Commands use this template, simply create additional files with
* different names to add commands.
*
* See https://api.slack.com/slash-commands for more details.
*
* @param {string} user The user id of the user that invoked this command (name is usable as well)
* @param {string} channel The channel id the command was executed in (name is usable as well)
* @param {string} text The text contents of the command
* @param {object} command The full Slack command object
* @param {string} botToken The bot token for the Slack bot you have activated
* @returns {object}
*/
module.exports = (user, channel, text = '', command = {}, botToken = null, callback) => {
if(Object.values(team).indexOf(user) > -1){
text = text.toLowerCase();
//using Google Sheets API to fetch data from spreadsheet
// Create a document object using the ID of the spreadsheet - obtained from its URL.
var doc = new GoogleSpreadsheet('1TORc-LBrt3_oe3mK3j-arickBm01UcqZHhoDBdqo3SU');
// Authenticate with the Google Spreadsheets API.
doc.useServiceAccountAuth(creds, function (err) {
// Get all of the cells from the spreadsheet.
doc.getCells(2, function (err, cells) {
//parse the info; see function definition for more
servers = getServersInfo(cells);
if(servers[text]) {
callback(null, {
response_type: 'ephemeral',
text:"Here are the cases for the month of "+`*${text}*\n`+
'- '+servers[text].number+" *Owner:* "+servers[text].owner+" *Status:* "+servers[text].status+" "+servers[text].link,
});
}
else {
callback(null, {
response_type: 'ephemeral',
text: `I can't find any info for *${text}*`
})
}
});
});
} else {
callback(null, {
response_type: 'ephemeral',
text: `Sorry, this command is exclusive to the XMPie team.`
});
}
//function to parse server login data recieved from google sheets
function getServersInfo(data) {
result = {};
for (var i = 0; i < data.length; i++) {
//start with the fisrt cell of each row; "data[i].row > 1" ignores the first row which is just labels
if(data[i].col == 1 && data[i].row > 1) {
/*
* here we constrcuct a new object for each server
* looks something like this:
*
* serverName : {
* ip: 192.168.168.168,
* user: username,
* password: password
* }
*
*/
result[data[i].value] = {
number : data[i+1] ? data[i+1].value : 'not provided',
link : data[i+2] ? data[i+2].value : 'not provided',
owner : data[i+3] ? data[i+3].value : 'not provided',
status : data[i+4] ? data[i+4].value : 'not provided'
}
}
}
return result;
};
};
| functions/commands/xmcases.js | const lib = require('lib')({token: process.env.STDLIB_TOKEN});
const GoogleSpreadsheet = require('google-spreadsheet');
const creds = require('../../sheetsAPI/client_secret.json');
const team = {
dennis: 'U0545PDQ3',
rodrigo: 'U0DU10LAU',
roger: 'U75RRPETH',
alejandro: 'U0408Q8R0',
amec: 'U707X17U3',
emily: 'U6XAQ854Y'
};
/**
* /hello
*
* Basic "Hello World" command.
* All Commands use this template, simply create additional files with
* different names to add commands.
*
* See https://api.slack.com/slash-commands for more details.
*
* @param {string} user The user id of the user that invoked this command (name is usable as well)
* @param {string} channel The channel id the command was executed in (name is usable as well)
* @param {string} text The text contents of the command
* @param {object} command The full Slack command object
* @param {string} botToken The bot token for the Slack bot you have activated
* @returns {object}
*/
module.exports = (user, channel, text = '', command = {}, botToken = null, callback) => {
if(Object.values(team).indexOf(user) > -1){
text = text.toLowerCase();
//using Google Sheets API to fetch data from spreadsheet
// Create a document object using the ID of the spreadsheet - obtained from its URL.
var doc = new GoogleSpreadsheet('1TORc-LBrt3_oe3mK3j-arickBm01UcqZHhoDBdqo3SU');
// Authenticate with the Google Spreadsheets API.
doc.useServiceAccountAuth(creds, function (err) {
// Get all of the cells from the spreadsheet.
doc.getCells(2, function (err, cells) {
//parse the info; see function definition for more
servers = getServersInfo(cells);
if(servers[text]) {
callback(null, {
response_type: 'ephemeral',
text: `Hey <@${user}> here are the Salesforce cases for the month of *${text}*:`,
attachments: [
{
fallback: `Hey <@${user}>, good luck`,
color: "good",
fields: [
{
title: 'Case Number',
value: servers[text].number,
short: false
},
{
title: 'Case Link',
value: servers[text].link,
short: true
},
{
title: 'Case Owner',
value: servers[text].owner,
short: true
},
{
title: 'Case Status',
value: servers[text].status,
short: true
}
]
},
]
});
}
else {
callback(null, {
response_type: 'ephemeral',
text: `I can't find any info on the *${text}* server`
})
}
});
});
} else {
callback(null, {
response_type: 'ephemeral',
text: `Sorry, this command is exclusive to the XMPie team.`
});
}
//function to parse server login data recieved from google sheets
function getServersInfo(data) {
result = {};
for (var i = 0; i < data.length; i++) {
//start with the fisrt cell of each row; "data[i].row > 1" ignores the first row which is just labels
if(data[i].col == 1 && data[i].row > 1) {
/*
* here we constrcuct a new object for each server
* looks something like this:
*
* serverName : {
* ip: 192.168.168.168,
* user: username,
* password: password
* }
*
*/
result[data[i].value] = {
number : data[i+1] ? data[i+1].value : 'not provided',
link : data[i+2] ? data[i+2].value : 'not provided',
owner : data[i+3] ? data[i+3].value : 'not provided',
status : data[i+4] ? data[i+4].value : 'not provided'
}
}
}
return result;
};
};
| mixtape, coming soon, 2078
| functions/commands/xmcases.js | mixtape, coming soon, 2078 | <ide><path>unctions/commands/xmcases.js
<ide> if(servers[text]) {
<ide> callback(null, {
<ide> response_type: 'ephemeral',
<del> text: `Hey <@${user}> here are the Salesforce cases for the month of *${text}*:`,
<del> attachments: [
<del> {
<del> fallback: `Hey <@${user}>, good luck`,
<del> color: "good",
<del> fields: [
<del> {
<del> title: 'Case Number',
<del> value: servers[text].number,
<del> short: false
<del> },
<del> {
<del> title: 'Case Link',
<del> value: servers[text].link,
<del> short: true
<del> },
<del> {
<del> title: 'Case Owner',
<del> value: servers[text].owner,
<del> short: true
<del> },
<del> {
<del> title: 'Case Status',
<del> value: servers[text].status,
<del> short: true
<del> }
<del> ]
<del> },
<del> ]
<add> text:"Here are the cases for the month of "+`*${text}*\n`+
<add> '- '+servers[text].number+" *Owner:* "+servers[text].owner+" *Status:* "+servers[text].status+" "+servers[text].link,
<ide> });
<ide> }
<ide> else {
<ide> callback(null, {
<ide> response_type: 'ephemeral',
<del> text: `I can't find any info on the *${text}* server`
<add> text: `I can't find any info for *${text}*`
<ide> })
<ide> }
<ide> }); |
|
Java | mit | error: pathspec 'Network.java' did not match any file(s) known to git
| 3980bb3bc1f92efb6030cc9aea91e7af021f67bb | 1 | Batev/Vienna-University-of-Technology,Batev/Vienna-University-of-Technology | package ad1.ss16.pa;
import java.util.*;
public class Network {
private ArrayList<HashSet<Integer>> graph;
private final int length;
private int criticalTime;
private static final int special = -1;
public Network(int n) {
this.graph = new ArrayList<>(n);
this.length = n;
this.criticalTime = 0;
for (int i = 0; i < n; i++) {
this.graph.add(new HashSet<>());
}
}
public ArrayList<HashSet<Integer>> getGraph() {
return this.graph;
}
public int numberOfNodes() {
return this.length;
}
public int numberOfConnections() {
int count = 0;
for (int i = 0; i < this.length; i++) {
count += this.graph.get(i).size();
}
return (count / 2);
}
public void addConnection(int v, int w) {
boolean edgeIsValid = (v < this.length) && (v >= 0) &&
(w < this.length) && (w >= 0) && (w != v) &&
(!this.graph.get(v).contains(w));
if (edgeIsValid) {
this.graph.get(v).add(w);
this.graph.get(w).add(v);
}
}
public void addAllConnections(int v) {
for (int i = 0; i < this.length; i++) {
this.addConnection(v, i);
}
}
public void deleteConnection(int v, int w) {
boolean edgeIsValid = (v < this.length) && (v >= 0) &&
(w < this.length) && (w >= 0) && (w != v) &&
(this.graph.get(v).contains(w));
if (edgeIsValid) {
this.graph.get(v).remove(w);
this.graph.get(w).remove(v);
}
}
public void deleteAllConnections(int v) {
if (!this.graph.get(v).isEmpty()) {
for (int i = 0; i < this.length; i++) {
this.deleteConnection(v, i);
}
}
}
private void dfsCount(boolean[] visited, int start) {
visited[start] = true;
for (int node : this.graph.get(start)) {
if (!visited[node]) {
dfsCount(visited, node);
}
}
}
public int numberOfComponents() {
boolean[] visited = new boolean[this.length];
int count = 0;
for (int i = 0; i < this.graph.size(); i++) {
if (!visited[i]) {
count++;
dfsCount(visited, i);
}
}
return count;
}
private boolean dfsCycle(boolean[] visited, int current, int parent) {
visited[current] = true;
for (int node : this.graph.get(current)) {
if (!visited[node]) {
if (dfsCycle(visited, node, current)) {
return true;
}
} else if (node != parent) {
return true;
}
}
return false;
}
public boolean hasCycle() {
boolean[] visited = new boolean[this.length];
for (int i = 0; i < this.length; i++) {
if (!visited[i]) {
if (dfsCycle(visited, i, special)) {
return true;
}
}
}
return false;
}
private int bfsLength(boolean[] visited, int start, int end) {
Queue<Integer> queue = new LinkedList<>();
queue.add(start);
queue.add(special);
visited[start] = true;
int level = 0;
while (!queue.isEmpty()) {
start = queue.remove();
if (start == special) {
if (queue.isEmpty()) {
return special;
} else {
queue.add(start);
level++;
}
} else if (start == end) {
return level;
} else {
for (int node : this.graph.get(start)) {
if (!visited[node]) {
visited[node] = true;
queue.add(node);
}
}
}
}
return special;
}
public int minimalNumberOfConnections(int start, int end) {
boolean edgeIsValid = (start < this.length) && (start >= 0) && (end < this.length) && (end >= 0);
if (edgeIsValid) {
if (start == end) {
return 0;
} else {
boolean[] visited = new boolean[this.length];
return bfsLength(visited, start, end);
}
}
return special;
}
public List<Integer> criticalNodes() {
List<Integer> critical = new LinkedList<>();
int parents[] = new int[this.length]; // array to store the parent of each node
for (int i = 0; i < this.length; i++) {
parents[i] = special;
}
int visitedTimes[] = new int[this.length];
int lowTimes[] = new int[this.length];
boolean visited[] = new boolean[this.length];
for (int i = 0; i < this.length; i++) {
if (!visited[i]) {
criticalDfs(i, critical, visitedTimes, lowTimes, visited, parents);
}
}
return critical;
}
private void criticalDfs(int next, List<Integer> critical, int visitedTimes[], int lowTimes[], boolean visited[], int parents[]) {
int children = 0;
visited[next] = true;
visitedTimes[next] = lowTimes[next] = ++criticalTime;
for (int current : this.graph.get(next)) {
if (!visited[current]) {
children++;
parents[current] = next;
criticalDfs(current, critical, visitedTimes, lowTimes, visited, parents);
lowTimes[next] = this.minNumber(lowTimes[next], lowTimes[current]);
if (parents[next] == special && children > 1 && (!critical.contains(next))) {
critical.add(next);
} else if (parents[next] != special && lowTimes[current] >= visitedTimes[next] && (!critical.contains(next))) {
critical.add(next);
}
} else if (current != parents[next]) {
lowTimes[next] = minNumber(lowTimes[next], visitedTimes[current]);
}
}
}
private int minNumber(int a, int b) {
return (a <= b) ? a : b;
}
public List<Integer> criticalNodesIter() {
List<Integer> critical = new LinkedList<>();
int after;
boolean hasCycle = this.hasCycle();
for (int i = 0; i < this.length; i++) {
if ((!hasCycle) && this.graph.get(i).size() > 1) {
critical.add(i);
}
else if(this.graph.get(i).size() > 1) {
after = this.criticalNumberOfComponents(i, this.graph.get(i));
if (after > 1) {
critical.add(i);
}
}
}
return critical;
}
private int criticalNumberOfComponents(int current, HashSet<Integer> temp) {
boolean[] visited = new boolean[this.length];
visited[current] = true;
int count = 0;
for(int node : temp) {
if (!visited[node]) {
count++;
if (count > 1) {
break;
}
else {
bfs(visited, node);
}
}
}
return count;
}
private void bfs(boolean[] visited, int start) {
Queue<Integer> queue = new LinkedList<>();
queue.add(start);
visited[start] = true;
while (!queue.isEmpty()) {
start = queue.remove();
for (int w : this.graph.get(start)) {
if(!visited[w]) {
visited[w] = true;
queue.add(w);
}
}
}
}
public static void main(String[] args) {
Network test = new Network(13);
test.addConnection(0, 1);
test.addConnection(0, 2);
test.addConnection(0, 6);
test.addConnection(1, 3);
test.addConnection(1, 4);
test.addConnection(2, 4);
test.addConnection(2, 6);
test.addConnection(2, 7);
test.addConnection(3, 4);
test.addConnection(4, 5);
test.addConnection(6, 7);
test.addConnection(8, 9);
test.addConnection(8, 10);
test.addConnection(9, 10);
test.addConnection(10, 11);
test.addConnection(11, 12);
System.out.println("numberOfNodes(): " + test.numberOfNodes());
System.out.println("numberOfConnections(): " + test.numberOfConnections());
System.out.println("numberOfComponents(): " + test.numberOfComponents());
System.out.println("hasCycle(): " + test.hasCycle());
System.out.println("minimalNumberOfConnections(0, 5): " + test.minimalNumberOfConnections(0, 5));
System.out.println("minimalNumberOfConnections(0, 9): " + test.minimalNumberOfConnections(0, 9));
System.out.println("criticalNodes(): " + test.criticalNodes());
System.out.println("criticalNodesIter(): " + test.criticalNodesIter());
System.out.println("All connections: ");
for (int i = 0; i < test.numberOfNodes(); i++) {
for (int number : test.getGraph().get(i)) {
System.out.println(i + " -> " + number);
}
}
}
} | Network.java | Network | Network.java | Network | <ide><path>etwork.java
<add>package ad1.ss16.pa;
<add>
<add>import java.util.*;
<add>
<add>public class Network {
<add>
<add> private ArrayList<HashSet<Integer>> graph;
<add> private final int length;
<add> private int criticalTime;
<add> private static final int special = -1;
<add>
<add> public Network(int n) {
<add> this.graph = new ArrayList<>(n);
<add> this.length = n;
<add> this.criticalTime = 0;
<add>
<add> for (int i = 0; i < n; i++) {
<add> this.graph.add(new HashSet<>());
<add> }
<add> }
<add>
<add> public ArrayList<HashSet<Integer>> getGraph() {
<add> return this.graph;
<add> }
<add>
<add> public int numberOfNodes() {
<add> return this.length;
<add> }
<add>
<add> public int numberOfConnections() {
<add> int count = 0;
<add> for (int i = 0; i < this.length; i++) {
<add> count += this.graph.get(i).size();
<add> }
<add> return (count / 2);
<add> }
<add>
<add> public void addConnection(int v, int w) {
<add> boolean edgeIsValid = (v < this.length) && (v >= 0) &&
<add> (w < this.length) && (w >= 0) && (w != v) &&
<add> (!this.graph.get(v).contains(w));
<add> if (edgeIsValid) {
<add>
<add> this.graph.get(v).add(w);
<add> this.graph.get(w).add(v);
<add> }
<add> }
<add>
<add> public void addAllConnections(int v) {
<add> for (int i = 0; i < this.length; i++) {
<add> this.addConnection(v, i);
<add> }
<add> }
<add>
<add> public void deleteConnection(int v, int w) {
<add> boolean edgeIsValid = (v < this.length) && (v >= 0) &&
<add> (w < this.length) && (w >= 0) && (w != v) &&
<add> (this.graph.get(v).contains(w));
<add> if (edgeIsValid) {
<add> this.graph.get(v).remove(w);
<add> this.graph.get(w).remove(v);
<add> }
<add> }
<add>
<add> public void deleteAllConnections(int v) {
<add> if (!this.graph.get(v).isEmpty()) {
<add> for (int i = 0; i < this.length; i++) {
<add> this.deleteConnection(v, i);
<add> }
<add> }
<add> }
<add>
<add> private void dfsCount(boolean[] visited, int start) {
<add> visited[start] = true;
<add> for (int node : this.graph.get(start)) {
<add> if (!visited[node]) {
<add> dfsCount(visited, node);
<add> }
<add> }
<add> }
<add>
<add> public int numberOfComponents() {
<add> boolean[] visited = new boolean[this.length];
<add> int count = 0;
<add> for (int i = 0; i < this.graph.size(); i++) {
<add> if (!visited[i]) {
<add> count++;
<add> dfsCount(visited, i);
<add> }
<add> }
<add> return count;
<add> }
<add>
<add> private boolean dfsCycle(boolean[] visited, int current, int parent) {
<add> visited[current] = true;
<add> for (int node : this.graph.get(current)) {
<add> if (!visited[node]) {
<add> if (dfsCycle(visited, node, current)) {
<add> return true;
<add> }
<add> } else if (node != parent) {
<add> return true;
<add> }
<add> }
<add> return false;
<add> }
<add>
<add> public boolean hasCycle() {
<add> boolean[] visited = new boolean[this.length];
<add> for (int i = 0; i < this.length; i++) {
<add> if (!visited[i]) {
<add> if (dfsCycle(visited, i, special)) {
<add> return true;
<add> }
<add> }
<add> }
<add> return false;
<add> }
<add>
<add> private int bfsLength(boolean[] visited, int start, int end) {
<add> Queue<Integer> queue = new LinkedList<>();
<add> queue.add(start);
<add> queue.add(special);
<add> visited[start] = true;
<add> int level = 0;
<add> while (!queue.isEmpty()) {
<add> start = queue.remove();
<add> if (start == special) {
<add> if (queue.isEmpty()) {
<add> return special;
<add> } else {
<add> queue.add(start);
<add> level++;
<add> }
<add> } else if (start == end) {
<add> return level;
<add> } else {
<add> for (int node : this.graph.get(start)) {
<add> if (!visited[node]) {
<add> visited[node] = true;
<add> queue.add(node);
<add>
<add> }
<add> }
<add> }
<add> }
<add> return special;
<add> }
<add>
<add> public int minimalNumberOfConnections(int start, int end) {
<add> boolean edgeIsValid = (start < this.length) && (start >= 0) && (end < this.length) && (end >= 0);
<add> if (edgeIsValid) {
<add> if (start == end) {
<add> return 0;
<add> } else {
<add> boolean[] visited = new boolean[this.length];
<add> return bfsLength(visited, start, end);
<add> }
<add> }
<add> return special;
<add> }
<add>
<add> public List<Integer> criticalNodes() {
<add> List<Integer> critical = new LinkedList<>();
<add> int parents[] = new int[this.length]; // array to store the parent of each node
<add>
<add> for (int i = 0; i < this.length; i++) {
<add> parents[i] = special;
<add> }
<add>
<add> int visitedTimes[] = new int[this.length];
<add> int lowTimes[] = new int[this.length];
<add> boolean visited[] = new boolean[this.length];
<add>
<add> for (int i = 0; i < this.length; i++) {
<add> if (!visited[i]) {
<add> criticalDfs(i, critical, visitedTimes, lowTimes, visited, parents);
<add> }
<add> }
<add> return critical;
<add> }
<add>
<add> private void criticalDfs(int next, List<Integer> critical, int visitedTimes[], int lowTimes[], boolean visited[], int parents[]) {
<add>
<add> int children = 0;
<add> visited[next] = true;
<add> visitedTimes[next] = lowTimes[next] = ++criticalTime;
<add> for (int current : this.graph.get(next)) {
<add> if (!visited[current]) {
<add> children++;
<add> parents[current] = next;
<add> criticalDfs(current, critical, visitedTimes, lowTimes, visited, parents);
<add> lowTimes[next] = this.minNumber(lowTimes[next], lowTimes[current]);
<add>
<add> if (parents[next] == special && children > 1 && (!critical.contains(next))) {
<add> critical.add(next);
<add> } else if (parents[next] != special && lowTimes[current] >= visitedTimes[next] && (!critical.contains(next))) {
<add> critical.add(next);
<add> }
<add> } else if (current != parents[next]) {
<add> lowTimes[next] = minNumber(lowTimes[next], visitedTimes[current]);
<add> }
<add> }
<add> }
<add>
<add> private int minNumber(int a, int b) {
<add> return (a <= b) ? a : b;
<add> }
<add>
<add> public List<Integer> criticalNodesIter() {
<add> List<Integer> critical = new LinkedList<>();
<add> int after;
<add> boolean hasCycle = this.hasCycle();
<add> for (int i = 0; i < this.length; i++) {
<add> if ((!hasCycle) && this.graph.get(i).size() > 1) {
<add> critical.add(i);
<add> }
<add> else if(this.graph.get(i).size() > 1) {
<add> after = this.criticalNumberOfComponents(i, this.graph.get(i));
<add> if (after > 1) {
<add> critical.add(i);
<add> }
<add> }
<add> }
<add> return critical;
<add> }
<add>
<add> private int criticalNumberOfComponents(int current, HashSet<Integer> temp) {
<add> boolean[] visited = new boolean[this.length];
<add> visited[current] = true;
<add> int count = 0;
<add> for(int node : temp) {
<add> if (!visited[node]) {
<add> count++;
<add> if (count > 1) {
<add> break;
<add> }
<add> else {
<add> bfs(visited, node);
<add> }
<add> }
<add> }
<add> return count;
<add> }
<add>
<add> private void bfs(boolean[] visited, int start) {
<add> Queue<Integer> queue = new LinkedList<>();
<add> queue.add(start);
<add> visited[start] = true;
<add> while (!queue.isEmpty()) {
<add> start = queue.remove();
<add> for (int w : this.graph.get(start)) {
<add> if(!visited[w]) {
<add> visited[w] = true;
<add> queue.add(w);
<add> }
<add> }
<add> }
<add> }
<add>
<add>
<add> public static void main(String[] args) {
<add> Network test = new Network(13);
<add>
<add> test.addConnection(0, 1);
<add> test.addConnection(0, 2);
<add> test.addConnection(0, 6);
<add> test.addConnection(1, 3);
<add> test.addConnection(1, 4);
<add> test.addConnection(2, 4);
<add> test.addConnection(2, 6);
<add> test.addConnection(2, 7);
<add> test.addConnection(3, 4);
<add> test.addConnection(4, 5);
<add> test.addConnection(6, 7);
<add> test.addConnection(8, 9);
<add> test.addConnection(8, 10);
<add> test.addConnection(9, 10);
<add> test.addConnection(10, 11);
<add> test.addConnection(11, 12);
<add>
<add> System.out.println("numberOfNodes(): " + test.numberOfNodes());
<add> System.out.println("numberOfConnections(): " + test.numberOfConnections());
<add> System.out.println("numberOfComponents(): " + test.numberOfComponents());
<add> System.out.println("hasCycle(): " + test.hasCycle());
<add> System.out.println("minimalNumberOfConnections(0, 5): " + test.minimalNumberOfConnections(0, 5));
<add> System.out.println("minimalNumberOfConnections(0, 9): " + test.minimalNumberOfConnections(0, 9));
<add> System.out.println("criticalNodes(): " + test.criticalNodes());
<add> System.out.println("criticalNodesIter(): " + test.criticalNodesIter());
<add>
<add> System.out.println("All connections: ");
<add> for (int i = 0; i < test.numberOfNodes(); i++) {
<add> for (int number : test.getGraph().get(i)) {
<add> System.out.println(i + " -> " + number);
<add> }
<add> }
<add> }
<add>} |
|
JavaScript | mit | f5c89f8b6b810711e20efb1291a3651009c65987 | 0 | UKForeignOffice/loi-payment-service |
// =====================================
// SETUP
// =====================================
const port = (process.argv[2] && !isNaN(process.argv[2]) ? process.argv[2] : (process.env.PORT || 4321));
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const morgan = require('morgan');
const cookieParser = require('cookie-parser');
const common = require('./config/common.js');
const configGovPay = common.config();
// =====================================
// CONFIGURATION
// =====================================
require('./config/logs');
app.use(bodyParser()); //get information from HTML forms
app.use(cookieParser());
const session = require("express-session")
let RedisStore = require("connect-redis")(session)
const { createClient } = require("redis")
let redisClient = createClient({
legacyMode: true,
password: configGovPay.sessionSettings.password,
socket: {
port: configGovPay.sessionSettings.port,
host: configGovPay.sessionSettings.host,
tls: process.env.NODE_ENV !== 'development'
}
})
redisClient.connect().catch(console.error)
app.use(
session({
store: new RedisStore({ client: redisClient }),
prefix: configGovPay.sessionSettings.prefix,
saveUninitialized: false,
secret: configGovPay.sessionSettings.secret,
key: configGovPay.sessionSettings.key,
resave: false,
rolling: true,
cookie: {
domain: configGovPay.sessionSettings.domain,
maxAge: configGovPay.sessionSettings.maxAge,
secure: 'auto'
}
})
)
app.set('view engine', 'ejs');
app.use(function (req, res, next) {
res.locals = {
piwikID: configGovPay.live_variables.piwikId,
feedbackURL:configGovPay.live_variables.feedbackURL,
service_public: configGovPay.live_variables.Public,
start_url: configGovPay.live_variables.startPageURL,
govuk_url: configGovPay.live_variables.GOVUKURL
};
next();
});
app.use(function(req, res, next) {
if (req.cookies['LoggedIn']){
res.cookie('LoggedIn',true,{ maxAge: 1800000, httpOnly: true });
}
return next();
});
app.use(morgan('dev')); //log every request to the console
app.use(function(req, res, next) {
res.removeHeader("X-Powered-By");
res.removeHeader("Server");
return next();
});
// =====================================
// MODELS (Sequelize ORM)
// =====================================
app.set('models', require('./models'));
// =====================================
// ASSETS
// =====================================
const path = require('path');
app.use("/api/payment/",express.static(__dirname + "/public"));
app.use("/api/payment/styles",express.static(__dirname + "/styles")); //static directory for stylesheets
app.use("/api/payment/images",express.static(__dirname + "/images")); //static directory for images
// =====================================
// ROUTES
// =====================================
const router = express.Router(); //get instance of Express router
require('./app/routes.js')(router, configGovPay, app); //load routes passing in app and configuration
app.use('/api/payment', router); //prefix all requests with 'api/payment'
//Pull in images from GOVUK packages
const fs = require('fs-extra');
fs.copy('node_modules/govuk_frontend_toolkit/images', 'images/govuk_frontend_toolkit', function (err) {
if (err) return null;
});
fs.mkdirs('images/govuk_frontend_toolkit/icons', function (err) {
if (err) return null;
});
fs.readdir('images/govuk_frontend_toolkit', function(err, items) {
for (var i=0; i<items.length; i++) {
if('images/govuk_frontend_toolkit/'+items[i].substr(0,5)=='images/govuk_frontend_toolkit/icon-' && items[i].substr(items[i].length-3,3)=='png'){
fs.move('images/govuk_frontend_toolkit/'+items[i], 'images/govuk_frontend_toolkit/icons/'+items[i],{ clobber: true }, function (err) {
if (err) return null;
});
}
}
});
// =====================================
// JOB SCHEDULER
// =====================================
//Schedule and run account expiry job every day
const schedule = require('node-schedule');
const jobs = require('./config/jobs.js');
// As there are 2 instances running, we need a random time, or the job will be executed on both instances
const randomSecond = Math.floor(Math.random() * 60);
const randomMin = Math.floor(Math.random() * 60); //Math.random returns a number from 0 to < 1 (never will return 60)
const jobScheduleRandom = randomSecond + " " + randomMin + " " + "*/" + configGovPay.configs.jobScheduleHourlyInterval + " * * *";
const paymentCleanup = schedule.scheduleJob(jobScheduleRandom, function(){jobs.paymentCleanup()});
// =====================================
// LAUNCH
// =====================================
app.listen(port);
console.log('is-payment-service running on port: ' + port);
console.log('payment cleanup job will run every %s hours at %sm %ss past the hour', configGovPay.configs.jobScheduleHourlyInterval, randomMin, randomSecond);
module.exports.getApp = app;
| server.js |
// =====================================
// SETUP
// =====================================
const port = (process.argv[2] && !isNaN(process.argv[2]) ? process.argv[2] : (process.env.PORT || 4321));
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const morgan = require('morgan');
const cookieParser = require('cookie-parser');
const common = require('./config/common.js');
const configGovPay = common.config();
// =====================================
// CONFIGURATION
// =====================================
require('./config/logs');
app.use(bodyParser()); //get information from HTML forms
app.use(cookieParser());
const session = require("express-session")
let RedisStore = require("connect-redis")(session)
const { createClient } = require("redis")
let redisClient = createClient({
legacyMode: true,
password: configGovPay.sessionSettings.password,
socket: {
port: configGovPay.sessionSettings.port,
host: configGovPay.sessionSettings.host,
tls: process.env.NODE_ENV !== 'development'
}
})
redisClient.connect().catch(console.error)
app.use(
session({
store: new RedisStore({ client: redisClient }),
prefix: configGovPay.sessionSettings.prefix,
saveUninitialized: false,
secret: configGovPay.sessionSettings.secret,
key: configGovPay.sessionSettings.key,
resave: false,
rolling: true,
cookie: {
domain: configGovPay.sessionSettings.domain,
maxAge: configGovPay.sessionSettings.maxAge,
secure: 'auto'
}
})
)
app.set('view engine', 'ejs');
app.use(function (req, res, next) {
res.locals = {
piwikID: configGovPay.live_variables.piwikId,
feedbackURL:configGovPay.live_variables.Public ? configGovPay.live_variables.feedbackURL : "https://www.smartsurvey.co.uk/s/legalisation1/",
service_public: configGovPay.live_variables.Public,
start_url: configGovPay.live_variables.startPageURL,
govuk_url: configGovPay.live_variables.GOVUKURL
};
next();
});
app.use(function(req, res, next) {
if (req.cookies['LoggedIn']){
res.cookie('LoggedIn',true,{ maxAge: 1800000, httpOnly: true });
}
return next();
});
app.use(morgan('dev')); //log every request to the console
app.use(function(req, res, next) {
res.removeHeader("X-Powered-By");
res.removeHeader("Server");
return next();
});
// =====================================
// MODELS (Sequelize ORM)
// =====================================
app.set('models', require('./models'));
// =====================================
// ASSETS
// =====================================
const path = require('path');
app.use("/api/payment/",express.static(__dirname + "/public"));
app.use("/api/payment/styles",express.static(__dirname + "/styles")); //static directory for stylesheets
app.use("/api/payment/images",express.static(__dirname + "/images")); //static directory for images
// =====================================
// ROUTES
// =====================================
const router = express.Router(); //get instance of Express router
require('./app/routes.js')(router, configGovPay, app); //load routes passing in app and configuration
app.use('/api/payment', router); //prefix all requests with 'api/payment'
//Pull in images from GOVUK packages
const fs = require('fs-extra');
fs.copy('node_modules/govuk_frontend_toolkit/images', 'images/govuk_frontend_toolkit', function (err) {
if (err) return null;
});
fs.mkdirs('images/govuk_frontend_toolkit/icons', function (err) {
if (err) return null;
});
fs.readdir('images/govuk_frontend_toolkit', function(err, items) {
for (var i=0; i<items.length; i++) {
if('images/govuk_frontend_toolkit/'+items[i].substr(0,5)=='images/govuk_frontend_toolkit/icon-' && items[i].substr(items[i].length-3,3)=='png'){
fs.move('images/govuk_frontend_toolkit/'+items[i], 'images/govuk_frontend_toolkit/icons/'+items[i],{ clobber: true }, function (err) {
if (err) return null;
});
}
}
});
// =====================================
// JOB SCHEDULER
// =====================================
//Schedule and run account expiry job every day
const schedule = require('node-schedule');
const jobs = require('./config/jobs.js');
// As there are 2 instances running, we need a random time, or the job will be executed on both instances
const randomSecond = Math.floor(Math.random() * 60);
const randomMin = Math.floor(Math.random() * 60); //Math.random returns a number from 0 to < 1 (never will return 60)
const jobScheduleRandom = randomSecond + " " + randomMin + " " + "*/" + configGovPay.configs.jobScheduleHourlyInterval + " * * *";
const paymentCleanup = schedule.scheduleJob(jobScheduleRandom, function(){jobs.paymentCleanup()});
// =====================================
// LAUNCH
// =====================================
app.listen(port);
console.log('is-payment-service running on port: ' + port);
console.log('payment cleanup job will run every %s hours at %sm %ss past the hour', configGovPay.configs.jobScheduleHourlyInterval, randomMin, randomSecond);
module.exports.getApp = app;
| Removed conditional
| server.js | Removed conditional | <ide><path>erver.js
<ide> app.use(function (req, res, next) {
<ide> res.locals = {
<ide> piwikID: configGovPay.live_variables.piwikId,
<del> feedbackURL:configGovPay.live_variables.Public ? configGovPay.live_variables.feedbackURL : "https://www.smartsurvey.co.uk/s/legalisation1/",
<add> feedbackURL:configGovPay.live_variables.feedbackURL,
<ide> service_public: configGovPay.live_variables.Public,
<ide> start_url: configGovPay.live_variables.startPageURL,
<ide> govuk_url: configGovPay.live_variables.GOVUKURL |
|
Java | apache-2.0 | 993d3ddaa17281f63536fa476a57d8e6c0e028f6 | 0 | opensingular/singular-core,opensingular/singular-core,opensingular/singular-core,opensingular/singular-core | package br.net.mirante.singular.form.mform;
import java.util.Objects;
public class SISimple<TIPO_NATIVO> extends SInstance {
private TIPO_NATIVO valor;
protected SISimple() {}
@Override
public TIPO_NATIVO getValue() {
return valor;
}
@Override
public void clearInstance() {
setValue(null);
}
@Override
public TIPO_NATIVO getValorWithDefault() {
TIPO_NATIVO v = getValue();
if (v == null) {
return getType().converter(getType().getValorAtributoOrDefaultValueIfNull());
}
return v;
}
@Override
final <T extends Object> T getValorWithDefaultIfNull(PathReader leitor, Class<T> classeDestino) {
if (!leitor.isEmpty()) {
throw new RuntimeException("Não ser aplica path a um tipo simples");
}
return getValorWithDefault(classeDestino);
}
@Override
protected void resetValue() {
setValue(null);
}
/** Indica que o valor da instância atual é null. */
public boolean isNull() {
return getValue() == null;
}
@Override
public boolean isEmptyOfData() {
return getValue() == null;
}
@Override
public final void setValue(Object valor) {
TIPO_NATIVO oldValue = this.getValue();
TIPO_NATIVO newValue = getType().converter(valor);
this.valor = onSetValor(oldValue, newValue);
if (getDocument() != null && !Objects.equals(oldValue, newValue)) {
if (isAttribute()) {
getDocument().getInstanceListeners().fireInstanceAttributeChanged(getAttributeOwner(), this, oldValue, newValue);
} else {
getDocument().getInstanceListeners().fireInstanceValueChanged(this, oldValue, newValue);
}
}
}
protected TIPO_NATIVO onSetValor(TIPO_NATIVO oldValue, TIPO_NATIVO newValue) {
return newValue;
}
@Override
@SuppressWarnings("unchecked")
public STypeSimple<?, TIPO_NATIVO> getType() {
return (STypeSimple<?, TIPO_NATIVO>) super.getType();
}
@Override
public String getDisplayString() {
if (getType().getProviderOpcoes() != null) {
String key = getOptionsConfig().getKeyFromOption(this);
return getOptionsConfig().getLabelFromKey(key);
} else {
return getType().toStringDisplay(getValue());
}
}
public String toStringPersistencia() {
if (getValue() == null) {
return null;
}
return getType().toStringPersistencia(getValue());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getType() == null) ? 0 : getType().hashCode());
result = prime * result + ((getValue() == null) ? 0 : getValue().hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SISimple<?> other = (SISimple<?>) obj;
if (!getType().equals(other.getType())
&& !getType().getName().equals(other.getType().getName())) {
return false;
}
if (getValue() == null) {
if (other.getValue() != null)
return false;
} else if (!getValue().equals(other.getValue()))
return false;
return true;
}
}
| form/core/src/main/java/br/net/mirante/singular/form/mform/SISimple.java | package br.net.mirante.singular.form.mform;
import java.util.Objects;
public class SISimple<TIPO_NATIVO> extends SInstance {
private TIPO_NATIVO valor;
protected SISimple() {}
@Override
public TIPO_NATIVO getValue() {
return valor;
}
@Override
public void clearInstance() {
setValue(null);
}
@Override
public TIPO_NATIVO getValorWithDefault() {
TIPO_NATIVO v = getValue();
if (v == null) {
return getType().converter(getType().getValorAtributoOrDefaultValueIfNull());
}
return v;
}
@Override
final <T extends Object> T getValorWithDefaultIfNull(PathReader leitor, Class<T> classeDestino) {
if (!leitor.isEmpty()) {
throw new RuntimeException("Não ser aplica path a um tipo simples");
}
return getValorWithDefault(classeDestino);
}
@Override
protected void resetValue() {
setValue(null);
}
/** Indica que o valor da instância atual é null. */
public boolean isNull() {
return getValue() == null;
}
@Override
public boolean isEmptyOfData() {
return getValue() == null;
}
@Override
public final void setValue(Object valor) {
TIPO_NATIVO oldValue = this.getValue();
TIPO_NATIVO newValue = getType().converter(valor);
this.valor = onSetValor(oldValue, newValue);
if (getDocument() != null && !Objects.equals(oldValue, newValue)) {
if (isAttribute()) {
getDocument().getInstanceListeners().fireInstanceAttributeChanged(getAttributeOwner(), this, oldValue, newValue);
} else {
getDocument().getInstanceListeners().fireInstanceValueChanged(this, oldValue, newValue);
}
}
}
protected TIPO_NATIVO onSetValor(TIPO_NATIVO oldValue, TIPO_NATIVO newValue) {
return newValue;
}
@Override
@SuppressWarnings("unchecked")
public STypeSimple<?, TIPO_NATIVO> getType() {
return (STypeSimple<?, TIPO_NATIVO>) super.getType();
}
@Override
public String getDisplayString() {
if (getType().getProviderOpcoes() != null) {
String key = getOptionsConfig().getKeyFromOptions(this);
return getOptionsConfig().getLabelFromKey(key);
} else {
return getType().toStringDisplay(getValue());
}
}
public String toStringPersistencia() {
if (getValue() == null) {
return null;
}
return getType().toStringPersistencia(getValue());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getType() == null) ? 0 : getType().hashCode());
result = prime * result + ((getValue() == null) ? 0 : getValue().hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SISimple<?> other = (SISimple<?>) obj;
if (!getType().equals(other.getType())
&& !getType().getName().equals(other.getType().getName())) {
return false;
}
if (getValue() == null) {
if (other.getValue() != null)
return false;
} else if (!getValue().equals(other.getValue()))
return false;
return true;
}
}
| Ajuste na chamado do método.
| form/core/src/main/java/br/net/mirante/singular/form/mform/SISimple.java | Ajuste na chamado do método. | <ide><path>orm/core/src/main/java/br/net/mirante/singular/form/mform/SISimple.java
<ide> @Override
<ide> public String getDisplayString() {
<ide> if (getType().getProviderOpcoes() != null) {
<del> String key = getOptionsConfig().getKeyFromOptions(this);
<add> String key = getOptionsConfig().getKeyFromOption(this);
<ide> return getOptionsConfig().getLabelFromKey(key);
<ide> } else {
<ide> return getType().toStringDisplay(getValue()); |
|
Java | apache-2.0 | e831b8b2ac8708a6c68883433ca2f836d8531420 | 0 | vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.content;
import com.yahoo.vespa.config.content.core.StorIntegritycheckerConfig;
import com.yahoo.vespa.config.content.core.StorVisitorConfig;
import com.yahoo.vespa.config.content.StorFilestorConfig;
import com.yahoo.vespa.config.content.core.StorServerConfig;
import com.yahoo.vespa.config.content.PersistenceConfig;
import com.yahoo.config.model.test.MockRoot;
import com.yahoo.documentmodel.NewDocumentType;
import static com.yahoo.vespa.defaults.Defaults.getDefaults;
import com.yahoo.vespa.model.content.cluster.ContentCluster;
import com.yahoo.vespa.model.content.storagecluster.StorageCluster;
import com.yahoo.vespa.model.content.utils.ContentClusterUtils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class StorageClusterTest {
StorageCluster parse(String xml) throws Exception {
MockRoot root = new MockRoot();
root.getDeployState().getDocumentModel().getDocumentManager().add(
new NewDocumentType(new NewDocumentType.Name("music"))
);
root.getDeployState().getDocumentModel().getDocumentManager().add(
new NewDocumentType(new NewDocumentType.Name("movies"))
);
ContentCluster cluster = ContentClusterUtils.createCluster(xml, root);
root.freezeModelTopology();
return cluster.getStorageNodes();
}
@Test
public void testBasics() throws Exception {
StorServerConfig.Builder builder = new StorServerConfig.Builder();
parse("<content id=\"foofighters\"><documents/>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</content>\n").
getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
assertEquals(false, config.is_distributor());
assertEquals("foofighters", config.cluster_name());
}
@Test
public void testMerges() throws Exception {
StorServerConfig.Builder builder = new StorServerConfig.Builder();
parse("" +
"<content id=\"foofighters\">\n" +
" <documents/>" +
" <tuning>" +
" <merges max-per-node=\"1K\" max-queue-size=\"10K\"/>\n" +
" </tuning>" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</content>"
).getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
assertEquals(1024, config.max_merges_per_node());
assertEquals(1024*10, config.max_merge_queue_size());
}
@Test
public void testVisitors() throws Exception {
StorVisitorConfig.Builder builder = new StorVisitorConfig.Builder();
parse(
"<cluster id=\"bees\">\n" +
" <documents/>" +
" <tuning>\n" +
" <visitors thread-count=\"7\" max-queue-size=\"1000\">\n" +
" <max-concurrent fixed=\"42\" variable=\"100\"/>\n" +
" </visitors>\n" +
" </tuning>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>"
).getConfig(builder);
StorVisitorConfig config = new StorVisitorConfig(builder);
assertEquals(42, config.maxconcurrentvisitors_fixed());
assertEquals(100, config.maxconcurrentvisitors_variable());
assertEquals(7, config.visitorthreads());
assertEquals(1000, config.maxvisitorqueuesize());
}
@Test
public void testPersistenceThreads() throws Exception {
StorFilestorConfig.Builder builder = new StorFilestorConfig.Builder();
parse(
"<cluster id=\"bees\">\n" +
" <documents/>" +
" <tuning>\n" +
" <persistence-threads>\n" +
" <thread lowest-priority=\"VERY_LOW\" count=\"2\"/>\n" +
" <thread lowest-priority=\"VERY_HIGH\" count=\"1\"/>\n" +
" <thread count=\"1\"/>\n" +
" </persistence-threads>\n" +
" </tuning>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>"
).getConfig(builder);
StorFilestorConfig config = new StorFilestorConfig(builder);
assertEquals(4, config.num_threads());
assertEquals(false, config.enable_multibit_split_optimalization());
}
@Test
public void testNoPersistenceThreads() throws Exception {
StorFilestorConfig.Builder builder = new StorFilestorConfig.Builder();
parse(
"<cluster id=\"bees\">\n" +
" <documents/>" +
" <tuning>\n" +
" </tuning>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>"
).getConfig(builder);
StorFilestorConfig config = new StorFilestorConfig(builder);
assertEquals(6, config.num_threads());
}
@Test
public void integrity_checker_explicitly_disabled_when_not_running_with_vds_provider() throws Exception {
StorIntegritycheckerConfig.Builder builder = new StorIntegritycheckerConfig.Builder();
parse(
"<cluster id=\"bees\">\n" +
" <documents/>" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>"
).getConfig(builder);
StorIntegritycheckerConfig config = new StorIntegritycheckerConfig(builder);
// '-' --> don't run on the given week day
assertEquals("-------", config.weeklycycle());
}
@Test
public void testCapacity() throws Exception {
String xml =
"<cluster id=\"storage\">\n" +
" <documents/>" +
" <group>\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" <node distribution-key=\"1\" hostalias=\"mockhost\" capacity=\"1.5\"/>\n" +
" <node distribution-key=\"2\" hostalias=\"mockhost\" capacity=\"2.0\"/>\n" +
" </group>\n" +
"</cluster>";
ContentCluster cluster = ContentClusterUtils.createCluster(xml, new MockRoot());
for (int i = 0; i < 3; ++i) {
StorageNode node = cluster.getStorageNodes().getChildren().get("" + i);
StorServerConfig.Builder builder = new StorServerConfig.Builder();
cluster.getStorageNodes().getConfig(builder);
node.getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
assertEquals(1.0 + (double)i * 0.5, config.node_capacity(), 0.001);
}
}
@Test
public void testRootFolder() throws Exception {
String xml =
"<cluster id=\"storage\">\n" +
" <documents/>" +
" <group>\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
"</cluster>";
ContentCluster cluster = ContentClusterUtils.createCluster(xml, new MockRoot());
StorageNode node = cluster.getStorageNodes().getChildren().get("0");
{
StorServerConfig.Builder builder = new StorServerConfig.Builder();
cluster.getStorageNodes().getConfig(builder);
node.getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
assertEquals(getDefaults().underVespaHome("var/db/vespa/search/storage/storage/0"), config.root_folder());
}
{
StorServerConfig.Builder builder = new StorServerConfig.Builder();
cluster.getDistributorNodes().getConfig(builder);
cluster.getDistributorNodes().getChildren().get("0").getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
assertEquals(getDefaults().underVespaHome("var/db/vespa/search/storage/distributor/0"), config.root_folder());
}
}
@Test
public void testGenericPersistenceTuning() throws Exception {
String xml =
"<cluster id=\"storage\">\n" +
"<documents/>" +
"<engine>\n" +
" <fail-partition-on-error>true</fail-partition-on-error>\n" +
" <revert-time>34m</revert-time>\n" +
" <recovery-time>5d</recovery-time>\n" +
"</engine>" +
" <group>\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
"</cluster>";
ContentCluster cluster = ContentClusterUtils.createCluster(xml, new MockRoot());
PersistenceConfig.Builder builder = new PersistenceConfig.Builder();
cluster.getStorageNodes().getConfig(builder);
PersistenceConfig config = new PersistenceConfig(builder);
assertEquals(true, config.fail_partition_on_error());
assertEquals(34 * 60, config.revert_time_period());
assertEquals(5 * 24 * 60 * 60, config.keep_remove_time_period());
}
@Test
public void requireThatUserDoesNotSpecifyBothGroupAndNodes() throws Exception {
String xml =
"<cluster id=\"storage\">\n" +
"<documents/>\n" +
"<engine>\n" +
" <fail-partition-on-error>true</fail-partition-on-error>\n" +
" <revert-time>34m</revert-time>\n" +
" <recovery-time>5d</recovery-time>\n" +
"</engine>" +
" <group>\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" <nodes>\n" +
" <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" +
" </nodes>\n" +
"</cluster>";
try {
final MockRoot root = new MockRoot();
root.getDeployState().getDocumentModel().getDocumentManager().add(
new NewDocumentType(new NewDocumentType.Name("music"))
);
ContentClusterUtils.createCluster(xml, root);
fail("Did not fail when having both group and nodes");
} catch (RuntimeException e) {
e.printStackTrace();
assertEquals("Both group and nodes exists, only one of these tags is legal", e.getMessage());
}
}
@Test
public void requireThatGroupNamesMustBeUniqueAmongstSiblings() throws Exception {
String xml =
"<cluster id=\"storage\">\n" +
"<documents/>\n" +
" <group>\n" +
" <distribution partitions=\"*\"/>\n" +
" <group distribution-key=\"0\" name=\"bar\">\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" <group distribution-key=\"0\" name=\"bar\">\n" +
" <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" </group>\n" +
"</cluster>";
try {
ContentClusterUtils.createCluster(xml, new MockRoot());
fail("Did not get exception with duplicate group names");
} catch (RuntimeException e) {
assertEquals("Cluster 'storage' has multiple groups with name 'bar' in the same subgroup. " +
"Group sibling names must be unique.", e.getMessage());
}
}
@Test
public void requireThatGroupNamesCanBeDuplicatedAcrossLevels() throws Exception {
String xml =
"<cluster id=\"storage\">\n" +
"<documents/>\n" +
" <group>\n" +
" <distribution partitions=\"*\"/>\n" +
" <group distribution-key=\"0\" name=\"bar\">\n" +
" <group distribution-key=\"0\" name=\"foo\">\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" </group>\n" +
" <group distribution-key=\"0\" name=\"foo\">\n" +
" <group distribution-key=\"0\" name=\"bar\">\n" +
" <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" </group>\n" +
" </group>\n" +
"</cluster>";
// Should not throw.
ContentClusterUtils.createCluster(xml, new MockRoot());
}
@Test
public void requireThatNestedGroupsRequireDistribution() throws Exception {
String xml =
"<cluster id=\"storage\">\n" +
"<documents/>\n" +
" <group>\n" +
" <group distribution-key=\"0\" name=\"bar\">\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" <group distribution-key=\"0\" name=\"baz\">\n" +
" <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" </group>\n" +
"</cluster>";
try {
ContentClusterUtils.createCluster(xml, new MockRoot());
fail("Did not get exception with missing distribution element");
} catch (RuntimeException e) {
assertEquals("'distribution' attribute is required with multiple subgroups", e.getMessage());
}
}
}
| config-model/src/test/java/com/yahoo/vespa/model/content/StorageClusterTest.java | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.content;
import com.yahoo.vespa.config.content.core.StorIntegritycheckerConfig;
import com.yahoo.vespa.config.content.core.StorVisitorConfig;
import com.yahoo.vespa.config.content.StorFilestorConfig;
import com.yahoo.vespa.config.content.core.StorServerConfig;
import com.yahoo.vespa.config.content.PersistenceConfig;
import com.yahoo.config.model.test.MockRoot;
import com.yahoo.documentmodel.NewDocumentType;
import static com.yahoo.vespa.defaults.Defaults.getDefaults;
import com.yahoo.vespa.model.content.cluster.ContentCluster;
import com.yahoo.vespa.model.content.storagecluster.StorageCluster;
import com.yahoo.vespa.model.content.utils.ContentClusterUtils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class StorageClusterTest {
StorageCluster parse(String xml) throws Exception {
MockRoot root = new MockRoot();
root.getDeployState().getDocumentModel().getDocumentManager().add(
new NewDocumentType(new NewDocumentType.Name("music"))
);
root.getDeployState().getDocumentModel().getDocumentManager().add(
new NewDocumentType(new NewDocumentType.Name("movies"))
);
ContentCluster cluster = ContentClusterUtils.createCluster(xml, root);
root.freezeModelTopology();
return cluster.getStorageNodes();
}
@Test
public void testBasics() throws Exception {
StorServerConfig.Builder builder = new StorServerConfig.Builder();
parse("<content id=\"foofighters\"><documents/>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</content>\n").
getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
assertEquals(false, config.is_distributor());
assertEquals("foofighters", config.cluster_name());
}
@Test
public void testMerges() throws Exception {
StorServerConfig.Builder builder = new StorServerConfig.Builder();
parse("" +
"<content id=\"foofighters\">\n" +
" <documents/>" +
" <tuning>" +
" <merges max-per-node=\"1K\" max-queue-size=\"10K\"/>\n" +
" </tuning>" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</content>"
).getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
assertEquals(1024, config.max_merges_per_node());
assertEquals(1024*10, config.max_merge_queue_size());
}
@Test
public void testVisitors() throws Exception {
StorVisitorConfig.Builder builder = new StorVisitorConfig.Builder();
parse(
"<cluster id=\"bees\">\n" +
" <documents/>" +
" <tuning>\n" +
" <visitors thread-count=\"7\" max-queue-size=\"1000\">\n" +
" <max-concurrent fixed=\"42\" variable=\"100\"/>\n" +
" </visitors>\n" +
" </tuning>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>"
).getConfig(builder);
StorVisitorConfig config = new StorVisitorConfig(builder);
assertEquals(42, config.maxconcurrentvisitors_fixed());
assertEquals(100, config.maxconcurrentvisitors_variable());
assertEquals(7, config.visitorthreads());
assertEquals(1000, config.maxvisitorqueuesize());
}
@Test
public void testPersistenceThreads() throws Exception {
StorFilestorConfig.Builder builder = new StorFilestorConfig.Builder();
parse(
"<cluster id=\"bees\">\n" +
" <documents/>" +
" <tuning>\n" +
" <persistence-threads>\n" +
" <thread lowest-priority=\"VERY_LOW\" count=\"2\"/>\n" +
" <thread lowest-priority=\"VERY_HIGH\" count=\"1\"/>\n" +
" <thread count=\"1\"/>\n" +
" </persistence-threads>\n" +
" </tuning>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>"
).getConfig(builder);
StorFilestorConfig config = new StorFilestorConfig(builder);
assertEquals(4, config.num_threads());
assertEquals(false, config.enable_multibit_split_optimalization());
}
@Test
public void testNoPersistenceThreads() throws Exception {
StorFilestorConfig.Builder builder = new StorFilestorConfig.Builder();
parse(
"<cluster id=\"bees\">\n" +
" <documents/>" +
" <tuning>\n" +
" </tuning>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>"
).getConfig(builder);
StorFilestorConfig config = new StorFilestorConfig(builder);
assertEquals(6, config.num_threads());
}
@Test
public void integrity_checker_explicitly_disabled_when_not_running_with_vds_provider() throws Exception {
StorIntegritycheckerConfig.Builder builder = new StorIntegritycheckerConfig.Builder();
parse(
"<cluster id=\"bees\">\n" +
" <documents/>" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>"
).getConfig(builder);
StorIntegritycheckerConfig config = new StorIntegritycheckerConfig(builder);
// '-' --> don't run on the given week day
assertEquals("-------", config.weeklycycle());
}
@Test
public void testCapacity() throws Exception {
String xml =
"<cluster id=\"storage\">\n" +
" <documents/>" +
" <group>\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" <node distribution-key=\"1\" hostalias=\"mockhost\" capacity=\"1.5\"/>\n" +
" <node distribution-key=\"2\" hostalias=\"mockhost\" capacity=\"2.0\"/>\n" +
" </group>\n" +
"</cluster>";
ContentCluster cluster = ContentClusterUtils.createCluster(xml, new MockRoot());
for (int i = 0; i < 3; ++i) {
StorageNode node = cluster.getStorageNodes().getChildren().get("" + i);
StorServerConfig.Builder builder = new StorServerConfig.Builder();
cluster.getStorageNodes().getConfig(builder);
node.getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
assertEquals(1.0 + (double)i * 0.5, config.node_capacity(), 0.001);
}
}
@Test
public void testRootFolder() throws Exception {
String xml =
"<cluster id=\"storage\">\n" +
" <documents/>" +
" <group>\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
"</cluster>";
ContentCluster cluster = ContentClusterUtils.createCluster(xml, new MockRoot());
StorageNode node = cluster.getStorageNodes().getChildren().get("0");
{
StorServerConfig.Builder builder = new StorServerConfig.Builder();
cluster.getStorageNodes().getConfig(builder);
node.getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
assertEquals(getDefaults().underVespaHome("var/db/vespa/vds/storage/storage/0"), config.root_folder());
}
{
StorServerConfig.Builder builder = new StorServerConfig.Builder();
cluster.getDistributorNodes().getConfig(builder);
cluster.getDistributorNodes().getChildren().get("0").getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
assertEquals(getDefaults().underVespaHome("var/db/vespa/vds/storage/distributor/0"), config.root_folder());
}
}
@Test
public void testGenericPersistenceTuning() throws Exception {
String xml =
"<cluster id=\"storage\">\n" +
"<documents/>" +
"<engine>\n" +
" <fail-partition-on-error>true</fail-partition-on-error>\n" +
" <revert-time>34m</revert-time>\n" +
" <recovery-time>5d</recovery-time>\n" +
"</engine>" +
" <group>\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
"</cluster>";
ContentCluster cluster = ContentClusterUtils.createCluster(xml, new MockRoot());
PersistenceConfig.Builder builder = new PersistenceConfig.Builder();
cluster.getStorageNodes().getConfig(builder);
PersistenceConfig config = new PersistenceConfig(builder);
assertEquals(true, config.fail_partition_on_error());
assertEquals(34 * 60, config.revert_time_period());
assertEquals(5 * 24 * 60 * 60, config.keep_remove_time_period());
}
@Test
public void requireThatUserDoesNotSpecifyBothGroupAndNodes() throws Exception {
String xml =
"<cluster id=\"storage\">\n" +
"<documents/>\n" +
"<engine>\n" +
" <fail-partition-on-error>true</fail-partition-on-error>\n" +
" <revert-time>34m</revert-time>\n" +
" <recovery-time>5d</recovery-time>\n" +
"</engine>" +
" <group>\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" <nodes>\n" +
" <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" +
" </nodes>\n" +
"</cluster>";
try {
final MockRoot root = new MockRoot();
root.getDeployState().getDocumentModel().getDocumentManager().add(
new NewDocumentType(new NewDocumentType.Name("music"))
);
ContentClusterUtils.createCluster(xml, root);
fail("Did not fail when having both group and nodes");
} catch (RuntimeException e) {
e.printStackTrace();
assertEquals("Both group and nodes exists, only one of these tags is legal", e.getMessage());
}
}
@Test
public void requireThatGroupNamesMustBeUniqueAmongstSiblings() throws Exception {
String xml =
"<cluster id=\"storage\">\n" +
"<documents/>\n" +
" <group>\n" +
" <distribution partitions=\"*\"/>\n" +
" <group distribution-key=\"0\" name=\"bar\">\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" <group distribution-key=\"0\" name=\"bar\">\n" +
" <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" </group>\n" +
"</cluster>";
try {
ContentClusterUtils.createCluster(xml, new MockRoot());
fail("Did not get exception with duplicate group names");
} catch (RuntimeException e) {
assertEquals("Cluster 'storage' has multiple groups with name 'bar' in the same subgroup. " +
"Group sibling names must be unique.", e.getMessage());
}
}
@Test
public void requireThatGroupNamesCanBeDuplicatedAcrossLevels() throws Exception {
String xml =
"<cluster id=\"storage\">\n" +
"<documents/>\n" +
" <group>\n" +
" <distribution partitions=\"*\"/>\n" +
" <group distribution-key=\"0\" name=\"bar\">\n" +
" <group distribution-key=\"0\" name=\"foo\">\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" </group>\n" +
" <group distribution-key=\"0\" name=\"foo\">\n" +
" <group distribution-key=\"0\" name=\"bar\">\n" +
" <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" </group>\n" +
" </group>\n" +
"</cluster>";
// Should not throw.
ContentClusterUtils.createCluster(xml, new MockRoot());
}
@Test
public void requireThatNestedGroupsRequireDistribution() throws Exception {
String xml =
"<cluster id=\"storage\">\n" +
"<documents/>\n" +
" <group>\n" +
" <group distribution-key=\"0\" name=\"bar\">\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" <group distribution-key=\"0\" name=\"baz\">\n" +
" <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" </group>\n" +
"</cluster>";
try {
ContentClusterUtils.createCluster(xml, new MockRoot());
fail("Did not get exception with missing distribution element");
} catch (RuntimeException e) {
assertEquals("'distribution' attribute is required with multiple subgroups", e.getMessage());
}
}
}
| Update test
| config-model/src/test/java/com/yahoo/vespa/model/content/StorageClusterTest.java | Update test | <ide><path>onfig-model/src/test/java/com/yahoo/vespa/model/content/StorageClusterTest.java
<ide> cluster.getStorageNodes().getConfig(builder);
<ide> node.getConfig(builder);
<ide> StorServerConfig config = new StorServerConfig(builder);
<del> assertEquals(getDefaults().underVespaHome("var/db/vespa/vds/storage/storage/0"), config.root_folder());
<add> assertEquals(getDefaults().underVespaHome("var/db/vespa/search/storage/storage/0"), config.root_folder());
<ide> }
<ide>
<ide> {
<ide> cluster.getDistributorNodes().getConfig(builder);
<ide> cluster.getDistributorNodes().getChildren().get("0").getConfig(builder);
<ide> StorServerConfig config = new StorServerConfig(builder);
<del> assertEquals(getDefaults().underVespaHome("var/db/vespa/vds/storage/distributor/0"), config.root_folder());
<add> assertEquals(getDefaults().underVespaHome("var/db/vespa/search/storage/distributor/0"), config.root_folder());
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | b695a78f7354aad5ff0ced512cd149f166a8f675 | 0 | gaieepo/HubTurbo,gaieepo/HubTurbo | package backend;
import backend.control.RepoOpControl;
import backend.resource.Model;
import backend.resource.MultiModel;
import backend.resource.TurboIssue;
import filter.expression.FilterExpression;
import filter.expression.Qualifier;
import filter.expression.QualifierType;
import javafx.application.Platform;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.logging.log4j.Logger;
import prefs.Preferences;
import ui.GuiElement;
import ui.TestController;
import ui.UI;
import ui.issuepanel.FilterPanel;
import util.Futures;
import util.HTLog;
import util.Utility;
import util.events.*;
import util.events.testevents.ClearLogicModelEvent;
import util.events.testevents.ClearLogicModelEventHandler;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import static util.Futures.withResult;
public class Logic {
private static final Logger logger = HTLog.get(Logic.class);
private final MultiModel models;
private final UIManager uiManager;
protected final Preferences prefs;
private final RepoIO repoIO = TestController.createApplicationRepoIO();
private final RepoOpControl repoOpControl = new RepoOpControl(repoIO);
public LoginController loginController;
public UpdateController updateController;
public Logic(UIManager uiManager, Preferences prefs, Optional<MultiModel> models) {
this.uiManager = uiManager;
this.prefs = prefs;
this.models = models.orElse(new MultiModel(prefs));
loginController = new LoginController(this);
updateController = new UpdateController(this);
// Only relevant to testing, need a different event type to avoid race condition
UI.events.registerEvent((ClearLogicModelEventHandler) this::onLogicModelClear);
}
private void onLogicModelClear(ClearLogicModelEvent e) {
// DELETE_* and RESET_REPO is handled jointly by Logic and DummyRepo
assert TestController.isTestMode();
assert e.repoId != null;
List<Model> toReplace = models.toModels();
logger.info("Attempting to reset " + e.repoId);
if (toReplace.remove(models.get(e.repoId))) {
logger.info("Clearing " + e.repoId + " successful.");
} else {
logger.info(e.repoId + " not currently in model.");
}
models.replace(toReplace);
// Re-"download" repo after clearing
openPrimaryRepository(e.repoId);
}
private CompletableFuture<Boolean> isRepositoryValid(String repoId) {
return repoIO.isRepositoryValid(repoId);
}
public void refresh() {
String message = "Refreshing " + models.toModels().stream()
.map(Model::getRepoId)
.collect(Collectors.joining(", "));
logger.info(message);
UI.status.displayMessage(message);
Futures.sequence(models.toModels().stream()
.map(repoOpControl::updateModel)
.collect(Collectors.toList()))
.thenApply(models::replace)
.thenRun(this::refreshUI)
.thenCompose(n -> getRateLimitResetTime())
.thenApply(this::updateRemainingRate)
.exceptionally(Futures::log);
}
/**
* Opens the repoId if it isn't already open, else simply refreshes the UI
* After opening the repo, it will trigger a PrimaryRepoOpenedEvent
*
* @param repoId
* @return
*/
public CompletableFuture<Boolean> openPrimaryRepository(String repoId) {
return openRepository(repoId, true, Optional.empty());
}
/**
* Opens the repoId if it isn't already open, else simply refreshes the UI
* After opening the repo, it will trigger a FilterOpeningEvent with panel as argument
*
* @param repoId
* @return
*/
public CompletableFuture<Boolean> openRepositoryFromFilter(String repoId, FilterPanel panel) {
return openRepository(repoId, false, Optional.of(panel));
}
/**
* Opens the repoId if it isn't already open, else simply refreshes the UI
*
* After opening the repo, it will trigger a PrimaryRepoOpenedEvent or AppliedFilterEvent depending on the
* caller origin determined by isPrimaryRepository
*
* @param repoId
* @param isPrimaryRepository false if it was due to repo being specified in a panel's filter
* @param panel should be Optional.empty() if isPrimaryRepository is true, else it should contain
* the panel whose filter specified the repo
* @return
*/
private CompletableFuture<Boolean> openRepository(String repoId, boolean isPrimaryRepository,
Optional<FilterPanel> panel) {
assert Utility.isWellFormedRepoId(repoId);
assert isPrimaryRepository ? !panel.isPresent() : panel.isPresent();
if (isPrimaryRepository) prefs.setLastViewedRepository(repoId);
if (isAlreadyOpen(repoId) || models.isRepositoryPending(repoId)) {
// The content of panels with an empty filter text should change when the primary repo is changed.
// Thus we refresh panels even when the repo is already open.
if (isPrimaryRepository) {
refreshUI();
} else {
Platform.runLater(() -> UI.events.triggerEvent(new AppliedFilterEvent(panel.get())));
}
return Futures.unit(false);
}
models.queuePendingRepository(repoId);
return isRepositoryValid(repoId).thenCompose(valid -> {
if (!valid) {
return Futures.unit(false);
}
logger.info("Opening " + repoId);
UI.status.displayMessage("Opening " + repoId);
notifyOpening(isPrimaryRepository);
return repoOpControl.openRepository(repoId)
.thenApply(models::addPending)
.thenRun(this::refreshUI)
.thenRun(() -> notifyDoneOpening(isPrimaryRepository, panel))
.thenCompose(n -> getRateLimitResetTime())
.thenApply(this::updateRemainingRate)
.thenApply(rateLimits -> true)
.exceptionally(withResult(false));
});
}
/**
* Triggers the relevant event based on the caller source determined by isPrimaryRepository
* @param isPrimaryRepository true if called by repository selector, else false
*/
private void notifyOpening(boolean isPrimaryRepository) {
if (isPrimaryRepository) {
Platform.runLater(() -> UI.events.triggerEvent(new PrimaryRepoOpeningEvent()));
} else {
Platform.runLater(() -> UI.events.triggerEvent(new FilterRepoOpeningEvent()));
}
}
/**
* Triggers the relevant event based on the caller source determined by isPrimaryRepository
* If called via filter, also notifies the relevant panel that the opening of repository is done
*
* Assumption: panel is present if isPrimaryRepository is false
* @param isPrimaryRepository true if called by repository selector, else false
* @param panel should be Optional.empty() if isPrimaryRepository is true, else it should contain
* the panel whose filter specified the repo
*/
private void notifyDoneOpening(boolean isPrimaryRepository, Optional<FilterPanel> panel) {
if (isPrimaryRepository) {
Platform.runLater(() -> UI.events.triggerEvent(new PrimaryRepoOpenedEvent()));
} else {
Platform.runLater(() -> UI.events.triggerEvent(new FilterRepoOpenedEvent()));
Platform.runLater(() -> UI.events.triggerEvent(new AppliedFilterEvent(panel.get())));
}
}
public Set<String> getOpenRepositories() {
return models.toModels().stream().map(Model::getRepoId).map(String::toLowerCase).collect(Collectors.toSet());
}
public Set<String> getStoredRepos() {
return repoIO.getStoredRepos().stream().collect(Collectors.toSet());
}
public boolean isAlreadyOpen(String repoId) {
return getOpenRepositories().contains(repoId.toLowerCase());
}
public void setDefaultRepo(String repoId) {
models.setDefaultRepo(repoId);
}
public String getDefaultRepo() {
return models.getDefaultRepo();
}
public CompletableFuture<Boolean> removeStoredRepository(String repoId) {
return repoOpControl.removeRepository(repoId);
}
/**
* Recommended Pre-condition: normalize reposInUse to lower case
* - using Utility.convertSetToLowerCase()
*/
public void removeUnusedModels(Set<String> reposInUse) {
models.toModels().stream().map(Model::getRepoId)
.filter(repoId -> !reposInUse.contains(repoId.toLowerCase()))
.forEach(models::removeRepoModelById);
}
public ImmutablePair<Integer, Long> updateRemainingRate
(ImmutablePair<Integer, Long> rateLimits) {
uiManager.updateRateLimits(rateLimits);
return rateLimits;
}
protected CompletableFuture<Boolean> repoIOLogin(UserCredentials credentials) {
return repoIO.login(credentials);
}
public Model getRepo(String repoId) {
return models.get(repoId);
}
public CompletableFuture<ImmutablePair<Integer, Long>> getRateLimitResetTime() {
return repoIO.getRateLimitResetTime();
}
/**
* Replaces existing labels with new labels in the issue object, the UI, and the server, in that order.
* Server update is done after the local update to reduce the lag between the user action and the UI response
*
* @param issue The issue object whose labels are to be replaced.
* @param newLabels The list of new labels to be assigned to the issue.
* @return true if label replacement on GitHub was a success, false otherwise.
*/
public CompletableFuture<Boolean> replaceIssueLabels(TurboIssue issue, List<String> newLabels) {
List<String> originalLabels = issue.getLabels();
logger.info("Changing labels for " + issue + " on UI");
/* Calls models to replace the issue's labels locally since the the reference to the issue here
could be invalidated by changes to the models elsewhere */
Optional<TurboIssue> localReplaceResult =
models.replaceIssueLabels(issue.getRepoId(), issue.getId(), newLabels);
if (!localReplaceResult.isPresent()) {
return CompletableFuture.completedFuture(false);
}
refreshUI();
return updateIssueLabelsOnServer(issue, newLabels)
.thenApply((isUpdateSuccessful) -> handleIssueLabelsUpdateOnServerResult(
isUpdateSuccessful, localReplaceResult.get(), originalLabels));
}
/**
* Gets the issue identified by {@code repoId} and {@code issueId} in {@link Logic#models}
* @param repoId
* @param issueId
* @return
*/
private Optional<TurboIssue> getIssue(String repoId, int issueId) {
Optional<Model> modelLookUpResult = models.getModelById(repoId);
return Utility.safeFlatMapOptional(modelLookUpResult,
(model) -> model.getIssueById(issueId),
() -> logger.error("Model " + repoId + " not found in models"));
}
private CompletableFuture<Boolean> updateIssueLabelsOnServer(TurboIssue issue, List<String> newLabels) {
logger.info("Changing labels for " + issue + " on GitHub");
return repoOpControl.replaceIssueLabels(issue, newLabels);
}
/**
* Handles the result of updating an issue's labels on server. Current implementation includes
* reverting back to the original labels locally if the server update failed.
* @param isUpdateSuccessful
* @param localModifiedIssue
* @param originalLabels
* @return true if the server update is successful
*/
private boolean handleIssueLabelsUpdateOnServerResult(boolean isUpdateSuccessful,
TurboIssue localModifiedIssue,
List<String> originalLabels) {
if (isUpdateSuccessful) {
return true;
}
logger.error("Unable to update model on server");
revertLocalLabelsReplace(localModifiedIssue, originalLabels);
return false;
}
/**
* Replaces labels of the issue in the {@link Logic#models} corresponding to {@code modifiedIssue} with
* {@code originalLabels} if the current labels on the issue is assigned at the same time as {@code modifiedIssue}
* @param modifiedIssue
* @param originalLabels
*/
private void revertLocalLabelsReplace(TurboIssue modifiedIssue, List<String> originalLabels) {
TurboIssue currentIssue = getIssue(modifiedIssue.getRepoId(), modifiedIssue.getId()).orElse(modifiedIssue);
LocalDateTime originalLabelsModifiedAt = modifiedIssue.getLabelsLastModifiedAt();
LocalDateTime currentLabelsAssignedAt = currentIssue.getLabelsLastModifiedAt();
boolean isCurrentLabelsModifiedFromOriginalLabels = originalLabelsModifiedAt.isEqual(currentLabelsAssignedAt);
if (isCurrentLabelsModifiedFromOriginalLabels) {
logger.info("Reverting labels for issue " + currentIssue);
models.replaceIssueLabels(currentIssue.getRepoId(), currentIssue.getId(), originalLabels);
refreshUI();
}
}
/**
* Determines data to be sent to the GUI to refresh the entire GUI with the current model in Logic,
* and then sends the data to the GUI.
*/
private void refreshUI() {
updateController.processAndRefresh(getAllPanels());
}
/**
* Feeds the panel's filter expression to updateController.
*
* @param panel The panel whose filter expression is to be processed by updateController.
*/
public void refreshPanel(FilterPanel panel) {
List<FilterPanel> panels = new ArrayList<>();
panels.add(panel);
updateController.processAndRefresh(panels);
// AppliedFilterEvent will be triggered asynchronously when repo(s) have finished opening, so just terminate
if (hasRepoSpecifiedInFilter(panel)) return;
Platform.runLater (() -> UI.events.triggerEvent(new AppliedFilterEvent(panel)));
}
private boolean hasRepoSpecifiedInFilter(FilterPanel panel) {
return !Qualifier.getMetaQualifierContent(panel.getCurrentFilterExpression(), QualifierType.REPO).isEmpty();
}
/**
* Retrieves metadata for given issues from the repository source, and then processes them for non-self
* update timings.
*
* @param repoId The repository containing issues to retrieve metadata for.
* @param issues Issues sharing the same repository requiring a metadata update.
* @return True if metadata retrieval was a success, false otherwise.
*/
public CompletableFuture<Boolean> getIssueMetadata(String repoId, List<TurboIssue> issues) {
String message = "Getting metadata for " + repoId + "...";
logger.info("Getting metadata for issues " + issues);
UI.status.displayMessage(message);
return repoIO.getIssueMetadata(repoId, issues).thenApply(this::processUpdates)
.thenApply(metadata -> insertMetadata(metadata, repoId, prefs.getLastLoginUsername()))
.exceptionally(withResult(false));
}
private boolean insertMetadata(Map<Integer, IssueMetadata> metadata, String repoId, String currentUser) {
String updatedMessage = "Received metadata from " + repoId + "!";
UI.status.displayMessage(updatedMessage);
models.insertMetadata(repoId, metadata, currentUser);
return true;
}
// Adds update times to the metadata map
private Map<Integer, IssueMetadata> processUpdates(Map<Integer, IssueMetadata> metadata) {
String currentUser = prefs.getLastLoginUsername();
// Iterates through each entry in the metadata set, and looks for the comment/event with
// the latest time created.
for (Map.Entry<Integer, IssueMetadata> entry : metadata.entrySet()) {
IssueMetadata currentMetadata = entry.getValue();
entry.setValue(currentMetadata.full(currentUser));
}
return metadata;
}
/**
* Carries the current set of GUI elements, as well as the current list of users in the model, to the GUI.
*/
public void updateUI(Map<FilterExpression, List<GuiElement>> elementsToShow) {
uiManager.update(elementsToShow, models.getUsers());
}
private List<FilterPanel> getAllPanels() {
return uiManager.getAllPanels();
}
/**
* For use by UpdateController to perform filtering.
*
* @return The currently held MultiModel.
*/
public MultiModel getModels() {
return models;
}
}
| src/main/java/backend/Logic.java | package backend;
import backend.control.RepoOpControl;
import backend.resource.Model;
import backend.resource.MultiModel;
import backend.resource.TurboIssue;
import filter.expression.FilterExpression;
import filter.expression.Qualifier;
import filter.expression.QualifierType;
import javafx.application.Platform;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.logging.log4j.Logger;
import prefs.Preferences;
import ui.GuiElement;
import ui.TestController;
import ui.UI;
import ui.issuepanel.FilterPanel;
import util.Futures;
import util.HTLog;
import util.Utility;
import util.events.*;
import util.events.testevents.ClearLogicModelEvent;
import util.events.testevents.ClearLogicModelEventHandler;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import static util.Futures.withResult;
public class Logic {
private static final Logger logger = HTLog.get(Logic.class);
private final MultiModel models;
private final UIManager uiManager;
protected final Preferences prefs;
private final RepoIO repoIO = TestController.createApplicationRepoIO();
private final RepoOpControl repoOpControl = new RepoOpControl(repoIO);
public LoginController loginController;
public UpdateController updateController;
public Logic(UIManager uiManager, Preferences prefs, Optional<MultiModel> models) {
this.uiManager = uiManager;
this.prefs = prefs;
this.models = models.orElse(new MultiModel(prefs));
loginController = new LoginController(this);
updateController = new UpdateController(this);
// Only relevant to testing, need a different event type to avoid race condition
UI.events.registerEvent((ClearLogicModelEventHandler) this::onLogicModelClear);
}
private void onLogicModelClear(ClearLogicModelEvent e) {
// DELETE_* and RESET_REPO is handled jointly by Logic and DummyRepo
assert TestController.isTestMode();
assert e.repoId != null;
List<Model> toReplace = models.toModels();
logger.info("Attempting to reset " + e.repoId);
if (toReplace.remove(models.get(e.repoId))) {
logger.info("Clearing " + e.repoId + " successful.");
} else {
logger.info(e.repoId + " not currently in model.");
}
models.replace(toReplace);
// Re-"download" repo after clearing
openPrimaryRepository(e.repoId);
}
private CompletableFuture<Boolean> isRepositoryValid(String repoId) {
return repoIO.isRepositoryValid(repoId);
}
public void refresh() {
String message = "Refreshing " + models.toModels().stream()
.map(Model::getRepoId)
.collect(Collectors.joining(", "));
logger.info(message);
UI.status.displayMessage(message);
Futures.sequence(models.toModels().stream()
.map(repoOpControl::updateModel)
.collect(Collectors.toList()))
.thenApply(models::replace)
.thenRun(this::refreshUI)
.thenCompose(n -> getRateLimitResetTime())
.thenApply(this::updateRemainingRate)
.exceptionally(Futures::log);
}
/**
* Opens the repoId if it isn't already open, else simply refreshes the UI
* After opening the repo, it will trigger a PrimaryRepoOpenedEvent
*
* @param repoId
* @return
*/
public CompletableFuture<Boolean> openPrimaryRepository(String repoId) {
return openRepository(repoId, true, Optional.empty());
}
/**
* Opens the repoId if it isn't already open, else simply refreshes the UI
* After opening the repo, it will trigger a FilterOpeningEvent with panel as argument
*
* @param repoId
* @return
*/
public CompletableFuture<Boolean> openRepositoryFromFilter(String repoId, FilterPanel panel) {
return openRepository(repoId, false, Optional.of(panel));
}
/**
* Opens the repoId if it isn't already open, else simply refreshes the UI
*
* After opening the repo, it will trigger a PrimaryRepoOpenedEvent or AppliedFilterEvent depending on the
* caller origin determined by isPrimaryRepository
*
* @param repoId
* @param isPrimaryRepository false if it was due to repo being specified in a panel's filter
* @param panel should be Optional.empty() if isPrimaryRepository is true, else it should contain
* the panel whose filter specified the repo
* @return
*/
private CompletableFuture<Boolean> openRepository(String repoId, boolean isPrimaryRepository,
Optional<FilterPanel> panel) {
assert Utility.isWellFormedRepoId(repoId);
assert isPrimaryRepository ? !panel.isPresent() : panel.isPresent();
if (isPrimaryRepository) prefs.setLastViewedRepository(repoId);
if (isAlreadyOpen(repoId) || models.isRepositoryPending(repoId)) {
// The content of panels with an empty filter text should change when the primary repo is changed.
// Thus we refresh panels even when the repo is already open.
if (isPrimaryRepository) refreshUI();
return Futures.unit(false);
}
models.queuePendingRepository(repoId);
return isRepositoryValid(repoId).thenCompose(valid -> {
if (!valid) {
return Futures.unit(false);
}
logger.info("Opening " + repoId);
UI.status.displayMessage("Opening " + repoId);
notifyOpening(isPrimaryRepository);
return repoOpControl.openRepository(repoId)
.thenApply(models::addPending)
.thenRun(this::refreshUI)
.thenRun(() -> notifyDoneOpening(isPrimaryRepository, panel))
.thenCompose(n -> getRateLimitResetTime())
.thenApply(this::updateRemainingRate)
.thenApply(rateLimits -> true)
.exceptionally(withResult(false));
});
}
/**
* Triggers the relevant event based on the caller source determined by isPrimaryRepository
* @param isPrimaryRepository true if called by repository selector, else false
*/
private void notifyOpening(boolean isPrimaryRepository) {
if (isPrimaryRepository) {
Platform.runLater(() -> UI.events.triggerEvent(new PrimaryRepoOpeningEvent()));
} else {
Platform.runLater(() -> UI.events.triggerEvent(new FilterRepoOpeningEvent()));
}
}
/**
* Triggers the relevant event based on the caller source determined by isPrimaryRepository
* If called via filter, also notifies the relevant panel that the opening of repository is done
*
* Assumption: panel is present if isPrimaryRepository is false
* @param isPrimaryRepository true if called by repository selector, else false
* @param panel should be Optional.empty() if isPrimaryRepository is true, else it should contain
* the panel whose filter specified the repo
*/
private void notifyDoneOpening(boolean isPrimaryRepository, Optional<FilterPanel> panel) {
if (isPrimaryRepository) {
Platform.runLater(() -> UI.events.triggerEvent(new PrimaryRepoOpenedEvent()));
} else {
Platform.runLater(() -> UI.events.triggerEvent(new FilterRepoOpenedEvent()));
Platform.runLater(() -> UI.events.triggerEvent(new AppliedFilterEvent(panel.get())));
}
}
public Set<String> getOpenRepositories() {
return models.toModels().stream().map(Model::getRepoId).map(String::toLowerCase).collect(Collectors.toSet());
}
public Set<String> getStoredRepos() {
return repoIO.getStoredRepos().stream().collect(Collectors.toSet());
}
public boolean isAlreadyOpen(String repoId) {
return getOpenRepositories().contains(repoId.toLowerCase());
}
public void setDefaultRepo(String repoId) {
models.setDefaultRepo(repoId);
}
public String getDefaultRepo() {
return models.getDefaultRepo();
}
public CompletableFuture<Boolean> removeStoredRepository(String repoId) {
return repoOpControl.removeRepository(repoId);
}
/**
* Recommended Pre-condition: normalize reposInUse to lower case
* - using Utility.convertSetToLowerCase()
*/
public void removeUnusedModels(Set<String> reposInUse) {
models.toModels().stream().map(Model::getRepoId)
.filter(repoId -> !reposInUse.contains(repoId.toLowerCase()))
.forEach(models::removeRepoModelById);
}
public ImmutablePair<Integer, Long> updateRemainingRate
(ImmutablePair<Integer, Long> rateLimits) {
uiManager.updateRateLimits(rateLimits);
return rateLimits;
}
protected CompletableFuture<Boolean> repoIOLogin(UserCredentials credentials) {
return repoIO.login(credentials);
}
public Model getRepo(String repoId) {
return models.get(repoId);
}
public CompletableFuture<ImmutablePair<Integer, Long>> getRateLimitResetTime() {
return repoIO.getRateLimitResetTime();
}
/**
* Replaces existing labels with new labels in the issue object, the UI, and the server, in that order.
* Server update is done after the local update to reduce the lag between the user action and the UI response
*
* @param issue The issue object whose labels are to be replaced.
* @param newLabels The list of new labels to be assigned to the issue.
* @return true if label replacement on GitHub was a success, false otherwise.
*/
public CompletableFuture<Boolean> replaceIssueLabels(TurboIssue issue, List<String> newLabels) {
List<String> originalLabels = issue.getLabels();
logger.info("Changing labels for " + issue + " on UI");
/* Calls models to replace the issue's labels locally since the the reference to the issue here
could be invalidated by changes to the models elsewhere */
Optional<TurboIssue> localReplaceResult =
models.replaceIssueLabels(issue.getRepoId(), issue.getId(), newLabels);
if (!localReplaceResult.isPresent()) {
return CompletableFuture.completedFuture(false);
}
refreshUI();
return updateIssueLabelsOnServer(issue, newLabels)
.thenApply((isUpdateSuccessful) -> handleIssueLabelsUpdateOnServerResult(
isUpdateSuccessful, localReplaceResult.get(), originalLabels));
}
/**
* Gets the issue identified by {@code repoId} and {@code issueId} in {@link Logic#models}
* @param repoId
* @param issueId
* @return
*/
private Optional<TurboIssue> getIssue(String repoId, int issueId) {
Optional<Model> modelLookUpResult = models.getModelById(repoId);
return Utility.safeFlatMapOptional(modelLookUpResult,
(model) -> model.getIssueById(issueId),
() -> logger.error("Model " + repoId + " not found in models"));
}
private CompletableFuture<Boolean> updateIssueLabelsOnServer(TurboIssue issue, List<String> newLabels) {
logger.info("Changing labels for " + issue + " on GitHub");
return repoOpControl.replaceIssueLabels(issue, newLabels);
}
/**
* Handles the result of updating an issue's labels on server. Current implementation includes
* reverting back to the original labels locally if the server update failed.
* @param isUpdateSuccessful
* @param localModifiedIssue
* @param originalLabels
* @return true if the server update is successful
*/
private boolean handleIssueLabelsUpdateOnServerResult(boolean isUpdateSuccessful,
TurboIssue localModifiedIssue,
List<String> originalLabels) {
if (isUpdateSuccessful) {
return true;
}
logger.error("Unable to update model on server");
revertLocalLabelsReplace(localModifiedIssue, originalLabels);
return false;
}
/**
* Replaces labels of the issue in the {@link Logic#models} corresponding to {@code modifiedIssue} with
* {@code originalLabels} if the current labels on the issue is assigned at the same time as {@code modifiedIssue}
* @param modifiedIssue
* @param originalLabels
*/
private void revertLocalLabelsReplace(TurboIssue modifiedIssue, List<String> originalLabels) {
TurboIssue currentIssue = getIssue(modifiedIssue.getRepoId(), modifiedIssue.getId()).orElse(modifiedIssue);
LocalDateTime originalLabelsModifiedAt = modifiedIssue.getLabelsLastModifiedAt();
LocalDateTime currentLabelsAssignedAt = currentIssue.getLabelsLastModifiedAt();
boolean isCurrentLabelsModifiedFromOriginalLabels = originalLabelsModifiedAt.isEqual(currentLabelsAssignedAt);
if (isCurrentLabelsModifiedFromOriginalLabels) {
logger.info("Reverting labels for issue " + currentIssue);
models.replaceIssueLabels(currentIssue.getRepoId(), currentIssue.getId(), originalLabels);
refreshUI();
}
}
/**
* Determines data to be sent to the GUI to refresh the entire GUI with the current model in Logic,
* and then sends the data to the GUI.
*/
private void refreshUI() {
updateController.processAndRefresh(getAllPanels());
}
/**
* Feeds the panel's filter expression to updateController.
*
* @param panel The panel whose filter expression is to be processed by updateController.
*/
public void refreshPanel(FilterPanel panel) {
List<FilterPanel> panels = new ArrayList<>();
panels.add(panel);
updateController.processAndRefresh(panels);
// AppliedFilterEvent will be triggered asynchronously when repo(s) have finished opening, so just terminate
if (hasRepoSpecifiedInFilter(panel)) return;
Platform.runLater (() -> UI.events.triggerEvent(new AppliedFilterEvent(panel)));
}
private boolean hasRepoSpecifiedInFilter(FilterPanel panel) {
return !Qualifier.getMetaQualifierContent(panel.getCurrentFilterExpression(), QualifierType.REPO).isEmpty();
}
/**
* Retrieves metadata for given issues from the repository source, and then processes them for non-self
* update timings.
*
* @param repoId The repository containing issues to retrieve metadata for.
* @param issues Issues sharing the same repository requiring a metadata update.
* @return True if metadata retrieval was a success, false otherwise.
*/
public CompletableFuture<Boolean> getIssueMetadata(String repoId, List<TurboIssue> issues) {
String message = "Getting metadata for " + repoId + "...";
logger.info("Getting metadata for issues " + issues);
UI.status.displayMessage(message);
return repoIO.getIssueMetadata(repoId, issues).thenApply(this::processUpdates)
.thenApply(metadata -> insertMetadata(metadata, repoId, prefs.getLastLoginUsername()))
.exceptionally(withResult(false));
}
private boolean insertMetadata(Map<Integer, IssueMetadata> metadata, String repoId, String currentUser) {
String updatedMessage = "Received metadata from " + repoId + "!";
UI.status.displayMessage(updatedMessage);
models.insertMetadata(repoId, metadata, currentUser);
return true;
}
// Adds update times to the metadata map
private Map<Integer, IssueMetadata> processUpdates(Map<Integer, IssueMetadata> metadata) {
String currentUser = prefs.getLastLoginUsername();
// Iterates through each entry in the metadata set, and looks for the comment/event with
// the latest time created.
for (Map.Entry<Integer, IssueMetadata> entry : metadata.entrySet()) {
IssueMetadata currentMetadata = entry.getValue();
entry.setValue(currentMetadata.full(currentUser));
}
return metadata;
}
/**
* Carries the current set of GUI elements, as well as the current list of users in the model, to the GUI.
*/
public void updateUI(Map<FilterExpression, List<GuiElement>> elementsToShow) {
uiManager.update(elementsToShow, models.getUsers());
}
private List<FilterPanel> getAllPanels() {
return uiManager.getAllPanels();
}
/**
* For use by UpdateController to perform filtering.
*
* @return The currently held MultiModel.
*/
public MultiModel getModels() {
return models;
}
}
| Modified openRepository to also trigger AppliedFilterEvent when it checks that the repo is already opened/being opened. This solves the problem of leftover loading indicators when there are many panels of the same specified repo being filtered at the same time e.g. when opening a board.
| src/main/java/backend/Logic.java | Modified openRepository to also trigger AppliedFilterEvent when it checks that the repo is already opened/being opened. This solves the problem of leftover loading indicators when there are many panels of the same specified repo being filtered at the same time e.g. when opening a board. | <ide><path>rc/main/java/backend/Logic.java
<ide> if (isAlreadyOpen(repoId) || models.isRepositoryPending(repoId)) {
<ide> // The content of panels with an empty filter text should change when the primary repo is changed.
<ide> // Thus we refresh panels even when the repo is already open.
<del> if (isPrimaryRepository) refreshUI();
<add> if (isPrimaryRepository) {
<add> refreshUI();
<add> } else {
<add> Platform.runLater(() -> UI.events.triggerEvent(new AppliedFilterEvent(panel.get())));
<add> }
<ide> return Futures.unit(false);
<ide> }
<ide> models.queuePendingRepository(repoId); |
|
JavaScript | mit | 890feb858f3ff8e22234ad41a11ac9f1bb1409ff | 0 | tadjik1/wof-admin-lookup,tadjik1/wof-admin-lookup | const peliasConfig = require('pelias-config').generate(require('./schema'));
const through = require('through2');
const _ = require('lodash');
const os = require('os');
module.exports = {
create: () => {
if (_.get(peliasConfig, 'imports.adminLookup.enabled', true)) {
const datapath = peliasConfig.imports.whosonfirst.datapath;
const resolver = require('./src/localPipResolver')(datapath);
// default maxConcurrentReqs to the number of cpus/cores * 10
const maxConcurrentReqs = _.get(peliasConfig, 'imports.adminLookup.maxConcurrentReqs', os.cpus().length*10);
return require('./src/lookupStream')(resolver, maxConcurrentReqs);
} else {
return through.obj();
}
},
resolver: (datapath) => {
const resolver = require('./src/localPipResolver')(
datapath || peliasConfig.imports.whosonfirst.datapath);
return resolver;
}
};
| index.js | const peliasConfig = require('pelias-config').generate(require('./schema'));
const through = require('through2');
const _ = require('lodash');
const os = require('os');
module.exports = {
create: () => {
if (_.get(peliasConfig, 'imports.adminLookup.enabled', true)) {
const datapath = peliasConfig.imports.whosonfirst.datapath;
const resolver = require('./src/localPipResolver')(datapath);
// default maxConcurrentReqs to the number of cpus/cores * 10
const maxConcurrentReqs = _.get(peliasConfig, 'imports.adminLookup.maxConcurrentReqs', os.cpus().length*10);
return require('./src/lookupStream')(resolver, maxConcurrentReqs);
} else {
return through.obj();
}
},
resolver: () => {
const datapath = peliasConfig.imports.whosonfirst.datapath;
const resolver = require('./src/localPipResolver')(datapath);
return resolver;
}
};
| added datapath parameter for non-config load
| index.js | added datapath parameter for non-config load | <ide><path>ndex.js
<ide> }
<ide>
<ide> },
<del> resolver: () => {
<del> const datapath = peliasConfig.imports.whosonfirst.datapath;
<del> const resolver = require('./src/localPipResolver')(datapath);
<add> resolver: (datapath) => {
<add> const resolver = require('./src/localPipResolver')(
<add> datapath || peliasConfig.imports.whosonfirst.datapath);
<ide> return resolver;
<ide> }
<ide> |
|
Java | apache-2.0 | 6bf452d54602a0e8cdd78abb3b795e5505569b20 | 0 | kickstarter/android-oss,kickstarter/android-oss,kickstarter/android-oss,kickstarter/android-oss | package com.kickstarter;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.preference.PreferenceManager;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.kickstarter.libs.ApiEndpoint;
import com.kickstarter.libs.AutoParcelAdapterFactory;
import com.kickstarter.libs.Build;
import com.kickstarter.libs.ConfigLoader;
import com.kickstarter.libs.CurrentUser;
import com.kickstarter.libs.DateTimeTypeConverter;
import com.kickstarter.libs.Font;
import com.kickstarter.libs.ForApplication;
import com.kickstarter.libs.Logout;
import com.kickstarter.libs.Money;
import com.kickstarter.libs.preferences.StringPreference;
import com.kickstarter.libs.qualifiers.AccessTokenPreference;
import com.kickstarter.libs.qualifiers.UserPreference;
import com.kickstarter.libs.qualifiers.WebEndpoint;
import com.kickstarter.services.ApiClient;
import com.kickstarter.services.KickstarterClient;
import com.kickstarter.services.KickstarterWebViewClient;
import org.joda.time.DateTime;
import java.net.CookieManager;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
@Module
public class ApplicationModule {
private final Application application;
public ApplicationModule(final Application application) {
this.application = application;
}
@Provides
@Singleton
@AccessTokenPreference
StringPreference provideAccessTokenPreference(final SharedPreferences sharedPreferences) {
return new StringPreference(sharedPreferences, "access_token");
}
@Provides
@Singleton
Application provideApplication() {
return application;
}
@Provides
@Singleton
ApiClient provideApiClient(final ApiEndpoint apiEndpoint, final Build build, final String clientId, final CurrentUser currentUser, final Gson gson) {
return new ApiClient(apiEndpoint, build, clientId, currentUser, gson);
}
@Provides
@Singleton
@ForApplication
Context provideApplicationContext() {
return application;
}
@Provides
@Singleton
AssetManager provideAssetManager() {
return application.getAssets();
}
@Provides
@Singleton
Build provideBuild(final PackageInfo packageInfo) {
return new Build(packageInfo);
}
@Provides
@Singleton
String provideClientId(final ApiEndpoint apiEndpoint) {
return apiEndpoint == ApiEndpoint.PRODUCTION ?
"***REMOVED***" :
"***REMOVED***";
}
@Provides
@Singleton
ConfigLoader provideConfigLoader(final AssetManager assetManager) {
return new ConfigLoader(assetManager);
}
@Provides
@Singleton
CookieManager provideCookieManager() {
return new CookieManager();
}
@Provides
@Singleton
CurrentUser provideCurrentUser(@AccessTokenPreference final StringPreference accessTokenPreference,
final Gson gson,
@UserPreference final StringPreference userPreference) {
return new CurrentUser(accessTokenPreference, gson, userPreference);
}
@Provides
@Singleton
@WebEndpoint
String provideWebEndpoint(final ApiEndpoint apiEndpoint) {
final String url = (apiEndpoint == ApiEndpoint.PRODUCTION) ?
"https://www.kickstarter.com" :
apiEndpoint.url.replaceAll("(?<=\\Ahttps?:\\/\\/)api.", "");
return url;
}
@Provides
@Singleton
Font provideFont(final AssetManager assetManager) {
return new Font(assetManager);
}
@Provides
@Singleton
Gson provideGson(final AssetManager assetManager) {
return new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.registerTypeAdapter(DateTime.class, new DateTimeTypeConverter())
.registerTypeAdapterFactory(new AutoParcelAdapterFactory())
.create();
}
@Provides
@Singleton
KickstarterClient provideKickstarterClient(final Build build, @WebEndpoint final String webEndpoint) {
return new KickstarterClient(build, webEndpoint);
}
@Provides
KickstarterWebViewClient provideKickstarterWebViewClient(final Build build,
final CookieManager cookieManager,
final CurrentUser currentUser,
@WebEndpoint final String webEndpoint) {
return new KickstarterWebViewClient(build, cookieManager, currentUser, webEndpoint);
}
@Provides
@Singleton
Logout provideLogout(final CookieManager cookieManager, final CurrentUser currentUser) {
return new Logout(cookieManager, currentUser);
}
@Provides
@Singleton
Money provideMoney(final ConfigLoader configLoader) {
return new Money(configLoader);
}
@Provides
@Singleton
PackageInfo providePackageInfo(final Application application) {
try {
return application.getPackageManager().getPackageInfo(application.getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
String providePackageName(final Application application) {
return application.getPackageName();
}
@Provides
@Singleton
SharedPreferences provideSharedPreferences() {
return PreferenceManager.getDefaultSharedPreferences(application);
}
@Provides
@Singleton
@UserPreference
StringPreference provideUserPreference(final SharedPreferences sharedPreferences) {
return new StringPreference(sharedPreferences, "user");
}
}
| app/src/main/java/com/kickstarter/ApplicationModule.java | package com.kickstarter;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.preference.PreferenceManager;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.kickstarter.libs.ApiEndpoint;
import com.kickstarter.libs.AutoParcelAdapterFactory;
import com.kickstarter.libs.Build;
import com.kickstarter.libs.ConfigLoader;
import com.kickstarter.libs.CurrentUser;
import com.kickstarter.libs.DateTimeTypeConverter;
import com.kickstarter.libs.Font;
import com.kickstarter.libs.ForApplication;
import com.kickstarter.libs.Logout;
import com.kickstarter.libs.Money;
import com.kickstarter.libs.preferences.StringPreference;
import com.kickstarter.libs.qualifiers.AccessTokenPreference;
import com.kickstarter.libs.qualifiers.UserPreference;
import com.kickstarter.libs.qualifiers.WebEndpoint;
import com.kickstarter.services.ApiClient;
import com.kickstarter.services.KickstarterClient;
import com.kickstarter.services.KickstarterWebViewClient;
import org.joda.time.DateTime;
import java.net.CookieManager;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
@Module
public class ApplicationModule {
private final Application application;
public ApplicationModule(final Application application) {
this.application = application;
}
@Provides
@Singleton
@AccessTokenPreference
StringPreference provideAccessTokenPreference(final SharedPreferences sharedPreferences) {
return new StringPreference(sharedPreferences, "access_token");
}
@Provides
@Singleton
Application provideApplication() {
return application;
}
@Provides
@Singleton
ApiClient provideApiClient(final ApiEndpoint apiEndpoint, final Build build, final String clientId, final CurrentUser currentUser, final Gson gson) {
return new ApiClient(apiEndpoint, build, clientId, currentUser, gson);
}
@Provides
@Singleton
@ForApplication
Context provideApplicationContext() {
return application;
}
@Provides
@Singleton
AssetManager provideAssetManager() {
return application.getAssets();
}
@Provides
@Singleton
Build provideBuild(final PackageInfo packageInfo) {
return new Build(packageInfo);
}
@Provides
@Singleton
String provideClientId(final ApiEndpoint apiEndpoint) {
return apiEndpoint == ApiEndpoint.PRODUCTION ?
"***REMOVED***" :
"***REMOVED***";
}
@Provides
@Singleton
ConfigLoader provideConfigLoader(final AssetManager assetManager) {
return new ConfigLoader(assetManager);
}
@Provides
@Singleton
CookieManager provideCookieManager() {
return new CookieManager();
}
@Provides
@Singleton
CurrentUser provideCurrentUser(@AccessTokenPreference final StringPreference accessTokenPreference,
final Gson gson,
@UserPreference final StringPreference userPreference) {
return new CurrentUser(accessTokenPreference, gson, userPreference);
}
@Provides
@Singleton
@WebEndpoint
String provideWebEndpoint(final ApiEndpoint apiEndpoint) {
final String url = (apiEndpoint == ApiEndpoint.PRODUCTION) ?
"https://www.kickstarter.com" :
apiEndpoint.url.replaceAll("(?<=\\Ahttps?:\\/\\/)api.", "");
return url;
}
@Provides
@Singleton
Font provideFont(final AssetManager assetManager) {
return new Font(assetManager);
}
@Provides
@Singleton
Gson provideGson(final AssetManager assetManager) {
return new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.registerTypeAdapter(DateTime.class, new DateTimeTypeConverter())
.registerTypeAdapterFactory(new AutoParcelAdapterFactory())
.create();
}
@Provides
@Singleton
KickstarterClient provideKickstarterClient(final Build build, @WebEndpoint final String webEndpoint) {
return new KickstarterClient(build, webEndpoint);
}
@Provides
KickstarterWebViewClient provideKickstarterWebViewClient(final Build build,
final CookieManager cookieManager,
final CurrentUser currentUser,
@WebEndpoint final String webEndpoint) {
return new KickstarterWebViewClient(build, cookieManager, currentUser, webEndpoint);
}
@Provides
@Singleton
Logout provideLogout(final CookieManager cookieManager, final CurrentUser currentUser) {
return new Logout(cookieManager, currentUser);
}
@Provides
@Singleton
Money provideMoney(final ConfigLoader configLoader) {
return new Money(configLoader);
}
@Provides
@Singleton
PackageInfo providePackageInfo(final Application application) {
try {
return application.getPackageManager().getPackageInfo(application.getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
String providePackageName(final Application application) {
return application.getPackageName();
}
@Provides
@Singleton
SharedPreferences provideSharedPreferences() {
return PreferenceManager.getDefaultSharedPreferences(application);
}
@Provides
@Singleton
@UserPreference
StringPreference provideUserPreference(final SharedPreferences sharedPreferences) {
return new StringPreference(sharedPreferences, "user");
}
}
| Whitespace
| app/src/main/java/com/kickstarter/ApplicationModule.java | Whitespace | <ide><path>pp/src/main/java/com/kickstarter/ApplicationModule.java
<ide> .registerTypeAdapter(DateTime.class, new DateTimeTypeConverter())
<ide> .registerTypeAdapterFactory(new AutoParcelAdapterFactory())
<ide> .create();
<del>
<ide> }
<ide>
<ide> @Provides |
|
Java | mit | 12aa22e58d2a5ea2f0ef84f165ce5bb4e3540b7a | 0 | jking31cs/pokemon-learning,jking31cs/pokemon-learning | package com.jking31cs;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.jking31cs.state.Team;
/**
* Created by jking31 on 11/20/16.
*/
public class TeamReader {
private static Map<String, Team> teamsMap;
private static Map<String, List<String>> pokemonIndex;
public static void main(String[] args) throws IOException {
Map<String, List<String>> x = pokemonTeamIndex();
System.out.println(x);
}
public static Map<String, Team> readTeamsFromFile() throws IOException {
if (teamsMap != null) return teamsMap;
File teamFile = new File("output/teams.json");
ObjectMapper om = new ObjectMapper();
om.registerModule(new GuavaModule());
JavaType teamType = om.getTypeFactory().constructMapType(HashMap.class, String.class, Team.class);
teamsMap = om.readValue(teamFile, teamType);
return teamsMap;
}
public static Map<String, List<String>> pokemonTeamIndex() throws IOException {
if (pokemonIndex != null) return pokemonIndex;
File teamFile = new File("output/indexes/pk-team-index.json");
ObjectMapper om = new ObjectMapper();
om.registerModule(new GuavaModule());
JavaType indexType = om.getTypeFactory().constructMapType(HashMap.class, String.class, List.class);
pokemonIndex = om.readValue(teamFile, indexType);
return pokemonIndex;
}
public static void createPokemonIndex() throws IOException {
Map<String, Team> teams = readTeamsFromFile();
Map<String, List<String>> index = new HashMap<>();
for (String pokemon : PokemonListingCache.getAll().keySet()) {
index.put(pokemon, new ArrayList<>());
}
for (Team t : teams.values()) {
index.get(t.getP1()).add(t.getId());
index.get(t.getP2()).add(t.getId());
index.get(t.getP3()).add(t.getId());
}
ObjectMapper om = new ObjectMapper();
om.registerModule(new GuavaModule());
File indexDir = new File("output/indexes");
if (!indexDir.exists()) indexDir.mkdir();
om.writeValue(new File(indexDir, "pk-team-index.json"), index);
}
}
| src/main/java/com/jking31cs/TeamReader.java | package com.jking31cs;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.jking31cs.state.Team;
/**
* Created by jking31 on 11/20/16.
*/
public class TeamReader {
public static Map<String, Team> readTeamsFromFile() throws IOException {
File teamFile = new File("output/teams.json");
ObjectMapper om = new ObjectMapper();
om.registerModule(new GuavaModule());
JavaType teamType = om.getTypeFactory().constructMapType(HashMap.class, String.class, Team.class);
return om.readValue(teamFile, teamType);
}
}
| Created Pokemon-team index
| src/main/java/com/jking31cs/TeamReader.java | Created Pokemon-team index | <ide><path>rc/main/java/com/jking31cs/TeamReader.java
<ide>
<ide> import java.io.File;
<ide> import java.io.IOException;
<add>import java.util.ArrayList;
<ide> import java.util.HashMap;
<add>import java.util.List;
<ide> import java.util.Map;
<ide>
<ide> import com.fasterxml.jackson.databind.JavaType;
<ide> */
<ide> public class TeamReader {
<ide>
<add> private static Map<String, Team> teamsMap;
<add> private static Map<String, List<String>> pokemonIndex;
<add>
<add> public static void main(String[] args) throws IOException {
<add> Map<String, List<String>> x = pokemonTeamIndex();
<add> System.out.println(x);
<add> }
<add>
<ide> public static Map<String, Team> readTeamsFromFile() throws IOException {
<add> if (teamsMap != null) return teamsMap;
<ide> File teamFile = new File("output/teams.json");
<ide> ObjectMapper om = new ObjectMapper();
<ide> om.registerModule(new GuavaModule());
<ide> JavaType teamType = om.getTypeFactory().constructMapType(HashMap.class, String.class, Team.class);
<del> return om.readValue(teamFile, teamType);
<add> teamsMap = om.readValue(teamFile, teamType);
<add> return teamsMap;
<add> }
<add>
<add> public static Map<String, List<String>> pokemonTeamIndex() throws IOException {
<add> if (pokemonIndex != null) return pokemonIndex;
<add> File teamFile = new File("output/indexes/pk-team-index.json");
<add> ObjectMapper om = new ObjectMapper();
<add> om.registerModule(new GuavaModule());
<add> JavaType indexType = om.getTypeFactory().constructMapType(HashMap.class, String.class, List.class);
<add> pokemonIndex = om.readValue(teamFile, indexType);
<add> return pokemonIndex;
<add> }
<add>
<add> public static void createPokemonIndex() throws IOException {
<add> Map<String, Team> teams = readTeamsFromFile();
<add>
<add> Map<String, List<String>> index = new HashMap<>();
<add> for (String pokemon : PokemonListingCache.getAll().keySet()) {
<add> index.put(pokemon, new ArrayList<>());
<add> }
<add>
<add> for (Team t : teams.values()) {
<add> index.get(t.getP1()).add(t.getId());
<add> index.get(t.getP2()).add(t.getId());
<add> index.get(t.getP3()).add(t.getId());
<add> }
<add>
<add> ObjectMapper om = new ObjectMapper();
<add> om.registerModule(new GuavaModule());
<add> File indexDir = new File("output/indexes");
<add> if (!indexDir.exists()) indexDir.mkdir();
<add> om.writeValue(new File(indexDir, "pk-team-index.json"), index);
<add>
<ide> }
<ide> } |
|
Java | apache-2.0 | d93310acbe4fb7ae0aa9a9cba287cdd539b7735e | 0 | rsahlin/super-performance-sprites | package com.super2k.tiledspriteengine;
import java.io.IOException;
import java.util.Random;
import com.nucleus.android.AndroidGLUtils;
import com.nucleus.common.TimeKeeper;
import com.nucleus.geometry.VertexBuffer;
import com.nucleus.matrix.MatrixEngine;
import com.nucleus.mmi.MMIEventListener;
import com.nucleus.mmi.MMIPointerEvent;
import com.nucleus.mmi.PointerInputProcessor;
import com.nucleus.opengl.GLES20Wrapper;
import com.nucleus.opengl.GLES20Wrapper.GLES20;
import com.nucleus.opengl.GLException;
import com.nucleus.opengl.GLUtils;
import com.nucleus.renderer.BaseRenderer;
import com.nucleus.resource.ResourceBias;
import com.nucleus.resource.ResourceBias.RESOLUTION;
import com.nucleus.texturing.Image;
import com.nucleus.texturing.ImageFactory;
import com.nucleus.texturing.Texture2D;
import com.nucleus.texturing.TextureUtils;
import com.nucleus.transform.Vector2D;
import com.super2k.tiledspriteengine.sprite.Sprite;
import com.super2k.tiledspriteengine.sprite.TiledSprite;
import com.super2k.tiledspriteengine.sprite.TiledSpriteController;
public class TiledSpriteRenderer extends BaseRenderer implements MMIEventListener {
protected final static String TILED_SPRITE_RENDERER_TAG = "TiledSpiteRenderer";
private final static String TEXTURE_NAME = "assets/af.png";
public final static int SPRITECOUNT = 1200;
public final static int SPRITE_FRAMES_X = 5;
public final static int SPRITE_FRAMES_Y = 1;
public final static int START_XPOS = -1;
public final static int START_YPOS = 0;
public final static float SPRITE_WIDTH = 0.05f;
public final static float SPRITE_HEIGHT = 0.05f;
private PointerInputProcessor inputProcessor;
private TiledSpriteProgram tiledSpriteProgram;
private Image[] textureImg;
private Texture2D texture;
private int textureID;
private TiledSpriteController spriteController;
private int currentSprite = 0;
private TimeKeeper timeKeeper = new TimeKeeper(30);
private Random random = new Random();
public TiledSpriteRenderer(GLES20Wrapper gles, ImageFactory imageFactory, MatrixEngine matrixEngine,
PointerInputProcessor inputProcessor) {
super(gles, imageFactory, matrixEngine);
this.inputProcessor = inputProcessor;
inputProcessor.addMMIListener(this);
}
/**
* Create the programs for the fractal renderer.
*
*/
private void createPrograms() {
ClassLoader classLoader = getClass().getClassLoader();
tiledSpriteProgram = new TiledSpriteProgram();
try {
tiledSpriteProgram.prepareProgram(gles,
classLoader.getResourceAsStream(TiledSpriteProgram.VERTEX_SHADER_NAME),
classLoader.getResourceAsStream(TiledSpriteProgram.FRAGMENT_SHADER_NAME));
} catch (IOException e) {
throw new RuntimeException(e);
} catch (GLException e) {
throw new RuntimeException(e.toString());
}
}
@Override
public void beginFrame() {
super.beginFrame();
/**
* For now handling of logic is done before rendering
* TODO: Add logic handler separated from rendering.
*/
float deltaTime = timeKeeper.update();
if (timeKeeper.getSampleDuration() > 3) {
System.out.println(TILED_SPRITE_RENDERER_TAG + ": Average FPS: " + timeKeeper.sampleFPS());
}
for (TiledSprite sprite : spriteController.getSprites()) {
sprite.process(deltaTime);
}
}
/**
* The main render method, all drawing shall take place here.
*/
@Override
public void render() {
super.render();
try {
GLUtils.handleError(gles, "Error");
gles.glClearColor(0, 0f, 0.4f, 1.0f);
gles.glClear(GLES20.GL_COLOR_BUFFER_BIT);
gles.glDisable(GLES20.GL_DEPTH_TEST);
gles.glDisable(GLES20.GL_CULL_FACE);
gles.glUseProgram(tiledSpriteProgram.getProgram());
AndroidGLUtils.handleError("Program error");
VertexBuffer positions = spriteController.getMesh().getVerticeBuffer(1);
positions.setArray(spriteController.getData(), 0, 0, SPRITECOUNT
* TiledSpriteController.SPRITE_ATTRIBUTE_DATA);
renderMesh(spriteController.getMesh());
GLUtils.handleError(gles, "Error");
} catch (GLException e) {
throw new RuntimeException(e);
}
}
@Override
public void inputEvent(MMIPointerEvent event) {
float[] delta = event.getPointerData().getDelta(1);
switch (event.getAction()) {
case INACTIVE:
break;
case MOVE:
case ACTIVE:
float[] pos = event.getPointerData().getCurrentPosition();
float[] start = event.getPointerData().getFirstPosition();
releaseSprite(start, pos);
break;
case ZOOM:
Vector2D zoom = event.getZoom();
float z = ((zoom.vector[Vector2D.MAGNITUDE] * zoom.vector[Vector2D.X_AXIS]) / 1000);
break;
default:
}
}
private void releaseSprite(float[] start, float[] pos) {
pos[0] = pos[0] / width;
pos[1] = pos[1] / height;
Sprite s = spriteController.getSprites()[currentSprite];
s.setPosition(pos[0], pos[1]);
s.floatData[Sprite.GRAVITY_Y] = 0;
s.floatData[Sprite.ELASTICITY] = 0.95f - (random.nextFloat() / 10);
s.moveVector.setNormalized(pos[0] - start[0], 0);
s.floatData[Sprite.ROTATE_SPEED] = s.moveVector.vector[Vector2D.X_AXIS];
currentSprite++;
if (currentSprite > SPRITECOUNT - 1) {
currentSprite = 0;
}
}
@Override
public void GLContextCreated(int width, int height) {
super.GLContextCreated(width, height);
System.out.println(TILED_SPRITE_RENDERER_TAG + ": GLContextCreated: " + width + ", " + height);
createPrograms();
int[] textures = new int[1];
gles.glGenTextures(1, textures, 0);
textureID = textures[0];
textureImg = TextureUtils.loadTextureMIPMAP(imageFactory, TEXTURE_NAME,
ResourceBias.getScaleFactorLandscape(width, height, RESOLUTION.HD.lines), 3);
try {
uploadTextures(GLES20.GL_TEXTURE0, textureID, textureImg);
} catch (GLException e) {
throw new IllegalArgumentException(e);
}
texture = new Texture2D(textureID, textureImg[0].getWidth(), textureImg[0].getHeight());
texture.setValues(GLES20.GL_LINEAR, GLES20.GL_LINEAR, GLES20.GL_CLAMP_TO_EDGE, GLES20.GL_CLAMP_TO_EDGE);
spriteController = new TiledSpriteController(SPRITECOUNT);
spriteController.createMesh(tiledSpriteProgram, texture, SPRITE_WIDTH, SPRITE_HEIGHT, 1f / SPRITE_FRAMES_X,
1f / SPRITE_FRAMES_Y);
viewFrustum.setOrthoProjection(0, 1, 1, 0, 0, 10);
int frame = 0;
int maxFrames = SPRITE_FRAMES_X * SPRITE_FRAMES_Y - 1;
for (TiledSprite sprite : spriteController.getSprites()) {
sprite.setFrame(frame++);
if (frame > maxFrames) {
frame = 0;
}
sprite.setPosition(START_XPOS, START_YPOS);
}
}
/**
* Sets the active texture, binds texName and calls glTexImage2D on the images in the array where
* mip-map level will be same as the image index.
*
* @param texture Texture unit number (active texture)
* @param texName Name of texture object
* @param textureImages Array with one or more images to send to GL. If more than
* one image is specified then multiple mip-map levels will be set.
* Level 0 shall be at index 0
* @throws GLException If there is an error uploading the textures.
*/
public void uploadTextures(int texture, int texName, Image[] textureImages) throws GLException {
gles.glActiveTexture(texture);
gles.glBindTexture(GLES20.GL_TEXTURE_2D, texName);
int level = 0;
for (Image textureImg : textureImages) {
if (textureImg != null) {
gles.glTexImage2D(GLES20.GL_TEXTURE_2D, level, textureImg.getFormat().getFormat(),
textureImg.getWidth(),
textureImg
.getHeight(), 0, textureImg.getFormat().getFormat(), GLES20.GL_UNSIGNED_BYTE,
textureImg
.getBuffer()
.position(0));
GLUtils.handleError(gles, "texImage2D");
}
level++;
}
}
}
| src/com/super2k/tiledspriteengine/TiledSpriteRenderer.java | package com.super2k.tiledspriteengine;
import java.io.IOException;
import java.util.Random;
import com.nucleus.android.AndroidGLUtils;
import com.nucleus.common.TimeKeeper;
import com.nucleus.geometry.VertexBuffer;
import com.nucleus.matrix.MatrixEngine;
import com.nucleus.mmi.MMIEventListener;
import com.nucleus.mmi.MMIPointerEvent;
import com.nucleus.mmi.PointerInputProcessor;
import com.nucleus.opengl.GLES20Wrapper;
import com.nucleus.opengl.GLES20Wrapper.GLES20;
import com.nucleus.opengl.GLException;
import com.nucleus.opengl.GLUtils;
import com.nucleus.renderer.BaseRenderer;
import com.nucleus.resource.ResourceBias;
import com.nucleus.shader.ShaderProgram;
import com.nucleus.texturing.Image;
import com.nucleus.texturing.ImageFactory;
import com.nucleus.texturing.Texture2D;
import com.nucleus.transform.Vector2D;
import com.super2k.tiledspriteengine.sprite.Sprite;
import com.super2k.tiledspriteengine.sprite.TiledSprite;
import com.super2k.tiledspriteengine.sprite.TiledSpriteController;
public class TiledSpriteRenderer extends BaseRenderer implements MMIEventListener {
protected final static String TILED_SPRITE_RENDERER_TAG = "TiledSpiteRenderer";
public final static int SPRITECOUNT = 1200;
public final static int SPRITE_FRAMES_X = 5;
public final static int SPRITE_FRAMES_Y = 1;
public final static int START_XPOS = -1;
public final static int START_YPOS = 0;
public final static float SPRITE_WIDTH = 0.05f;
public final static float SPRITE_HEIGHT = 0.05f;
private PointerInputProcessor inputProcessor;
private ShaderProgram tiledSpriteProgram;
private Image[] textureImg;
private Texture2D texture;
private int textureID;
private TiledSpriteController spriteController;
private int currentSprite = 0;
private TimeKeeper timeKeeper = new TimeKeeper(30);
private Random random = new Random();
public TiledSpriteRenderer(GLES20Wrapper gles, ImageFactory imageFactory, MatrixEngine matrixEngine,
PointerInputProcessor inputProcessor) {
super(gles, imageFactory, matrixEngine);
this.inputProcessor = inputProcessor;
inputProcessor.addMMIListener(this);
}
/**
* Create the programs for the fractal renderer.
*
*/
private void createPrograms() {
ClassLoader classLoader = getClass().getClassLoader();
tiledSpriteProgram = new TiledSpriteProgram();
try {
tiledSpriteProgram.prepareProgram(gles,
classLoader.getResourceAsStream(TiledSpriteProgram.VERTEX_SHADER_NAME),
classLoader.getResourceAsStream(TiledSpriteProgram.FRAGMENT_SHADER_NAME));
} catch (IOException e) {
throw new RuntimeException(e);
} catch (GLException e) {
throw new RuntimeException(e.toString());
}
}
@Override
public void beginFrame() {
super.beginFrame();
/**
* For now handling of logic is done before rendering
* TODO: Add logic handler separated from rendering.
*/
float deltaTime = timeKeeper.update();
if (timeKeeper.getSampleDuration() > 3) {
System.out.println(TILED_SPRITE_RENDERER_TAG + ": Average FPS: " + timeKeeper.sampleFPS());
}
for (TiledSprite sprite : spriteController.getSprites()) {
sprite.process(deltaTime);
}
}
/**
* The main render method, all drawing shall take place here.
*/
@Override
public void render() {
super.render();
try {
GLUtils.handleError(gles, "Error");
gles.glClearColor(0, 0f, 0.4f, 1.0f);
gles.glClear(GLES20.GL_COLOR_BUFFER_BIT);
gles.glDisable(GLES20.GL_DEPTH_TEST);
gles.glDisable(GLES20.GL_CULL_FACE);
gles.glUseProgram(tiledSpriteProgram.getProgram());
AndroidGLUtils.handleError("Program error");
VertexBuffer positions = spriteController.getMesh().getVerticeBuffer(1);
positions.setArray(spriteController.getData(), 0, 0, SPRITECOUNT
* TiledSpriteController.SPRITE_ATTRIBUTE_DATA);
renderMesh(spriteController.getMesh());
GLUtils.handleError(gles, "Error");
} catch (GLException e) {
throw new RuntimeException(e);
}
}
@Override
public void inputEvent(MMIPointerEvent event) {
float[] delta = event.getPointerData().getDelta(1);
switch (event.getAction()) {
case INACTIVE:
break;
case MOVE:
case ACTIVE:
float[] pos = event.getPointerData().getCurrentPosition();
float[] start = event.getPointerData().getFirstPosition();
releaseSprite(start, pos);
break;
case ZOOM:
Vector2D zoom = event.getZoom();
float z = ((zoom.vector[Vector2D.MAGNITUDE] * zoom.vector[Vector2D.X_AXIS]) / 1000);
break;
default:
}
}
private void releaseSprite(float[] start, float[] pos) {
pos[0] = pos[0] / width;
pos[1] = pos[1] / height;
Sprite s = spriteController.getSprites()[currentSprite];
s.setPosition(pos[0], pos[1]);
s.floatData[Sprite.GRAVITY_Y] = 0;
s.floatData[Sprite.ELASTICITY] = 0.95f - (random.nextFloat() / 10);
s.moveVector.setNormalized(pos[0] - start[0], 0);
s.floatData[Sprite.ROTATE_SPEED] = s.moveVector.vector[Vector2D.X_AXIS];
currentSprite++;
if (currentSprite > SPRITECOUNT - 1) {
currentSprite = 0;
}
}
@Override
public void GLContextCreated(int width, int height) {
super.GLContextCreated(width, height);
System.out.println(TILED_SPRITE_RENDERER_TAG + ": GLContextCreated: " + width + ", " + height);
createPrograms();
int[] textures = new int[1];
gles.glGenTextures(1, textures, 0);
textureID = textures[0];
textureImg = loadTextureMIPMAP("assets/af.png", 1080, 3);
try {
uploadTextures(GLES20.GL_TEXTURE0, textureID, textureImg);
} catch (GLException e) {
throw new IllegalArgumentException(e);
}
texture = new Texture2D(textureID, textureImg[0].getWidth(), textureImg[0].getHeight());
texture.setValues(GLES20.GL_LINEAR, GLES20.GL_LINEAR, GLES20.GL_CLAMP_TO_EDGE, GLES20.GL_CLAMP_TO_EDGE);
spriteController = new TiledSpriteController(SPRITECOUNT);
spriteController
.createMesh(tiledSpriteProgram, texture, SPRITE_WIDTH, SPRITE_HEIGHT, 1f / SPRITE_FRAMES_X,
1f / SPRITE_FRAMES_Y);
viewFrustum.setOrthoProjection(0, 1, 1, 0, 0, 10);
int frame = 0;
int maxFrames = SPRITE_FRAMES_X * SPRITE_FRAMES_Y - 1;
for (TiledSprite sprite : spriteController.getSprites()) {
sprite.setFrame(frame++);
if (frame > maxFrames) {
frame = 0;
}
sprite.setPosition(START_XPOS, START_YPOS);
}
}
/**
* Loads an image into several mip-map levels, the same image will be scaled to produce the
* different mip-map levels.
* TODO: Add method to ImageFactory to scale existing image - currently re-loads image and scales.
*
* @param imageName Name of image to load
* @param baseHeight Base height of assets, image will be scaled compared to
* screen height. ie If base is 1080 and display height is 540 then the first mip-map level
* will be 1/2 original size.
* @param levels Number of mip-map levels
* @return Array with an image for each mip-map level.
*/
private Image[] loadTextureMIPMAP(String imageName, int baseHeight, int levels) {
Image[] images = new Image[levels];
try {
float scale = ResourceBias.getScaleFactorLandscape(width, height, baseHeight);
for (int i = 0; i < levels; i++) {
images[i] = imageFactory.createImage(imageName, scale, scale);
scale = scale * 0.5f;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return images;
}
/**
* Sets the active texture, binds texName and calls glTexImage2D on the images in the array where
* mip-map level will be same as the image index.
*
* @param texture Texture unit number (active texture)
* @param texName Name of texture object
* @param textureImages Array with one or more images to send to GL. If more than
* one image is specified then multiple mip-map levels will be set.
* Level 0 shall be at index 0
* @throws GLException If there is an error uploading the textures.
*/
public void uploadTextures(int texture, int texName, Image[] textureImages) throws GLException {
gles.glActiveTexture(texture);
gles.glBindTexture(GLES20.GL_TEXTURE_2D, texName);
int level = 0;
for (Image textureImg : textureImages) {
if (textureImg != null) {
gles.glTexImage2D(GLES20.GL_TEXTURE_2D, level, textureImg.getFormat().getFormat(),
textureImg.getWidth(),
textureImg
.getHeight(), 0, textureImg.getFormat().getFormat(), GLES20.GL_UNSIGNED_BYTE,
textureImg
.getBuffer()
.position(0));
GLUtils.handleError(gles, "texImage2D");
}
level++;
}
}
}
| Remove loadTexture function and use TextureUtils to load texture
| src/com/super2k/tiledspriteengine/TiledSpriteRenderer.java | Remove loadTexture function and use TextureUtils to load texture | <ide><path>rc/com/super2k/tiledspriteengine/TiledSpriteRenderer.java
<ide> import com.nucleus.opengl.GLUtils;
<ide> import com.nucleus.renderer.BaseRenderer;
<ide> import com.nucleus.resource.ResourceBias;
<del>import com.nucleus.shader.ShaderProgram;
<add>import com.nucleus.resource.ResourceBias.RESOLUTION;
<ide> import com.nucleus.texturing.Image;
<ide> import com.nucleus.texturing.ImageFactory;
<ide> import com.nucleus.texturing.Texture2D;
<add>import com.nucleus.texturing.TextureUtils;
<ide> import com.nucleus.transform.Vector2D;
<ide> import com.super2k.tiledspriteengine.sprite.Sprite;
<ide> import com.super2k.tiledspriteengine.sprite.TiledSprite;
<ide> public class TiledSpriteRenderer extends BaseRenderer implements MMIEventListener {
<ide>
<ide> protected final static String TILED_SPRITE_RENDERER_TAG = "TiledSpiteRenderer";
<add> private final static String TEXTURE_NAME = "assets/af.png";
<ide> public final static int SPRITECOUNT = 1200;
<ide> public final static int SPRITE_FRAMES_X = 5;
<ide> public final static int SPRITE_FRAMES_Y = 1;
<ide> public final static float SPRITE_HEIGHT = 0.05f;
<ide>
<ide> private PointerInputProcessor inputProcessor;
<del> private ShaderProgram tiledSpriteProgram;
<add> private TiledSpriteProgram tiledSpriteProgram;
<ide> private Image[] textureImg;
<ide> private Texture2D texture;
<ide> private int textureID;
<ide>
<ide> textureID = textures[0];
<ide>
<del> textureImg = loadTextureMIPMAP("assets/af.png", 1080, 3);
<add> textureImg = TextureUtils.loadTextureMIPMAP(imageFactory, TEXTURE_NAME,
<add> ResourceBias.getScaleFactorLandscape(width, height, RESOLUTION.HD.lines), 3);
<ide>
<ide> try {
<ide> uploadTextures(GLES20.GL_TEXTURE0, textureID, textureImg);
<ide> texture = new Texture2D(textureID, textureImg[0].getWidth(), textureImg[0].getHeight());
<ide> texture.setValues(GLES20.GL_LINEAR, GLES20.GL_LINEAR, GLES20.GL_CLAMP_TO_EDGE, GLES20.GL_CLAMP_TO_EDGE);
<ide> spriteController = new TiledSpriteController(SPRITECOUNT);
<del> spriteController
<del> .createMesh(tiledSpriteProgram, texture, SPRITE_WIDTH, SPRITE_HEIGHT, 1f / SPRITE_FRAMES_X,
<del> 1f / SPRITE_FRAMES_Y);
<add> spriteController.createMesh(tiledSpriteProgram, texture, SPRITE_WIDTH, SPRITE_HEIGHT, 1f / SPRITE_FRAMES_X,
<add> 1f / SPRITE_FRAMES_Y);
<ide> viewFrustum.setOrthoProjection(0, 1, 1, 0, 0, 10);
<ide> int frame = 0;
<ide> int maxFrames = SPRITE_FRAMES_X * SPRITE_FRAMES_Y - 1;
<ide> sprite.setPosition(START_XPOS, START_YPOS);
<ide> }
<ide>
<del> }
<del>
<del> /**
<del> * Loads an image into several mip-map levels, the same image will be scaled to produce the
<del> * different mip-map levels.
<del> * TODO: Add method to ImageFactory to scale existing image - currently re-loads image and scales.
<del> *
<del> * @param imageName Name of image to load
<del> * @param baseHeight Base height of assets, image will be scaled compared to
<del> * screen height. ie If base is 1080 and display height is 540 then the first mip-map level
<del> * will be 1/2 original size.
<del> * @param levels Number of mip-map levels
<del> * @return Array with an image for each mip-map level.
<del> */
<del> private Image[] loadTextureMIPMAP(String imageName, int baseHeight, int levels) {
<del>
<del> Image[] images = new Image[levels];
<del> try {
<del> float scale = ResourceBias.getScaleFactorLandscape(width, height, baseHeight);
<del> for (int i = 0; i < levels; i++) {
<del> images[i] = imageFactory.createImage(imageName, scale, scale);
<del> scale = scale * 0.5f;
<del> }
<del> } catch (IOException e) {
<del> throw new RuntimeException(e);
<del> }
<del> return images;
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | error: pathspec 'src/main/java/com/gochinatv/cdn/api/basic/nio/ByteBufferTest.java' did not match any file(s) known to git
| d6a3fe8dc166e72fe6cf363660989ea03a60de04 | 1 | jacktomcat/aggregation | package com.gochinatv.cdn.api.basic.nio;
import java.nio.ByteBuffer;
public class ByteBufferTest {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(5);
System.out.println("初始化 capacity:" +buffer.capacity()+" limit:"+buffer.limit()+" position:"+buffer.position()+" remaining:"+buffer.remaining());
buffer.put("abcde".getBytes());
System.out.println("put 字符串 `zhang`之后 capacity:" +buffer.capacity()+" limit:"+buffer.limit()+" position:"+buffer.position()+" remaining:"+buffer.remaining());
buffer.flip();
System.out.println("flip 之后 capacity:" +buffer.capacity()+" limit:"+buffer.limit()+" position:"+buffer.position()+" remaining:"+buffer.remaining());
//buffer.compact();// 切换compact写模式
//buffer.put("d".getBytes());
byte[] dest_copy = new byte[buffer.limit()];
buffer.duplicate().get(dest_copy);
System.out.println(new String(dest_copy));
byte[] dest = new byte[buffer.limit()];
buffer.get(dest, 0, buffer.limit());
System.out.println(new String(dest));
System.out.println(buffer.get());
//buffer.clear();
//buffer.mark();
//System.out.println("clear 之后 capacity:" +buffer.capacity()+" limit:"+buffer.limit()+" position:"+buffer.position()+" remaining:"+buffer.remaining());
//buffer.put("springtyp".getBytes());
}
}
| src/main/java/com/gochinatv/cdn/api/basic/nio/ByteBufferTest.java | add nio support | src/main/java/com/gochinatv/cdn/api/basic/nio/ByteBufferTest.java | add nio support | <ide><path>rc/main/java/com/gochinatv/cdn/api/basic/nio/ByteBufferTest.java
<add>package com.gochinatv.cdn.api.basic.nio;
<add>
<add>import java.nio.ByteBuffer;
<add>
<add>
<add>public class ByteBufferTest {
<add>
<add>
<add> public static void main(String[] args) {
<add>
<add> ByteBuffer buffer = ByteBuffer.allocate(5);
<add> System.out.println("初始化 capacity:" +buffer.capacity()+" limit:"+buffer.limit()+" position:"+buffer.position()+" remaining:"+buffer.remaining());
<add> buffer.put("abcde".getBytes());
<add> System.out.println("put 字符串 `zhang`之后 capacity:" +buffer.capacity()+" limit:"+buffer.limit()+" position:"+buffer.position()+" remaining:"+buffer.remaining());
<add> buffer.flip();
<add> System.out.println("flip 之后 capacity:" +buffer.capacity()+" limit:"+buffer.limit()+" position:"+buffer.position()+" remaining:"+buffer.remaining());
<add> //buffer.compact();// 切换compact写模式
<add> //buffer.put("d".getBytes());
<add> byte[] dest_copy = new byte[buffer.limit()];
<add> buffer.duplicate().get(dest_copy);
<add> System.out.println(new String(dest_copy));
<add>
<add> byte[] dest = new byte[buffer.limit()];
<add> buffer.get(dest, 0, buffer.limit());
<add> System.out.println(new String(dest));
<add>
<add> System.out.println(buffer.get());
<add>
<add> //buffer.clear();
<add> //buffer.mark();
<add>
<add> //System.out.println("clear 之后 capacity:" +buffer.capacity()+" limit:"+buffer.limit()+" position:"+buffer.position()+" remaining:"+buffer.remaining());
<add>
<add> //buffer.put("springtyp".getBytes());
<add> }
<add>
<add>
<add>} |
|
Java | apache-2.0 | ac5d3dce1fdd7692a9a7db83348a670aafeeaa01 | 0 | yanagishima/yanagishima,yanagishima/yanagishima,yanagishima/yanagishima,yanagishima/yanagishima | package yanagishima.servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import yanagishima.config.YanagishimaConfig;
import yanagishima.result.PrestoQueryResult;
import yanagishima.service.PrestoService;
import yanagishima.util.AccessControlUtil;
import yanagishima.util.HttpRequestUtil;
import yanagishima.util.JsonUtil;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import static com.facebook.presto.client.OkHttpUtil.basicAuth;
import static com.google.common.base.Preconditions.checkArgument;
import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
import static yanagishima.util.Constants.YANAGISHIMA_COMMENT;
@Singleton
public class PrestoPartitionServlet extends HttpServlet {
private static Logger LOGGER = LoggerFactory
.getLogger(PrestoPartitionServlet.class);
private static final long serialVersionUID = 1L;
private PrestoService prestoService;
private YanagishimaConfig yanagishimaConfig;
@Inject
public PrestoPartitionServlet(PrestoService prestoService, YanagishimaConfig yanagishimaConfig) {
this.prestoService = prestoService;
this.yanagishimaConfig = yanagishimaConfig;
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HashMap<String, Object> retVal = new HashMap<String, Object>();
try {
String datasource = HttpRequestUtil.getParam(request, "datasource");
if (yanagishimaConfig.isCheckDatasource()) {
if (!AccessControlUtil.validateDatasource(request, datasource)) {
try {
response.sendError(SC_FORBIDDEN);
return;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
String userName = null;
Optional<String> prestoUser = Optional.ofNullable(request.getParameter("user"));
Optional<String> prestoPassword = Optional.ofNullable(request.getParameter("password"));
if(yanagishimaConfig.isUseAuditHttpHeaderName()) {
userName = request.getHeader(yanagishimaConfig.getAuditHttpHeaderName());
} else {
if (prestoUser.isPresent() && prestoPassword.isPresent()) {
userName = prestoUser.get();
}
}
String catalog = HttpRequestUtil.getParam(request, "catalog");
String schema = HttpRequestUtil.getParam(request, "schema");
String table = HttpRequestUtil.getParam(request, "table");
String partitionColumn = request.getParameter("partitionColumn");
String partitionColumnType = request.getParameter("partitionColumnType");
String partitionValue = request.getParameter("partitionValue");
if (partitionColumn == null || partitionValue == null) {
Optional<String> webhdfsUrlOptional = yanagishimaConfig.getWebhdfsUrl(datasource, catalog, schema, table);
if(webhdfsUrlOptional.isPresent()) {
setFirstPartitionWIthWebhdfs(retVal, prestoUser, prestoPassword, webhdfsUrlOptional.get());
} else {
String query = null;
if(yanagishimaConfig.isUseNewShowPartitions(datasource)) {
query = String.format("%sSELECT * FROM %s.%s.\"%s$partitions\"", YANAGISHIMA_COMMENT, catalog, schema, table);
} else {
query = String.format("%sSHOW PARTITIONS FROM %s.%s.\"%s\"", YANAGISHIMA_COMMENT, catalog, schema, table);
}
if(userName != null) {
LOGGER.info(String.format("%s executed %s in %s", userName, query, datasource));
}
PrestoQueryResult prestoQueryResult = prestoService.doQuery(datasource, query, userName, prestoUser, prestoPassword, false, Integer.MAX_VALUE);
retVal.put("column", prestoQueryResult.getColumns().get(0));
Set<String> partitions = new TreeSet<>();
List<List<String>> records = prestoQueryResult.getRecords();
for (List<String> row : records) {
String data = row.get(0);
if(data != null) {
partitions.add(data);
}
}
retVal.put("partitions", partitions);
}
} else {
String[] partitionColumnArray = partitionColumn.split(",");
String[] partitionColumnTypeArray = partitionColumnType.split(",");
String[] partitionValuesArray = partitionValue.split(",");
if(partitionColumnArray.length != partitionValuesArray.length) {
throw new RuntimeException("The number of partitionColumn must be same as partitionValue");
}
Optional<String> webhdfsUrlOptional = yanagishimaConfig.getWebhdfsUrl(datasource, catalog, schema, table);
if(webhdfsUrlOptional.isPresent()) {
List pathList = new ArrayList<>();
for(int i=0; i<partitionColumnArray.length; i++) {
pathList.add(String.format("%s=%s", partitionColumnArray[i], partitionValuesArray[i]));
}
setFirstPartitionWIthWebhdfs(retVal, prestoUser, prestoPassword, webhdfsUrlOptional.get() + "/" + String.join("/", pathList));
} else {
List whereList = new ArrayList<>();
for(int i=0; i<partitionColumnArray.length; i++) {
if(partitionColumnTypeArray[i].equals("varchar")) {
whereList.add(String.format("%s = '%s'", partitionColumnArray[i], partitionValuesArray[i]));
} else {
whereList.add(String.format("%s = %s", partitionColumnArray[i], partitionValuesArray[i]));
}
}
String query = null;
if(yanagishimaConfig.isUseNewShowPartitions(datasource)) {
query = String.format("%sSELECT * FROM %s.%s.\"%s$partitions\" WHERE %s", YANAGISHIMA_COMMENT, catalog, schema, table, String.join(" AND ", whereList));
} else {
query = String.format("%sSHOW PARTITIONS FROM %s.%s.%s WHERE %s", YANAGISHIMA_COMMENT, catalog, schema, table, String.join(" AND ", whereList));
}
if(userName != null) {
LOGGER.info(String.format("%s executed %s in %s", userName, query, datasource));
}
PrestoQueryResult prestoQueryResult = prestoService.doQuery(datasource, query, userName, prestoUser, prestoPassword, false, Integer.MAX_VALUE);
List<String> columns = prestoQueryResult.getColumns();
int index = 0;
for (String column : columns) {
if (column.equals(partitionColumnArray[partitionColumnArray.length-1])) {
break;
}
index++;
}
retVal.put("column", columns.get(index + 1));
Set<String> partitions = new TreeSet<>();
List<List<String>> records = prestoQueryResult.getRecords();
for (List<String> row : records) {
partitions.add(row.get(index + 1));
}
retVal.put("partitions", partitions);
}
}
} catch (Throwable e) {
LOGGER.error(e.getMessage(), e);
retVal.put("error", e.getMessage());
}
JsonUtil.writeJSON(response, retVal);
}
private void setFirstPartitionWIthWebhdfs(HashMap<String, Object> retVal, Optional<String> prestoUser, Optional<String> prestoPassword, String webhdfsUrl) throws IOException {
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
if (prestoUser.isPresent() && prestoPassword.isPresent()) {
checkArgument(webhdfsUrl.startsWith("https"),
"Authentication using username/password requires HTTPS to be enabled");
clientBuilder.addInterceptor(basicAuth(prestoUser.get(), prestoPassword.get()));
}
OkHttpClient client = clientBuilder.build();
Request okhttpRequest = new Request.Builder().url(webhdfsUrl + "?op=LISTSTATUS").build();
try (Response okhttpResponse = client.newCall(okhttpRequest).execute()) {
if (!okhttpResponse.isSuccessful()) {
throw new IOException("Unexpected code " + okhttpResponse);
}
String json = okhttpResponse.body().string();
// "FileStatuses": {
// "FileStatus": [
// {
// "accessTime": 0,
// "blockSize": 0,
// "childrenNum": 271,
// "fileId": 43732679,
// "group": "hdfs",
// "length": 0,
// "modificationTime": 1527567948631,
// "owner": "hive",
// "pathSuffix": "hoge=piyo",
// "permission": "777",
// "replication": 0,
// "storagePolicy": 0,
// "type": "DIRECTORY"
// },
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readValue(json, Map.class);
List<Map> partitionList = (List) ((Map) map.get("FileStatuses")).get("FileStatus");
if(partitionList.size() > 0) {
Set<String> partitions = new TreeSet<>();
for(Map m : partitionList) {
String data = (String)m.get("pathSuffix");
if(data != null && data.contains("=")) {
if(retVal.get("column") == null) {
retVal.put("column", data.split("=")[0]);
}
partitions.add(data.split("=")[1]);
}
}
retVal.put("partitions", partitions);
}
}
}
}
| src/main/java/yanagishima/servlet/PrestoPartitionServlet.java | package yanagishima.servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import yanagishima.config.YanagishimaConfig;
import yanagishima.result.PrestoQueryResult;
import yanagishima.service.PrestoService;
import yanagishima.util.AccessControlUtil;
import yanagishima.util.HttpRequestUtil;
import yanagishima.util.JsonUtil;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import static com.facebook.presto.client.OkHttpUtil.basicAuth;
import static com.google.common.base.Preconditions.checkArgument;
import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
import static yanagishima.util.Constants.YANAGISHIMA_COMMENT;
@Singleton
public class PrestoPartitionServlet extends HttpServlet {
private static Logger LOGGER = LoggerFactory
.getLogger(PrestoPartitionServlet.class);
private static final long serialVersionUID = 1L;
private PrestoService prestoService;
private YanagishimaConfig yanagishimaConfig;
@Inject
public PrestoPartitionServlet(PrestoService prestoService, YanagishimaConfig yanagishimaConfig) {
this.prestoService = prestoService;
this.yanagishimaConfig = yanagishimaConfig;
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HashMap<String, Object> retVal = new HashMap<String, Object>();
try {
String datasource = HttpRequestUtil.getParam(request, "datasource");
if (yanagishimaConfig.isCheckDatasource()) {
if (!AccessControlUtil.validateDatasource(request, datasource)) {
try {
response.sendError(SC_FORBIDDEN);
return;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
String userName = null;
Optional<String> prestoUser = Optional.ofNullable(request.getParameter("user"));
Optional<String> prestoPassword = Optional.ofNullable(request.getParameter("password"));
if(yanagishimaConfig.isUseAuditHttpHeaderName()) {
userName = request.getHeader(yanagishimaConfig.getAuditHttpHeaderName());
} else {
if (prestoUser.isPresent() && prestoPassword.isPresent()) {
userName = prestoUser.get();
}
}
String catalog = HttpRequestUtil.getParam(request, "catalog");
String schema = HttpRequestUtil.getParam(request, "schema");
String table = HttpRequestUtil.getParam(request, "table");
String partitionColumn = request.getParameter("partitionColumn");
String partitionColumnType = request.getParameter("partitionColumnType");
String partitionValue = request.getParameter("partitionValue");
if (partitionColumn == null || partitionValue == null) {
Optional<String> webhdfsUrlOptional = yanagishimaConfig.getWebhdfsUrl(datasource, catalog, schema, table);
if(webhdfsUrlOptional.isPresent()) {
String webhdfsUrl = webhdfsUrlOptional.get();
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
if (prestoUser.isPresent() && prestoPassword.isPresent()) {
checkArgument(webhdfsUrl.startsWith("https"),
"Authentication using username/password requires HTTPS to be enabled");
clientBuilder.addInterceptor(basicAuth(prestoUser.get(), prestoPassword.get()));
}
OkHttpClient client = clientBuilder.build();
Request okhttpRequest = new Request.Builder().url(webhdfsUrl).build();
try (Response okhttpResponse = client.newCall(okhttpRequest).execute()) {
if (!okhttpResponse.isSuccessful()) {
throw new IOException("Unexpected code " + okhttpResponse);
}
String json = okhttpResponse.body().string();
// "FileStatuses": {
// "FileStatus": [
// {
// "accessTime": 0,
// "blockSize": 0,
// "childrenNum": 271,
// "fileId": 43732679,
// "group": "hdfs",
// "length": 0,
// "modificationTime": 1527567948631,
// "owner": "hive",
// "pathSuffix": "hoge=piyo",
// "permission": "777",
// "replication": 0,
// "storagePolicy": 0,
// "type": "DIRECTORY"
// },
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readValue(json, Map.class);
List<Map> topLevelPartitionList = (List) ((Map) map.get("FileStatuses")).get("FileStatus");
if(topLevelPartitionList.size() > 0) {
Set<String> partitions = new TreeSet<>();
for(Map m : topLevelPartitionList) {
String data = (String)m.get("pathSuffix");
if(data != null && data.contains("=")) {
if(retVal.get("column") == null) {
retVal.put("column", data.split("=")[0]);
}
partitions.add(data.split("=")[1]);
}
}
retVal.put("partitions", partitions);
}
}
} else {
String query = null;
if(yanagishimaConfig.isUseNewShowPartitions(datasource)) {
query = String.format("%sSELECT * FROM %s.%s.\"%s$partitions\"", YANAGISHIMA_COMMENT, catalog, schema, table);
} else {
query = String.format("%sSHOW PARTITIONS FROM %s.%s.\"%s\"", YANAGISHIMA_COMMENT, catalog, schema, table);
}
if(userName != null) {
LOGGER.info(String.format("%s executed %s in %s", userName, query, datasource));
}
PrestoQueryResult prestoQueryResult = prestoService.doQuery(datasource, query, userName, prestoUser, prestoPassword, false, Integer.MAX_VALUE);
retVal.put("column", prestoQueryResult.getColumns().get(0));
Set<String> partitions = new TreeSet<>();
List<List<String>> records = prestoQueryResult.getRecords();
for (List<String> row : records) {
String data = row.get(0);
if(data != null) {
partitions.add(data);
}
}
retVal.put("partitions", partitions);
}
} else {
String[] partitionColumnArray = partitionColumn.split(",");
String[] partitionColumnTypeArray = partitionColumnType.split(",");
String[] partitionValuesArray = partitionValue.split(",");
if(partitionColumnArray.length != partitionValuesArray.length) {
throw new RuntimeException("The number of partitionColumn must be same as partitionValue");
}
List whereList = new ArrayList<>();
for(int i=0; i<partitionColumnArray.length; i++) {
if(partitionColumnTypeArray[i].equals("varchar")) {
whereList.add(String.format("%s = '%s'", partitionColumnArray[i], partitionValuesArray[i]));
} else {
whereList.add(String.format("%s = %s", partitionColumnArray[i], partitionValuesArray[i]));
}
}
String query = null;
if(yanagishimaConfig.isUseNewShowPartitions(datasource)) {
query = String.format("%sSELECT * FROM %s.%s.\"%s$partitions\" WHERE %s", YANAGISHIMA_COMMENT, catalog, schema, table, String.join(" AND ", whereList));
} else {
query = String.format("%sSHOW PARTITIONS FROM %s.%s.%s WHERE %s", YANAGISHIMA_COMMENT, catalog, schema, table, String.join(" AND ", whereList));
}
if(userName != null) {
LOGGER.info(String.format("%s executed %s in %s", userName, query, datasource));
}
PrestoQueryResult prestoQueryResult = prestoService.doQuery(datasource, query, userName, prestoUser, prestoPassword, false, Integer.MAX_VALUE);
List<String> columns = prestoQueryResult.getColumns();
int index = 0;
for (String column : columns) {
if (column.equals(partitionColumnArray[partitionColumnArray.length-1])) {
break;
}
index++;
}
retVal.put("column", columns.get(index + 1));
Set<String> partitions = new TreeSet<>();
List<List<String>> records = prestoQueryResult.getRecords();
for (List<String> row : records) {
partitions.add(row.get(index + 1));
}
retVal.put("partitions", partitions);
}
} catch (Throwable e) {
LOGGER.error(e.getMessage(), e);
retVal.put("error", e.getMessage());
}
JsonUtil.writeJSON(response, retVal);
}
}
| improve partition fetching logic with webhdfs
| src/main/java/yanagishima/servlet/PrestoPartitionServlet.java | improve partition fetching logic with webhdfs | <ide><path>rc/main/java/yanagishima/servlet/PrestoPartitionServlet.java
<ide> if (partitionColumn == null || partitionValue == null) {
<ide> Optional<String> webhdfsUrlOptional = yanagishimaConfig.getWebhdfsUrl(datasource, catalog, schema, table);
<ide> if(webhdfsUrlOptional.isPresent()) {
<del> String webhdfsUrl = webhdfsUrlOptional.get();
<del> OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
<del> if (prestoUser.isPresent() && prestoPassword.isPresent()) {
<del> checkArgument(webhdfsUrl.startsWith("https"),
<del> "Authentication using username/password requires HTTPS to be enabled");
<del> clientBuilder.addInterceptor(basicAuth(prestoUser.get(), prestoPassword.get()));
<del> }
<del> OkHttpClient client = clientBuilder.build();
<del> Request okhttpRequest = new Request.Builder().url(webhdfsUrl).build();
<del> try (Response okhttpResponse = client.newCall(okhttpRequest).execute()) {
<del> if (!okhttpResponse.isSuccessful()) {
<del> throw new IOException("Unexpected code " + okhttpResponse);
<del> }
<del> String json = okhttpResponse.body().string();
<add> setFirstPartitionWIthWebhdfs(retVal, prestoUser, prestoPassword, webhdfsUrlOptional.get());
<add> } else {
<add> String query = null;
<add> if(yanagishimaConfig.isUseNewShowPartitions(datasource)) {
<add> query = String.format("%sSELECT * FROM %s.%s.\"%s$partitions\"", YANAGISHIMA_COMMENT, catalog, schema, table);
<add> } else {
<add> query = String.format("%sSHOW PARTITIONS FROM %s.%s.\"%s\"", YANAGISHIMA_COMMENT, catalog, schema, table);
<add> }
<add> if(userName != null) {
<add> LOGGER.info(String.format("%s executed %s in %s", userName, query, datasource));
<add> }
<add> PrestoQueryResult prestoQueryResult = prestoService.doQuery(datasource, query, userName, prestoUser, prestoPassword, false, Integer.MAX_VALUE);
<add> retVal.put("column", prestoQueryResult.getColumns().get(0));
<add> Set<String> partitions = new TreeSet<>();
<add> List<List<String>> records = prestoQueryResult.getRecords();
<add> for (List<String> row : records) {
<add> String data = row.get(0);
<add> if(data != null) {
<add> partitions.add(data);
<add> }
<add> }
<add> retVal.put("partitions", partitions);
<add> }
<add> } else {
<add> String[] partitionColumnArray = partitionColumn.split(",");
<add> String[] partitionColumnTypeArray = partitionColumnType.split(",");
<add> String[] partitionValuesArray = partitionValue.split(",");
<add> if(partitionColumnArray.length != partitionValuesArray.length) {
<add> throw new RuntimeException("The number of partitionColumn must be same as partitionValue");
<add> }
<add>
<add> Optional<String> webhdfsUrlOptional = yanagishimaConfig.getWebhdfsUrl(datasource, catalog, schema, table);
<add> if(webhdfsUrlOptional.isPresent()) {
<add> List pathList = new ArrayList<>();
<add> for(int i=0; i<partitionColumnArray.length; i++) {
<add> pathList.add(String.format("%s=%s", partitionColumnArray[i], partitionValuesArray[i]));
<add> }
<add> setFirstPartitionWIthWebhdfs(retVal, prestoUser, prestoPassword, webhdfsUrlOptional.get() + "/" + String.join("/", pathList));
<add> } else {
<add> List whereList = new ArrayList<>();
<add> for(int i=0; i<partitionColumnArray.length; i++) {
<add> if(partitionColumnTypeArray[i].equals("varchar")) {
<add> whereList.add(String.format("%s = '%s'", partitionColumnArray[i], partitionValuesArray[i]));
<add> } else {
<add> whereList.add(String.format("%s = %s", partitionColumnArray[i], partitionValuesArray[i]));
<add> }
<add> }
<add> String query = null;
<add> if(yanagishimaConfig.isUseNewShowPartitions(datasource)) {
<add> query = String.format("%sSELECT * FROM %s.%s.\"%s$partitions\" WHERE %s", YANAGISHIMA_COMMENT, catalog, schema, table, String.join(" AND ", whereList));
<add> } else {
<add> query = String.format("%sSHOW PARTITIONS FROM %s.%s.%s WHERE %s", YANAGISHIMA_COMMENT, catalog, schema, table, String.join(" AND ", whereList));
<add> }
<add> if(userName != null) {
<add> LOGGER.info(String.format("%s executed %s in %s", userName, query, datasource));
<add> }
<add> PrestoQueryResult prestoQueryResult = prestoService.doQuery(datasource, query, userName, prestoUser, prestoPassword, false, Integer.MAX_VALUE);
<add> List<String> columns = prestoQueryResult.getColumns();
<add> int index = 0;
<add> for (String column : columns) {
<add> if (column.equals(partitionColumnArray[partitionColumnArray.length-1])) {
<add> break;
<add> }
<add> index++;
<add> }
<add> retVal.put("column", columns.get(index + 1));
<add> Set<String> partitions = new TreeSet<>();
<add> List<List<String>> records = prestoQueryResult.getRecords();
<add> for (List<String> row : records) {
<add> partitions.add(row.get(index + 1));
<add> }
<add> retVal.put("partitions", partitions);
<add> }
<add> }
<add> } catch (Throwable e) {
<add> LOGGER.error(e.getMessage(), e);
<add> retVal.put("error", e.getMessage());
<add> }
<add>
<add> JsonUtil.writeJSON(response, retVal);
<add>
<add> }
<add>
<add> private void setFirstPartitionWIthWebhdfs(HashMap<String, Object> retVal, Optional<String> prestoUser, Optional<String> prestoPassword, String webhdfsUrl) throws IOException {
<add> OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
<add> if (prestoUser.isPresent() && prestoPassword.isPresent()) {
<add> checkArgument(webhdfsUrl.startsWith("https"),
<add> "Authentication using username/password requires HTTPS to be enabled");
<add> clientBuilder.addInterceptor(basicAuth(prestoUser.get(), prestoPassword.get()));
<add> }
<add> OkHttpClient client = clientBuilder.build();
<add> Request okhttpRequest = new Request.Builder().url(webhdfsUrl + "?op=LISTSTATUS").build();
<add> try (Response okhttpResponse = client.newCall(okhttpRequest).execute()) {
<add> if (!okhttpResponse.isSuccessful()) {
<add> throw new IOException("Unexpected code " + okhttpResponse);
<add> }
<add> String json = okhttpResponse.body().string();
<ide> // "FileStatuses": {
<ide> // "FileStatus": [
<ide> // {
<ide> // "storagePolicy": 0,
<ide> // "type": "DIRECTORY"
<ide> // },
<del> ObjectMapper mapper = new ObjectMapper();
<del> Map map = mapper.readValue(json, Map.class);
<del> List<Map> topLevelPartitionList = (List) ((Map) map.get("FileStatuses")).get("FileStatus");
<del> if(topLevelPartitionList.size() > 0) {
<del> Set<String> partitions = new TreeSet<>();
<del> for(Map m : topLevelPartitionList) {
<del> String data = (String)m.get("pathSuffix");
<del> if(data != null && data.contains("=")) {
<del> if(retVal.get("column") == null) {
<del> retVal.put("column", data.split("=")[0]);
<del> }
<del> partitions.add(data.split("=")[1]);
<del> }
<del> }
<del> retVal.put("partitions", partitions);
<del> }
<del> }
<del> } else {
<del> String query = null;
<del> if(yanagishimaConfig.isUseNewShowPartitions(datasource)) {
<del> query = String.format("%sSELECT * FROM %s.%s.\"%s$partitions\"", YANAGISHIMA_COMMENT, catalog, schema, table);
<del> } else {
<del> query = String.format("%sSHOW PARTITIONS FROM %s.%s.\"%s\"", YANAGISHIMA_COMMENT, catalog, schema, table);
<del> }
<del> if(userName != null) {
<del> LOGGER.info(String.format("%s executed %s in %s", userName, query, datasource));
<del> }
<del> PrestoQueryResult prestoQueryResult = prestoService.doQuery(datasource, query, userName, prestoUser, prestoPassword, false, Integer.MAX_VALUE);
<del> retVal.put("column", prestoQueryResult.getColumns().get(0));
<del> Set<String> partitions = new TreeSet<>();
<del> List<List<String>> records = prestoQueryResult.getRecords();
<del> for (List<String> row : records) {
<del> String data = row.get(0);
<del> if(data != null) {
<del> partitions.add(data);
<del> }
<del> }
<del> retVal.put("partitions", partitions);
<del> }
<del> } else {
<del> String[] partitionColumnArray = partitionColumn.split(",");
<del> String[] partitionColumnTypeArray = partitionColumnType.split(",");
<del> String[] partitionValuesArray = partitionValue.split(",");
<del> if(partitionColumnArray.length != partitionValuesArray.length) {
<del> throw new RuntimeException("The number of partitionColumn must be same as partitionValue");
<del> }
<del> List whereList = new ArrayList<>();
<del> for(int i=0; i<partitionColumnArray.length; i++) {
<del> if(partitionColumnTypeArray[i].equals("varchar")) {
<del> whereList.add(String.format("%s = '%s'", partitionColumnArray[i], partitionValuesArray[i]));
<del> } else {
<del> whereList.add(String.format("%s = %s", partitionColumnArray[i], partitionValuesArray[i]));
<del> }
<del> }
<del> String query = null;
<del> if(yanagishimaConfig.isUseNewShowPartitions(datasource)) {
<del> query = String.format("%sSELECT * FROM %s.%s.\"%s$partitions\" WHERE %s", YANAGISHIMA_COMMENT, catalog, schema, table, String.join(" AND ", whereList));
<del> } else {
<del> query = String.format("%sSHOW PARTITIONS FROM %s.%s.%s WHERE %s", YANAGISHIMA_COMMENT, catalog, schema, table, String.join(" AND ", whereList));
<del> }
<del> if(userName != null) {
<del> LOGGER.info(String.format("%s executed %s in %s", userName, query, datasource));
<del> }
<del> PrestoQueryResult prestoQueryResult = prestoService.doQuery(datasource, query, userName, prestoUser, prestoPassword, false, Integer.MAX_VALUE);
<del> List<String> columns = prestoQueryResult.getColumns();
<del> int index = 0;
<del> for (String column : columns) {
<del> if (column.equals(partitionColumnArray[partitionColumnArray.length-1])) {
<del> break;
<del> }
<del> index++;
<del> }
<del> retVal.put("column", columns.get(index + 1));
<add> ObjectMapper mapper = new ObjectMapper();
<add> Map map = mapper.readValue(json, Map.class);
<add> List<Map> partitionList = (List) ((Map) map.get("FileStatuses")).get("FileStatus");
<add> if(partitionList.size() > 0) {
<ide> Set<String> partitions = new TreeSet<>();
<del> List<List<String>> records = prestoQueryResult.getRecords();
<del> for (List<String> row : records) {
<del> partitions.add(row.get(index + 1));
<add> for(Map m : partitionList) {
<add> String data = (String)m.get("pathSuffix");
<add> if(data != null && data.contains("=")) {
<add> if(retVal.get("column") == null) {
<add> retVal.put("column", data.split("=")[0]);
<add> }
<add> partitions.add(data.split("=")[1]);
<add> }
<ide> }
<ide> retVal.put("partitions", partitions);
<ide> }
<del>
<del>
<del> } catch (Throwable e) {
<del> LOGGER.error(e.getMessage(), e);
<del> retVal.put("error", e.getMessage());
<ide> }
<del>
<del> JsonUtil.writeJSON(response, retVal);
<del>
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | 20a8b76dc9d8aedf862b07780209d6e5e52c9c82 | 0 | JoeyFan/wish-pay,JoeyFan/wish-pay | package com.wish.pay.web.controller;
import com.wish.pay.ali.common.SceneEnum;
import com.wish.pay.ali.service.AliPayServiceImpl;
import com.wish.pay.common.model.*;
import com.wish.pay.common.model.result.RefundResult;
import com.wish.pay.common.model.result.TradeQueryResult;
import com.wish.pay.common.model.result.TradeResult;
import com.wish.pay.common.utils.BeanMapper;
import com.wish.pay.common.utils.TradeStatusEnum;
import com.wish.pay.common.utils.ZxingUtils;
import com.wish.pay.common.utils.validator.ValidationResult;
import com.wish.pay.common.utils.validator.ValidationUtils;
import com.wish.pay.web.bean.CreatePayBean;
import com.wish.pay.web.bean.QueryRefundTrade;
import com.wish.pay.web.bean.QueryTradeStatus;
import com.wish.pay.web.bean.RefundTrade;
import com.wish.pay.web.dao.entity.TradeOrder;
import com.wish.pay.web.exception.BusinessException;
import com.wish.pay.web.service.ITradeOrderService;
import com.wish.pay.wx.model.common.ProtocolResData;
import com.wish.pay.wx.service.WxPayServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Map;
@Controller
@RequestMapping("/pay")
public class PayController {
Logger logger = LoggerFactory.getLogger(PayController.class);
@Autowired
ITradeOrderService tradeOrderService;
@Autowired
AliPayServiceImpl aliPayService;
@Autowired
WxPayServiceImpl wxPayService;
@Value("${aliPay.notifyResultUrl}")
String ALiPayNotifyResultUrl;
@Value("${wxPay.notifyResultUrl}")
String WXPayNotifyResultUrl;
@Value("${aliPay.alipayPublicKey}")
String AliPayPublicKey;
/**
* 创建阿里支付订单
*
* @param createPay
* @return
* @throws Exception
*/
@RequestMapping(value = "/createPay", method = {RequestMethod.POST, RequestMethod.GET}, produces = "image/jpeg;charset=UTF-8")
@ResponseBody
public byte[] createPay(CreatePayBean createPay) throws Exception {
//1.校验参数
ValidationResult result = ValidationUtils.validateEntity(createPay);
if (result.isHasErrors()) {
throw new BusinessException(result.toString());
}
TradeOrder order = new TradeOrder();
BeanMapper.copy(createPay, order);
//2.插入订单记录
boolean insertResult = tradeOrderService.save(order);
//3.调用支付宝,创建订单,返回参数(订单支付url)
if (insertResult) {
TradePrecreate tradePrecreate = new TradePrecreate();
tradePrecreate.setOutTradeNo(order.getOrderSerial());
tradePrecreate.setScene(SceneEnum.BarCode.getType());
tradePrecreate.setSubject("购买" + order.getGoodsName());
tradePrecreate.setStoreId("test_001");
tradePrecreate.setTotalAmount(order.getAmount().toString());
tradePrecreate.setTimeoutExpress("90m");
TradeResult tradeResult = null;
if (createPay.getPayWay().equalsIgnoreCase(PayTypeEnum.AliPay.getType())) {
tradeResult = aliPayService.createTradeOrder(tradePrecreate, ALiPayNotifyResultUrl);
} else if (createPay.getPayWay().equalsIgnoreCase(PayTypeEnum.WxPay.getType())) {
tradeResult = wxPayService.createTradeOrder(tradePrecreate, ALiPayNotifyResultUrl);
}
if (tradeResult != null && tradeResult.isTradeSuccess()) {//支付成功
BufferedImage bufferedImage = ZxingUtils.writeInfoToJpgBuffImg(tradeResult.getQrCode(), 400, 400);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "JPEG", baos);
return baos.toByteArray();
}
}
return null;
}
/**
* 查询交易状态
*
* @param tradeStatus
* @return
* @throws Exception
*/
@RequestMapping(value = "/queryTradeOrderStatus", method = {RequestMethod.GET})
@ResponseBody
public TradeQueryResult queryTradeOrderStatus(QueryTradeStatus tradeStatus) throws Exception {
ValidationResult result = ValidationUtils.validateEntity(tradeStatus);
if (result.isHasErrors()) {
throw new BusinessException(result.toString());
}
TradeQuery query = new TradeQuery();
query.setOutTradeNo(tradeStatus.getOrderSerial());
if (tradeStatus.getPayWay().equals("0")) {//支付宝
return aliPayService.queryPreTradeOrder(query);
} else if (tradeStatus.getPayWay().equals("1")) {//微信
return wxPayService.queryPreTradeOrder(query);
}
return null;
}
/**
* 交易退款
*
* @param refundTrade
* @return
*/
@RequestMapping(value = "/refundTradeOrder", method = {RequestMethod.GET})
@ResponseBody
public String refundTradeOrder(RefundTrade refundTrade) throws Exception {
ValidationResult result = ValidationUtils.validateEntity(refundTrade);
if (result.isHasErrors()) {
throw new BusinessException(result.toString());
}
TradeRefund refund = new TradeRefund();
BeanMapper.copy(refundTrade, refund);
TradeResult tradeResult = new TradeResult();
if (refundTrade.getPayWay().equals("0")) {//支付宝支付宝
tradeResult = aliPayService.refundTradeOrder(refund);
logger.info("[refundTradeOrder][alipay]退款返回结果", tradeResult);
} else if (refundTrade.getPayWay().equals("1")) {//微信
tradeResult = wxPayService.refundTradeOrder(refund);
logger.info("[refundTradeOrder][wxPay]退款返回结果", tradeResult);
}
return tradeResult.getMsg();
}
/**
* 查询交易退款
*
* @param queryRefundTrade
* @return
*/
@RequestMapping(value = "/queryRefundTradeOrder", method = {RequestMethod.GET})
@ResponseBody
public String queryRefundTradeOrder(QueryRefundTrade queryRefundTrade) throws Exception {
ValidationResult result = ValidationUtils.validateEntity(queryRefundTrade);
if (result.isHasErrors()) {
throw new BusinessException(result.toString());
}
TradeRefund refund = new TradeRefund();
BeanMapper.copy(queryRefundTrade, refund);
RefundResult tradeResult = new RefundResult();
if (queryRefundTrade.getPayWay().equals("0")) {//支付宝
tradeResult = aliPayService.queryRefundTradeOrder(refund);
logger.info("[refundTradeOrder][alipay]退款返回结果", tradeResult);
} else if (queryRefundTrade.getPayWay().equals("1")) {//微信
tradeResult = wxPayService.queryRefundTradeOrder(refund);
logger.info("[refundTradeOrder][wxPay]退款返回结果", tradeResult);
}
return tradeResult.getMsg();
}
/**
* 微信通知接口
*
* @param request
* @return
* @throws Exception
*/
@RequestMapping(value = "/notifyFromWx", method = {RequestMethod.POST, RequestMethod.GET})
@ResponseBody
public ProtocolResData notifyFromWx(HttpServletRequest request, HttpServletResponse response) throws Exception {
logger.info("notifyFromWx begin--->", request);
System.out.println("notifyFromWx" + request.toString());
ProtocolResData resData = new ProtocolResData();
try {
Map<String, String> resultMap = aliPayService.notifyResult(request, AliPayPublicKey);
String value = resultMap.get(Contains.WishPayResultKey);
if (StringUtils.isNotBlank(value) && value.equalsIgnoreCase(Contains.SUCCESS)) {
//TODO:业务逻辑处理
/*商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号,并判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额),
同时需要校验通知中的seller_id(或者seller_email) 是否为out_trade_no这笔单据的对应的操作方(有的时候,一个商户可能有多个seller_id/seller_email),
上述有任何一个验证不通过,则表明本次通知是异常通知,务必忽略。
在上述验证通过后商户必须根据支付宝不同类型的业务通知,正确的进行不同的业务处理,并且过滤重复的通知结果数据。
在支付宝的业务通知中,只有交易通知状态为TRADE_SUCCESS或TRADE_FINISHED时,支付宝才会认定为买家付款成功。*/
String out_trade_no = resultMap.get("out_trade_no");
String total_amount = resultMap.get("total_amount");
String trade_status = resultMap.get("trade_status");
TradeOrder tradeOrder = tradeOrderService.getTradeOrderByOrderSerial(out_trade_no);
System.out.println((tradeOrder.getAmount().doubleValue() + "").equals(total_amount));
if (tradeOrder != null && (tradeOrder.getAmount().doubleValue() + "").equals(total_amount) &&
(trade_status.equals("TRADE_SUCCESS") || trade_status.equals("TRADE_FINISHED"))) {
tradeOrder.setStatus(TradeStatusEnum.PAY_SUCCESS.getValue());//交易成功
boolean updateResult = tradeOrderService.update(tradeOrder);
if (!updateResult) {
logger.error("流水号:" + out_trade_no + " 更新状态更新出错");
throw new Exception("业务出错");
}
}
}
resData.setReturn_code("SUCCESS");
resData.setReturn_msg("OK");
} catch (Exception e) {
resData.setReturn_code("Fail");
resData.setReturn_msg("NOOK");
resData.setReturn_msg("程序业务处理失败");
e.printStackTrace();
//return WxUtils.notifyFalseXml();
}
return resData;
}
/**
* 支付宝请求此接口,是post方式,而且
* 支付宝通知接口,如果成功则会输出success,
* 程序执行完后必须打印输出“success”(不包含引号)否则支付宝服务器会不断重发通知,直到超过24小时22分钟。
* 一般情况下,25小时以内完成8次通知(通知的间隔频率一般是:4m,10m,10m,1h,2h,6h,15h);
*
* @param request
* @return
* @throws Exception
*/
@RequestMapping(value = "/notifyFromAli", method = {RequestMethod.POST})
@ResponseBody
public String notifyFromAli(HttpServletRequest request) throws Exception {
logger.info("notifyFromAli begin--->", request);
System.out.println("notifyFromAli" + request.toString());
Map<String, String> resultMap = aliPayService.notifyResult(request, AliPayPublicKey);
String value = resultMap.get(Contains.WishPayResultKey);
if (StringUtils.isNotBlank(value) && value.equalsIgnoreCase(Contains.SUCCESS)) {
//TODO:业务逻辑处理
/*商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号,并判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额),
同时需要校验通知中的seller_id(或者seller_email) 是否为out_trade_no这笔单据的对应的操作方(有的时候,一个商户可能有多个seller_id/seller_email),
上述有任何一个验证不通过,则表明本次通知是异常通知,务必忽略。
在上述验证通过后商户必须根据支付宝不同类型的业务通知,正确的进行不同的业务处理,并且过滤重复的通知结果数据。
在支付宝的业务通知中,只有交易通知状态为TRADE_SUCCESS或TRADE_FINISHED时,支付宝才会认定为买家付款成功。*/
String out_trade_no = resultMap.get("out_trade_no");
String total_amount = resultMap.get("total_amount");
String trade_status = resultMap.get("trade_status");
TradeOrder tradeOrder = tradeOrderService.getTradeOrderByOrderSerial(out_trade_no);
System.out.println((tradeOrder.getAmount().doubleValue() + "").equals(total_amount));
if (tradeOrder != null && (tradeOrder.getAmount().doubleValue() + "").equals(total_amount) &&
(trade_status.equals("TRADE_SUCCESS") || trade_status.equals("TRADE_FINISHED"))) {
tradeOrder.setStatus(TradeStatusEnum.PAY_SUCCESS.getValue());//交易成功
boolean updateResult = tradeOrderService.update(tradeOrder);
if (!updateResult) {
logger.error("流水号:" + out_trade_no + " 更新状态更新出错");
throw new Exception("业务出错");
}
}
}
return value;
}
}
| wish-pay-web/src/main/java/com/wish/pay/web/controller/PayController.java | package com.wish.pay.web.controller;
import com.wish.pay.ali.common.SceneEnum;
import com.wish.pay.ali.service.AliPayServiceImpl;
import com.wish.pay.common.model.*;
import com.wish.pay.common.model.result.RefundResult;
import com.wish.pay.common.model.result.TradeQueryResult;
import com.wish.pay.common.model.result.TradeResult;
import com.wish.pay.common.utils.BeanMapper;
import com.wish.pay.common.utils.TradeStatusEnum;
import com.wish.pay.common.utils.ZxingUtils;
import com.wish.pay.common.utils.validator.ValidationResult;
import com.wish.pay.common.utils.validator.ValidationUtils;
import com.wish.pay.web.bean.CreatePayBean;
import com.wish.pay.web.bean.QueryRefundTrade;
import com.wish.pay.web.bean.QueryTradeStatus;
import com.wish.pay.web.bean.RefundTrade;
import com.wish.pay.web.dao.entity.TradeOrder;
import com.wish.pay.web.exception.BusinessException;
import com.wish.pay.web.service.ITradeOrderService;
import com.wish.pay.wx.model.common.ProtocolResData;
import com.wish.pay.wx.service.WxPayServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Map;
@Controller
@RequestMapping("/pay")
public class PayController {
Logger logger = LoggerFactory.getLogger(PayController.class);
@Autowired
ITradeOrderService tradeOrderService;
@Autowired
AliPayServiceImpl aliPayService;
@Autowired
WxPayServiceImpl wxPayService;
@Value("${aliPay.notifyResultUrl}")
String ALiPayNotifyResultUrl;
@Value("${wxPay.notifyResultUrl}")
String WXPayNotifyResultUrl;
@Value("${aliPay.alipayPublicKey}")
String AliPayPublicKey;
/**
* 创建阿里支付订单
*
* @param createPay
* @return
* @throws Exception
*/
@RequestMapping(value = "/createPay", method = {RequestMethod.POST, RequestMethod.GET}, produces = "image/jpeg;charset=UTF-8")
@ResponseBody
public byte[] createPay(CreatePayBean createPay) throws Exception {
//1.校验参数
ValidationResult result = ValidationUtils.validateEntity(createPay);
if (result.isHasErrors()) {
throw new BusinessException(result.toString());
}
TradeOrder order = new TradeOrder();
BeanMapper.copy(createPay, order);
//2.插入订单记录
boolean insertResult = tradeOrderService.save(order);
//3.调用支付宝,创建订单,返回参数(订单支付url)
if (insertResult) {
TradePrecreate tradePrecreate = new TradePrecreate();
tradePrecreate.setOutTradeNo(order.getOrderSerial());
tradePrecreate.setScene(SceneEnum.BarCode.getType());
tradePrecreate.setSubject("购买" + order.getGoodsName());
tradePrecreate.setStoreId("test_001");
tradePrecreate.setTotalAmount(order.getAmount().toString());
tradePrecreate.setTimeoutExpress("90m");
TradeResult tradeResult = null;
if (createPay.getPayWay().equalsIgnoreCase(PayTypeEnum.AliPay.getType())) {
tradeResult = aliPayService.createTradeOrder(tradePrecreate, ALiPayNotifyResultUrl);
} else if (createPay.getPayWay().equalsIgnoreCase(PayTypeEnum.WxPay.getType())) {
tradeResult = wxPayService.createTradeOrder(tradePrecreate, ALiPayNotifyResultUrl);
}
if (tradeResult != null && tradeResult.isTradeSuccess()) {//支付成功
BufferedImage bufferedImage = ZxingUtils.writeInfoToJpgBuffImg(tradeResult.getQrCode(), 400, 400);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "JPEG", baos);
return baos.toByteArray();
}
}
return null;
}
/**
* 查询交易状态
*
* @param tradeStatus
* @return
* @throws Exception
*/
@RequestMapping(value = "/queryTradeOrderStatus", method = {RequestMethod.GET})
@ResponseBody
public TradeQueryResult queryTradeOrderStatus(QueryTradeStatus tradeStatus) throws Exception {
ValidationResult result = ValidationUtils.validateEntity(tradeStatus);
if (result.isHasErrors()) {
throw new BusinessException(result.toString());
}
TradeQuery query = new TradeQuery();
query.setOutTradeNo(tradeStatus.getOrderSerial());
if (tradeStatus.getPayWay().equals("0")) {//支付宝
return aliPayService.queryPreTradeOrder(query);
} else if (tradeStatus.getPayWay().equals("1")) {//微信
return wxPayService.queryPreTradeOrder(query);
}
return null;
}
/**
* 交易退款
*
* @param refundTrade
* @return
*/
@RequestMapping(value = "/refundTradeOrder", method = {RequestMethod.GET})
@ResponseBody
public String refundTradeOrder(RefundTrade refundTrade) throws Exception {
ValidationResult result = ValidationUtils.validateEntity(refundTrade);
if (result.isHasErrors()) {
throw new BusinessException(result.toString());
}
TradeRefund refund = new TradeRefund();
BeanMapper.copy(refundTrade, refund);
TradeResult tradeResult = new TradeResult();
if (refundTrade.getPayWay().equals("0")) {//支付宝支付宝
tradeResult = aliPayService.refundTradeOrder(refund);
logger.info("[refundTradeOrder][alipay]退款返回结果", tradeResult);
} else if (refundTrade.getPayWay().equals("1")) {//微信
tradeResult = wxPayService.refundTradeOrder(refund);
logger.info("[refundTradeOrder][wxPay]退款返回结果", tradeResult);
}
return tradeResult.getMsg();
}
/**
* 查询交易退款
*
* @param queryRefundTrade
* @return
*/
@RequestMapping(value = "/queryRefundTradeOrder", method = {RequestMethod.GET})
@ResponseBody
public String queryRefundTradeOrder(QueryRefundTrade queryRefundTrade) throws Exception {
ValidationResult result = ValidationUtils.validateEntity(queryRefundTrade);
if (result.isHasErrors()) {
throw new BusinessException(result.toString());
}
TradeRefund refund = new TradeRefund();
BeanMapper.copy(queryRefundTrade, refund);
RefundResult tradeResult = new RefundResult();
if (queryRefundTrade.getPayWay().equals("0")) {//支付宝
tradeResult = aliPayService.queryRefundTradeOrder(refund);
logger.info("[refundTradeOrder][alipay]退款返回结果", tradeResult);
} else if (queryRefundTrade.getPayWay().equals("1")) {//微信
tradeResult = wxPayService.queryRefundTradeOrder(refund);
logger.info("[refundTradeOrder][wxPay]退款返回结果", tradeResult);
}
return tradeResult.getMsg();
}
/**
* 微信通知接口
*
* @param request
* @return
* @throws Exception
*/
@RequestMapping(value = "/notifyFromWx", method = {RequestMethod.POST, RequestMethod.GET})
@ResponseBody
public ProtocolResData notifyFromWx(HttpServletRequest request, HttpServletResponse response) throws Exception {
logger.info("notifyFromWx begin--->", request);
System.out.println("notifyFromWx" + request.toString());
ProtocolResData resData = new ProtocolResData();
try {
Map<String, String> resultMap = aliPayService.notifyResult(request, AliPayPublicKey);
String value = resultMap.get(Contains.WishPayResultKey);
if (StringUtils.isNotBlank(value) && value.equalsIgnoreCase(Contains.SUCCESS)) {
//TODO:业务逻辑处理
/*商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号,并判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额),
同时需要校验通知中的seller_id(或者seller_email) 是否为out_trade_no这笔单据的对应的操作方(有的时候,一个商户可能有多个seller_id/seller_email),
上述有任何一个验证不通过,则表明本次通知是异常通知,务必忽略。
在上述验证通过后商户必须根据支付宝不同类型的业务通知,正确的进行不同的业务处理,并且过滤重复的通知结果数据。
在支付宝的业务通知中,只有交易通知状态为TRADE_SUCCESS或TRADE_FINISHED时,支付宝才会认定为买家付款成功。*/
String out_trade_no = resultMap.get("out_trade_no");
String total_amount = resultMap.get("total_amount");
String trade_status = resultMap.get("trade_status");
TradeOrder tradeOrder = tradeOrderService.getTradeOrderByOrderSerial(out_trade_no);
System.out.println((tradeOrder.getAmount().doubleValue() + "").equals(total_amount));
if (tradeOrder != null && (tradeOrder.getAmount().doubleValue() + "").equals(total_amount) &&
(trade_status.equals("TRADE_SUCCESS") || trade_status.equals("TRADE_FINISHED"))) {
tradeOrder.setStatus(TradeStatusEnum.PAY_SUCCESS.getValue());//交易成功
boolean updateResult = tradeOrderService.update(tradeOrder);
if (!updateResult) {
logger.error("流水号:" + out_trade_no + " 更新状态更新出错");
throw new Exception("业务出错");
}
}
}
resData.setReturn_code("SUCCESS");
resData.setReturn_msg("OK");
} catch (Exception e) {
resData.setReturn_code("Fail");
resData.setReturn_msg("NOOK");
resData.setReturn_msg("程序业务处理失败");
e.printStackTrace();
//return WxUtils.notifyFalseXml();
}
return resData;
}
/**
* 支付宝请求此接口,是post方式,而且
* 支付宝通知接口,如果成功则会输出success,
* 程序执行完后必须打印输出“success”(不包含引号)否则支付宝服务器会不断重发通知,直到超过24小时22分钟。
* 一般情况下,25小时以内完成8次通知(通知的间隔频率一般是:4m,10m,10m,1h,2h,6h,15h);
*
* @param request
* @return
* @throws Exception
*/
@RequestMapping(value = "/notifyFromAli", method = {RequestMethod.POST})
@ResponseBody
public String notifyFromAli(HttpServletRequest request) throws Exception {
logger.info("notifyFromAli begin--->", request);
System.out.println("notifyFromAli" + request.toString());
Map<String, String> resultMap = aliPayService.notifyResult(request, AliPayPublicKey);
String value = resultMap.get(Contains.WishPayResultKey);
if (StringUtils.isNotBlank(value) && value.equalsIgnoreCase(Contains.SUCCESS)) {
//TODO:业务逻辑处理
/*商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号,并判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额),
同时需要校验通知中的seller_id(或者seller_email) 是否为out_trade_no这笔单据的对应的操作方(有的时候,一个商户可能有多个seller_id/seller_email),
上述有任何一个验证不通过,则表明本次通知是异常通知,务必忽略。
在上述验证通过后商户必须根据支付宝不同类型的业务通知,正确的进行不同的业务处理,并且过滤重复的通知结果数据。
在支付宝的业务通知中,只有交易通知状态为TRADE_SUCCESS或TRADE_FINISHED时,支付宝才会认定为买家付款成功。*/
String out_trade_no = resultMap.get("out_trade_no");
String total_amount = resultMap.get("total_amount");
String trade_status = resultMap.get("trade_status");
TradeOrder tradeOrder = tradeOrderService.getTradeOrderByOrderSerial(out_trade_no);
System.out.println((tradeOrder.getAmount().doubleValue() + "").equals(total_amount));
if (tradeOrder != null && (tradeOrder.getAmount().doubleValue() + "").equals(total_amount) &&
(trade_status.equals("TRADE_SUCCESS") || trade_status.equals("TRADE_FINISHED"))) {
tradeOrder.setStatus(TradeStatusEnum.PAY_SUCCESS.getValue());//交易成功
boolean updateResult = tradeOrderService.update(tradeOrder);
if (!updateResult) {
logger.error("流水号:" + out_trade_no + " 更新状态更新出错");
throw new Exception("业务出错");
}
}
}
return value;
}
} | Update PayController.java | wish-pay-web/src/main/java/com/wish/pay/web/controller/PayController.java | Update PayController.java | <ide><path>ish-pay-web/src/main/java/com/wish/pay/web/controller/PayController.java
<ide> return value;
<ide> }
<ide>
<del>
<ide> } |
|
Java | mit | cbc91e49bdd9c21cf19ba804287410557ae03cc0 | 0 | krinsdeath/ChatSuite | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.krinsoft.chat;
import com.onarandombox.MultiverseCore.MVWorld;
import com.onarandombox.MultiverseCore.MultiverseCore;
import java.util.HashMap;
import java.util.List;
import org.bukkit.World;
import org.bukkit.plugin.Plugin;
/**
*
* @author Krin
*/
public class WorldManager {
private ChatCore plugin;
private HashMap<String, String> aliases = new HashMap<String, String>();
private HashMap<String, ChatWorld> worlds = new HashMap<String, ChatWorld>();
public WorldManager(ChatCore aThis) {
plugin = aThis;
fetchWorlds();
fetchAliases();
}
public String getAlias(String world) {
return (aliases.containsKey(world) ? aliases.get(world) : world);
}
public ChatWorld getWorld(String world) {
String a = world;
for (String w : aliases.keySet()) {
if (aliases.get(w).equals(world)) {
a = w;
}
}
return worlds.get(a);
}
public List<ChatWorld> getWorlds() {
return (List<ChatWorld>) worlds.values();
}
private void fetchWorlds() {
for (World w : plugin.getServer().getWorlds()) {
worlds.put(w.getName(), new ChatWorld(plugin, w.getName()));
}
}
private void fetchAliases() {
Plugin tmp = plugin.getServer().getPluginManager().getPlugin("Multiverse-Core");
if (tmp != null) {
plugin.debug("Found Multiverse-Core! Registering aliases...");
MultiverseCore multiverse = (MultiverseCore) tmp;
// Nest a bunch of method attempts for various Multiverse-Core versions
try {
for (MVWorld mv : multiverse.getMVWorldManager().getMVWorlds()) {
aliases.put(mv.getName(), mv.getColoredWorldString());
}
} catch (NoSuchMethodError e) {
try {
for (MVWorld mv : multiverse.getWorldManager().getMVWorlds()) {
aliases.put(mv.getName(), mv.getColoredWorldString());
}
} catch (NoSuchMethodError e) {
plugin.debug(e.getLocalizedMessage());
for (MVWorld mv : multiverse.getMVWorlds()) {
aliases.put(mv.getName(), mv.getColoredWorldString());
}
}
}
}
}
}
| src/main/java/net/krinsoft/chat/WorldManager.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.krinsoft.chat;
import com.onarandombox.MultiverseCore.MVWorld;
import com.onarandombox.MultiverseCore.MultiverseCore;
import java.util.HashMap;
import java.util.List;
import org.bukkit.World;
import org.bukkit.plugin.Plugin;
/**
*
* @author Krin
*/
public class WorldManager {
private ChatCore plugin;
private HashMap<String, String> aliases = new HashMap<String, String>();
private HashMap<String, ChatWorld> worlds = new HashMap<String, ChatWorld>();
public WorldManager(ChatCore aThis) {
plugin = aThis;
fetchWorlds();
fetchAliases();
}
public String getAlias(String world) {
return (aliases.containsKey(world) ? aliases.get(world) : world);
}
public ChatWorld getWorld(String world) {
String a = world;
for (String w : aliases.keySet()) {
if (aliases.get(w).equals(world)) {
a = w;
}
}
return worlds.get(a);
}
public List<ChatWorld> getWorlds() {
return (List<ChatWorld>) worlds.values();
}
private void fetchWorlds() {
for (World w : plugin.getServer().getWorlds()) {
worlds.put(w.getName(), new ChatWorld(plugin, w.getName()));
}
}
private void fetchAliases() {
Plugin tmp = plugin.getServer().getPluginManager().getPlugin("Multiverse-Core");
if (tmp != null) {
plugin.debug("Found Multiverse-Core! Registering aliases...");
MultiverseCore multiverse = (MultiverseCore) tmp;
try {
for (MVWorld mv : multiverse.getWorldManager().getMVWorlds()) {
aliases.put(mv.getName(), mv.getColoredWorldString());
}
} catch (NoSuchMethodError e) {
plugin.debug(e.getLocalizedMessage());
for (MVWorld mv : multiverse.getMVWorlds()) {
aliases.put(mv.getName(), mv.getColoredWorldString());
}
}
}
}
}
| Adapt for new `getMVWorldManager()` method on core class | src/main/java/net/krinsoft/chat/WorldManager.java | Adapt for new `getMVWorldManager()` method on core class | <ide><path>rc/main/java/net/krinsoft/chat/WorldManager.java
<ide> if (tmp != null) {
<ide> plugin.debug("Found Multiverse-Core! Registering aliases...");
<ide> MultiverseCore multiverse = (MultiverseCore) tmp;
<add> // Nest a bunch of method attempts for various Multiverse-Core versions
<ide> try {
<del> for (MVWorld mv : multiverse.getWorldManager().getMVWorlds()) {
<add> for (MVWorld mv : multiverse.getMVWorldManager().getMVWorlds()) {
<ide> aliases.put(mv.getName(), mv.getColoredWorldString());
<ide> }
<ide> } catch (NoSuchMethodError e) {
<del> plugin.debug(e.getLocalizedMessage());
<del> for (MVWorld mv : multiverse.getMVWorlds()) {
<del> aliases.put(mv.getName(), mv.getColoredWorldString());
<add> try {
<add> for (MVWorld mv : multiverse.getWorldManager().getMVWorlds()) {
<add> aliases.put(mv.getName(), mv.getColoredWorldString());
<add> }
<add> } catch (NoSuchMethodError e) {
<add> plugin.debug(e.getLocalizedMessage());
<add> for (MVWorld mv : multiverse.getMVWorlds()) {
<add> aliases.put(mv.getName(), mv.getColoredWorldString());
<add> }
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | 9e0405a5d4effc0e87d9a68b8c1fc5113ae5f569 | 0 | sundrio/sundrio,sundrio/sundrio | /*
* Copyright 2016 The original 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.sundr.codegen.converters;
import io.sundr.codegen.functions.ElementTo;
import io.sundr.codegen.model.ClassRefBuilder;
import io.sundr.codegen.model.PrimitiveRefBuilder;
import io.sundr.codegen.model.TypeDef;
import io.sundr.codegen.model.TypeRef;
import io.sundr.codegen.model.VoidRefBuilder;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ErrorType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.NoType;
import javax.lang.model.type.NullType;
import javax.lang.model.type.PrimitiveType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import javax.lang.model.type.WildcardType;
import javax.lang.model.util.AbstractTypeVisitor6;
import java.util.ArrayList;
import java.util.List;
public class TypeRefTypeVisitor extends AbstractTypeVisitor6<TypeRef, Integer> {
public TypeRef visitPrimitive(PrimitiveType t, Integer dimension) {
return new PrimitiveRefBuilder()
.withName(t.getKind().name().toLowerCase())
.withDimensions(dimension)
.build();
}
public TypeRef visitNull(NullType t, Integer dimension) {
return null;
}
public TypeRef visitArray(ArrayType t, Integer dimension) {
return t.getComponentType().accept(this, dimension + 1);
}
public TypeRef visitDeclared(DeclaredType t, Integer dimension) {
List<TypeRef> arguments = new ArrayList<TypeRef>();
for (TypeMirror typeMirror : t.getTypeArguments()) {
TypeRef arg = typeMirror.accept(this, dimension);
if (arg != null) {
arguments.add(arg);
}
}
TypeDef typeDef = new TypeDefElementVisitor().visit(t.asElement()).build();
return new ClassRefBuilder()
.withDefinition(typeDef)
.withDimensions(dimension)
.withArguments(arguments)
.build();
}
public TypeRef visitError(ErrorType t, Integer dimension) {
return new ClassRefBuilder().withDefinition(new TypeDefElementVisitor().visit(t.asElement()).build()).build();
}
public TypeRef visitTypeVariable(TypeVariable t, Integer dimension) {
return ElementTo.TYPEVARIABLE_TO_TYPEPARAM_REF.apply(t);
}
public TypeRef visitWildcard(WildcardType t, Integer dimension) {
return null;
}
public TypeRef visitExecutable(ExecutableType t, Integer dimension) {
return null;
}
public TypeRef visitNoType(NoType t, Integer dimension) {
return new VoidRefBuilder().build();
}
public TypeRef visitUnknown(TypeMirror t, Integer dimension) {
return null;
}
}
| codegen/src/main/java/io/sundr/codegen/converters/TypeRefTypeVisitor.java | /*
* Copyright 2016 The original 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.sundr.codegen.converters;
import io.sundr.codegen.functions.ElementTo;
import io.sundr.codegen.model.ClassRefBuilder;
import io.sundr.codegen.model.PrimitiveRefBuilder;
import io.sundr.codegen.model.TypeDef;
import io.sundr.codegen.model.TypeRef;
import io.sundr.codegen.model.VoidRefBuilder;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ErrorType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.NoType;
import javax.lang.model.type.NullType;
import javax.lang.model.type.PrimitiveType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import javax.lang.model.type.WildcardType;
import javax.lang.model.util.AbstractTypeVisitor6;
import java.util.ArrayList;
import java.util.List;
public class TypeRefTypeVisitor extends AbstractTypeVisitor6<TypeRef, Integer> {
public TypeRef visitPrimitive(PrimitiveType t, Integer dimension) {
return new PrimitiveRefBuilder()
.withName(t.toString())
.withDimensions(dimension)
.build();
}
public TypeRef visitNull(NullType t, Integer dimension) {
return null;
}
public TypeRef visitArray(ArrayType t, Integer dimension) {
return t.getComponentType().accept(this, dimension + 1);
}
public TypeRef visitDeclared(DeclaredType t, Integer dimension) {
List<TypeRef> arguments = new ArrayList<TypeRef>();
for (TypeMirror typeMirror : t.getTypeArguments()) {
TypeRef arg = typeMirror.accept(this, dimension);
if (arg != null) {
arguments.add(arg);
}
}
TypeDef typeDef = new TypeDefElementVisitor().visit(t.asElement()).build();
return new ClassRefBuilder()
.withDefinition(typeDef)
.withDimensions(dimension)
.withArguments(arguments)
.build();
}
public TypeRef visitError(ErrorType t, Integer dimension) {
return new ClassRefBuilder().withDefinition(new TypeDefElementVisitor().visit(t.asElement()).build()).build();
}
public TypeRef visitTypeVariable(TypeVariable t, Integer dimension) {
return ElementTo.TYPEVARIABLE_TO_TYPEPARAM_REF.apply(t);
}
public TypeRef visitWildcard(WildcardType t, Integer dimension) {
return null;
}
public TypeRef visitExecutable(ExecutableType t, Integer dimension) {
return null;
}
public TypeRef visitNoType(NoType t, Integer dimension) {
return new VoidRefBuilder().build();
}
public TypeRef visitUnknown(TypeMirror t, Integer dimension) {
return null;
}
}
| fix: handling of primitive types is now more robust.
| codegen/src/main/java/io/sundr/codegen/converters/TypeRefTypeVisitor.java | fix: handling of primitive types is now more robust. | <ide><path>odegen/src/main/java/io/sundr/codegen/converters/TypeRefTypeVisitor.java
<ide>
<ide> public TypeRef visitPrimitive(PrimitiveType t, Integer dimension) {
<ide> return new PrimitiveRefBuilder()
<del> .withName(t.toString())
<add> .withName(t.getKind().name().toLowerCase())
<ide> .withDimensions(dimension)
<ide> .build();
<ide> } |
|
Java | mit | 4a13a71e7e4b2d6998eac5b4e7218b2a96634fc9 | 0 | kmdouglass/Micro-Manager,kmdouglass/Micro-Manager | ///////////////////////////////////////////////////////////////////////////////
//FILE: MMStudioMainFrame.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
//-----------------------------------------------------------------------------
//AUTHOR: Nenad Amodaj, [email protected], Jul 18, 2005
// Modifications by Arthur Edelstein, Nico Stuurman, Henry Pinkard
//COPYRIGHT: University of California, San Francisco, 2006-2013
// 100X Imaging Inc, www.100ximaging.com, 2008
//LICENSE: This file is distributed under the BSD license.
// License text is included with the source distribution.
// This file 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.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//CVS: $Id$
//
package org.micromanager;
import ij.IJ;
import ij.ImageJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.gui.Line;
import ij.gui.Roi;
import ij.process.ImageProcessor;
import ij.process.ShortProcessor;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Point2D;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.Preferences;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.UIManager;
import mmcorej.CMMCore;
import mmcorej.DeviceType;
import mmcorej.MMCoreJ;
import mmcorej.MMEventCallback;
import mmcorej.StrVector;
import org.json.JSONObject;
import org.micromanager.acquisition.AcquisitionManager;
import org.micromanager.api.Autofocus;
import org.micromanager.api.DataProcessor;
import org.micromanager.api.MMPlugin;
import org.micromanager.api.MMTags;
import org.micromanager.api.PositionList;
import org.micromanager.api.ScriptInterface;
import org.micromanager.api.MMListenerInterface;
import org.micromanager.api.SequenceSettings;
import org.micromanager.conf2.ConfiguratorDlg2;
import org.micromanager.conf2.MMConfigFileException;
import org.micromanager.conf2.MicroscopeModel;
import org.micromanager.graph.GraphData;
import org.micromanager.graph.GraphFrame;
import org.micromanager.navigation.CenterAndDragListener;
import org.micromanager.navigation.XYZKeyListener;
import org.micromanager.navigation.ZWheelListener;
import org.micromanager.utils.AutofocusManager;
import org.micromanager.utils.ContrastSettings;
import org.micromanager.utils.GUIColors;
import org.micromanager.utils.GUIUtils;
import org.micromanager.utils.JavaUtils;
import org.micromanager.utils.MMException;
import org.micromanager.utils.MMScriptException;
import org.micromanager.utils.NumberUtils;
import org.micromanager.utils.TextUtils;
import org.micromanager.utils.WaitDialog;
import bsh.EvalError;
import bsh.Interpreter;
import com.swtdesigner.SwingResourceManager;
import ij.gui.ImageCanvas;
import ij.gui.ImageWindow;
import ij.gui.Toolbar;
import java.awt.*;
import java.awt.dnd.DropTarget;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.Collator;
import java.util.Collections;
import java.util.Comparator;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import mmcorej.TaggedImage;
import org.json.JSONException;
import org.micromanager.acquisition.*;
import org.micromanager.api.ImageCache;
import org.micromanager.api.IAcquisitionEngine2010;
import org.micromanager.graph.HistogramSettings;
import org.micromanager.internalinterfaces.LiveModeListener;
import org.micromanager.utils.DragDropUtil;
import org.micromanager.utils.FileDialogs;
import org.micromanager.utils.FileDialogs.FileType;
import org.micromanager.utils.HotKeysDialog;
import org.micromanager.utils.ImageUtils;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.MMKeyDispatcher;
import org.micromanager.utils.ReportingUtils;
import org.micromanager.utils.UIMonitor;
/*
* Main panel and application class for the MMStudio.
*/
public class MMStudioMainFrame extends JFrame implements ScriptInterface {
private static final String MICRO_MANAGER_TITLE = "Micro-Manager";
private static final long serialVersionUID = 3556500289598574541L;
private static final String MAIN_FRAME_X = "x";
private static final String MAIN_FRAME_Y = "y";
private static final String MAIN_FRAME_WIDTH = "width";
private static final String MAIN_FRAME_HEIGHT = "height";
private static final String MAIN_FRAME_DIVIDER_POS = "divider_pos";
private static final String MAIN_EXPOSURE = "exposure";
private static final String MAIN_SAVE_METHOD = "saveMethod";
private static final String SYSTEM_CONFIG_FILE = "sysconfig_file";
private static final String OPEN_ACQ_DIR = "openDataDir";
private static final String SCRIPT_CORE_OBJECT = "mmc";
private static final String SCRIPT_ACQENG_OBJECT = "acq";
private static final String SCRIPT_GUI_OBJECT = "gui";
private static final String AUTOFOCUS_DEVICE = "autofocus_device";
private static final String MOUSE_MOVES_STAGE = "mouse_moves_stage";
private static final String EXPOSURE_SETTINGS_NODE = "MainExposureSettings";
private static final String CONTRAST_SETTINGS_NODE = "MainContrastSettings";
private static final int TOOLTIP_DISPLAY_DURATION_MILLISECONDS = 15000;
private static final int TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS = 2000;
// cfg file saving
private static final String CFGFILE_ENTRY_BASE = "CFGFileEntry"; // + {0, 1, 2, 3, 4}
// GUI components
private JComboBox comboBinning_;
private JComboBox shutterComboBox_;
private JTextField textFieldExp_;
private JLabel labelImageDimensions_;
private JToggleButton liveButton_;
private JCheckBox autoShutterCheckBox_;
private MMOptions options_;
private boolean runsAsPlugin_;
private JCheckBoxMenuItem centerAndDragMenuItem_;
private JButton snapButton_;
private JButton autofocusNowButton_;
private JButton autofocusConfigureButton_;
private JToggleButton toggleShutterButton_;
private GUIColors guiColors_;
private GraphFrame profileWin_;
private PropertyEditor propertyBrowser_;
private CalibrationListDlg calibrationListDlg_;
private AcqControlDlg acqControlWin_;
private ReportProblemDialog reportProblemDialog_;
private JMenu pluginMenu_;
private ArrayList<PluginItem> plugins_;
private List<MMListenerInterface> MMListeners_
= Collections.synchronizedList(new ArrayList<MMListenerInterface>());
private List<LiveModeListener> liveModeListeners_
= Collections.synchronizedList(new ArrayList<LiveModeListener>());
private List<Component> MMFrames_
= Collections.synchronizedList(new ArrayList<Component>());
private AutofocusManager afMgr_;
private final static String DEFAULT_CONFIG_FILE_NAME = "MMConfig_demo.cfg";
private ArrayList<String> MRUConfigFiles_;
private static final int maxMRUCfgs_ = 5;
private String sysConfigFile_;
private String startupScriptFile_;
private String sysStateFile_ = "MMSystemState.cfg";
private ConfigGroupPad configPad_;
private LiveModeTimer liveModeTimer_;
private GraphData lineProfileData_;
// labels for standard devices
private String cameraLabel_;
private String zStageLabel_;
private String shutterLabel_;
private String xyStageLabel_;
// applications settings
private Preferences mainPrefs_;
private Preferences systemPrefs_;
private Preferences colorPrefs_;
private Preferences exposurePrefs_;
private Preferences contrastPrefs_;
// MMcore
private CMMCore core_;
private AcquisitionWrapperEngine engine_;
private PositionList posList_;
private PositionListDlg posListDlg_;
private String openAcqDirectory_ = "";
private boolean running_;
private boolean configChanged_ = false;
private StrVector shutters_ = null;
private JButton saveConfigButton_;
private ScriptPanel scriptPanel_;
private org.micromanager.utils.HotKeys hotKeys_;
private CenterAndDragListener centerAndDragListener_;
private ZWheelListener zWheelListener_;
private XYZKeyListener xyzKeyListener_;
private AcquisitionManager acqMgr_;
private static VirtualAcquisitionDisplay simpleDisplay_;
private Color[] multiCameraColors_ = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.CYAN};
private boolean liveModeSuspended_;
public Font defaultScriptFont_ = null;
public static final String SIMPLE_ACQ = "Snap/Live Window";
public static FileType MM_CONFIG_FILE
= new FileType("MM_CONFIG_FILE",
"Micro-Manager Config File",
"./MyScope.cfg",
true, "cfg");
// Our instance
private static MMStudioMainFrame gui_;
// Callback
private CoreEventCallback cb_;
// Lock invoked while shutting down
private final Object shutdownLock_ = new Object();
private JMenuBar menuBar_;
private ConfigPadButtonPanel configPadButtonPanel_;
private final JMenu switchConfigurationMenu_;
private final MetadataPanel metadataPanel_;
public static FileType MM_DATA_SET
= new FileType("MM_DATA_SET",
"Micro-Manager Image Location",
System.getProperty("user.home") + "/Untitled",
false, (String[]) null);
private Thread acquisitionEngine2010LoadingThread = null;
private Class<?> acquisitionEngine2010Class = null;
private IAcquisitionEngine2010 acquisitionEngine2010 = null;
private final JSplitPane splitPane_;
private volatile boolean ignorePropertyChanges_;
private AbstractButton setRoiButton_;
private AbstractButton clearRoiButton_;
private DropTarget dt_;
// private ProcessorStackManager processorStackManager_;
public ImageWindow getImageWin() {
return getSnapLiveWin();
}
@Override
public ImageWindow getSnapLiveWin() {
if (simpleDisplay_ == null) {
return null;
}
return simpleDisplay_.getHyperImage().getWindow();
}
public static VirtualAcquisitionDisplay getSimpleDisplay() {
return simpleDisplay_;
}
public static void createSimpleDisplay(String name, ImageCache cache) throws MMScriptException {
simpleDisplay_ = new VirtualAcquisitionDisplay(cache, name);
}
public void checkSimpleAcquisition() {
if (core_.getCameraDevice().length() == 0) {
ReportingUtils.showError("No camera configured");
return;
}
int width = (int) core_.getImageWidth();
int height = (int) core_.getImageHeight();
int depth = (int) core_.getBytesPerPixel();
int bitDepth = (int) core_.getImageBitDepth();
int numCamChannels = (int) core_.getNumberOfCameraChannels();
try {
if (acquisitionExists(SIMPLE_ACQ)) {
if ((getAcquisitionImageWidth(SIMPLE_ACQ) != width)
|| (getAcquisitionImageHeight(SIMPLE_ACQ) != height)
|| (getAcquisitionImageByteDepth(SIMPLE_ACQ) != depth)
|| (getAcquisitionImageBitDepth(SIMPLE_ACQ) != bitDepth)
|| (getAcquisitionMultiCamNumChannels(SIMPLE_ACQ) != numCamChannels)) { //Need to close and reopen simple window
closeAcquisitionWindow(SIMPLE_ACQ);
}
}
if (!acquisitionExists(SIMPLE_ACQ)) {
openAcquisition(SIMPLE_ACQ, "", 1, numCamChannels, 1, true);
if (numCamChannels > 1) {
for (long i = 0; i < numCamChannels; i++) {
String chName = core_.getCameraChannelName(i);
int defaultColor = multiCameraColors_[(int) i % multiCameraColors_.length].getRGB();
setChannelColor(SIMPLE_ACQ, (int) i, getChannelColor(chName, defaultColor));
setChannelName(SIMPLE_ACQ, (int) i, chName);
}
}
initializeSimpleAcquisition(SIMPLE_ACQ, width, height, depth, bitDepth, numCamChannels);
getAcquisition(SIMPLE_ACQ).promptToSave(false);
getAcquisition(SIMPLE_ACQ).toFront();
this.updateCenterAndDragListener();
}
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
}
public void checkSimpleAcquisition(TaggedImage image) {
try {
JSONObject tags = image.tags;
int width = MDUtils.getWidth(tags);
int height = MDUtils.getHeight(tags);
int depth = MDUtils.getDepth(tags);
int bitDepth = MDUtils.getBitDepth(tags);
int numCamChannels = (int) core_.getNumberOfCameraChannels();
if (acquisitionExists(SIMPLE_ACQ)) {
if ((getAcquisitionImageWidth(SIMPLE_ACQ) != width)
|| (getAcquisitionImageHeight(SIMPLE_ACQ) != height)
|| (getAcquisitionImageByteDepth(SIMPLE_ACQ) != depth)
|| (getAcquisitionImageBitDepth(SIMPLE_ACQ) != bitDepth)
|| (getAcquisitionMultiCamNumChannels(SIMPLE_ACQ) != numCamChannels)) { //Need to close and reopen simple window
closeAcquisitionWindow(SIMPLE_ACQ);
// Seems that closeAcquisitionWindow also closes the acquisition...
//closeAcquisition(SIMPLE_ACQ);
}
}
if (!acquisitionExists(SIMPLE_ACQ)) {
openAcquisition(SIMPLE_ACQ, "", 1, numCamChannels, 1, true);
if (numCamChannels > 1) {
for (long i = 0; i < numCamChannels; i++) {
String chName = core_.getCameraChannelName(i);
int defaultColor = multiCameraColors_[(int) i % multiCameraColors_.length].getRGB();
setChannelColor(SIMPLE_ACQ, (int) i, getChannelColor(chName, defaultColor));
setChannelName(SIMPLE_ACQ, (int) i, chName);
}
}
initializeSimpleAcquisition(SIMPLE_ACQ, width, height, depth, bitDepth, numCamChannels);
getAcquisition(SIMPLE_ACQ).promptToSave(false);
getAcquisition(SIMPLE_ACQ).toFront();
this.updateCenterAndDragListener();
}
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
}
public void saveChannelColor(String chName, int rgb)
{
if (colorPrefs_ != null) {
colorPrefs_.putInt("Color_" + chName, rgb);
}
}
public Color getChannelColor(String chName, int defaultColor)
{
if (colorPrefs_ != null) {
defaultColor = colorPrefs_.getInt("Color_" + chName, defaultColor);
}
return new Color(defaultColor);
}
@Override
public void enableRoiButtons(final boolean enabled) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
setRoiButton_.setEnabled(enabled);
clearRoiButton_.setEnabled(enabled);
}
});
}
public void copyFromLiveModeToAlbum(VirtualAcquisitionDisplay display) throws MMScriptException, JSONException {
ImageCache ic = display.getImageCache();
int channels = ic.getSummaryMetadata().getInt("Channels");
if (channels == 1) {
//RGB or monchrome
addToAlbum(ic.getImage(0, 0, 0, 0), ic.getDisplayAndComments());
} else {
//multicamera
for (int i = 0; i < channels; i++) {
addToAlbum(ic.getImage(i, 0, 0, 0), ic.getDisplayAndComments());
}
}
}
private void createActiveShutterChooser(JPanel topPanel) {
createLabel("Shutter", false, topPanel, 111, 73, 158, 86);
shutterComboBox_ = new JComboBox();
shutterComboBox_.setName("Shutter");
shutterComboBox_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
try {
if (shutterComboBox_.getSelectedItem() != null) {
core_.setShutterDevice((String) shutterComboBox_.getSelectedItem());
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
});
GUIUtils.addWithEdges(topPanel, shutterComboBox_, 170, 70, 275, 92);
}
private void createBinningChooser(JPanel topPanel) {
createLabel("Binning", false, topPanel, 111, 43, 199, 64);
comboBinning_ = new JComboBox();
comboBinning_.setName("Binning");
comboBinning_.setFont(new Font("Arial", Font.PLAIN, 10));
comboBinning_.setMaximumRowCount(4);
comboBinning_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
changeBinning();
}
});
GUIUtils.addWithEdges(topPanel, comboBinning_, 200, 43, 275, 66);
}
private void createExposureField(JPanel topPanel) {
createLabel("Exposure [ms]", false, topPanel, 111, 23, 198, 39);
textFieldExp_ = new JTextField();
textFieldExp_.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent fe) {
synchronized(shutdownLock_) {
if (core_ != null)
setExposure();
}
}
});
textFieldExp_.setFont(new Font("Arial", Font.PLAIN, 10));
textFieldExp_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setExposure();
}
});
GUIUtils.addWithEdges(topPanel, textFieldExp_, 203, 21, 276, 40);
}
private void toggleAutoShutter() {
shutterLabel_ = core_.getShutterDevice();
if (shutterLabel_.length() == 0) {
toggleShutterButton_.setEnabled(false);
} else {
if (autoShutterCheckBox_.isSelected()) {
try {
core_.setAutoShutter(true);
core_.setShutterOpen(false);
toggleShutterButton_.setSelected(false);
toggleShutterButton_.setText("Open");
toggleShutterButton_.setEnabled(false);
} catch (Exception e2) {
ReportingUtils.logError(e2);
}
} else {
try {
core_.setAutoShutter(false);
core_.setShutterOpen(false);
toggleShutterButton_.setEnabled(true);
toggleShutterButton_.setText("Open");
} catch (Exception exc) {
ReportingUtils.logError(exc);
}
}
}
}
private void createShutterControls(JPanel topPanel) {
autoShutterCheckBox_ = new JCheckBox();
autoShutterCheckBox_.setFont(new Font("Arial", Font.PLAIN, 10));
autoShutterCheckBox_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
toggleAutoShutter();
}
});
autoShutterCheckBox_.setIconTextGap(6);
autoShutterCheckBox_.setHorizontalTextPosition(SwingConstants.LEADING);
autoShutterCheckBox_.setText("Auto shutter");
GUIUtils.addWithEdges(topPanel, autoShutterCheckBox_, 107, 96, 199, 119);
toggleShutterButton_ = (JToggleButton) GUIUtils.createButton(true,
"toggleShutterButton", "Open",
"Open/close the shutter",
new Runnable() {
public void run() {
toggleShutter();
}
}, null, topPanel, 203, 96, 275, 117); // Shutter button
}
private void createCameraSettingsWidgets(JPanel topPanel) {
createLabel("Camera settings", true, topPanel, 109, 2, 211, 22);
createExposureField(topPanel);
createBinningChooser(topPanel);
createActiveShutterChooser(topPanel);
createShutterControls(topPanel);
}
private void createConfigurationControls(JPanel topPanel) {
createLabel("Configuration settings", true, topPanel, 280, 2, 430, 22);
saveConfigButton_ = (JButton) GUIUtils.createButton(false,
"saveConfigureButton", "Save",
"Save current presets to the configuration file",
new Runnable() {
public void run() {
saveConfigPresets();
}
}, null, topPanel, -80, 2, -5, 20);
configPad_ = new ConfigGroupPad();
configPadButtonPanel_ = new ConfigPadButtonPanel();
configPadButtonPanel_.setConfigPad(configPad_);
configPadButtonPanel_.setGUI(MMStudioMainFrame.getInstance());
configPad_.setFont(new Font("", Font.PLAIN, 10));
GUIUtils.addWithEdges(topPanel, configPad_, 280, 21, -4, -44);
GUIUtils.addWithEdges(topPanel, configPadButtonPanel_, 280, -40, -4, -20);
}
private void createMainButtons(JPanel topPanel) {
snapButton_ = (JButton) GUIUtils.createButton(false, "Snap", "Snap",
"Snap single image",
new Runnable() {
public void run() {
doSnap();
}
}, "camera.png", topPanel, 7, 4, 95, 25);
liveButton_ = (JToggleButton) GUIUtils.createButton(true,
"Live", "Live",
"Continuous live view",
new Runnable() {
public void run() {
enableLiveMode(!isLiveModeOn());
}
}, "camera_go.png", topPanel, 7, 26, 95, 47);
/* toAlbumButton_ = (JButton) */ GUIUtils.createButton(false, "Album", "Album",
"Acquire single frame and add to an album",
new Runnable() {
public void run() {
snapAndAddToImage5D();
}
}, "camera_plus_arrow.png", topPanel, 7, 48, 95, 69);
/* MDA Button = */ GUIUtils.createButton(false,
"Multi-D Acq.", "Multi-D Acq.",
"Open multi-dimensional acquisition window",
new Runnable() {
public void run() {
openAcqControlDialog();
}
}, "film.png", topPanel, 7, 70, 95, 91);
/* Refresh = */ GUIUtils.createButton(false, "Refresh", "Refresh",
"Refresh all GUI controls directly from the hardware",
new Runnable() {
public void run() {
core_.updateSystemStateCache();
updateGUI(true);
}
}, "arrow_refresh.png", topPanel, 7, 92, 95, 113);
}
private static MetadataPanel createMetadataPanel(JPanel bottomPanel) {
MetadataPanel metadataPanel = new MetadataPanel();
GUIUtils.addWithEdges(bottomPanel, metadataPanel, 0, 0, 0, 0);
metadataPanel.setBorder(BorderFactory.createEmptyBorder());
return metadataPanel;
}
private void createPleaLabel(JPanel topPanel) {
JLabel citePleaLabel = new JLabel("<html>Please <a href=\"http://micro-manager.org\">cite Micro-Manager</a> so funding will continue!</html>");
citePleaLabel.setFont(new Font("Arial", Font.PLAIN, 11));
GUIUtils.addWithEdges(topPanel, citePleaLabel, 7, 119, 270, 139);
class Pleader extends Thread{
Pleader(){
super("pleader");
}
@Override
public void run(){
try {
ij.plugin.BrowserLauncher.openURL("https://micro-manager.org/wiki/Citing_Micro-Manager");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
}
citePleaLabel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
Pleader p = new Pleader();
p.start();
}
});
// add a listener to the main ImageJ window to catch it quitting out on us
if (ij.IJ.getInstance() != null) {
ij.IJ.getInstance().addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
closeSequence(true);
};
});
}
}
private JSplitPane createSplitPane(int dividerPos) {
JPanel topPanel = new JPanel();
JPanel bottomPanel = new JPanel();
topPanel.setLayout(new SpringLayout());
topPanel.setMinimumSize(new Dimension(580, 195));
bottomPanel.setLayout(new SpringLayout());
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true,
topPanel, bottomPanel);
splitPane.setBorder(BorderFactory.createEmptyBorder());
splitPane.setDividerLocation(dividerPos);
splitPane.setResizeWeight(0.0);
return splitPane;
}
private void createTopPanelWidgets(JPanel topPanel) {
createMainButtons(topPanel);
createCameraSettingsWidgets(topPanel);
createPleaLabel(topPanel);
createUtilityButtons(topPanel);
createConfigurationControls(topPanel);
labelImageDimensions_ = createLabel("", false, topPanel, 5, -20, 0, 0);
}
private void createUtilityButtons(JPanel topPanel) {
// ROI
createLabel("ROI", true, topPanel, 8, 140, 71, 154);
setRoiButton_ = GUIUtils.createButton(false, "setRoiButton", null,
"Set Region Of Interest to selected rectangle",
new Runnable() {
public void run() {
setROI();
}
}, "shape_handles.png", topPanel, 7, 154, 37, 174);
clearRoiButton_ = GUIUtils.createButton(false, "clearRoiButton", null,
"Reset Region of Interest to full frame",
new Runnable() {
public void run() {
clearROI();
}
}, "arrow_out.png", topPanel, 40, 154, 70, 174);
// Zoom
createLabel("Zoom", true, topPanel, 81, 140, 139, 154);
GUIUtils.createButton(false, "zoomInButton", null,
"Zoom in",
new Runnable() {
public void run() {
zoomIn();
}
}, "zoom_in.png", topPanel, 80, 154, 110, 174);
GUIUtils.createButton(false, "zoomOutButton", null,
"Zoom out",
new Runnable() {
public void run() {
zoomOut();
}
}, "zoom_out.png", topPanel, 113, 154, 143, 174);
// Profile
createLabel("Profile", true, topPanel, 154, 140, 217, 154);
GUIUtils.createButton(false, "lineProfileButton", null,
"Open line profile window (requires line selection)",
new Runnable() {
public void run() {
openLineProfileWindow();
}
}, "chart_curve.png", topPanel, 153, 154, 183, 174);
// Autofocus
createLabel("Autofocus", true, topPanel, 194, 140, 276, 154);
autofocusNowButton_ = (JButton) GUIUtils.createButton(false,
"autofocusNowButton", null,
"Autofocus now",
new Runnable() {
public void run() {
autofocusNow();
}
}, "find.png", topPanel, 193, 154, 223, 174);
autofocusConfigureButton_ = (JButton) GUIUtils.createButton(false,
"autofocusConfigureButton", null,
"Set autofocus options",
new Runnable() {
public void run() {
showAutofocusDialog();
}
}, "wrench_orange.png", topPanel, 226, 154, 256, 174);
}
private void initializeFileMenu() {
JMenu fileMenu = GUIUtils.createMenuInMenuBar(menuBar_, "File");
GUIUtils.addMenuItem(fileMenu, "Open (Virtual)...", null,
new Runnable() {
public void run() {
new Thread() {
@Override
public void run() {
openAcquisitionData(false);
}
}.start();
}
});
GUIUtils.addMenuItem(fileMenu, "Open (RAM)...", null,
new Runnable() {
public void run() {
new Thread() {
@Override
public void run() {
openAcquisitionData(true);
}
}.start();
}
});
fileMenu.addSeparator();
GUIUtils.addMenuItem(fileMenu, "Exit", null,
new Runnable() {
public void run() {
closeSequence(false);
}
});
}
private void initializeHelpMenu() {
final JMenu helpMenu = GUIUtils.createMenuInMenuBar(menuBar_, "Help");
GUIUtils.addMenuItem(helpMenu, "User's Guide", null,
new Runnable() {
public void run() {
try {
ij.plugin.BrowserLauncher.openURL("http://micro-manager.org/wiki/Micro-Manager_User%27s_Guide");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
});
GUIUtils.addMenuItem(helpMenu, "Configuration Guide", null,
new Runnable() {
public void run() {
try {
ij.plugin.BrowserLauncher.openURL("http://micro-manager.org/wiki/Micro-Manager_Configuration_Guide");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
});
if (!systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false)) {
GUIUtils.addMenuItem(helpMenu, "Register your copy of Micro-Manager...", null,
new Runnable() {
public void run() {
try {
RegistrationDlg regDlg = new RegistrationDlg(systemPrefs_);
regDlg.setVisible(true);
} catch (Exception e1) {
ReportingUtils.showError(e1);
}
}
});
}
GUIUtils.addMenuItem(helpMenu, "Report Problem...", null,
new Runnable() {
public void run() {
if (null == reportProblemDialog_) {
reportProblemDialog_ = new ReportProblemDialog(core_, MMStudioMainFrame.this, options_);
MMStudioMainFrame.this.addMMBackgroundListener(reportProblemDialog_);
reportProblemDialog_.setBackground(guiColors_.background.get(options_.displayBackground_));
}
reportProblemDialog_.setVisible(true);
}
});
GUIUtils.addMenuItem(helpMenu, "About Micromanager", null,
new Runnable() {
public void run() {
MMAboutDlg dlg = new MMAboutDlg();
String versionInfo = "MM Studio version: " + MMVersion.VERSION_STRING;
versionInfo += "\n" + core_.getVersionInfo();
versionInfo += "\n" + core_.getAPIVersionInfo();
versionInfo += "\nUser: " + core_.getUserId();
versionInfo += "\nHost: " + core_.getHostName();
dlg.setVersionInfo(versionInfo);
dlg.setVisible(true);
}
});
menuBar_.validate();
}
private void initializeToolsMenu() {
// Tools menu
final JMenu toolsMenu = GUIUtils.createMenuInMenuBar(menuBar_, "Tools");
GUIUtils.addMenuItem(toolsMenu, "Refresh GUI",
"Refresh all GUI controls directly from the hardware",
new Runnable() {
public void run() {
core_.updateSystemStateCache();
updateGUI(true);
}
},
"arrow_refresh.png");
GUIUtils.addMenuItem(toolsMenu, "Rebuild GUI",
"Regenerate Micro-Manager user interface",
new Runnable() {
public void run() {
initializeGUI();
core_.updateSystemStateCache();
}
});
toolsMenu.addSeparator();
GUIUtils.addMenuItem(toolsMenu, "Script Panel...",
"Open Micro-Manager script editor window",
new Runnable() {
public void run() {
scriptPanel_.setVisible(true);
}
});
GUIUtils.addMenuItem(toolsMenu, "Shortcuts...",
"Create keyboard shortcuts to activate image acquisition, mark positions, or run custom scripts",
new Runnable() {
public void run() {
HotKeysDialog hk = new HotKeysDialog(guiColors_.background.get((options_.displayBackground_)));
//hk.setBackground(guiColors_.background.get((options_.displayBackground_)));
}
});
GUIUtils.addMenuItem(toolsMenu, "Device/Property Browser...",
"Open new window to view and edit property values in current configuration",
new Runnable() {
public void run() {
createPropertyEditor();
}
});
toolsMenu.addSeparator();
GUIUtils.addMenuItem(toolsMenu, "XY List...",
"Open position list manager window",
new Runnable() {
public void run() {
showXYPositionList();
}
},
"application_view_list.png");
GUIUtils.addMenuItem(toolsMenu, "Multi-Dimensional Acquisition...",
"Open multi-dimensional acquisition setup window",
new Runnable() {
public void run() {
openAcqControlDialog();
}
},
"film.png");
centerAndDragMenuItem_ = GUIUtils.addCheckBoxMenuItem(toolsMenu,
"Mouse Moves Stage (use Hand Tool)",
"When enabled, double clicking or dragging in the snap/live\n"
+ "window moves the XY-stage. Requires the hand tool.",
new Runnable() {
public void run() {
updateCenterAndDragListener();
IJ.setTool(Toolbar.HAND);
mainPrefs_.putBoolean(MOUSE_MOVES_STAGE, centerAndDragMenuItem_.isSelected());
}
},
mainPrefs_.getBoolean(MOUSE_MOVES_STAGE, false));
GUIUtils.addMenuItem(toolsMenu, "Pixel Size Calibration...",
"Define size calibrations specific to each objective lens. "
+ "When the objective in use has a calibration defined, "
+ "micromanager will automatically use it when "
+ "calculating metadata",
new Runnable() {
public void run() {
createCalibrationListDlg();
}
});
/*
GUIUtils.addMenuItem(toolsMenu, "Image Processor Manager",
"Control the order in which Image Processor plugins"
+ "are applied to incoming images.",
new Runnable() {
public void run() {
processorStackManager_.show();
}
});
*/
toolsMenu.addSeparator();
GUIUtils.addMenuItem(toolsMenu, "Hardware Configuration Wizard...",
"Open wizard to create new hardware configuration",
new Runnable() {
public void run() {
runHardwareWizard();
}
});
GUIUtils.addMenuItem(toolsMenu, "Load Hardware Configuration...",
"Un-initialize current configuration and initialize new one",
new Runnable() {
public void run() {
loadConfiguration();
initializeGUI();
}
});
GUIUtils.addMenuItem(toolsMenu, "Reload Hardware Configuration",
"Shutdown current configuration and initialize most recently loaded configuration",
new Runnable() {
public void run() {
loadSystemConfiguration();
initializeGUI();
}
});
for (int i=0; i<5; i++)
{
JMenuItem configItem = new JMenuItem();
configItem.setText(Integer.toString(i));
switchConfigurationMenu_.add(configItem);
}
switchConfigurationMenu_.setText("Switch Hardware Configuration");
toolsMenu.add(switchConfigurationMenu_);
switchConfigurationMenu_.setToolTipText("Switch between recently used configurations");
GUIUtils.addMenuItem(toolsMenu, "Save Configuration Settings as...",
"Save current configuration settings as new configuration file",
new Runnable() {
public void run() {
saveConfigPresets();
updateChannelCombos();
}
});
toolsMenu.addSeparator();
final MMStudioMainFrame thisInstance = this;
GUIUtils.addMenuItem(toolsMenu, "Options...",
"Set a variety of Micro-Manager configuration options",
new Runnable() {
public void run() {
final int oldBufsize = options_.circularBufferSizeMB_;
OptionsDlg dlg = new OptionsDlg(options_, core_, mainPrefs_,
thisInstance);
dlg.setVisible(true);
// adjust memory footprint if necessary
if (oldBufsize != options_.circularBufferSizeMB_) {
try {
core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_);
} catch (Exception exc) {
ReportingUtils.showError(exc);
}
}
}
});
}
private void showRegistrationDialogMaybe() {
// show registration dialog if not already registered
// first check user preferences (for legacy compatibility reasons)
boolean userReg = mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION,
false) || mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false);
if (!userReg) {
boolean systemReg = systemPrefs_.getBoolean(
RegistrationDlg.REGISTRATION, false) || systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false);
if (!systemReg) {
// prompt for registration info
RegistrationDlg dlg = new RegistrationDlg(systemPrefs_);
dlg.setVisible(true);
}
}
}
private void updateSwitchConfigurationMenu() {
switchConfigurationMenu_.removeAll();
for (final String configFile : MRUConfigFiles_) {
if (!configFile.equals(sysConfigFile_)) {
GUIUtils.addMenuItem(switchConfigurationMenu_,
configFile, null,
new Runnable() {
public void run() {
sysConfigFile_ = configFile;
loadSystemConfiguration();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
}
});
}
}
}
/**
* Allows MMListeners to register themselves
*/
@Override
public void addMMListener(MMListenerInterface newL) {
if (MMListeners_.contains(newL))
return;
MMListeners_.add(newL);
}
/**
* Allows MMListeners to remove themselves
*/
@Override
public void removeMMListener(MMListenerInterface oldL) {
if (!MMListeners_.contains(oldL))
return;
MMListeners_.remove(oldL);
}
public final void addLiveModeListener (LiveModeListener listener) {
if (liveModeListeners_.contains(listener)) {
return;
}
liveModeListeners_.add(listener);
}
public void removeLiveModeListener(LiveModeListener listener) {
liveModeListeners_.remove(listener);
}
public void callLiveModeListeners(boolean enable) {
for (LiveModeListener listener : liveModeListeners_) {
listener.liveModeEnabled(enable);
}
}
/**
* Lets JComponents register themselves so that their background can be
* manipulated
*/
@Override
public void addMMBackgroundListener(Component comp) {
if (MMFrames_.contains(comp))
return;
MMFrames_.add(comp);
}
/**
* Lets JComponents remove themselves from the list whose background gets
* changes
*/
@Override
public void removeMMBackgroundListener(Component comp) {
if (!MMFrames_.contains(comp))
return;
MMFrames_.remove(comp);
}
/**
* Part of ScriptInterface
* Manipulate acquisition so that it looks like a burst
*/
public void runBurstAcquisition() throws MMScriptException {
double interval = engine_.getFrameIntervalMs();
int nr = engine_.getNumFrames();
boolean doZStack = engine_.isZSliceSettingEnabled();
boolean doChannels = engine_.isChannelsSettingEnabled();
engine_.enableZSliceSetting(false);
engine_.setFrames(nr, 0);
engine_.enableChannelsSetting(false);
try {
engine_.acquire();
} catch (MMException e) {
throw new MMScriptException(e);
}
engine_.setFrames(nr, interval);
engine_.enableZSliceSetting(doZStack);
engine_.enableChannelsSetting(doChannels);
}
public void runBurstAcquisition(int nr) throws MMScriptException {
int originalNr = engine_.getNumFrames();
double interval = engine_.getFrameIntervalMs();
engine_.setFrames(nr, 0);
this.runBurstAcquisition();
engine_.setFrames(originalNr, interval);
}
public void runBurstAcquisition(int nr, String name, String root) throws MMScriptException {
String originalRoot = engine_.getRootName();
engine_.setDirName(name);
engine_.setRootName(root);
this.runBurstAcquisition(nr);
engine_.setRootName(originalRoot);
}
/**
* Inserts version info for various components in the Corelog
*/
@Override
public void logStartupProperties() {
core_.enableDebugLog(options_.debugLogEnabled_);
core_.logMessage("MM Studio version: " + getVersion());
core_.logMessage(core_.getVersionInfo());
core_.logMessage(core_.getAPIVersionInfo());
core_.logMessage("Operating System: " + System.getProperty("os.name") +
" (" + System.getProperty("os.arch") + ") " + System.getProperty("os.version"));
core_.logMessage("JVM: " + System.getProperty("java.vm.name") +
", version " + System.getProperty("java.version") + ", " +
System.getProperty("sun.arch.data.model") + "-bit");
}
/**
* @Deprecated
* @throws MMScriptException
*/
public void startBurstAcquisition() throws MMScriptException {
runAcquisition();
}
public boolean isBurstAcquisitionRunning() throws MMScriptException {
if (engine_ == null)
return false;
return engine_.isAcquisitionRunning();
}
private void startLoadingPipelineClass() {
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
acquisitionEngine2010LoadingThread = new Thread("Pipeline Class loading thread") {
@Override
public void run() {
try {
acquisitionEngine2010Class = Class.forName("org.micromanager.AcquisitionEngine2010");
} catch (Exception ex) {
ReportingUtils.logError(ex);
acquisitionEngine2010Class = null;
}
}
};
acquisitionEngine2010LoadingThread.start();
}
@Override
public ImageCache getAcquisitionImageCache(String acquisitionName) throws MMScriptException {
return getAcquisition(acquisitionName).getImageCache();
}
/**
* Shows images as they appear in the default display window. Uses
* the default processor stack to process images as they arrive on
* the rawImageQueue.
*/
public void runDisplayThread(BlockingQueue<TaggedImage> rawImageQueue,
final DisplayImageRoutine displayImageRoutine) {
final BlockingQueue<TaggedImage> processedImageQueue =
ProcessorStack.run(rawImageQueue,
getAcquisitionEngine().getImageProcessors());
new Thread("Display thread") {
@Override
public void run() {
try {
TaggedImage image;
do {
image = processedImageQueue.take();
if (image != TaggedImageQueue.POISON) {
displayImageRoutine.show(image);
}
} while (image != TaggedImageQueue.POISON);
} catch (InterruptedException ex) {
ReportingUtils.logError(ex);
}
}
}.start();
}
private static JLabel createLabel(String text, boolean big,
JPanel parentPanel, int west, int north, int east, int south) {
final JLabel label = new JLabel();
label.setFont(new Font("Arial",
big ? Font.BOLD : Font.PLAIN,
big ? 11 : 10));
label.setText(text);
GUIUtils.addWithEdges(parentPanel, label, west, north, east, south);
return label;
}
public interface DisplayImageRoutine {
public void show(TaggedImage image);
}
/**
* Callback to update GUI when a change happens in the MMCore.
*/
public class CoreEventCallback extends MMEventCallback {
public CoreEventCallback() {
super();
}
@Override
public void onPropertiesChanged() {
// TODO: remove test once acquisition engine is fully multithreaded
if (engine_ != null && engine_.isAcquisitionRunning()) {
core_.logMessage("Notification from MMCore ignored because acquistion is running!", true);
} else {
if (ignorePropertyChanges_) {
core_.logMessage("Notification from MMCore ignored since the system is still loading", true);
} else {
core_.updateSystemStateCache();
updateGUI(true);
// update all registered listeners
for (MMListenerInterface mmIntf : MMListeners_) {
mmIntf.propertiesChangedAlert();
}
core_.logMessage("Notification from MMCore!", true);
}
}
}
@Override
public void onPropertyChanged(String deviceName, String propName, String propValue) {
core_.logMessage("Notification for Device: " + deviceName + " Property: " +
propName + " changed to value: " + propValue, true);
// update all registered listeners
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.propertyChangedAlert(deviceName, propName, propValue);
}
}
@Override
public void onConfigGroupChanged(String groupName, String newConfig) {
try {
configPad_.refreshGroup(groupName, newConfig);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.configGroupChangedAlert(groupName, newConfig);
}
} catch (Exception e) {
}
}
@Override
public void onSystemConfigurationLoaded() {
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.systemConfigurationLoaded();
}
}
@Override
public void onPixelSizeChanged(double newPixelSizeUm) {
updatePixSizeUm (newPixelSizeUm);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.pixelSizeChangedAlert(newPixelSizeUm);
}
}
@Override
public void onStagePositionChanged(String deviceName, double pos) {
if (deviceName.equals(zStageLabel_)) {
updateZPos(pos);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.stagePositionChangedAlert(deviceName, pos);
}
}
}
@Override
public void onStagePositionChangedRelative(String deviceName, double pos) {
if (deviceName.equals(zStageLabel_))
updateZPosRelative(pos);
}
@Override
public void onXYStagePositionChanged(String deviceName, double xPos, double yPos) {
if (deviceName.equals(xyStageLabel_)) {
updateXYPos(xPos, yPos);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.xyStagePositionChanged(deviceName, xPos, yPos);
}
}
}
@Override
public void onXYStagePositionChangedRelative(String deviceName, double xPos, double yPos) {
if (deviceName.equals(xyStageLabel_))
updateXYPosRelative(xPos, yPos);
}
@Override
public void onExposureChanged(String deviceName, double exposure) {
if (deviceName.equals(cameraLabel_)){
// update exposure in gui
textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure));
}
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.exposureChanged(deviceName, exposure);
}
}
}
private class PluginItem {
public Class<?> pluginClass = null;
public String menuItem = "undefined";
public MMPlugin plugin = null;
public String className = "";
public void instantiate() {
try {
if (plugin == null) {
plugin = (MMPlugin) pluginClass.newInstance();
}
} catch (InstantiationException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
plugin.setApp(MMStudioMainFrame.this);
}
}
/*
* Simple class used to cache static info
*/
private class StaticInfo {
public long width_;
public long height_;
public long bytesPerPixel_;
public long imageBitDepth_;
public double pixSizeUm_;
public double zPos_;
public double x_;
public double y_;
}
private StaticInfo staticInfo_ = new StaticInfo();
private void setupWindowHandlers() {
// add window listeners
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
closeSequence(false);
}
@Override
public void windowOpened(WindowEvent e) {
// -------------------
// initialize hardware
// -------------------
try {
core_ = new CMMCore();
} catch(UnsatisfiedLinkError ex) {
ReportingUtils.showError(ex, "Failed to load the MMCoreJ_wrap native library");
return;
}
ReportingUtils.setCore(core_);
logStartupProperties();
cameraLabel_ = "";
shutterLabel_ = "";
zStageLabel_ = "";
xyStageLabel_ = "";
engine_ = new AcquisitionWrapperEngine(acqMgr_);
// processorStackManager_ = new ProcessorStackManager(engine_);
// register callback for MMCore notifications, this is a global
// to avoid garbage collection
cb_ = new CoreEventCallback();
core_.registerCallback(cb_);
try {
core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_);
} catch (Exception e2) {
ReportingUtils.showError(e2);
}
MMStudioMainFrame parent = (MMStudioMainFrame) e.getWindow();
if (parent != null) {
engine_.setParentGUI(parent);
}
loadMRUConfigFiles();
afMgr_ = new AutofocusManager(gui_);
Thread pluginLoader = initializePlugins();
toFront();
if (!options_.doNotAskForConfigFile_) {
MMIntroDlg introDlg = new MMIntroDlg(MMVersion.VERSION_STRING, MRUConfigFiles_);
introDlg.setConfigFile(sysConfigFile_);
introDlg.setBackground(guiColors_.background.get((options_.displayBackground_)));
introDlg.setVisible(true);
if (!introDlg.okChosen()) {
closeSequence(false);
return;
}
sysConfigFile_ = introDlg.getConfigFile();
}
saveMRUConfigFiles();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
paint(MMStudioMainFrame.this.getGraphics());
engine_.setCore(core_, afMgr_);
posList_ = new PositionList();
engine_.setPositionList(posList_);
// load (but do no show) the scriptPanel
createScriptPanel();
// Create an instance of HotKeys so that they can be read in from prefs
hotKeys_ = new org.micromanager.utils.HotKeys();
hotKeys_.loadSettings();
// before loading the system configuration, we need to wait
// until the plugins are loaded
try {
pluginLoader.join(2000);
} catch (InterruptedException ex) {
ReportingUtils.logError(ex, "Plugin loader thread was interupted");
}
// if an error occurred during config loading,
// do not display more errors than needed
if (!loadSystemConfiguration())
ReportingUtils.showErrorOn(false);
executeStartupScript();
// Create Multi-D window here but do not show it.
// This window needs to be created in order to properly set the "ChannelGroup"
// based on the Multi-D parameters
acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, MMStudioMainFrame.this, options_);
addMMBackgroundListener(acqControlWin_);
configPad_.setCore(core_);
if (parent != null) {
configPad_.setParentGUI(parent);
}
configPadButtonPanel_.setCore(core_);
// initialize controls
// initializeGUI(); Not needed since it is already called in loadSystemConfiguration
initializeHelpMenu();
String afDevice = mainPrefs_.get(AUTOFOCUS_DEVICE, "");
if (afMgr_.hasDevice(afDevice)) {
try {
afMgr_.selectDevice(afDevice);
} catch (MMException e1) {
// this error should never happen
ReportingUtils.showError(e1);
}
}
centerAndDragListener_ = new CenterAndDragListener(gui_);
zWheelListener_ = new ZWheelListener(core_, gui_);
gui_.addLiveModeListener(zWheelListener_);
xyzKeyListener_ = new XYZKeyListener(core_, gui_);
gui_.addLiveModeListener(xyzKeyListener_);
// switch error reporting back on
ReportingUtils.showErrorOn(true);
}
private Thread initializePlugins() {
pluginMenu_ = GUIUtils.createMenuInMenuBar(menuBar_, "Plugins");
Thread myThread = new ThreadPluginLoading("Plugin loading");
myThread.start();
return myThread;
}
class ThreadPluginLoading extends Thread {
public ThreadPluginLoading(String string) {
super(string);
}
@Override
public void run() {
// Needed for loading clojure-based jars:
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
loadPlugins();
}
}
});
}
/**
* Main procedure for stand alone operation.
*/
public static void main(String args[]) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
MMStudioMainFrame frame = new MMStudioMainFrame(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
} catch (Throwable e) {
ReportingUtils.showError(e, "A java error has caused Micro-Manager to exit.");
System.exit(1);
}
}
@SuppressWarnings("LeakingThisInConstructor")
public MMStudioMainFrame(boolean pluginStatus) {
org.micromanager.diagnostics.ThreadExceptionLogger.setUp();
startLoadingPipelineClass();
options_ = new MMOptions();
try {
options_.loadSettings();
} catch (NullPointerException ex) {
ReportingUtils.logError(ex);
}
UIMonitor.enable(options_.debugLogEnabled_);
guiColors_ = new GUIColors();
plugins_ = new ArrayList<PluginItem>();
gui_ = this;
runsAsPlugin_ = pluginStatus;
setIconImage(SwingResourceManager.getImage(MMStudioMainFrame.class,
"icons/microscope.gif"));
running_ = true;
acqMgr_ = new AcquisitionManager();
sysConfigFile_ = System.getProperty("user.dir") + "/"
+ DEFAULT_CONFIG_FILE_NAME;
if (options_.startupScript_.length() > 0) {
startupScriptFile_ = System.getProperty("user.dir") + "/"
+ options_.startupScript_;
} else {
startupScriptFile_ = "";
}
ReportingUtils.SetContainingFrame(gui_);
// set the location for app preferences
try {
mainPrefs_ = Preferences.userNodeForPackage(this.getClass());
} catch (Exception e) {
ReportingUtils.logError(e);
}
systemPrefs_ = mainPrefs_;
colorPrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + "/" +
AcqControlDlg.COLOR_SETTINGS_NODE);
exposurePrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + "/" +
EXPOSURE_SETTINGS_NODE);
contrastPrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + "/" +
CONTRAST_SETTINGS_NODE);
// check system preferences
try {
Preferences p = Preferences.systemNodeForPackage(this.getClass());
if (null != p) {
// if we can not write to the systemPrefs, use AppPrefs instead
if (JavaUtils.backingStoreAvailable(p)) {
systemPrefs_ = p;
}
}
} catch (Exception e) {
ReportingUtils.logError(e);
}
showRegistrationDialogMaybe();
// load application preferences
// NOTE: only window size and position preferences are loaded,
// not the settings for the camera and live imaging -
// attempting to set those automatically on startup may cause problems
// with the hardware
int x = mainPrefs_.getInt(MAIN_FRAME_X, 100);
int y = mainPrefs_.getInt(MAIN_FRAME_Y, 100);
int width = mainPrefs_.getInt(MAIN_FRAME_WIDTH, 644);
int height = mainPrefs_.getInt(MAIN_FRAME_HEIGHT, 570);
openAcqDirectory_ = mainPrefs_.get(OPEN_ACQ_DIR, "");
try {
ImageUtils.setImageStorageClass(Class.forName (mainPrefs_.get(MAIN_SAVE_METHOD,
ImageUtils.getImageStorageClass().getName()) ) );
} catch (ClassNotFoundException ex) {
ReportingUtils.logError(ex, "Class not found error. Should never happen");
}
ToolTipManager ttManager = ToolTipManager.sharedInstance();
ttManager.setDismissDelay(TOOLTIP_DISPLAY_DURATION_MILLISECONDS);
ttManager.setInitialDelay(TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS);
setBounds(x, y, width, height);
setExitStrategy(options_.closeOnExit_);
setTitle(MICRO_MANAGER_TITLE + " " + MMVersion.VERSION_STRING);
setBackground(guiColors_.background.get((options_.displayBackground_)));
setMinimumSize(new Dimension(605,480));
menuBar_ = new JMenuBar();
switchConfigurationMenu_ = new JMenu();
setJMenuBar(menuBar_);
initializeFileMenu();
initializeToolsMenu();
splitPane_ = createSplitPane(mainPrefs_.getInt(MAIN_FRAME_DIVIDER_POS, 200));
getContentPane().add(splitPane_);
createTopPanelWidgets((JPanel) splitPane_.getComponent(0));
metadataPanel_ = createMetadataPanel((JPanel) splitPane_.getComponent(1));
setupWindowHandlers();
// Add our own keyboard manager that handles Micro-Manager shortcuts
MMKeyDispatcher mmKD = new MMKeyDispatcher(gui_);
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(mmKD);
dt_ = new DropTarget(this, new DragDropUtil());
}
private void handleException(Exception e, String msg) {
String errText = "Exception occurred: ";
if (msg.length() > 0) {
errText += msg + " -- ";
}
if (options_.debugLogEnabled_) {
errText += e.getMessage();
} else {
errText += e.toString() + "\n";
ReportingUtils.showError(e);
}
handleError(errText);
}
private void handleException(Exception e) {
handleException(e, "");
}
private void handleError(String message) {
if (isLiveModeOn()) {
// Should we always stop live mode on any error?
enableLiveMode(false);
}
JOptionPane.showMessageDialog(this, message);
core_.logMessage(message);
}
@Override
public void makeActive() {
toFront();
}
/**
* used to store contrast settings to be later used for initialization of contrast of new windows.
* Shouldn't be called by loaded data sets, only
* ones that have been acquired
*/
public void saveChannelHistogramSettings(String channelGroup, String channel, boolean mda,
HistogramSettings settings) {
String type = mda ? "MDA_" : "SnapLive_";
if (options_.syncExposureMainAndMDA_) {
type = ""; //only one group of contrast settings
}
contrastPrefs_.putInt("ContrastMin_" + channelGroup + "_" + type + channel, settings.min_);
contrastPrefs_.putInt("ContrastMax_" + channelGroup + "_" + type + channel, settings.max_);
contrastPrefs_.putDouble("ContrastGamma_" + channelGroup + "_" + type + channel, settings.gamma_);
contrastPrefs_.putInt("ContrastHistMax_" + channelGroup + "_" + type + channel, settings.histMax_);
contrastPrefs_.putInt("ContrastHistDisplayMode_" + channelGroup + "_" + type + channel, settings.displayMode_);
}
public HistogramSettings loadStoredChannelHisotgramSettings(String channelGroup, String channel, boolean mda) {
String type = mda ? "MDA_" : "SnapLive_";
if (options_.syncExposureMainAndMDA_) {
type = ""; //only one group of contrast settings
}
return new HistogramSettings(
contrastPrefs_.getInt("ContrastMin_" + channelGroup + "_" + type + channel,0),
contrastPrefs_.getInt("ContrastMax_" + channelGroup + "_" + type + channel, 65536),
contrastPrefs_.getDouble("ContrastGamma_" + channelGroup + "_" + type + channel, 1.0),
contrastPrefs_.getInt("ContrastHistMax_" + channelGroup + "_" + type + channel, -1),
contrastPrefs_.getInt("ContrastHistDisplayMode_" + channelGroup + "_" + type + channel, 1) );
}
private void setExposure() {
try {
if (!isLiveModeOn()) {
core_.setExposure(NumberUtils.displayStringToDouble(
textFieldExp_.getText()));
} else {
liveModeTimer_.stop();
core_.setExposure(NumberUtils.displayStringToDouble(
textFieldExp_.getText()));
try {
liveModeTimer_.begin();
} catch (Exception e) {
ReportingUtils.showError("Couldn't restart live mode");
liveModeTimer_.stop();
}
}
// Display the new exposure time
double exposure = core_.getExposure();
textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure));
// update current channel in MDA window with this exposure
String channelGroup = core_.getChannelGroup();
String channel = core_.getCurrentConfigFromCache(channelGroup);
if (!channel.equals("") ) {
exposurePrefs_.putDouble("Exposure_" + channelGroup + "_"
+ channel, exposure);
if (options_.syncExposureMainAndMDA_) {
getAcqDlg().setChannelExposureTime(channelGroup, channel, exposure);
}
}
} catch (Exception exp) {
// Do nothing.
}
}
/**
* Returns exposure time for the desired preset in the given channelgroup
* Acquires its info from the preferences
* Same thing is used in MDA window, but this class keeps its own copy
*
* @param channelGroup
* @param channel -
* @param defaultExp - default value
* @return exposure time
*/
@Override
public double getChannelExposureTime(String channelGroup, String channel,
double defaultExp) {
return exposurePrefs_.getDouble("Exposure_" + channelGroup
+ "_" + channel, defaultExp);
}
/**
* Updates the exposure time in the given preset
* Will also update current exposure if it the given channel and channelgroup
* are the current one
*
* @param channelGroup -
*
* @param channel - preset for which to change exposure time
* @param exposure - desired exposure time
*/
@Override
public void setChannelExposureTime(String channelGroup, String channel,
double exposure) {
try {
exposurePrefs_.putDouble("Exposure_" + channelGroup + "_"
+ channel, exposure);
if (channelGroup != null && channelGroup.equals(core_.getChannelGroup())) {
if (channel != null && !channel.equals("") &&
channel.equals(core_.getCurrentConfigFromCache(channelGroup))) {
textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure));
setExposure();
}
}
} catch (Exception ex) {
ReportingUtils.logError("Failed to set Exposure prefs using Channelgroup: "
+ channelGroup + ", channel: " + channel + ", exposure: " + exposure);
}
}
@Override
public boolean getAutoreloadOption() {
return options_.autoreloadDevices_;
}
public double getPreferredWindowMag() {
return options_.windowMag_;
}
public boolean getMetadataFileWithMultipageTiff() {
return options_.mpTiffMetadataFile_;
}
public boolean getSeparateFilesForPositionsMPTiff() {
return options_.mpTiffSeparateFilesForPositions_;
}
@Override
public boolean getHideMDADisplayOption() {
return options_.hideMDADisplay_;
}
private void updateTitle() {
this.setTitle(MICRO_MANAGER_TITLE + " " + MMVersion.VERSION_STRING + " - " + sysConfigFile_);
}
public void updateLineProfile() {
if (WindowManager.getCurrentWindow() == null || profileWin_ == null
|| !profileWin_.isShowing()) {
return;
}
calculateLineProfileData(WindowManager.getCurrentImage());
profileWin_.setData(lineProfileData_);
}
private void openLineProfileWindow() {
if (WindowManager.getCurrentWindow() == null || WindowManager.getCurrentWindow().isClosed()) {
return;
}
calculateLineProfileData(WindowManager.getCurrentImage());
if (lineProfileData_ == null) {
return;
}
profileWin_ = new GraphFrame();
profileWin_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
profileWin_.setData(lineProfileData_);
profileWin_.setAutoScale();
profileWin_.setTitle("Live line profile");
profileWin_.setBackground(guiColors_.background.get((options_.displayBackground_)));
addMMBackgroundListener(profileWin_);
profileWin_.setVisible(true);
}
@Override
public Rectangle getROI() throws MMScriptException {
// ROI values are given as x,y,w,h in individual one-member arrays (pointers in C++):
int[][] a = new int[4][1];
try {
core_.getROI(a[0], a[1], a[2], a[3]);
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
// Return as a single array with x,y,w,h:
return new Rectangle(a[0][0], a[1][0], a[2][0], a[3][0]);
}
private void calculateLineProfileData(ImagePlus imp) {
// generate line profile
Roi roi = imp.getRoi();
if (roi == null || !roi.isLine()) {
// if there is no line ROI, create one
Rectangle r = imp.getProcessor().getRoi();
int iWidth = r.width;
int iHeight = r.height;
int iXROI = r.x;
int iYROI = r.y;
if (roi == null) {
iXROI += iWidth / 2;
iYROI += iHeight / 2;
}
roi = new Line(iXROI - iWidth / 4, iYROI - iWidth / 4, iXROI
+ iWidth / 4, iYROI + iHeight / 4);
imp.setRoi(roi);
roi = imp.getRoi();
}
ImageProcessor ip = imp.getProcessor();
ip.setInterpolate(true);
Line line = (Line) roi;
if (lineProfileData_ == null) {
lineProfileData_ = new GraphData();
}
lineProfileData_.setData(line.getPixels());
}
@Override
public void setROI(Rectangle r) throws MMScriptException {
boolean liveRunning = false;
if (isLiveModeOn()) {
liveRunning = true;
enableLiveMode(false);
}
try {
core_.setROI(r.x, r.y, r.width, r.height);
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
}
private void setROI() {
ImagePlus curImage = WindowManager.getCurrentImage();
if (curImage == null) {
return;
}
Roi roi = curImage.getRoi();
try {
if (roi == null) {
// if there is no ROI, create one
Rectangle r = curImage.getProcessor().getRoi();
int iWidth = r.width;
int iHeight = r.height;
int iXROI = r.x;
int iYROI = r.y;
if (roi == null) {
iWidth /= 2;
iHeight /= 2;
iXROI += iWidth / 2;
iYROI += iHeight / 2;
}
curImage.setRoi(iXROI, iYROI, iWidth, iHeight);
roi = curImage.getRoi();
}
if (roi.getType() != Roi.RECTANGLE) {
handleError("ROI must be a rectangle.\nUse the ImageJ rectangle tool to draw the ROI.");
return;
}
Rectangle r = roi.getBounds();
// if we already had an ROI defined, correct for the offsets
Rectangle cameraR = getROI();
r.x += cameraR.x;
r.y += cameraR.y;
// Stop (and restart) live mode if it is running
setROI(r);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
private void clearROI() {
try {
boolean liveRunning = false;
if (isLiveModeOn()) {
liveRunning = true;
enableLiveMode(false);
}
core_.clearROI();
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
/**
* Returns instance of the core uManager object;
*/
@Override
public CMMCore getMMCore() {
return core_;
}
/**
* Returns singleton instance of MMStudioMainFrame
*/
public static MMStudioMainFrame getInstance() {
return gui_;
}
public MetadataPanel getMetadataPanel() {
return metadataPanel_;
}
public final void setExitStrategy(boolean closeOnExit) {
if (closeOnExit) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
else {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
@Override
public void saveConfigPresets() {
MicroscopeModel model = new MicroscopeModel();
try {
model.loadFromFile(sysConfigFile_);
model.createSetupConfigsFromHardware(core_);
model.createResolutionsFromHardware(core_);
File f = FileDialogs.save(this, "Save the configuration file", MM_CONFIG_FILE);
if (f != null) {
model.saveToFile(f.getAbsolutePath());
sysConfigFile_ = f.getAbsolutePath();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
configChanged_ = false;
setConfigSaveButtonStatus(configChanged_);
updateTitle();
}
} catch (MMConfigFileException e) {
ReportingUtils.showError(e);
}
}
protected void setConfigSaveButtonStatus(boolean changed) {
saveConfigButton_.setEnabled(changed);
}
public String getAcqDirectory() {
return openAcqDirectory_;
}
/**
* Get currently used configuration file
* @return - Path to currently used configuration file
*/
public String getSysConfigFile() {
return sysConfigFile_;
}
public void setAcqDirectory(String dir) {
openAcqDirectory_ = dir;
}
/**
* Open an existing acquisition directory and build viewer window.
*
*/
public void openAcquisitionData(boolean inRAM) {
// choose the directory
// --------------------
File f = FileDialogs.openDir(this, "Please select an image data set", MM_DATA_SET);
if (f != null) {
if (f.isDirectory()) {
openAcqDirectory_ = f.getAbsolutePath();
} else {
openAcqDirectory_ = f.getParent();
}
String acq = null;
try {
acq = openAcquisitionData(openAcqDirectory_, inRAM);
} catch (MMScriptException ex) {
ReportingUtils.showError(ex);
} finally {
try {
acqMgr_.closeAcquisition(acq);
} catch (MMScriptException ex) {
ReportingUtils.logError(ex);
}
}
}
}
@Override
public String openAcquisitionData(String dir, boolean inRAM, boolean show)
throws MMScriptException {
String rootDir = new File(dir).getAbsolutePath();
String name = new File(dir).getName();
rootDir = rootDir.substring(0, rootDir.length() - (name.length() + 1));
name = acqMgr_.getUniqueAcquisitionName(name);
acqMgr_.openAcquisition(name, rootDir, show, !inRAM, true);
try {
getAcquisition(name).initialize();
} catch (MMScriptException mex) {
acqMgr_.closeAcquisition(name);
throw (mex);
}
return name;
}
/**
* Opens an existing data set. Shows the acquisition in a window.
* @return The acquisition object.
*/
@Override
public String openAcquisitionData(String dir, boolean inRam) throws MMScriptException {
return openAcquisitionData(dir, inRam, true);
}
protected void zoomOut() {
ImageWindow curWin = WindowManager.getCurrentWindow();
if (curWin != null) {
ImageCanvas canvas = curWin.getCanvas();
Rectangle r = canvas.getBounds();
canvas.zoomOut(r.width / 2, r.height / 2);
VirtualAcquisitionDisplay vad = VirtualAcquisitionDisplay.getDisplay(curWin.getImagePlus());
if (vad != null) {
vad.storeWindowSizeAfterZoom(curWin);
vad.updateWindowTitleAndStatus();
}
}
}
protected void zoomIn() {
ImageWindow curWin = WindowManager.getCurrentWindow();
if (curWin != null) {
ImageCanvas canvas = curWin.getCanvas();
Rectangle r = canvas.getBounds();
canvas.zoomIn(r.width / 2, r.height / 2);
VirtualAcquisitionDisplay vad = VirtualAcquisitionDisplay.getDisplay(curWin.getImagePlus());
if (vad != null) {
vad.storeWindowSizeAfterZoom(curWin);
vad.updateWindowTitleAndStatus();
}
}
}
protected void changeBinning() {
try {
boolean liveRunning = false;
if (isLiveModeOn() ) {
liveRunning = true;
enableLiveMode(false);
}
if (isCameraAvailable()) {
Object item = comboBinning_.getSelectedItem();
if (item != null) {
core_.setProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning(), item.toString());
}
}
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
private void createPropertyEditor() {
if (propertyBrowser_ != null) {
propertyBrowser_.dispose();
}
propertyBrowser_ = new PropertyEditor();
propertyBrowser_.setGui(this);
propertyBrowser_.setVisible(true);
propertyBrowser_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
propertyBrowser_.setCore(core_);
}
private void createCalibrationListDlg() {
if (calibrationListDlg_ != null) {
calibrationListDlg_.dispose();
}
calibrationListDlg_ = new CalibrationListDlg(core_);
calibrationListDlg_.setVisible(true);
calibrationListDlg_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
calibrationListDlg_.setParentGUI(this);
}
public CalibrationListDlg getCalibrationListDlg() {
if (calibrationListDlg_ == null) {
createCalibrationListDlg();
}
return calibrationListDlg_;
}
private void createScriptPanel() {
if (scriptPanel_ == null) {
scriptPanel_ = new ScriptPanel(core_, options_, this);
scriptPanel_.insertScriptingObject(SCRIPT_CORE_OBJECT, core_);
scriptPanel_.insertScriptingObject(SCRIPT_ACQENG_OBJECT, engine_);
scriptPanel_.setParentGUI(this);
scriptPanel_.setBackground(guiColors_.background.get((options_.displayBackground_)));
addMMBackgroundListener(scriptPanel_);
}
}
/**
* Updates Status line in main window from cached values
*/
private void updateStaticInfoFromCache() {
String dimText = "Image info (from camera): " + staticInfo_.width_ + " X " + staticInfo_.height_ + " X "
+ staticInfo_.bytesPerPixel_ + ", Intensity range: " + staticInfo_.imageBitDepth_ + " bits";
dimText += ", " + TextUtils.FMT0.format(staticInfo_.pixSizeUm_ * 1000) + "nm/pix";
if (zStageLabel_.length() > 0) {
dimText += ", Z=" + TextUtils.FMT2.format(staticInfo_.zPos_) + "um";
}
if (xyStageLabel_.length() > 0) {
dimText += ", XY=(" + TextUtils.FMT2.format(staticInfo_.x_) + "," + TextUtils.FMT2.format(staticInfo_.y_) + ")um";
}
labelImageDimensions_.setText(dimText);
}
public void updateXYPos(double x, double y) {
staticInfo_.x_ = x;
staticInfo_.y_ = y;
updateStaticInfoFromCache();
}
public void updateZPos(double z) {
staticInfo_.zPos_ = z;
updateStaticInfoFromCache();
}
public void updateXYPosRelative(double x, double y) {
staticInfo_.x_ += x;
staticInfo_.y_ += y;
updateStaticInfoFromCache();
}
public void updateZPosRelative(double z) {
staticInfo_.zPos_ += z;
updateStaticInfoFromCache();
}
public void updateXYStagePosition(){
double x[] = new double[1];
double y[] = new double[1];
try {
if (xyStageLabel_.length() > 0)
core_.getXYPosition(xyStageLabel_, x, y);
} catch (Exception e) {
ReportingUtils.showError(e);
}
staticInfo_.x_ = x[0];
staticInfo_.y_ = y[0];
updateStaticInfoFromCache();
}
private void updatePixSizeUm (double pixSizeUm) {
staticInfo_.pixSizeUm_ = pixSizeUm;
updateStaticInfoFromCache();
}
private void updateStaticInfo() {
double zPos = 0.0;
double x[] = new double[1];
double y[] = new double[1];
try {
if (zStageLabel_.length() > 0) {
zPos = core_.getPosition(zStageLabel_);
}
if (xyStageLabel_.length() > 0) {
core_.getXYPosition(xyStageLabel_, x, y);
}
} catch (Exception e) {
handleException(e);
}
staticInfo_.width_ = core_.getImageWidth();
staticInfo_.height_ = core_.getImageHeight();
staticInfo_.bytesPerPixel_ = core_.getBytesPerPixel();
staticInfo_.imageBitDepth_ = core_.getImageBitDepth();
staticInfo_.pixSizeUm_ = core_.getPixelSizeUm();
staticInfo_.zPos_ = zPos;
staticInfo_.x_ = x[0];
staticInfo_.y_ = y[0];
updateStaticInfoFromCache();
}
public void toggleShutter() {
try {
if (!toggleShutterButton_.isEnabled())
return;
toggleShutterButton_.requestFocusInWindow();
if (toggleShutterButton_.getText().equals("Open")) {
setShutterButton(true);
core_.setShutterOpen(true);
} else {
core_.setShutterOpen(false);
setShutterButton(false);
}
} catch (Exception e1) {
ReportingUtils.showError(e1);
}
}
private void updateCenterAndDragListener() {
if (centerAndDragMenuItem_.isSelected()) {
centerAndDragListener_.start();
} else {
centerAndDragListener_.stop();
}
}
private void setShutterButton(boolean state) {
if (state) {
toggleShutterButton_.setText("Close");
} else {
toggleShutterButton_.setText("Open");
}
}
// //////////////////////////////////////////////////////////////////////////
// public interface available for scripting access
// //////////////////////////////////////////////////////////////////////////
@Override
public void snapSingleImage() {
doSnap();
}
public Object getPixels() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip != null) {
return ip.getProcessor().getPixels();
}
return null;
}
public void setPixels(Object obj) {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip == null) {
return;
}
ip.getProcessor().setPixels(obj);
}
public int getImageHeight() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip != null)
return ip.getHeight();
return 0;
}
public int getImageWidth() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip != null)
return ip.getWidth();
return 0;
}
public int getImageDepth() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip != null)
return ip.getBitDepth();
return 0;
}
public ImageProcessor getImageProcessor() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip == null)
return null;
return ip.getProcessor();
}
private boolean isCameraAvailable() {
return cameraLabel_.length() > 0;
}
/**
* Part of ScriptInterface API
* Opens the XYPositionList when it is not opened
* Adds the current position to the list (same as pressing the "Mark" button)
*/
@Override
public void markCurrentPosition() {
if (posListDlg_ == null) {
showXYPositionList();
}
if (posListDlg_ != null) {
posListDlg_.markPosition();
}
}
/**
* Implements ScriptInterface
*/
@Override
public AcqControlDlg getAcqDlg() {
return acqControlWin_;
}
/**
* Implements ScriptInterface
*/
@Override
public PositionListDlg getXYPosListDlg() {
if (posListDlg_ == null)
posListDlg_ = new PositionListDlg(core_, this, posList_, options_);
return posListDlg_;
}
/**
* Implements ScriptInterface
*/
@Override
public boolean isAcquisitionRunning() {
if (engine_ == null)
return false;
return engine_.isAcquisitionRunning();
}
/**
* Implements ScriptInterface
*/
@Override
public boolean versionLessThan(String version) throws MMScriptException {
try {
String[] v = MMVersion.VERSION_STRING.split(" ", 2);
String[] m = v[0].split("\\.", 3);
String[] v2 = version.split(" ", 2);
String[] m2 = v2[0].split("\\.", 3);
for (int i=0; i < 3; i++) {
if (Integer.parseInt(m[i]) < Integer.parseInt(m2[i])) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return true;
}
if (Integer.parseInt(m[i]) > Integer.parseInt(m2[i])) {
return false;
}
}
if (v2.length < 2 || v2[1].equals("") )
return false;
if (v.length < 2 ) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return true;
}
if (Integer.parseInt(v[1]) < Integer.parseInt(v2[1])) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return false;
}
return true;
} catch (Exception ex) {
throw new MMScriptException ("Format of version String should be \"a.b.c\"");
}
}
@Override
public boolean isLiveModeOn() {
return liveModeTimer_ != null && liveModeTimer_.isRunning();
}
public LiveModeTimer getLiveModeTimer() {
if (liveModeTimer_ == null) {
liveModeTimer_ = new LiveModeTimer();
}
return liveModeTimer_;
}
@Override
public void enableLiveMode(boolean enable) {
if (core_ == null) {
return;
}
if (enable == isLiveModeOn()) {
return;
}
if (enable) {
try {
if (core_.getCameraDevice().length() == 0) {
ReportingUtils.showError("No camera configured");
updateButtonsForLiveMode(false);
return;
}
if (liveModeTimer_ == null) {
liveModeTimer_ = new LiveModeTimer();
}
liveModeTimer_.begin();
callLiveModeListeners(enable);
} catch (Exception e) {
ReportingUtils.showError(e);
liveModeTimer_.stop();
callLiveModeListeners(false);
updateButtonsForLiveMode(false);
return;
}
} else {
liveModeTimer_.stop();
callLiveModeListeners(enable);
}
updateButtonsForLiveMode(enable);
}
public void updateButtonsForLiveMode(boolean enable) {
autoShutterCheckBox_.setEnabled(!enable);
if (core_.getAutoShutter()) {
toggleShutterButton_.setText(enable ? "Close" : "Open" );
}
snapButton_.setEnabled(!enable);
//toAlbumButton_.setEnabled(!enable);
liveButton_.setIcon(enable ? SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/cancel.png")
: SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/camera_go.png"));
liveButton_.setSelected(false);
liveButton_.setText(enable ? "Stop Live" : "Live");
}
public boolean getLiveMode() {
return isLiveModeOn();
}
public boolean updateImage() {
try {
if (isLiveModeOn()) {
enableLiveMode(false);
return true; // nothing to do, just show the last image
}
if (WindowManager.getCurrentWindow() == null) {
return false;
}
ImagePlus ip = WindowManager.getCurrentImage();
core_.snapImage();
Object img = core_.getImage();
ip.getProcessor().setPixels(img);
ip.updateAndRepaintWindow();
if (!isCurrentImageFormatSupported()) {
return false;
}
updateLineProfile();
} catch (Exception e) {
ReportingUtils.showError(e);
return false;
}
return true;
}
public boolean displayImage(final Object pixels) {
if (pixels instanceof TaggedImage) {
return displayTaggedImage((TaggedImage) pixels, true);
} else {
return displayImage(pixels, true);
}
}
public boolean displayImage(final Object pixels, boolean wait) {
checkSimpleAcquisition();
try {
int width = getAcquisition(SIMPLE_ACQ).getWidth();
int height = getAcquisition(SIMPLE_ACQ).getHeight();
int byteDepth = getAcquisition(SIMPLE_ACQ).getByteDepth();
TaggedImage ti = ImageUtils.makeTaggedImage(pixels, 0, 0, 0,0, width, height, byteDepth);
simpleDisplay_.getImageCache().putImage(ti);
simpleDisplay_.showImage(ti, wait);
return true;
} catch (Exception ex) {
ReportingUtils.showError(ex);
return false;
}
}
public boolean displayImageWithStatusLine(Object pixels, String statusLine) {
boolean ret = displayImage(pixels);
simpleDisplay_.displayStatusLine(statusLine);
return ret;
}
public void displayStatusLine(String statusLine) {
ImagePlus ip = WindowManager.getCurrentImage();
if (!(ip.getWindow() instanceof VirtualAcquisitionDisplay.DisplayWindow)) {
return;
}
VirtualAcquisitionDisplay.getDisplay(ip).displayStatusLine(statusLine);
}
private boolean isCurrentImageFormatSupported() {
boolean ret = false;
long channels = core_.getNumberOfComponents();
long bpp = core_.getBytesPerPixel();
if (channels > 1 && channels != 4 && bpp != 1) {
handleError("Unsupported image format.");
} else {
ret = true;
}
return ret;
}
public void doSnap() {
doSnap(false);
}
public void doSnap(final boolean album) {
if (core_.getCameraDevice().length() == 0) {
ReportingUtils.showError("No camera configured");
return;
}
BlockingQueue<TaggedImage> snapImageQueue =
new LinkedBlockingQueue<TaggedImage>();
try {
core_.snapImage();
long c = core_.getNumberOfCameraChannels();
runDisplayThread(snapImageQueue, new DisplayImageRoutine() {
@Override
public void show(final TaggedImage image) {
if (album) {
try {
addToAlbum(image);
} catch (MMScriptException ex) {
ReportingUtils.showError(ex);
}
} else {
displayImage(image);
}
}
});
for (int i = 0; i < c; ++i) {
TaggedImage img = core_.getTaggedImage(i);
img.tags.put("Channels", c);
snapImageQueue.put(img);
}
snapImageQueue.put(TaggedImageQueue.POISON);
if (simpleDisplay_ != null) {
ImagePlus imgp = simpleDisplay_.getImagePlus();
if (imgp != null) {
ImageWindow win = imgp.getWindow();
if (win != null) {
win.toFront();
}
}
}
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
}
/**
* Is this function still needed? It does some magic with tags. I found
* it to do harmful thing with tags when a Multi-Camera device is
* present (that issue is now fixed).
*/
public void normalizeTags(TaggedImage ti) {
if (ti != TaggedImageQueue.POISON) {
int channel = 0;
try {
if (ti.tags.has("ChannelIndex")) {
channel = MDUtils.getChannelIndex(ti.tags);
}
MDUtils.setChannelIndex(ti.tags, channel);
MDUtils.setPositionIndex(ti.tags, 0);
MDUtils.setSliceIndex(ti.tags, 0);
MDUtils.setFrameIndex(ti.tags, 0);
} catch (JSONException ex) {
ReportingUtils.logError(ex);
}
}
}
@Override
public boolean displayImage(TaggedImage ti) {
normalizeTags(ti);
return displayTaggedImage(ti, true);
}
private boolean displayTaggedImage(TaggedImage ti, boolean update) {
try {
checkSimpleAcquisition(ti);
setCursor(new Cursor(Cursor.WAIT_CURSOR));
ti.tags.put("Summary", getAcquisition(SIMPLE_ACQ).getSummaryMetadata());
addStagePositionToTags(ti);
addImage(SIMPLE_ACQ, ti, update, true);
} catch (Exception ex) {
ReportingUtils.logError(ex);
return false;
}
if (update) {
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
updateLineProfile();
}
return true;
}
public void addStagePositionToTags(TaggedImage ti) throws JSONException {
if (gui_.xyStageLabel_.length() > 0) {
ti.tags.put("XPositionUm", gui_.staticInfo_.x_);
ti.tags.put("YPositionUm", gui_.staticInfo_.y_);
}
if (gui_.zStageLabel_.length() > 0) {
ti.tags.put("ZPositionUm", gui_.staticInfo_.zPos_);
}
}
private void configureBinningCombo() throws Exception {
if (cameraLabel_.length() > 0) {
ActionListener[] listeners;
// binning combo
if (comboBinning_.getItemCount() > 0) {
comboBinning_.removeAllItems();
}
StrVector binSizes = core_.getAllowedPropertyValues(
cameraLabel_, MMCoreJ.getG_Keyword_Binning());
listeners = comboBinning_.getActionListeners();
for (int i = 0; i < listeners.length; i++) {
comboBinning_.removeActionListener(listeners[i]);
}
for (int i = 0; i < binSizes.size(); i++) {
comboBinning_.addItem(binSizes.get(i));
}
comboBinning_.setMaximumRowCount((int) binSizes.size());
if (binSizes.isEmpty()) {
comboBinning_.setEditable(true);
} else {
comboBinning_.setEditable(false);
}
for (int i = 0; i < listeners.length; i++) {
comboBinning_.addActionListener(listeners[i]);
}
}
}
public void initializeGUI() {
try {
// establish device roles
cameraLabel_ = core_.getCameraDevice();
shutterLabel_ = core_.getShutterDevice();
zStageLabel_ = core_.getFocusDevice();
xyStageLabel_ = core_.getXYStageDevice();
engine_.setZStageDevice(zStageLabel_);
configureBinningCombo();
// active shutter combo
try {
shutters_ = core_.getLoadedDevicesOfType(DeviceType.ShutterDevice);
} catch (Exception e) {
ReportingUtils.logError(e);
}
if (shutters_ != null) {
String items[] = new String[(int) shutters_.size()];
for (int i = 0; i < shutters_.size(); i++) {
items[i] = shutters_.get(i);
}
GUIUtils.replaceComboContents(shutterComboBox_, items);
String activeShutter = core_.getShutterDevice();
if (activeShutter != null) {
shutterComboBox_.setSelectedItem(activeShutter);
} else {
shutterComboBox_.setSelectedItem("");
}
}
// Autofocus
autofocusConfigureButton_.setEnabled(afMgr_.getDevice() != null);
autofocusNowButton_.setEnabled(afMgr_.getDevice() != null);
// Rebuild stage list in XY PositinList
if (posListDlg_ != null) {
posListDlg_.rebuildAxisList();
}
updateGUI(true);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
@Override
public String getVersion() {
return MMVersion.VERSION_STRING;
}
/**
* Adds plugin items to the plugins menu
* @param plugin - plugin to be added to the menu
*/
private void addPluginToMenu(final PluginItem plugin) {
Class<?> cl = plugin.pluginClass;
String toolTipDescription = "";
try {
// Get this static field from the class implementing MMPlugin.
toolTipDescription = (String) cl.getDeclaredField("tooltipDescription").get(null);
} catch (SecurityException e) {
ReportingUtils.logError(e);
toolTipDescription = "Description not available";
} catch (NoSuchFieldException e) {
toolTipDescription = "Description not available";
ReportingUtils.logMessage(cl.getName() + " fails to implement static String tooltipDescription.");
} catch (IllegalArgumentException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
GUIUtils.addMenuItem(pluginMenu_, plugin.menuItem, toolTipDescription,
new Runnable() {
public void run() {
ReportingUtils.logMessage("Plugin command: " + plugin.menuItem);
plugin.instantiate();
plugin.plugin.show();
}
});
pluginMenu_.validate();
menuBar_.validate();
}
public void updateGUI(boolean updateConfigPadStructure) {
updateGUI(updateConfigPadStructure, false);
}
public void updateGUI(boolean updateConfigPadStructure, boolean fromCache) {
try {
// establish device roles
cameraLabel_ = core_.getCameraDevice();
shutterLabel_ = core_.getShutterDevice();
zStageLabel_ = core_.getFocusDevice();
xyStageLabel_ = core_.getXYStageDevice();
afMgr_.refresh();
// camera settings
if (isCameraAvailable()) {
double exp = core_.getExposure();
textFieldExp_.setText(NumberUtils.doubleToDisplayString(exp));
configureBinningCombo();
String binSize;
if (fromCache) {
binSize = core_.getPropertyFromCache(cameraLabel_, MMCoreJ.getG_Keyword_Binning());
} else {
binSize = core_.getProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning());
}
GUIUtils.setComboSelection(comboBinning_, binSize);
}
if (liveModeTimer_ == null || !liveModeTimer_.isRunning()) {
autoShutterCheckBox_.setSelected(core_.getAutoShutter());
boolean shutterOpen = core_.getShutterOpen();
setShutterButton(shutterOpen);
if (autoShutterCheckBox_.isSelected()) {
toggleShutterButton_.setEnabled(false);
} else {
toggleShutterButton_.setEnabled(true);
}
}
// active shutter combo
if (shutters_ != null) {
String activeShutter = core_.getShutterDevice();
if (activeShutter != null) {
shutterComboBox_.setSelectedItem(activeShutter);
} else {
shutterComboBox_.setSelectedItem("");
}
}
// state devices
if (updateConfigPadStructure && (configPad_ != null)) {
configPad_.refreshStructure(fromCache);
// Needed to update read-only properties. May slow things down...
if (!fromCache)
core_.updateSystemStateCache();
}
// update Channel menus in Multi-dimensional acquisition dialog
updateChannelCombos();
// update list of pixel sizes in pixel size configuration window
if (calibrationListDlg_ != null) {
calibrationListDlg_.refreshCalibrations();
}
if (propertyBrowser_ != null) {
propertyBrowser_.refresh();
}
} catch (Exception e) {
ReportingUtils.logError(e);
}
updateStaticInfo();
updateTitle();
}
//TODO: Deprecated @Override
public boolean okToAcquire() {
return !isLiveModeOn();
}
//TODO: Deprecated @Override
public void stopAllActivity() {
if (this.acquisitionEngine2010 != null) {
this.acquisitionEngine2010.stop();
}
enableLiveMode(false);
}
/**
* Cleans up resources while shutting down
*
* @param calledByImageJ
* @return flag indicating success. Shut down should abort when flag is false
*/
private boolean cleanupOnClose(boolean calledByImageJ) {
// Save config presets if they were changed.
if (configChanged_) {
Object[] options = {"Yes", "No"};
int n = JOptionPane.showOptionDialog(null,
"Save Changed Configuration?", "Micro-Manager",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options, options[0]);
if (n == JOptionPane.YES_OPTION) {
saveConfigPresets();
// if the configChanged_ flag did not become false, the user
// must have cancelled the configuration saving and we should cancel
// quitting as well
if (configChanged_) {
return false;
}
}
}
if (liveModeTimer_ != null)
liveModeTimer_.stop();
// check needed to avoid deadlock
if (!calledByImageJ) {
if (!WindowManager.closeAllWindows()) {
core_.logMessage("Failed to close some windows");
}
}
if (profileWin_ != null) {
removeMMBackgroundListener(profileWin_);
profileWin_.dispose();
}
if (scriptPanel_ != null) {
removeMMBackgroundListener(scriptPanel_);
scriptPanel_.closePanel();
}
if (propertyBrowser_ != null) {
removeMMBackgroundListener(propertyBrowser_);
propertyBrowser_.dispose();
}
if (acqControlWin_ != null) {
removeMMBackgroundListener(acqControlWin_);
acqControlWin_.close();
}
if (engine_ != null) {
engine_.shutdown();
}
if (afMgr_ != null) {
afMgr_.closeOptionsDialog();
}
// dispose plugins
for (int i = 0; i < plugins_.size(); i++) {
MMPlugin plugin = plugins_.get(i).plugin;
if (plugin != null) {
plugin.dispose();
}
}
synchronized (shutdownLock_) {
try {
if (core_ != null) {
ReportingUtils.setCore(null);
core_.delete();
core_ = null;
}
} catch (Exception err) {
ReportingUtils.showError(err);
}
}
return true;
}
private void saveSettings() {
Rectangle r = this.getBounds();
mainPrefs_.putInt(MAIN_FRAME_X, r.x);
mainPrefs_.putInt(MAIN_FRAME_Y, r.y);
mainPrefs_.putInt(MAIN_FRAME_WIDTH, r.width);
mainPrefs_.putInt(MAIN_FRAME_HEIGHT, r.height);
mainPrefs_.putInt(MAIN_FRAME_DIVIDER_POS, this.splitPane_.getDividerLocation());
mainPrefs_.put(OPEN_ACQ_DIR, openAcqDirectory_);
mainPrefs_.put(MAIN_SAVE_METHOD,
ImageUtils.getImageStorageClass().getName());
// save field values from the main window
// NOTE: automatically restoring these values on startup may cause
// problems
mainPrefs_.put(MAIN_EXPOSURE, textFieldExp_.getText());
// NOTE: do not save auto shutter state
if (afMgr_ != null && afMgr_.getDevice() != null) {
mainPrefs_.put(AUTOFOCUS_DEVICE, afMgr_.getDevice().getDeviceName());
}
}
private void loadConfiguration() {
File f = FileDialogs.openFile(this, "Load a config file",MM_CONFIG_FILE);
if (f != null) {
sysConfigFile_ = f.getAbsolutePath();
configChanged_ = false;
setConfigSaveButtonStatus(configChanged_);
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
loadSystemConfiguration();
}
}
public synchronized boolean closeSequence(boolean calledByImageJ) {
if (!this.isRunning()) {
if (core_ != null) {
core_.logMessage("MMStudioMainFrame::closeSequence called while running_ is false");
}
return true;
}
if (engine_ != null && engine_.isAcquisitionRunning()) {
int result = JOptionPane.showConfirmDialog(
this,
"Acquisition in progress. Are you sure you want to exit and discard all data?",
"Micro-Manager", JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE);
if (result == JOptionPane.NO_OPTION) {
return false;
}
}
stopAllActivity();
try {
// Close all image windows associated with MM. Canceling saving of
// any of these should abort shutdown
if (!acqMgr_.closeAllImageWindows()) {
return false;
}
} catch (MMScriptException ex) {
// Not sure what to do here...
}
if (!cleanupOnClose(calledByImageJ)) {
return false;
}
running_ = false;
saveSettings();
try {
configPad_.saveSettings();
options_.saveSettings();
hotKeys_.saveSettings();
} catch (NullPointerException e) {
if (core_ != null)
this.logError(e);
}
// disposing sometimes hangs ImageJ!
// this.dispose();
if (options_.closeOnExit_) {
if (!runsAsPlugin_) {
System.exit(0);
} else {
ImageJ ij = IJ.getInstance();
if (ij != null) {
ij.quit();
}
}
} else {
this.dispose();
}
return true;
}
public void applyContrastSettings(ContrastSettings contrast8,
ContrastSettings contrast16) {
ImagePlus img = WindowManager.getCurrentImage();
if (img == null|| VirtualAcquisitionDisplay.getDisplay(img) == null )
return;
if (img.getBytesPerPixel() == 1)
VirtualAcquisitionDisplay.getDisplay(img).setChannelContrast(0,
contrast8.min, contrast8.max, contrast8.gamma);
else
VirtualAcquisitionDisplay.getDisplay(img).setChannelContrast(0,
contrast16.min, contrast16.max, contrast16.gamma);
}
//TODO: Deprecated @Override
public ContrastSettings getContrastSettings() {
ImagePlus img = WindowManager.getCurrentImage();
if (img == null || VirtualAcquisitionDisplay.getDisplay(img) == null )
return null;
return VirtualAcquisitionDisplay.getDisplay(img).getChannelContrastSettings(0);
}
public boolean is16bit() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip != null && ip.getProcessor() instanceof ShortProcessor) {
return true;
}
return false;
}
public boolean isRunning() {
return running_;
}
/**
* Executes the beanShell script. This script instance only supports
* commands directed to the core object.
*/
private void executeStartupScript() {
// execute startup script
File f = new File(startupScriptFile_);
if (startupScriptFile_.length() > 0 && f.exists()) {
WaitDialog waitDlg = new WaitDialog(
"Executing startup script, please wait...");
waitDlg.showDialog();
Interpreter interp = new Interpreter();
try {
// insert core object only
interp.set(SCRIPT_CORE_OBJECT, core_);
interp.set(SCRIPT_ACQENG_OBJECT, engine_);
interp.set(SCRIPT_GUI_OBJECT, this);
// read text file and evaluate
interp.eval(TextUtils.readTextFile(startupScriptFile_));
} catch (IOException exc) {
ReportingUtils.logError(exc, "Unable to read the startup script (" + startupScriptFile_ + ").");
} catch (EvalError exc) {
ReportingUtils.logError(exc);
} finally {
waitDlg.closeDialog();
}
} else {
if (startupScriptFile_.length() > 0)
ReportingUtils.logMessage("Startup script file ("+startupScriptFile_+") not present.");
}
}
/**
* Loads system configuration from the cfg file.
*/
private boolean loadSystemConfiguration() {
boolean result = true;
saveMRUConfigFiles();
final WaitDialog waitDlg = new WaitDialog(
"Loading system configuration, please wait...");
waitDlg.setAlwaysOnTop(true);
waitDlg.showDialog();
this.setEnabled(false);
try {
if (sysConfigFile_.length() > 0) {
GUIUtils.preventDisplayAdapterChangeExceptions();
core_.waitForSystem();
ignorePropertyChanges_ = true;
core_.loadSystemConfiguration(sysConfigFile_);
ignorePropertyChanges_ = false;
GUIUtils.preventDisplayAdapterChangeExceptions();
}
} catch (final Exception err) {
GUIUtils.preventDisplayAdapterChangeExceptions();
ReportingUtils.showError(err);
result = false;
} finally {
waitDlg.closeDialog();
}
setEnabled(true);
initializeGUI();
updateSwitchConfigurationMenu();
FileDialogs.storePath(MM_CONFIG_FILE, new File(sysConfigFile_));
return result;
}
private void saveMRUConfigFiles() {
if (0 < sysConfigFile_.length()) {
if (MRUConfigFiles_.contains(sysConfigFile_)) {
MRUConfigFiles_.remove(sysConfigFile_);
}
if (maxMRUCfgs_ <= MRUConfigFiles_.size()) {
MRUConfigFiles_.remove(maxMRUCfgs_ - 1);
}
MRUConfigFiles_.add(0, sysConfigFile_);
// save the MRU list to the preferences
for (Integer icfg = 0; icfg < MRUConfigFiles_.size(); ++icfg) {
String value = "";
if (null != MRUConfigFiles_.get(icfg)) {
value = MRUConfigFiles_.get(icfg).toString();
}
mainPrefs_.put(CFGFILE_ENTRY_BASE + icfg.toString(), value);
}
}
}
private void loadMRUConfigFiles() {
sysConfigFile_ = mainPrefs_.get(SYSTEM_CONFIG_FILE, sysConfigFile_);
// startupScriptFile_ = mainPrefs_.get(STARTUP_SCRIPT_FILE,
// startupScriptFile_);
MRUConfigFiles_ = new ArrayList<String>();
for (Integer icfg = 0; icfg < maxMRUCfgs_; ++icfg) {
String value = "";
value = mainPrefs_.get(CFGFILE_ENTRY_BASE + icfg.toString(), value);
if (0 < value.length()) {
File ruFile = new File(value);
if (ruFile.exists()) {
if (!MRUConfigFiles_.contains(value)) {
MRUConfigFiles_.add(value);
}
}
}
}
// initialize MRU list from old persistant data containing only SYSTEM_CONFIG_FILE
if (0 < sysConfigFile_.length()) {
if (!MRUConfigFiles_.contains(sysConfigFile_)) {
// in case persistant data is inconsistent
if (maxMRUCfgs_ <= MRUConfigFiles_.size()) {
MRUConfigFiles_.remove(maxMRUCfgs_ - 1);
}
MRUConfigFiles_.add(0, sysConfigFile_);
}
}
}
/**
* Opens Acquisition dialog.
*/
private void openAcqControlDialog() {
try {
if (acqControlWin_ == null) {
acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, this, options_);
}
if (acqControlWin_.isActive()) {
acqControlWin_.setTopPosition();
}
acqControlWin_.setVisible(true);
acqControlWin_.repaint();
// TODO: this call causes a strange exception the first time the
// dialog is created
// something to do with the order in which combo box creation is
// performed
// acqControlWin_.updateGroupsCombo();
} catch (Exception exc) {
ReportingUtils.showError(exc,
"\nAcquistion window failed to open due to invalid or corrupted settings.\n"
+ "Try resetting registry settings to factory defaults (Menu Tools|Options).");
}
}
/**
* Opens a dialog to record stage positions
*/
@Override
public void showXYPositionList() {
if (posListDlg_ == null) {
posListDlg_ = new PositionListDlg(core_, this, posList_, options_);
}
posListDlg_.setVisible(true);
}
private void updateChannelCombos() {
if (this.acqControlWin_ != null) {
this.acqControlWin_.updateChannelAndGroupCombo();
}
}
@Override
public void setConfigChanged(boolean status) {
configChanged_ = status;
setConfigSaveButtonStatus(configChanged_);
}
/**
* Returns the current background color
* @return current background color
*/
@Override
public Color getBackgroundColor() {
return guiColors_.background.get((options_.displayBackground_));
}
/*
* Changes background color of this window and all other MM windows
*/
@Override
public void setBackgroundStyle(String backgroundType) {
setBackground(guiColors_.background.get((backgroundType)));
paint(MMStudioMainFrame.this.getGraphics());
// sets background of all registered Components
for (Component comp:MMFrames_) {
if (comp != null)
comp.setBackground(guiColors_.background.get(backgroundType));
}
}
@Override
public String getBackgroundStyle() {
return options_.displayBackground_;
}
// //////////////////////////////////////////////////////////////////////////
// Scripting interface
// //////////////////////////////////////////////////////////////////////////
private class ExecuteAcq implements Runnable {
public ExecuteAcq() {
}
@Override
public void run() {
if (acqControlWin_ != null) {
acqControlWin_.runAcquisition();
}
}
}
private void testForAbortRequests() throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
}
}
/**
* @Deprecated - used to be in api/AcquisitionEngine
*/
public void startAcquisition() throws MMScriptException {
testForAbortRequests();
SwingUtilities.invokeLater(new ExecuteAcq());
}
@Override
public String runAcquisition() throws MMScriptException {
if (SwingUtilities.isEventDispatchThread()) {
throw new MMScriptException("Acquisition can not be run from this (EDT) thread");
}
testForAbortRequests();
if (acqControlWin_ != null) {
String name = acqControlWin_.runAcquisition();
try {
while (acqControlWin_.isAcquisitionRunning()) {
Thread.sleep(50);
}
} catch (InterruptedException e) {
ReportingUtils.showError(e);
}
return name;
} else {
throw new MMScriptException(
"Acquisition setup window must be open for this command to work.");
}
}
@Override
public String runAcquisition(String name, String root)
throws MMScriptException {
testForAbortRequests();
if (acqControlWin_ != null) {
String acqName = acqControlWin_.runAcquisition(name, root);
try {
while (acqControlWin_.isAcquisitionRunning()) {
Thread.sleep(100);
}
// ensure that the acquisition has finished.
// This does not seem to work, needs something better
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
boolean finished = false;
while (!finished) {
ImageCache imCache = acq.getImageCache();
if (imCache != null) {
if (imCache.isFinished()) {
finished = true;
} else {
Thread.sleep(100);
}
}
}
} catch (InterruptedException e) {
ReportingUtils.showError(e);
}
return acqName;
} else {
throw new MMScriptException(
"Acquisition setup window must be open for this command to work.");
}
}
/**
* @Deprecated used to be part of api
*/
public String runAcqusition(String name, String root) throws MMScriptException {
return runAcquisition(name, root);
}
/**
* Loads acquisition settings from file
* @param path file containing previously saved acquisition settings
* @throws MMScriptException
*/
@Override
public void loadAcquisition(String path) throws MMScriptException {
testForAbortRequests();
try {
engine_.shutdown();
// load protocol
if (acqControlWin_ != null) {
acqControlWin_.loadAcqSettingsFromFile(path);
}
} catch (Exception ex) {
throw new MMScriptException(ex.getMessage());
}
}
@Override
public void setPositionList(PositionList pl) throws MMScriptException {
testForAbortRequests();
// use serialization to clone the PositionList object
posList_ = pl; // PositionList.newInstance(pl);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (posListDlg_ != null)
posListDlg_.setPositionList(posList_);
if (engine_ != null)
engine_.setPositionList(posList_);
if (acqControlWin_ != null)
acqControlWin_.updateGUIContents();
}
});
}
@Override
public PositionList getPositionList() throws MMScriptException {
testForAbortRequests();
// use serialization to clone the PositionList object
return posList_; //PositionList.newInstance(posList_);
}
@Override
public void sleep(long ms) throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
scriptPanel_.sleep(ms);
}
}
@Override
public String getUniqueAcquisitionName(String stub) {
return acqMgr_.getUniqueAcquisitionName(stub);
}
//@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions) throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices,
nrPositions, true, false);
}
//@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices) throws MMScriptException {
openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0);
}
//@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions, boolean show)
throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, nrPositions, show, false);
}
//@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, boolean show)
throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, false);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions, boolean show, boolean save)
throws MMScriptException {
acqMgr_.openAcquisition(name, rootDir, show, save);
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.setDimensions(nrFrames, nrChannels, nrSlices, nrPositions);
}
//@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, boolean show, boolean virtual)
throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, virtual);
}
//@Override
public String createAcquisition(JSONObject summaryMetadata, boolean diskCached) {
return createAcquisition(summaryMetadata, diskCached, false);
}
@Override
public String createAcquisition(JSONObject summaryMetadata, boolean diskCached, boolean displayOff) {
return acqMgr_.createAcquisition(summaryMetadata, diskCached, engine_, displayOff);
}
//@Override
public void initializeSimpleAcquisition(String name, int width, int height,
int byteDepth, int bitDepth, int multiCamNumCh) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.setImagePhysicalDimensions(width, height, byteDepth, bitDepth, multiCamNumCh);
acq.initializeSimpleAcq();
}
@Override
public void initializeAcquisition(String name, int width, int height, int byteDepth, int bitDepth) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
//number of multi-cam cameras is set to 1 here for backwards compatibility
//might want to change this later
acq.setImagePhysicalDimensions(width, height, byteDepth, bitDepth, 1);
acq.initialize();
}
@Override
public int getAcquisitionImageWidth(String acqName) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getWidth();
}
@Override
public int getAcquisitionImageHeight(String acqName) throws MMScriptException{
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getHeight();
}
@Override
public int getAcquisitionImageBitDepth(String acqName) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getBitDepth();
}
@Override
public int getAcquisitionImageByteDepth(String acqName) throws MMScriptException{
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getByteDepth();
}
@Override public int getAcquisitionMultiCamNumChannels(String acqName) throws MMScriptException{
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getMultiCameraNumChannels();
}
@Override
public Boolean acquisitionExists(String name) {
return acqMgr_.acquisitionExists(name);
}
@Override
public void closeAcquisition(String name) throws MMScriptException {
acqMgr_.closeAcquisition(name);
}
/**
* @Deprecated use closeAcquisitionWindow instead
* @Deprecated - used to be in api/AcquisitionEngine
*/
public void closeAcquisitionImage5D(String acquisitionName) throws MMScriptException {
acqMgr_.closeImageWindow(acquisitionName);
}
@Override
public void closeAcquisitionWindow(String acquisitionName) throws MMScriptException {
acqMgr_.closeImageWindow(acquisitionName);
}
/**
* @Deprecated - used to be in api/AcquisitionEngine
* Since Burst and normal acquisition are now carried out by the same engine,
* loadBurstAcquistion simply calls loadAcquisition
* t
* @param path - path to file specifying acquisition settings
*/
public void loadBurstAcquisition(String path) throws MMScriptException {
this.loadAcquisition(path);
}
@Override
public void refreshGUI() {
updateGUI(true);
}
@Override
public void refreshGUIFromCache() {
updateGUI(true, true);
}
@Override
public void setAcquisitionProperty(String acqName, String propertyName,
String value) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
acq.setProperty(propertyName, value);
}
public void setAcquisitionSystemState(String acqName, JSONObject md) throws MMScriptException {
// acqMgr_.getAcquisition(acqName).setSystemState(md);
setAcquisitionSummary(acqName, md);
}
//@Override
public void setAcquisitionSummary(String acqName, JSONObject md) throws MMScriptException {
acqMgr_.getAcquisition(acqName).setSummaryProperties(md);
}
@Override
public void setImageProperty(String acqName, int frame, int channel,
int slice, String propName, String value) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
acq.setProperty(frame, channel, slice, propName, value);
}
@Override
public String getCurrentAlbum() {
return acqMgr_.getCurrentAlbum();
}
public String createNewAlbum() {
return acqMgr_.createNewAlbum();
}
public void appendImage(String name, TaggedImage taggedImg) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
int f = 1 + acq.getLastAcquiredFrame();
try {
MDUtils.setFrameIndex(taggedImg.tags, f);
} catch (JSONException e) {
throw new MMScriptException("Unable to set the frame index.");
}
acq.insertTaggedImage(taggedImg, f, 0, 0);
}
@Override
public void addToAlbum(TaggedImage taggedImg) throws MMScriptException {
addToAlbum(taggedImg, null);
}
public void addToAlbum(TaggedImage taggedImg, JSONObject displaySettings) throws MMScriptException {
normalizeTags(taggedImg);
acqMgr_.addToAlbum(taggedImg,displaySettings);
}
public void addImage(String name, Object img, int frame, int channel,
int slice) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.insertImage(img, frame, channel, slice);
}
//@Override
public void addImage(String name, TaggedImage taggedImg) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
if (!acq.isInitialized()) {
JSONObject tags = taggedImg.tags;
// initialize physical dimensions of the image
try {
int width = tags.getInt(MMTags.Image.WIDTH);
int height = tags.getInt(MMTags.Image.HEIGHT);
int byteDepth = MDUtils.getDepth(tags);
int bitDepth = tags.getInt(MMTags.Image.BIT_DEPTH);
initializeAcquisition(name, width, height, byteDepth, bitDepth);
} catch (JSONException e) {
throw new MMScriptException(e);
}
}
acq.insertImage(taggedImg);
}
@Override
/**
* The basic method for adding images to an existing data set.
* If the acquisition was not previously initialized, it will attempt to initialize it from the available image data
*/
public void addImageToAcquisition(String name, int frame, int channel, int slice, int position, TaggedImage taggedImg) throws MMScriptException {
// TODO: complete the tag set and initialize the acquisition
MMAcquisition acq = acqMgr_.getAcquisition(name);
// check position, for multi-position data set the number of declared positions should be at least 2
if (acq.getPositions() <= 1 && position > 0) {
throw new MMScriptException("The acquisition was open as a single position data set.\n"
+ "Open acqusition with two or more positions in order to crate a multi-position data set.");
}
// check position, for multi-position data set the number of declared positions should be at least 2
if (acq.getChannels() <= channel) {
throw new MMScriptException("This acquisition was opened with " + acq.getChannels() + " channels.\n"
+ "The channel number must not exceed declared number of positions.");
}
JSONObject tags = taggedImg.tags;
// if the acquisition was not previously initialized, set physical dimensions of the image
if (!acq.isInitialized()) {
// automatically initialize physical dimensions of the image
try {
int width = tags.getInt(MMTags.Image.WIDTH);
int height = tags.getInt(MMTags.Image.HEIGHT);
int byteDepth = MDUtils.getDepth(tags);
int bitDepth = byteDepth * 8;
if (tags.has(MMTags.Image.BIT_DEPTH))
bitDepth = tags.getInt(MMTags.Image.BIT_DEPTH);
initializeAcquisition(name, width, height, byteDepth, bitDepth);
} catch (JSONException e) {
throw new MMScriptException(e);
}
}
// create required coordinate tags
try {
tags.put(MMTags.Image.FRAME_INDEX, frame);
tags.put(MMTags.Image.FRAME, frame);
tags.put(MMTags.Image.CHANNEL_INDEX, channel);
tags.put(MMTags.Image.SLICE_INDEX, slice);
tags.put(MMTags.Image.POS_INDEX, position);
if (!tags.has(MMTags.Summary.SLICES_FIRST) && !tags.has(MMTags.Summary.TIME_FIRST)) {
// add default setting
tags.put(MMTags.Summary.SLICES_FIRST, true);
tags.put(MMTags.Summary.TIME_FIRST, false);
}
if (acq.getPositions() > 1) {
// if no position name is defined we need to insert a default one
if (tags.has(MMTags.Image.POS_NAME))
tags.put(MMTags.Image.POS_NAME, "Pos" + position);
}
// update frames if necessary
if (acq.getFrames() <= frame) {
acq.setProperty(MMTags.Summary.FRAMES, Integer.toString(frame+1));
}
} catch (JSONException e) {
throw new MMScriptException(e);
}
// System.out.println("Inserting frame: " + frame + ", channel: " + channel + ", slice: " + slice + ", pos: " + position);
acq.insertImage(taggedImg);
}
@Override
/**
* A quick way to implicitly snap an image and add it to the data set.
* Works in the same way as above.
*/
public void snapAndAddImage(String name, int frame, int channel, int slice, int position) throws MMScriptException {
TaggedImage ti;
try {
if (core_.isSequenceRunning()) {
ti = core_.getLastTaggedImage();
} else {
core_.snapImage();
ti = core_.getTaggedImage();
}
MDUtils.setChannelIndex(ti.tags, channel);
MDUtils.setFrameIndex(ti.tags, frame);
MDUtils.setSliceIndex(ti.tags, slice);
MDUtils.setPositionIndex(ti.tags, position);
MMAcquisition acq = acqMgr_.getAcquisition(name);
if (!acq.isInitialized()) {
long width = core_.getImageWidth();
long height = core_.getImageHeight();
long depth = core_.getBytesPerPixel();
long bitDepth = core_.getImageBitDepth();
int multiCamNumCh = (int) core_.getNumberOfCameraChannels();
acq.setImagePhysicalDimensions((int) width, (int) height, (int) depth, (int) bitDepth, multiCamNumCh);
acq.initialize();
}
if (acq.getPositions() > 1) {
MDUtils.setPositionName(ti.tags, "Pos" + position);
}
addImageToAcquisition(name, frame, channel, slice, position, ti);
} catch (Exception e) {
throw new MMScriptException(e);
}
}
//@Override
public void addImage(String name, TaggedImage img, boolean updateDisplay) throws MMScriptException {
acqMgr_.getAcquisition(name).insertImage(img, updateDisplay);
}
//@Override
public void addImage(String name, TaggedImage taggedImg,
boolean updateDisplay,
boolean waitForDisplay) throws MMScriptException {
acqMgr_.getAcquisition(name).insertImage(taggedImg, updateDisplay, waitForDisplay);
}
//@Override
public void addImage(String name, TaggedImage taggedImg, int frame, int channel,
int slice, int position) throws MMScriptException {
try {
acqMgr_.getAcquisition(name).insertImage(taggedImg, frame, channel, slice, position);
} catch (JSONException ex) {
ReportingUtils.showError(ex);
}
}
//@Override
public void addImage(String name, TaggedImage taggedImg, int frame, int channel,
int slice, int position, boolean updateDisplay) throws MMScriptException {
try {
acqMgr_.getAcquisition(name).insertImage(taggedImg, frame, channel, slice, position, updateDisplay);
} catch (JSONException ex) {
ReportingUtils.showError(ex);
}
}
//@Override
public void addImage(String name, TaggedImage taggedImg, int frame, int channel,
int slice, int position, boolean updateDisplay, boolean waitForDisplay) throws MMScriptException {
try {
acqMgr_.getAcquisition(name).insertImage(taggedImg, frame, channel, slice, position, updateDisplay, waitForDisplay);
} catch (JSONException ex) {
ReportingUtils.showError(ex);
}
}
/**
* Closes all acquisitions
*/
@Override
public void closeAllAcquisitions() {
acqMgr_.closeAll();
}
@Override
public String[] getAcquisitionNames()
{
return acqMgr_.getAcqusitionNames();
}
@Override
public MMAcquisition getAcquisition(String name) throws MMScriptException {
return acqMgr_.getAcquisition(name);
}
private class ScriptConsoleMessage implements Runnable {
String msg_;
public ScriptConsoleMessage(String text) {
msg_ = text;
}
@Override
public void run() {
if (scriptPanel_ != null)
scriptPanel_.message(msg_);
}
}
@Override
public void message(String text) throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
SwingUtilities.invokeLater(new ScriptConsoleMessage(text));
}
}
@Override
public void clearMessageWindow() throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
scriptPanel_.clearOutput();
}
}
public void clearOutput() throws MMScriptException {
clearMessageWindow();
}
public void clear() throws MMScriptException {
clearMessageWindow();
}
@Override
public void setChannelContrast(String title, int channel, int min, int max)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelContrast(channel, min, max);
}
@Override
public void setChannelName(String title, int channel, String name)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelName(channel, name);
}
@Override
public void setChannelColor(String title, int channel, Color color)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelColor(channel, color.getRGB());
}
@Override
public void setContrastBasedOnFrame(String title, int frame, int slice)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setContrastBasedOnFrame(frame, slice);
}
@Override
public void setStagePosition(double z) throws MMScriptException {
try {
core_.setPosition(core_.getFocusDevice(),z);
core_.waitForDevice(core_.getFocusDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
@Override
public void setRelativeStagePosition(double z) throws MMScriptException {
try {
core_.setRelativePosition(core_.getFocusDevice(), z);
core_.waitForDevice(core_.getFocusDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
@Override
public void setXYStagePosition(double x, double y) throws MMScriptException {
try {
core_.setXYPosition(core_.getXYStageDevice(), x, y);
core_.waitForDevice(core_.getXYStageDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
@Override
public void setRelativeXYStagePosition(double x, double y) throws MMScriptException {
try {
core_.setRelativeXYPosition(core_.getXYStageDevice(), x, y);
core_.waitForDevice(core_.getXYStageDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
@Override
public Point2D.Double getXYStagePosition() throws MMScriptException {
String stage = core_.getXYStageDevice();
if (stage.length() == 0) {
throw new MMScriptException("XY Stage device is not available");
}
double x[] = new double[1];
double y[] = new double[1];
try {
core_.getXYPosition(stage, x, y);
Point2D.Double pt = new Point2D.Double(x[0], y[0]);
return pt;
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
@Override
public String getXYStageName() {
return core_.getXYStageDevice();
}
@Override
public void setXYOrigin(double x, double y) throws MMScriptException {
String xyStage = core_.getXYStageDevice();
try {
core_.setAdapterOriginXY(xyStage, x, y);
} catch (Exception e) {
throw new MMScriptException(e);
}
}
public AcquisitionWrapperEngine getAcquisitionEngine() {
return engine_;
}
/**
* Helper class for plugin loader functions
*/
private class PluginItemAndClass {
private String msg_;
private Class<?> cl_;
private PluginItem pi_;
public PluginItemAndClass(String msg, Class<?> cl, PluginItem pi) {
msg_ = msg;
cl_ = cl;
pi_ = pi;
}
public Class<?> getItsClass () {return cl_;}
public String getMessage() {return msg_;}
public PluginItem getPluginItem() {return pi_;}
}
private class PluginItemAndClassComparator implements Comparator<PluginItemAndClass> {
public int compare(PluginItemAndClass t1, PluginItemAndClass t2) {
try {
String m1 = t1.getPluginItem().menuItem;
String m2 = t2.getPluginItem().menuItem;
Collator collator = Collator.getInstance();
collator.setStrength(Collator.PRIMARY);
return collator.compare(m1, m2);
} catch (NullPointerException npe) {
ReportingUtils.logError("NullPointerException in PluginItemAndClassCopmarator");
}
return 0;
}
}
public String installPlugin(Class<?> cl) {
PluginItemAndClass piac = declarePlugin(cl);
final PluginItem pi = piac.getPluginItem();
if (pi != null) {
addPluginToMenuLater(pi);
}
String msg = piac.getMessage();
if (msg != null) {
return msg;
}
ReportingUtils.logError("In MMStudioMainFrame:installPlugin, msg was null");
return piac.getMessage();
}
private PluginItemAndClass declarePlugin(Class<?> cl) {
String className = cl.getSimpleName();
String msg = className + " module loaded.";
PluginItem pi = new PluginItem();
try {
for (PluginItem plugin : plugins_) {
if (plugin.className.contentEquals(className)) {
msg = className + " already loaded";
PluginItemAndClass piac = new PluginItemAndClass(msg, cl, null);
return piac;
}
}
pi.className = className;
try {
// Get this static field from the class implementing MMPlugin.
pi.menuItem = (String) cl.getDeclaredField("menuName").get(null);
} catch (SecurityException e) {
ReportingUtils.logError(e);
pi.menuItem = className;
} catch (NoSuchFieldException e) {
pi.menuItem = className;
ReportingUtils.logMessage(className + " fails to implement static String menuName.");
} catch (IllegalArgumentException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
if (pi.menuItem == null) {
pi.menuItem = className;
}
pi.menuItem = pi.menuItem.replace("_", " ");
pi.pluginClass = cl;
plugins_.add(pi);
} catch (NoClassDefFoundError e) {
msg = className + " class definition not found.";
ReportingUtils.logError(e, msg);
}
PluginItemAndClass piac = new PluginItemAndClass(msg, cl, pi);
return piac;
}
private void addPluginToMenuLater(final PluginItem pi) {
SwingUtilities.invokeLater(
new Runnable() {
@Override
public void run() {
addPluginToMenu(pi);
}
});
}
public String installPlugin(String className, String menuName) {
String msg = "installPlugin(String className, String menuName) is Deprecated. Use installPlugin(String className) instead.";
core_.logMessage(msg);
installPlugin(className);
return msg;
}
@Override
public String installPlugin(String className) {
try {
Class clazz = Class.forName(className);
return installPlugin(clazz);
} catch (ClassNotFoundException e) {
String msg = className + " plugin not found.";
ReportingUtils.logError(e, msg);
return msg;
}
}
@Override
public String installAutofocusPlugin(String className) {
try {
return installAutofocusPlugin(Class.forName(className));
} catch (ClassNotFoundException e) {
String msg = "Internal error: AF manager not instantiated.";
ReportingUtils.logError(e, msg);
return msg;
}
}
public String installAutofocusPlugin(Class<?> autofocus) {
String msg = autofocus.getSimpleName() + " module loaded.";
if (afMgr_ != null) {
afMgr_.setAFPluginClassName(autofocus.getSimpleName());
try {
afMgr_.refresh();
} catch (MMException e) {
msg = e.getMessage();
ReportingUtils.logError(e);
}
} else {
msg = "Internal error: AF manager not instantiated.";
}
return msg;
}
public CMMCore getCore() {
return core_;
}
@Override
public IAcquisitionEngine2010 getAcquisitionEngine2010() {
try {
acquisitionEngine2010LoadingThread.join();
if (acquisitionEngine2010 == null) {
acquisitionEngine2010 = (IAcquisitionEngine2010) acquisitionEngine2010Class.getConstructor(ScriptInterface.class).newInstance(this);
}
return acquisitionEngine2010;
} catch (Exception e) {
ReportingUtils.logError(e);
return null;
}
}
@Override
public void addImageProcessor(DataProcessor<TaggedImage> processor) {
System.out.println("Processor: "+processor.getClass().getSimpleName());
getAcquisitionEngine().addImageProcessor(processor);
}
@Override
public void removeImageProcessor(DataProcessor<TaggedImage> processor) {
getAcquisitionEngine().removeImageProcessor(processor);
}
@Override
public void setPause(boolean state) {
getAcquisitionEngine().setPause(state);
}
@Override
public boolean isPaused() {
return getAcquisitionEngine().isPaused();
}
@Override
public void attachRunnable(int frame, int position, int channel, int slice, Runnable runnable) {
getAcquisitionEngine().attachRunnable(frame, position, channel, slice, runnable);
}
@Override
public void clearRunnables() {
getAcquisitionEngine().clearRunnables();
}
@Override
public SequenceSettings getAcqusitionSettings() {
if (engine_ == null)
return new SequenceSettings();
return engine_.getSequenceSettings();
}
@Override
public String getAcquisitionPath() {
if (engine_ == null)
return null;
return engine_.getImageCache().getDiskLocation();
}
@Override
public void promptToSaveAcqusition(String name, boolean prompt) throws MMScriptException {
MMAcquisition acq = getAcquisition(name);
getAcquisition(name).promptToSave(prompt);
}
public void snapAndAddToImage5D() {
if (core_.getCameraDevice().length() == 0) {
ReportingUtils.showError("No camera configured");
return;
}
try {
if (this.isLiveModeOn()) {
copyFromLiveModeToAlbum(simpleDisplay_);
} else {
doSnap(true);
}
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
public void setAcquisitionEngine(AcquisitionWrapperEngine eng) {
engine_ = eng;
}
public void suspendLiveMode() {
liveModeSuspended_ = isLiveModeOn();
enableLiveMode(false);
}
public void resumeLiveMode() {
if (liveModeSuspended_) {
enableLiveMode(true);
}
}
@Override
public Autofocus getAutofocus() {
return afMgr_.getDevice();
}
@Override
public void showAutofocusDialog() {
if (afMgr_.getDevice() != null) {
afMgr_.showOptionsDialog();
}
}
@Override
public AutofocusManager getAutofocusManager() {
return afMgr_;
}
public void selectConfigGroup(String groupName) {
configPad_.setGroup(groupName);
}
public String regenerateDeviceList() {
Cursor oldc = Cursor.getDefaultCursor();
Cursor waitc = new Cursor(Cursor.WAIT_CURSOR);
setCursor(waitc);
StringBuffer resultFile = new StringBuffer();
MicroscopeModel.generateDeviceListFile(resultFile, core_);
//MicroscopeModel.generateDeviceListFile();
setCursor(oldc);
return resultFile.toString();
}
@Override
public void setImageSavingFormat(Class imageSavingClass) throws MMScriptException {
if (! (imageSavingClass.equals(TaggedImageStorageDiskDefault.class) ||
imageSavingClass.equals(TaggedImageStorageMultipageTiff.class))) {
throw new MMScriptException("Unrecognized saving class");
}
ImageUtils.setImageStorageClass(imageSavingClass);
if (acqControlWin_ != null) {
acqControlWin_.updateSavingTypeButtons();
}
}
/**
* Discovers Micro-Manager plugins and autofocus plugins at runtime
* Adds these to the plugins menu
*/
private void loadPlugins() {
ArrayList<Class<?>> pluginClasses = new ArrayList<Class<?>>();
ArrayList<Class<?>> autofocusClasses = new ArrayList<Class<?>>();
List<Class<?>> classes;
try {
long t1 = System.currentTimeMillis();
classes = JavaUtils.findClasses(new File("mmplugins"), 2);
for (Class<?> clazz : classes) {
for (Class<?> iface : clazz.getInterfaces()) {
if (iface == MMPlugin.class) {
pluginClasses.add(clazz);
}
}
}
classes = JavaUtils.findClasses(new File("mmautofocus"), 2);
for (Class<?> clazz : classes) {
for (Class<?> iface : clazz.getInterfaces()) {
//core_.logMessage("interface found: " + iface.getName());
if (iface == Autofocus.class) {
autofocusClasses.add(clazz);
}
}
}
} catch (ClassNotFoundException e1) {
ReportingUtils.logError(e1);
}
ArrayList<PluginItemAndClass> piacs = new ArrayList<PluginItemAndClass>();
for (Class<?> plugin : pluginClasses) {
try {
ReportingUtils.logMessage("Attempting to install plugin " + plugin.getName());
PluginItemAndClass piac = declarePlugin(plugin);
if (piac.getPluginItem() != null) {
piacs.add(piac);
}
} catch (Exception e) {
ReportingUtils.logError(e, "Failed to install the \"" + plugin.getName() + "\" plugin .");
}
}
Collections.sort(piacs, new PluginItemAndClassComparator());
for (PluginItemAndClass piac : piacs) {
final PluginItem pi = piac.getPluginItem();
if (pi != null) {
addPluginToMenuLater(pi);
}
}
for (Class<?> autofocus : autofocusClasses) {
try {
ReportingUtils.logMessage("Attempting to install autofocus plugin " + autofocus.getName());
installAutofocusPlugin(autofocus.getName());
} catch (Exception e) {
ReportingUtils.logError("Failed to install the \"" + autofocus.getName() + "\" autofocus plugin.");
}
}
}
@Override
public void logMessage(String msg) {
ReportingUtils.logMessage(msg);
}
@Override
public void showMessage(String msg) {
ReportingUtils.showMessage(msg);
}
@Override
public void logError(Exception e, String msg) {
ReportingUtils.logError(e, msg);
}
@Override
public void logError(Exception e) {
ReportingUtils.logError(e);
}
@Override
public void logError(String msg) {
ReportingUtils.logError(msg);
}
@Override
public void showError(Exception e, String msg) {
ReportingUtils.showError(e, msg);
}
@Override
public void showError(Exception e) {
ReportingUtils.showError(e);
}
@Override
public void showError(String msg) {
ReportingUtils.showError(msg);
}
private void runHardwareWizard() {
try {
if (configChanged_) {
Object[] options = {"Yes", "No"};
int n = JOptionPane.showOptionDialog(null,
"Save Changed Configuration?", "Micro-Manager",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options,
options[0]);
if (n == JOptionPane.YES_OPTION) {
saveConfigPresets();
}
configChanged_ = false;
}
boolean liveRunning = false;
if (isLiveModeOn()) {
liveRunning = true;
enableLiveMode(false);
}
// unload all devices before starting configurator
core_.reset();
GUIUtils.preventDisplayAdapterChangeExceptions();
// run Configurator
ConfiguratorDlg2 cfg2 = null;
try {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
cfg2 = new ConfiguratorDlg2(core_, sysConfigFile_);
} finally {
setCursor(Cursor.getDefaultCursor());
}
if (cfg2 == null)
{
ReportingUtils.showError("Failed to launch Hardware Configuration Wizard");
return;
}
cfg2.setVisible(true);
GUIUtils.preventDisplayAdapterChangeExceptions();
// re-initialize the system with the new configuration file
sysConfigFile_ = cfg2.getFileName();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
loadSystemConfiguration();
GUIUtils.preventDisplayAdapterChangeExceptions();
if (liveRunning) {
enableLiveMode(liveRunning);
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
private void autofocusNow() {
if (afMgr_.getDevice() != null) {
new Thread() {
@Override
public void run() {
try {
boolean lmo = isLiveModeOn();
if (lmo) {
enableLiveMode(false);
}
afMgr_.getDevice().fullFocus();
if (lmo) {
enableLiveMode(true);
}
} catch (MMException ex) {
ReportingUtils.logError(ex);
}
}
}.start(); // or any other method from Autofocus.java API
}
}
}
class BooleanLock extends Object {
private boolean value;
public BooleanLock(boolean initialValue) {
value = initialValue;
}
public BooleanLock() {
this(false);
}
public synchronized void setValue(boolean newValue) {
if (newValue != value) {
value = newValue;
notifyAll();
}
}
public synchronized boolean waitToSetTrue(long msTimeout)
throws InterruptedException {
boolean success = waitUntilFalse(msTimeout);
if (success) {
setValue(true);
}
return success;
}
public synchronized boolean waitToSetFalse(long msTimeout)
throws InterruptedException {
boolean success = waitUntilTrue(msTimeout);
if (success) {
setValue(false);
}
return success;
}
public synchronized boolean isTrue() {
return value;
}
public synchronized boolean isFalse() {
return !value;
}
public synchronized boolean waitUntilTrue(long msTimeout)
throws InterruptedException {
return waitUntilStateIs(true, msTimeout);
}
public synchronized boolean waitUntilFalse(long msTimeout)
throws InterruptedException {
return waitUntilStateIs(false, msTimeout);
}
public synchronized boolean waitUntilStateIs(
boolean state,
long msTimeout) throws InterruptedException {
if (msTimeout == 0L) {
while (value != state) {
wait();
}
return true;
}
long endTime = System.currentTimeMillis() + msTimeout;
long msRemaining = msTimeout;
while ((value != state) && (msRemaining > 0L)) {
wait(msRemaining);
msRemaining = endTime - System.currentTimeMillis();
}
return (value == state);
}
}
| mmstudio/src/org/micromanager/MMStudioMainFrame.java | ///////////////////////////////////////////////////////////////////////////////
//FILE: MMStudioMainFrame.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
//-----------------------------------------------------------------------------
//AUTHOR: Nenad Amodaj, [email protected], Jul 18, 2005
// Modifications by Arthur Edelstein, Nico Stuurman, Henry Pinkard
//COPYRIGHT: University of California, San Francisco, 2006-2013
// 100X Imaging Inc, www.100ximaging.com, 2008
//LICENSE: This file is distributed under the BSD license.
// License text is included with the source distribution.
// This file 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.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//CVS: $Id$
//
package org.micromanager;
import ij.IJ;
import ij.ImageJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.gui.Line;
import ij.gui.Roi;
import ij.process.ImageProcessor;
import ij.process.ShortProcessor;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Point2D;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.Preferences;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.UIManager;
import mmcorej.CMMCore;
import mmcorej.DeviceType;
import mmcorej.MMCoreJ;
import mmcorej.MMEventCallback;
import mmcorej.StrVector;
import org.json.JSONObject;
import org.micromanager.acquisition.AcquisitionManager;
import org.micromanager.api.Autofocus;
import org.micromanager.api.DataProcessor;
import org.micromanager.api.MMPlugin;
import org.micromanager.api.MMTags;
import org.micromanager.api.PositionList;
import org.micromanager.api.ScriptInterface;
import org.micromanager.api.MMListenerInterface;
import org.micromanager.api.SequenceSettings;
import org.micromanager.conf2.ConfiguratorDlg2;
import org.micromanager.conf2.MMConfigFileException;
import org.micromanager.conf2.MicroscopeModel;
import org.micromanager.graph.GraphData;
import org.micromanager.graph.GraphFrame;
import org.micromanager.navigation.CenterAndDragListener;
import org.micromanager.navigation.XYZKeyListener;
import org.micromanager.navigation.ZWheelListener;
import org.micromanager.utils.AutofocusManager;
import org.micromanager.utils.ContrastSettings;
import org.micromanager.utils.GUIColors;
import org.micromanager.utils.GUIUtils;
import org.micromanager.utils.JavaUtils;
import org.micromanager.utils.MMException;
import org.micromanager.utils.MMScriptException;
import org.micromanager.utils.NumberUtils;
import org.micromanager.utils.TextUtils;
import org.micromanager.utils.WaitDialog;
import bsh.EvalError;
import bsh.Interpreter;
import com.swtdesigner.SwingResourceManager;
import ij.gui.ImageCanvas;
import ij.gui.ImageWindow;
import ij.gui.Toolbar;
import java.awt.*;
import java.awt.dnd.DropTarget;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collections;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import mmcorej.TaggedImage;
import org.json.JSONException;
import org.micromanager.acquisition.*;
import org.micromanager.api.ImageCache;
import org.micromanager.api.IAcquisitionEngine2010;
import org.micromanager.graph.HistogramSettings;
import org.micromanager.internalinterfaces.LiveModeListener;
import org.micromanager.utils.DragDropUtil;
import org.micromanager.utils.FileDialogs;
import org.micromanager.utils.FileDialogs.FileType;
import org.micromanager.utils.HotKeysDialog;
import org.micromanager.utils.ImageUtils;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.MMKeyDispatcher;
import org.micromanager.utils.ReportingUtils;
import org.micromanager.utils.UIMonitor;
/*
* Main panel and application class for the MMStudio.
*/
public class MMStudioMainFrame extends JFrame implements ScriptInterface {
private static final String MICRO_MANAGER_TITLE = "Micro-Manager";
private static final long serialVersionUID = 3556500289598574541L;
private static final String MAIN_FRAME_X = "x";
private static final String MAIN_FRAME_Y = "y";
private static final String MAIN_FRAME_WIDTH = "width";
private static final String MAIN_FRAME_HEIGHT = "height";
private static final String MAIN_FRAME_DIVIDER_POS = "divider_pos";
private static final String MAIN_EXPOSURE = "exposure";
private static final String MAIN_SAVE_METHOD = "saveMethod";
private static final String SYSTEM_CONFIG_FILE = "sysconfig_file";
private static final String OPEN_ACQ_DIR = "openDataDir";
private static final String SCRIPT_CORE_OBJECT = "mmc";
private static final String SCRIPT_ACQENG_OBJECT = "acq";
private static final String SCRIPT_GUI_OBJECT = "gui";
private static final String AUTOFOCUS_DEVICE = "autofocus_device";
private static final String MOUSE_MOVES_STAGE = "mouse_moves_stage";
private static final String EXPOSURE_SETTINGS_NODE = "MainExposureSettings";
private static final String CONTRAST_SETTINGS_NODE = "MainContrastSettings";
private static final int TOOLTIP_DISPLAY_DURATION_MILLISECONDS = 15000;
private static final int TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS = 2000;
// cfg file saving
private static final String CFGFILE_ENTRY_BASE = "CFGFileEntry"; // + {0, 1, 2, 3, 4}
// GUI components
private JComboBox comboBinning_;
private JComboBox shutterComboBox_;
private JTextField textFieldExp_;
private JLabel labelImageDimensions_;
private JToggleButton liveButton_;
private JCheckBox autoShutterCheckBox_;
private MMOptions options_;
private boolean runsAsPlugin_;
private JCheckBoxMenuItem centerAndDragMenuItem_;
private JButton snapButton_;
private JButton autofocusNowButton_;
private JButton autofocusConfigureButton_;
private JToggleButton toggleShutterButton_;
private GUIColors guiColors_;
private GraphFrame profileWin_;
private PropertyEditor propertyBrowser_;
private CalibrationListDlg calibrationListDlg_;
private AcqControlDlg acqControlWin_;
private ReportProblemDialog reportProblemDialog_;
private JMenu pluginMenu_;
private ArrayList<PluginItem> plugins_;
private List<MMListenerInterface> MMListeners_
= Collections.synchronizedList(new ArrayList<MMListenerInterface>());
private List<LiveModeListener> liveModeListeners_
= Collections.synchronizedList(new ArrayList<LiveModeListener>());
private List<Component> MMFrames_
= Collections.synchronizedList(new ArrayList<Component>());
private AutofocusManager afMgr_;
private final static String DEFAULT_CONFIG_FILE_NAME = "MMConfig_demo.cfg";
private ArrayList<String> MRUConfigFiles_;
private static final int maxMRUCfgs_ = 5;
private String sysConfigFile_;
private String startupScriptFile_;
private String sysStateFile_ = "MMSystemState.cfg";
private ConfigGroupPad configPad_;
private LiveModeTimer liveModeTimer_;
private GraphData lineProfileData_;
// labels for standard devices
private String cameraLabel_;
private String zStageLabel_;
private String shutterLabel_;
private String xyStageLabel_;
// applications settings
private Preferences mainPrefs_;
private Preferences systemPrefs_;
private Preferences colorPrefs_;
private Preferences exposurePrefs_;
private Preferences contrastPrefs_;
// MMcore
private CMMCore core_;
private AcquisitionWrapperEngine engine_;
private PositionList posList_;
private PositionListDlg posListDlg_;
private String openAcqDirectory_ = "";
private boolean running_;
private boolean configChanged_ = false;
private StrVector shutters_ = null;
private JButton saveConfigButton_;
private ScriptPanel scriptPanel_;
private org.micromanager.utils.HotKeys hotKeys_;
private CenterAndDragListener centerAndDragListener_;
private ZWheelListener zWheelListener_;
private XYZKeyListener xyzKeyListener_;
private AcquisitionManager acqMgr_;
private static VirtualAcquisitionDisplay simpleDisplay_;
private Color[] multiCameraColors_ = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.CYAN};
private boolean liveModeSuspended_;
public Font defaultScriptFont_ = null;
public static final String SIMPLE_ACQ = "Snap/Live Window";
public static FileType MM_CONFIG_FILE
= new FileType("MM_CONFIG_FILE",
"Micro-Manager Config File",
"./MyScope.cfg",
true, "cfg");
// Our instance
private static MMStudioMainFrame gui_;
// Callback
private CoreEventCallback cb_;
// Lock invoked while shutting down
private final Object shutdownLock_ = new Object();
private JMenuBar menuBar_;
private ConfigPadButtonPanel configPadButtonPanel_;
private final JMenu switchConfigurationMenu_;
private final MetadataPanel metadataPanel_;
public static FileType MM_DATA_SET
= new FileType("MM_DATA_SET",
"Micro-Manager Image Location",
System.getProperty("user.home") + "/Untitled",
false, (String[]) null);
private Thread acquisitionEngine2010LoadingThread = null;
private Class<?> acquisitionEngine2010Class = null;
private IAcquisitionEngine2010 acquisitionEngine2010 = null;
private final JSplitPane splitPane_;
private volatile boolean ignorePropertyChanges_;
private AbstractButton setRoiButton_;
private AbstractButton clearRoiButton_;
private DropTarget dt_;
// private ProcessorStackManager processorStackManager_;
public ImageWindow getImageWin() {
return getSnapLiveWin();
}
@Override
public ImageWindow getSnapLiveWin() {
if (simpleDisplay_ == null) {
return null;
}
return simpleDisplay_.getHyperImage().getWindow();
}
public static VirtualAcquisitionDisplay getSimpleDisplay() {
return simpleDisplay_;
}
public static void createSimpleDisplay(String name, ImageCache cache) throws MMScriptException {
simpleDisplay_ = new VirtualAcquisitionDisplay(cache, name);
}
public void checkSimpleAcquisition() {
if (core_.getCameraDevice().length() == 0) {
ReportingUtils.showError("No camera configured");
return;
}
int width = (int) core_.getImageWidth();
int height = (int) core_.getImageHeight();
int depth = (int) core_.getBytesPerPixel();
int bitDepth = (int) core_.getImageBitDepth();
int numCamChannels = (int) core_.getNumberOfCameraChannels();
try {
if (acquisitionExists(SIMPLE_ACQ)) {
if ((getAcquisitionImageWidth(SIMPLE_ACQ) != width)
|| (getAcquisitionImageHeight(SIMPLE_ACQ) != height)
|| (getAcquisitionImageByteDepth(SIMPLE_ACQ) != depth)
|| (getAcquisitionImageBitDepth(SIMPLE_ACQ) != bitDepth)
|| (getAcquisitionMultiCamNumChannels(SIMPLE_ACQ) != numCamChannels)) { //Need to close and reopen simple window
closeAcquisitionWindow(SIMPLE_ACQ);
}
}
if (!acquisitionExists(SIMPLE_ACQ)) {
openAcquisition(SIMPLE_ACQ, "", 1, numCamChannels, 1, true);
if (numCamChannels > 1) {
for (long i = 0; i < numCamChannels; i++) {
String chName = core_.getCameraChannelName(i);
int defaultColor = multiCameraColors_[(int) i % multiCameraColors_.length].getRGB();
setChannelColor(SIMPLE_ACQ, (int) i, getChannelColor(chName, defaultColor));
setChannelName(SIMPLE_ACQ, (int) i, chName);
}
}
initializeSimpleAcquisition(SIMPLE_ACQ, width, height, depth, bitDepth, numCamChannels);
getAcquisition(SIMPLE_ACQ).promptToSave(false);
getAcquisition(SIMPLE_ACQ).toFront();
this.updateCenterAndDragListener();
}
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
}
public void checkSimpleAcquisition(TaggedImage image) {
try {
JSONObject tags = image.tags;
int width = MDUtils.getWidth(tags);
int height = MDUtils.getHeight(tags);
int depth = MDUtils.getDepth(tags);
int bitDepth = MDUtils.getBitDepth(tags);
int numCamChannels = (int) core_.getNumberOfCameraChannels();
if (acquisitionExists(SIMPLE_ACQ)) {
if ((getAcquisitionImageWidth(SIMPLE_ACQ) != width)
|| (getAcquisitionImageHeight(SIMPLE_ACQ) != height)
|| (getAcquisitionImageByteDepth(SIMPLE_ACQ) != depth)
|| (getAcquisitionImageBitDepth(SIMPLE_ACQ) != bitDepth)
|| (getAcquisitionMultiCamNumChannels(SIMPLE_ACQ) != numCamChannels)) { //Need to close and reopen simple window
closeAcquisitionWindow(SIMPLE_ACQ);
// Seems that closeAcquisitionWindow also closes the acquisition...
//closeAcquisition(SIMPLE_ACQ);
}
}
if (!acquisitionExists(SIMPLE_ACQ)) {
openAcquisition(SIMPLE_ACQ, "", 1, numCamChannels, 1, true);
if (numCamChannels > 1) {
for (long i = 0; i < numCamChannels; i++) {
String chName = core_.getCameraChannelName(i);
int defaultColor = multiCameraColors_[(int) i % multiCameraColors_.length].getRGB();
setChannelColor(SIMPLE_ACQ, (int) i, getChannelColor(chName, defaultColor));
setChannelName(SIMPLE_ACQ, (int) i, chName);
}
}
initializeSimpleAcquisition(SIMPLE_ACQ, width, height, depth, bitDepth, numCamChannels);
getAcquisition(SIMPLE_ACQ).promptToSave(false);
getAcquisition(SIMPLE_ACQ).toFront();
this.updateCenterAndDragListener();
}
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
}
public void saveChannelColor(String chName, int rgb)
{
if (colorPrefs_ != null) {
colorPrefs_.putInt("Color_" + chName, rgb);
}
}
public Color getChannelColor(String chName, int defaultColor)
{
if (colorPrefs_ != null) {
defaultColor = colorPrefs_.getInt("Color_" + chName, defaultColor);
}
return new Color(defaultColor);
}
@Override
public void enableRoiButtons(final boolean enabled) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
setRoiButton_.setEnabled(enabled);
clearRoiButton_.setEnabled(enabled);
}
});
}
public void copyFromLiveModeToAlbum(VirtualAcquisitionDisplay display) throws MMScriptException, JSONException {
ImageCache ic = display.getImageCache();
int channels = ic.getSummaryMetadata().getInt("Channels");
if (channels == 1) {
//RGB or monchrome
addToAlbum(ic.getImage(0, 0, 0, 0), ic.getDisplayAndComments());
} else {
//multicamera
for (int i = 0; i < channels; i++) {
addToAlbum(ic.getImage(i, 0, 0, 0), ic.getDisplayAndComments());
}
}
}
private void createActiveShutterChooser(JPanel topPanel) {
createLabel("Shutter", false, topPanel, 111, 73, 158, 86);
shutterComboBox_ = new JComboBox();
shutterComboBox_.setName("Shutter");
shutterComboBox_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
try {
if (shutterComboBox_.getSelectedItem() != null) {
core_.setShutterDevice((String) shutterComboBox_.getSelectedItem());
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
});
GUIUtils.addWithEdges(topPanel, shutterComboBox_, 170, 70, 275, 92);
}
private void createBinningChooser(JPanel topPanel) {
createLabel("Binning", false, topPanel, 111, 43, 199, 64);
comboBinning_ = new JComboBox();
comboBinning_.setName("Binning");
comboBinning_.setFont(new Font("Arial", Font.PLAIN, 10));
comboBinning_.setMaximumRowCount(4);
comboBinning_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
changeBinning();
}
});
GUIUtils.addWithEdges(topPanel, comboBinning_, 200, 43, 275, 66);
}
private void createExposureField(JPanel topPanel) {
createLabel("Exposure [ms]", false, topPanel, 111, 23, 198, 39);
textFieldExp_ = new JTextField();
textFieldExp_.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent fe) {
synchronized(shutdownLock_) {
if (core_ != null)
setExposure();
}
}
});
textFieldExp_.setFont(new Font("Arial", Font.PLAIN, 10));
textFieldExp_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setExposure();
}
});
GUIUtils.addWithEdges(topPanel, textFieldExp_, 203, 21, 276, 40);
}
private void toggleAutoShutter() {
shutterLabel_ = core_.getShutterDevice();
if (shutterLabel_.length() == 0) {
toggleShutterButton_.setEnabled(false);
} else {
if (autoShutterCheckBox_.isSelected()) {
try {
core_.setAutoShutter(true);
core_.setShutterOpen(false);
toggleShutterButton_.setSelected(false);
toggleShutterButton_.setText("Open");
toggleShutterButton_.setEnabled(false);
} catch (Exception e2) {
ReportingUtils.logError(e2);
}
} else {
try {
core_.setAutoShutter(false);
core_.setShutterOpen(false);
toggleShutterButton_.setEnabled(true);
toggleShutterButton_.setText("Open");
} catch (Exception exc) {
ReportingUtils.logError(exc);
}
}
}
}
private void createShutterControls(JPanel topPanel) {
autoShutterCheckBox_ = new JCheckBox();
autoShutterCheckBox_.setFont(new Font("Arial", Font.PLAIN, 10));
autoShutterCheckBox_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
toggleAutoShutter();
}
});
autoShutterCheckBox_.setIconTextGap(6);
autoShutterCheckBox_.setHorizontalTextPosition(SwingConstants.LEADING);
autoShutterCheckBox_.setText("Auto shutter");
GUIUtils.addWithEdges(topPanel, autoShutterCheckBox_, 107, 96, 199, 119);
toggleShutterButton_ = (JToggleButton) GUIUtils.createButton(true,
"toggleShutterButton", "Open",
"Open/close the shutter",
new Runnable() {
public void run() {
toggleShutter();
}
}, null, topPanel, 203, 96, 275, 117); // Shutter button
}
private void createCameraSettingsWidgets(JPanel topPanel) {
createLabel("Camera settings", true, topPanel, 109, 2, 211, 22);
createExposureField(topPanel);
createBinningChooser(topPanel);
createActiveShutterChooser(topPanel);
createShutterControls(topPanel);
}
private void createConfigurationControls(JPanel topPanel) {
createLabel("Configuration settings", true, topPanel, 280, 2, 430, 22);
saveConfigButton_ = (JButton) GUIUtils.createButton(false,
"saveConfigureButton", "Save",
"Save current presets to the configuration file",
new Runnable() {
public void run() {
saveConfigPresets();
}
}, null, topPanel, -80, 2, -5, 20);
configPad_ = new ConfigGroupPad();
configPadButtonPanel_ = new ConfigPadButtonPanel();
configPadButtonPanel_.setConfigPad(configPad_);
configPadButtonPanel_.setGUI(MMStudioMainFrame.getInstance());
configPad_.setFont(new Font("", Font.PLAIN, 10));
GUIUtils.addWithEdges(topPanel, configPad_, 280, 21, -4, -44);
GUIUtils.addWithEdges(topPanel, configPadButtonPanel_, 280, -40, -4, -20);
}
private void createMainButtons(JPanel topPanel) {
snapButton_ = (JButton) GUIUtils.createButton(false, "Snap", "Snap",
"Snap single image",
new Runnable() {
public void run() {
doSnap();
}
}, "camera.png", topPanel, 7, 4, 95, 25);
liveButton_ = (JToggleButton) GUIUtils.createButton(true,
"Live", "Live",
"Continuous live view",
new Runnable() {
public void run() {
enableLiveMode(!isLiveModeOn());
}
}, "camera_go.png", topPanel, 7, 26, 95, 47);
/* toAlbumButton_ = (JButton) */ GUIUtils.createButton(false, "Album", "Album",
"Acquire single frame and add to an album",
new Runnable() {
public void run() {
snapAndAddToImage5D();
}
}, "camera_plus_arrow.png", topPanel, 7, 48, 95, 69);
/* MDA Button = */ GUIUtils.createButton(false,
"Multi-D Acq.", "Multi-D Acq.",
"Open multi-dimensional acquisition window",
new Runnable() {
public void run() {
openAcqControlDialog();
}
}, "film.png", topPanel, 7, 70, 95, 91);
/* Refresh = */ GUIUtils.createButton(false, "Refresh", "Refresh",
"Refresh all GUI controls directly from the hardware",
new Runnable() {
public void run() {
core_.updateSystemStateCache();
updateGUI(true);
}
}, "arrow_refresh.png", topPanel, 7, 92, 95, 113);
}
private static MetadataPanel createMetadataPanel(JPanel bottomPanel) {
MetadataPanel metadataPanel = new MetadataPanel();
GUIUtils.addWithEdges(bottomPanel, metadataPanel, 0, 0, 0, 0);
metadataPanel.setBorder(BorderFactory.createEmptyBorder());
return metadataPanel;
}
private void createPleaLabel(JPanel topPanel) {
JLabel citePleaLabel = new JLabel("<html>Please <a href=\"http://micro-manager.org\">cite Micro-Manager</a> so funding will continue!</html>");
citePleaLabel.setFont(new Font("Arial", Font.PLAIN, 11));
GUIUtils.addWithEdges(topPanel, citePleaLabel, 7, 119, 270, 139);
class Pleader extends Thread{
Pleader(){
super("pleader");
}
@Override
public void run(){
try {
ij.plugin.BrowserLauncher.openURL("https://micro-manager.org/wiki/Citing_Micro-Manager");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
}
citePleaLabel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
Pleader p = new Pleader();
p.start();
}
});
// add a listener to the main ImageJ window to catch it quitting out on us
if (ij.IJ.getInstance() != null) {
ij.IJ.getInstance().addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
closeSequence(true);
};
});
}
}
private JSplitPane createSplitPane(int dividerPos) {
JPanel topPanel = new JPanel();
JPanel bottomPanel = new JPanel();
topPanel.setLayout(new SpringLayout());
topPanel.setMinimumSize(new Dimension(580, 195));
bottomPanel.setLayout(new SpringLayout());
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true,
topPanel, bottomPanel);
splitPane.setBorder(BorderFactory.createEmptyBorder());
splitPane.setDividerLocation(dividerPos);
splitPane.setResizeWeight(0.0);
return splitPane;
}
private void createTopPanelWidgets(JPanel topPanel) {
createMainButtons(topPanel);
createCameraSettingsWidgets(topPanel);
createPleaLabel(topPanel);
createUtilityButtons(topPanel);
createConfigurationControls(topPanel);
labelImageDimensions_ = createLabel("", false, topPanel, 5, -20, 0, 0);
}
private void createUtilityButtons(JPanel topPanel) {
// ROI
createLabel("ROI", true, topPanel, 8, 140, 71, 154);
setRoiButton_ = GUIUtils.createButton(false, "setRoiButton", null,
"Set Region Of Interest to selected rectangle",
new Runnable() {
public void run() {
setROI();
}
}, "shape_handles.png", topPanel, 7, 154, 37, 174);
clearRoiButton_ = GUIUtils.createButton(false, "clearRoiButton", null,
"Reset Region of Interest to full frame",
new Runnable() {
public void run() {
clearROI();
}
}, "arrow_out.png", topPanel, 40, 154, 70, 174);
// Zoom
createLabel("Zoom", true, topPanel, 81, 140, 139, 154);
GUIUtils.createButton(false, "zoomInButton", null,
"Zoom in",
new Runnable() {
public void run() {
zoomIn();
}
}, "zoom_in.png", topPanel, 80, 154, 110, 174);
GUIUtils.createButton(false, "zoomOutButton", null,
"Zoom out",
new Runnable() {
public void run() {
zoomOut();
}
}, "zoom_out.png", topPanel, 113, 154, 143, 174);
// Profile
createLabel("Profile", true, topPanel, 154, 140, 217, 154);
GUIUtils.createButton(false, "lineProfileButton", null,
"Open line profile window (requires line selection)",
new Runnable() {
public void run() {
openLineProfileWindow();
}
}, "chart_curve.png", topPanel, 153, 154, 183, 174);
// Autofocus
createLabel("Autofocus", true, topPanel, 194, 140, 276, 154);
autofocusNowButton_ = (JButton) GUIUtils.createButton(false,
"autofocusNowButton", null,
"Autofocus now",
new Runnable() {
public void run() {
autofocusNow();
}
}, "find.png", topPanel, 193, 154, 223, 174);
autofocusConfigureButton_ = (JButton) GUIUtils.createButton(false,
"autofocusConfigureButton", null,
"Set autofocus options",
new Runnable() {
public void run() {
showAutofocusDialog();
}
}, "wrench_orange.png", topPanel, 226, 154, 256, 174);
}
private void initializeFileMenu() {
JMenu fileMenu = GUIUtils.createMenuInMenuBar(menuBar_, "File");
GUIUtils.addMenuItem(fileMenu, "Open (Virtual)...", null,
new Runnable() {
public void run() {
new Thread() {
@Override
public void run() {
openAcquisitionData(false);
}
}.start();
}
});
GUIUtils.addMenuItem(fileMenu, "Open (RAM)...", null,
new Runnable() {
public void run() {
new Thread() {
@Override
public void run() {
openAcquisitionData(true);
}
}.start();
}
});
fileMenu.addSeparator();
GUIUtils.addMenuItem(fileMenu, "Exit", null,
new Runnable() {
public void run() {
closeSequence(false);
}
});
}
private void initializeHelpMenu() {
final JMenu helpMenu = GUIUtils.createMenuInMenuBar(menuBar_, "Help");
GUIUtils.addMenuItem(helpMenu, "User's Guide", null,
new Runnable() {
public void run() {
try {
ij.plugin.BrowserLauncher.openURL("http://micro-manager.org/wiki/Micro-Manager_User%27s_Guide");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
});
GUIUtils.addMenuItem(helpMenu, "Configuration Guide", null,
new Runnable() {
public void run() {
try {
ij.plugin.BrowserLauncher.openURL("http://micro-manager.org/wiki/Micro-Manager_Configuration_Guide");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
});
if (!systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false)) {
GUIUtils.addMenuItem(helpMenu, "Register your copy of Micro-Manager...", null,
new Runnable() {
public void run() {
try {
RegistrationDlg regDlg = new RegistrationDlg(systemPrefs_);
regDlg.setVisible(true);
} catch (Exception e1) {
ReportingUtils.showError(e1);
}
}
});
}
GUIUtils.addMenuItem(helpMenu, "Report Problem...", null,
new Runnable() {
public void run() {
if (null == reportProblemDialog_) {
reportProblemDialog_ = new ReportProblemDialog(core_, MMStudioMainFrame.this, options_);
MMStudioMainFrame.this.addMMBackgroundListener(reportProblemDialog_);
reportProblemDialog_.setBackground(guiColors_.background.get(options_.displayBackground_));
}
reportProblemDialog_.setVisible(true);
}
});
GUIUtils.addMenuItem(helpMenu, "About Micromanager", null,
new Runnable() {
public void run() {
MMAboutDlg dlg = new MMAboutDlg();
String versionInfo = "MM Studio version: " + MMVersion.VERSION_STRING;
versionInfo += "\n" + core_.getVersionInfo();
versionInfo += "\n" + core_.getAPIVersionInfo();
versionInfo += "\nUser: " + core_.getUserId();
versionInfo += "\nHost: " + core_.getHostName();
dlg.setVersionInfo(versionInfo);
dlg.setVisible(true);
}
});
menuBar_.validate();
}
private void initializeToolsMenu() {
// Tools menu
final JMenu toolsMenu = GUIUtils.createMenuInMenuBar(menuBar_, "Tools");
GUIUtils.addMenuItem(toolsMenu, "Refresh GUI",
"Refresh all GUI controls directly from the hardware",
new Runnable() {
public void run() {
core_.updateSystemStateCache();
updateGUI(true);
}
},
"arrow_refresh.png");
GUIUtils.addMenuItem(toolsMenu, "Rebuild GUI",
"Regenerate Micro-Manager user interface",
new Runnable() {
public void run() {
initializeGUI();
core_.updateSystemStateCache();
}
});
toolsMenu.addSeparator();
GUIUtils.addMenuItem(toolsMenu, "Script Panel...",
"Open Micro-Manager script editor window",
new Runnable() {
public void run() {
scriptPanel_.setVisible(true);
}
});
GUIUtils.addMenuItem(toolsMenu, "Shortcuts...",
"Create keyboard shortcuts to activate image acquisition, mark positions, or run custom scripts",
new Runnable() {
public void run() {
HotKeysDialog hk = new HotKeysDialog(guiColors_.background.get((options_.displayBackground_)));
//hk.setBackground(guiColors_.background.get((options_.displayBackground_)));
}
});
GUIUtils.addMenuItem(toolsMenu, "Device/Property Browser...",
"Open new window to view and edit property values in current configuration",
new Runnable() {
public void run() {
createPropertyEditor();
}
});
toolsMenu.addSeparator();
GUIUtils.addMenuItem(toolsMenu, "XY List...",
"Open position list manager window",
new Runnable() {
public void run() {
showXYPositionList();
}
},
"application_view_list.png");
GUIUtils.addMenuItem(toolsMenu, "Multi-Dimensional Acquisition...",
"Open multi-dimensional acquisition setup window",
new Runnable() {
public void run() {
openAcqControlDialog();
}
},
"film.png");
centerAndDragMenuItem_ = GUIUtils.addCheckBoxMenuItem(toolsMenu,
"Mouse Moves Stage (use Hand Tool)",
"When enabled, double clicking or dragging in the snap/live\n"
+ "window moves the XY-stage. Requires the hand tool.",
new Runnable() {
public void run() {
updateCenterAndDragListener();
IJ.setTool(Toolbar.HAND);
mainPrefs_.putBoolean(MOUSE_MOVES_STAGE, centerAndDragMenuItem_.isSelected());
}
},
mainPrefs_.getBoolean(MOUSE_MOVES_STAGE, false));
GUIUtils.addMenuItem(toolsMenu, "Pixel Size Calibration...",
"Define size calibrations specific to each objective lens. "
+ "When the objective in use has a calibration defined, "
+ "micromanager will automatically use it when "
+ "calculating metadata",
new Runnable() {
public void run() {
createCalibrationListDlg();
}
});
/*
GUIUtils.addMenuItem(toolsMenu, "Image Processor Manager",
"Control the order in which Image Processor plugins"
+ "are applied to incoming images.",
new Runnable() {
public void run() {
processorStackManager_.show();
}
});
*/
toolsMenu.addSeparator();
GUIUtils.addMenuItem(toolsMenu, "Hardware Configuration Wizard...",
"Open wizard to create new hardware configuration",
new Runnable() {
public void run() {
runHardwareWizard();
}
});
GUIUtils.addMenuItem(toolsMenu, "Load Hardware Configuration...",
"Un-initialize current configuration and initialize new one",
new Runnable() {
public void run() {
loadConfiguration();
initializeGUI();
}
});
GUIUtils.addMenuItem(toolsMenu, "Reload Hardware Configuration",
"Shutdown current configuration and initialize most recently loaded configuration",
new Runnable() {
public void run() {
loadSystemConfiguration();
initializeGUI();
}
});
for (int i=0; i<5; i++)
{
JMenuItem configItem = new JMenuItem();
configItem.setText(Integer.toString(i));
switchConfigurationMenu_.add(configItem);
}
switchConfigurationMenu_.setText("Switch Hardware Configuration");
toolsMenu.add(switchConfigurationMenu_);
switchConfigurationMenu_.setToolTipText("Switch between recently used configurations");
GUIUtils.addMenuItem(toolsMenu, "Save Configuration Settings as...",
"Save current configuration settings as new configuration file",
new Runnable() {
public void run() {
saveConfigPresets();
updateChannelCombos();
}
});
toolsMenu.addSeparator();
final MMStudioMainFrame thisInstance = this;
GUIUtils.addMenuItem(toolsMenu, "Options...",
"Set a variety of Micro-Manager configuration options",
new Runnable() {
public void run() {
final int oldBufsize = options_.circularBufferSizeMB_;
OptionsDlg dlg = new OptionsDlg(options_, core_, mainPrefs_,
thisInstance);
dlg.setVisible(true);
// adjust memory footprint if necessary
if (oldBufsize != options_.circularBufferSizeMB_) {
try {
core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_);
} catch (Exception exc) {
ReportingUtils.showError(exc);
}
}
}
});
}
private void showRegistrationDialogMaybe() {
// show registration dialog if not already registered
// first check user preferences (for legacy compatibility reasons)
boolean userReg = mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION,
false) || mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false);
if (!userReg) {
boolean systemReg = systemPrefs_.getBoolean(
RegistrationDlg.REGISTRATION, false) || systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false);
if (!systemReg) {
// prompt for registration info
RegistrationDlg dlg = new RegistrationDlg(systemPrefs_);
dlg.setVisible(true);
}
}
}
private void updateSwitchConfigurationMenu() {
switchConfigurationMenu_.removeAll();
for (final String configFile : MRUConfigFiles_) {
if (!configFile.equals(sysConfigFile_)) {
GUIUtils.addMenuItem(switchConfigurationMenu_,
configFile, null,
new Runnable() {
public void run() {
sysConfigFile_ = configFile;
loadSystemConfiguration();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
}
});
}
}
}
/**
* Allows MMListeners to register themselves
*/
@Override
public void addMMListener(MMListenerInterface newL) {
if (MMListeners_.contains(newL))
return;
MMListeners_.add(newL);
}
/**
* Allows MMListeners to remove themselves
*/
@Override
public void removeMMListener(MMListenerInterface oldL) {
if (!MMListeners_.contains(oldL))
return;
MMListeners_.remove(oldL);
}
public final void addLiveModeListener (LiveModeListener listener) {
if (liveModeListeners_.contains(listener)) {
return;
}
liveModeListeners_.add(listener);
}
public void removeLiveModeListener(LiveModeListener listener) {
liveModeListeners_.remove(listener);
}
public void callLiveModeListeners(boolean enable) {
for (LiveModeListener listener : liveModeListeners_) {
listener.liveModeEnabled(enable);
}
}
/**
* Lets JComponents register themselves so that their background can be
* manipulated
*/
@Override
public void addMMBackgroundListener(Component comp) {
if (MMFrames_.contains(comp))
return;
MMFrames_.add(comp);
}
/**
* Lets JComponents remove themselves from the list whose background gets
* changes
*/
@Override
public void removeMMBackgroundListener(Component comp) {
if (!MMFrames_.contains(comp))
return;
MMFrames_.remove(comp);
}
/**
* Part of ScriptInterface
* Manipulate acquisition so that it looks like a burst
*/
public void runBurstAcquisition() throws MMScriptException {
double interval = engine_.getFrameIntervalMs();
int nr = engine_.getNumFrames();
boolean doZStack = engine_.isZSliceSettingEnabled();
boolean doChannels = engine_.isChannelsSettingEnabled();
engine_.enableZSliceSetting(false);
engine_.setFrames(nr, 0);
engine_.enableChannelsSetting(false);
try {
engine_.acquire();
} catch (MMException e) {
throw new MMScriptException(e);
}
engine_.setFrames(nr, interval);
engine_.enableZSliceSetting(doZStack);
engine_.enableChannelsSetting(doChannels);
}
public void runBurstAcquisition(int nr) throws MMScriptException {
int originalNr = engine_.getNumFrames();
double interval = engine_.getFrameIntervalMs();
engine_.setFrames(nr, 0);
this.runBurstAcquisition();
engine_.setFrames(originalNr, interval);
}
public void runBurstAcquisition(int nr, String name, String root) throws MMScriptException {
String originalRoot = engine_.getRootName();
engine_.setDirName(name);
engine_.setRootName(root);
this.runBurstAcquisition(nr);
engine_.setRootName(originalRoot);
}
/**
* Inserts version info for various components in the Corelog
*/
@Override
public void logStartupProperties() {
core_.enableDebugLog(options_.debugLogEnabled_);
core_.logMessage("MM Studio version: " + getVersion());
core_.logMessage(core_.getVersionInfo());
core_.logMessage(core_.getAPIVersionInfo());
core_.logMessage("Operating System: " + System.getProperty("os.name") +
" (" + System.getProperty("os.arch") + ") " + System.getProperty("os.version"));
core_.logMessage("JVM: " + System.getProperty("java.vm.name") +
", version " + System.getProperty("java.version") + ", " +
System.getProperty("sun.arch.data.model") + "-bit");
}
/**
* @Deprecated
* @throws MMScriptException
*/
public void startBurstAcquisition() throws MMScriptException {
runAcquisition();
}
public boolean isBurstAcquisitionRunning() throws MMScriptException {
if (engine_ == null)
return false;
return engine_.isAcquisitionRunning();
}
private void startLoadingPipelineClass() {
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
acquisitionEngine2010LoadingThread = new Thread("Pipeline Class loading thread") {
@Override
public void run() {
try {
acquisitionEngine2010Class = Class.forName("org.micromanager.AcquisitionEngine2010");
} catch (Exception ex) {
ReportingUtils.logError(ex);
acquisitionEngine2010Class = null;
}
}
};
acquisitionEngine2010LoadingThread.start();
}
@Override
public ImageCache getAcquisitionImageCache(String acquisitionName) throws MMScriptException {
return getAcquisition(acquisitionName).getImageCache();
}
/**
* Shows images as they appear in the default display window. Uses
* the default processor stack to process images as they arrive on
* the rawImageQueue.
*/
public void runDisplayThread(BlockingQueue<TaggedImage> rawImageQueue,
final DisplayImageRoutine displayImageRoutine) {
final BlockingQueue<TaggedImage> processedImageQueue =
ProcessorStack.run(rawImageQueue,
getAcquisitionEngine().getImageProcessors());
new Thread("Display thread") {
@Override
public void run() {
try {
TaggedImage image;
do {
image = processedImageQueue.take();
if (image != TaggedImageQueue.POISON) {
displayImageRoutine.show(image);
}
} while (image != TaggedImageQueue.POISON);
} catch (InterruptedException ex) {
ReportingUtils.logError(ex);
}
}
}.start();
}
private static JLabel createLabel(String text, boolean big,
JPanel parentPanel, int west, int north, int east, int south) {
final JLabel label = new JLabel();
label.setFont(new Font("Arial",
big ? Font.BOLD : Font.PLAIN,
big ? 11 : 10));
label.setText(text);
GUIUtils.addWithEdges(parentPanel, label, west, north, east, south);
return label;
}
public interface DisplayImageRoutine {
public void show(TaggedImage image);
}
/**
* Callback to update GUI when a change happens in the MMCore.
*/
public class CoreEventCallback extends MMEventCallback {
public CoreEventCallback() {
super();
}
@Override
public void onPropertiesChanged() {
// TODO: remove test once acquisition engine is fully multithreaded
if (engine_ != null && engine_.isAcquisitionRunning()) {
core_.logMessage("Notification from MMCore ignored because acquistion is running!", true);
} else {
if (ignorePropertyChanges_) {
core_.logMessage("Notification from MMCore ignored since the system is still loading", true);
} else {
core_.updateSystemStateCache();
updateGUI(true);
// update all registered listeners
for (MMListenerInterface mmIntf : MMListeners_) {
mmIntf.propertiesChangedAlert();
}
core_.logMessage("Notification from MMCore!", true);
}
}
}
@Override
public void onPropertyChanged(String deviceName, String propName, String propValue) {
core_.logMessage("Notification for Device: " + deviceName + " Property: " +
propName + " changed to value: " + propValue, true);
// update all registered listeners
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.propertyChangedAlert(deviceName, propName, propValue);
}
}
@Override
public void onConfigGroupChanged(String groupName, String newConfig) {
try {
configPad_.refreshGroup(groupName, newConfig);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.configGroupChangedAlert(groupName, newConfig);
}
} catch (Exception e) {
}
}
@Override
public void onSystemConfigurationLoaded() {
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.systemConfigurationLoaded();
}
}
@Override
public void onPixelSizeChanged(double newPixelSizeUm) {
updatePixSizeUm (newPixelSizeUm);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.pixelSizeChangedAlert(newPixelSizeUm);
}
}
@Override
public void onStagePositionChanged(String deviceName, double pos) {
if (deviceName.equals(zStageLabel_)) {
updateZPos(pos);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.stagePositionChangedAlert(deviceName, pos);
}
}
}
@Override
public void onStagePositionChangedRelative(String deviceName, double pos) {
if (deviceName.equals(zStageLabel_))
updateZPosRelative(pos);
}
@Override
public void onXYStagePositionChanged(String deviceName, double xPos, double yPos) {
if (deviceName.equals(xyStageLabel_)) {
updateXYPos(xPos, yPos);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.xyStagePositionChanged(deviceName, xPos, yPos);
}
}
}
@Override
public void onXYStagePositionChangedRelative(String deviceName, double xPos, double yPos) {
if (deviceName.equals(xyStageLabel_))
updateXYPosRelative(xPos, yPos);
}
@Override
public void onExposureChanged(String deviceName, double exposure) {
if (deviceName.equals(cameraLabel_)){
// update exposure in gui
textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure));
}
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.exposureChanged(deviceName, exposure);
}
}
}
private class PluginItem {
public Class<?> pluginClass = null;
public String menuItem = "undefined";
public MMPlugin plugin = null;
public String className = "";
public void instantiate() {
try {
if (plugin == null) {
plugin = (MMPlugin) pluginClass.newInstance();
}
} catch (InstantiationException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
plugin.setApp(MMStudioMainFrame.this);
}
}
/*
* Simple class used to cache static info
*/
private class StaticInfo {
public long width_;
public long height_;
public long bytesPerPixel_;
public long imageBitDepth_;
public double pixSizeUm_;
public double zPos_;
public double x_;
public double y_;
}
private StaticInfo staticInfo_ = new StaticInfo();
private void setupWindowHandlers() {
// add window listeners
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
closeSequence(false);
}
@Override
public void windowOpened(WindowEvent e) {
// -------------------
// initialize hardware
// -------------------
try {
core_ = new CMMCore();
} catch(UnsatisfiedLinkError ex) {
ReportingUtils.showError(ex, "Failed to load the MMCoreJ_wrap native library");
return;
}
ReportingUtils.setCore(core_);
logStartupProperties();
cameraLabel_ = "";
shutterLabel_ = "";
zStageLabel_ = "";
xyStageLabel_ = "";
engine_ = new AcquisitionWrapperEngine(acqMgr_);
// processorStackManager_ = new ProcessorStackManager(engine_);
// register callback for MMCore notifications, this is a global
// to avoid garbage collection
cb_ = new CoreEventCallback();
core_.registerCallback(cb_);
try {
core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_);
} catch (Exception e2) {
ReportingUtils.showError(e2);
}
MMStudioMainFrame parent = (MMStudioMainFrame) e.getWindow();
if (parent != null) {
engine_.setParentGUI(parent);
}
loadMRUConfigFiles();
afMgr_ = new AutofocusManager(gui_);
Thread pluginLoader = initializePlugins();
toFront();
if (!options_.doNotAskForConfigFile_) {
MMIntroDlg introDlg = new MMIntroDlg(MMVersion.VERSION_STRING, MRUConfigFiles_);
introDlg.setConfigFile(sysConfigFile_);
introDlg.setBackground(guiColors_.background.get((options_.displayBackground_)));
introDlg.setVisible(true);
if (!introDlg.okChosen()) {
closeSequence(false);
return;
}
sysConfigFile_ = introDlg.getConfigFile();
}
saveMRUConfigFiles();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
paint(MMStudioMainFrame.this.getGraphics());
engine_.setCore(core_, afMgr_);
posList_ = new PositionList();
engine_.setPositionList(posList_);
// load (but do no show) the scriptPanel
createScriptPanel();
// Create an instance of HotKeys so that they can be read in from prefs
hotKeys_ = new org.micromanager.utils.HotKeys();
hotKeys_.loadSettings();
// before loading the system configuration, we need to wait
// until the plugins are loaded
try {
pluginLoader.join(2000);
} catch (InterruptedException ex) {
ReportingUtils.logError(ex, "Plugin loader thread was interupted");
}
// if an error occurred during config loading,
// do not display more errors than needed
if (!loadSystemConfiguration())
ReportingUtils.showErrorOn(false);
executeStartupScript();
// Create Multi-D window here but do not show it.
// This window needs to be created in order to properly set the "ChannelGroup"
// based on the Multi-D parameters
acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, MMStudioMainFrame.this, options_);
addMMBackgroundListener(acqControlWin_);
configPad_.setCore(core_);
if (parent != null) {
configPad_.setParentGUI(parent);
}
configPadButtonPanel_.setCore(core_);
// initialize controls
// initializeGUI(); Not needed since it is already called in loadSystemConfiguration
initializeHelpMenu();
String afDevice = mainPrefs_.get(AUTOFOCUS_DEVICE, "");
if (afMgr_.hasDevice(afDevice)) {
try {
afMgr_.selectDevice(afDevice);
} catch (MMException e1) {
// this error should never happen
ReportingUtils.showError(e1);
}
}
centerAndDragListener_ = new CenterAndDragListener(gui_);
zWheelListener_ = new ZWheelListener(core_, gui_);
gui_.addLiveModeListener(zWheelListener_);
xyzKeyListener_ = new XYZKeyListener(core_, gui_);
gui_.addLiveModeListener(xyzKeyListener_);
// switch error reporting back on
ReportingUtils.showErrorOn(true);
}
private Thread initializePlugins() {
pluginMenu_ = GUIUtils.createMenuInMenuBar(menuBar_, "Plugins");
Thread myThread = new ThreadPluginLoading("Plugin loading");
myThread.start();
return myThread;
}
class ThreadPluginLoading extends Thread {
public ThreadPluginLoading(String string) {
super(string);
}
@Override
public void run() {
// Needed for loading clojure-based jars:
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
loadPlugins();
}
}
});
}
/**
* Main procedure for stand alone operation.
*/
public static void main(String args[]) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
MMStudioMainFrame frame = new MMStudioMainFrame(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
} catch (Throwable e) {
ReportingUtils.showError(e, "A java error has caused Micro-Manager to exit.");
System.exit(1);
}
}
@SuppressWarnings("LeakingThisInConstructor")
public MMStudioMainFrame(boolean pluginStatus) {
org.micromanager.diagnostics.ThreadExceptionLogger.setUp();
startLoadingPipelineClass();
options_ = new MMOptions();
try {
options_.loadSettings();
} catch (NullPointerException ex) {
ReportingUtils.logError(ex);
}
UIMonitor.enable(options_.debugLogEnabled_);
guiColors_ = new GUIColors();
plugins_ = new ArrayList<PluginItem>();
gui_ = this;
runsAsPlugin_ = pluginStatus;
setIconImage(SwingResourceManager.getImage(MMStudioMainFrame.class,
"icons/microscope.gif"));
running_ = true;
acqMgr_ = new AcquisitionManager();
sysConfigFile_ = System.getProperty("user.dir") + "/"
+ DEFAULT_CONFIG_FILE_NAME;
if (options_.startupScript_.length() > 0) {
startupScriptFile_ = System.getProperty("user.dir") + "/"
+ options_.startupScript_;
} else {
startupScriptFile_ = "";
}
ReportingUtils.SetContainingFrame(gui_);
// set the location for app preferences
try {
mainPrefs_ = Preferences.userNodeForPackage(this.getClass());
} catch (Exception e) {
ReportingUtils.logError(e);
}
systemPrefs_ = mainPrefs_;
colorPrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + "/" +
AcqControlDlg.COLOR_SETTINGS_NODE);
exposurePrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + "/" +
EXPOSURE_SETTINGS_NODE);
contrastPrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + "/" +
CONTRAST_SETTINGS_NODE);
// check system preferences
try {
Preferences p = Preferences.systemNodeForPackage(this.getClass());
if (null != p) {
// if we can not write to the systemPrefs, use AppPrefs instead
if (JavaUtils.backingStoreAvailable(p)) {
systemPrefs_ = p;
}
}
} catch (Exception e) {
ReportingUtils.logError(e);
}
showRegistrationDialogMaybe();
// load application preferences
// NOTE: only window size and position preferences are loaded,
// not the settings for the camera and live imaging -
// attempting to set those automatically on startup may cause problems
// with the hardware
int x = mainPrefs_.getInt(MAIN_FRAME_X, 100);
int y = mainPrefs_.getInt(MAIN_FRAME_Y, 100);
int width = mainPrefs_.getInt(MAIN_FRAME_WIDTH, 644);
int height = mainPrefs_.getInt(MAIN_FRAME_HEIGHT, 570);
openAcqDirectory_ = mainPrefs_.get(OPEN_ACQ_DIR, "");
try {
ImageUtils.setImageStorageClass(Class.forName (mainPrefs_.get(MAIN_SAVE_METHOD,
ImageUtils.getImageStorageClass().getName()) ) );
} catch (ClassNotFoundException ex) {
ReportingUtils.logError(ex, "Class not found error. Should never happen");
}
ToolTipManager ttManager = ToolTipManager.sharedInstance();
ttManager.setDismissDelay(TOOLTIP_DISPLAY_DURATION_MILLISECONDS);
ttManager.setInitialDelay(TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS);
setBounds(x, y, width, height);
setExitStrategy(options_.closeOnExit_);
setTitle(MICRO_MANAGER_TITLE + " " + MMVersion.VERSION_STRING);
setBackground(guiColors_.background.get((options_.displayBackground_)));
setMinimumSize(new Dimension(605,480));
menuBar_ = new JMenuBar();
switchConfigurationMenu_ = new JMenu();
setJMenuBar(menuBar_);
initializeFileMenu();
initializeToolsMenu();
splitPane_ = createSplitPane(mainPrefs_.getInt(MAIN_FRAME_DIVIDER_POS, 200));
getContentPane().add(splitPane_);
createTopPanelWidgets((JPanel) splitPane_.getComponent(0));
metadataPanel_ = createMetadataPanel((JPanel) splitPane_.getComponent(1));
setupWindowHandlers();
// Add our own keyboard manager that handles Micro-Manager shortcuts
MMKeyDispatcher mmKD = new MMKeyDispatcher(gui_);
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(mmKD);
dt_ = new DropTarget(this, new DragDropUtil());
}
private void handleException(Exception e, String msg) {
String errText = "Exception occurred: ";
if (msg.length() > 0) {
errText += msg + " -- ";
}
if (options_.debugLogEnabled_) {
errText += e.getMessage();
} else {
errText += e.toString() + "\n";
ReportingUtils.showError(e);
}
handleError(errText);
}
private void handleException(Exception e) {
handleException(e, "");
}
private void handleError(String message) {
if (isLiveModeOn()) {
// Should we always stop live mode on any error?
enableLiveMode(false);
}
JOptionPane.showMessageDialog(this, message);
core_.logMessage(message);
}
@Override
public void makeActive() {
toFront();
}
/**
* used to store contrast settings to be later used for initialization of contrast of new windows.
* Shouldn't be called by loaded data sets, only
* ones that have been acquired
*/
public void saveChannelHistogramSettings(String channelGroup, String channel, boolean mda,
HistogramSettings settings) {
String type = mda ? "MDA_" : "SnapLive_";
if (options_.syncExposureMainAndMDA_) {
type = ""; //only one group of contrast settings
}
contrastPrefs_.putInt("ContrastMin_" + channelGroup + "_" + type + channel, settings.min_);
contrastPrefs_.putInt("ContrastMax_" + channelGroup + "_" + type + channel, settings.max_);
contrastPrefs_.putDouble("ContrastGamma_" + channelGroup + "_" + type + channel, settings.gamma_);
contrastPrefs_.putInt("ContrastHistMax_" + channelGroup + "_" + type + channel, settings.histMax_);
contrastPrefs_.putInt("ContrastHistDisplayMode_" + channelGroup + "_" + type + channel, settings.displayMode_);
}
public HistogramSettings loadStoredChannelHisotgramSettings(String channelGroup, String channel, boolean mda) {
String type = mda ? "MDA_" : "SnapLive_";
if (options_.syncExposureMainAndMDA_) {
type = ""; //only one group of contrast settings
}
return new HistogramSettings(
contrastPrefs_.getInt("ContrastMin_" + channelGroup + "_" + type + channel,0),
contrastPrefs_.getInt("ContrastMax_" + channelGroup + "_" + type + channel, 65536),
contrastPrefs_.getDouble("ContrastGamma_" + channelGroup + "_" + type + channel, 1.0),
contrastPrefs_.getInt("ContrastHistMax_" + channelGroup + "_" + type + channel, -1),
contrastPrefs_.getInt("ContrastHistDisplayMode_" + channelGroup + "_" + type + channel, 1) );
}
private void setExposure() {
try {
if (!isLiveModeOn()) {
core_.setExposure(NumberUtils.displayStringToDouble(
textFieldExp_.getText()));
} else {
liveModeTimer_.stop();
core_.setExposure(NumberUtils.displayStringToDouble(
textFieldExp_.getText()));
try {
liveModeTimer_.begin();
} catch (Exception e) {
ReportingUtils.showError("Couldn't restart live mode");
liveModeTimer_.stop();
}
}
// Display the new exposure time
double exposure = core_.getExposure();
textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure));
// update current channel in MDA window with this exposure
String channelGroup = core_.getChannelGroup();
String channel = core_.getCurrentConfigFromCache(channelGroup);
if (!channel.equals("") ) {
exposurePrefs_.putDouble("Exposure_" + channelGroup + "_"
+ channel, exposure);
if (options_.syncExposureMainAndMDA_) {
getAcqDlg().setChannelExposureTime(channelGroup, channel, exposure);
}
}
} catch (Exception exp) {
// Do nothing.
}
}
/**
* Returns exposure time for the desired preset in the given channelgroup
* Acquires its info from the preferences
* Same thing is used in MDA window, but this class keeps its own copy
*
* @param channelGroup
* @param channel -
* @param defaultExp - default value
* @return exposure time
*/
@Override
public double getChannelExposureTime(String channelGroup, String channel,
double defaultExp) {
return exposurePrefs_.getDouble("Exposure_" + channelGroup
+ "_" + channel, defaultExp);
}
/**
* Updates the exposure time in the given preset
* Will also update current exposure if it the given channel and channelgroup
* are the current one
*
* @param channelGroup -
*
* @param channel - preset for which to change exposure time
* @param exposure - desired exposure time
*/
@Override
public void setChannelExposureTime(String channelGroup, String channel,
double exposure) {
try {
exposurePrefs_.putDouble("Exposure_" + channelGroup + "_"
+ channel, exposure);
if (channelGroup != null && channelGroup.equals(core_.getChannelGroup())) {
if (channel != null && !channel.equals("") &&
channel.equals(core_.getCurrentConfigFromCache(channelGroup))) {
textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure));
setExposure();
}
}
} catch (Exception ex) {
ReportingUtils.logError("Failed to set Exposure prefs using Channelgroup: "
+ channelGroup + ", channel: " + channel + ", exposure: " + exposure);
}
}
@Override
public boolean getAutoreloadOption() {
return options_.autoreloadDevices_;
}
public double getPreferredWindowMag() {
return options_.windowMag_;
}
public boolean getMetadataFileWithMultipageTiff() {
return options_.mpTiffMetadataFile_;
}
public boolean getSeparateFilesForPositionsMPTiff() {
return options_.mpTiffSeparateFilesForPositions_;
}
@Override
public boolean getHideMDADisplayOption() {
return options_.hideMDADisplay_;
}
private void updateTitle() {
this.setTitle(MICRO_MANAGER_TITLE + " " + MMVersion.VERSION_STRING + " - " + sysConfigFile_);
}
public void updateLineProfile() {
if (WindowManager.getCurrentWindow() == null || profileWin_ == null
|| !profileWin_.isShowing()) {
return;
}
calculateLineProfileData(WindowManager.getCurrentImage());
profileWin_.setData(lineProfileData_);
}
private void openLineProfileWindow() {
if (WindowManager.getCurrentWindow() == null || WindowManager.getCurrentWindow().isClosed()) {
return;
}
calculateLineProfileData(WindowManager.getCurrentImage());
if (lineProfileData_ == null) {
return;
}
profileWin_ = new GraphFrame();
profileWin_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
profileWin_.setData(lineProfileData_);
profileWin_.setAutoScale();
profileWin_.setTitle("Live line profile");
profileWin_.setBackground(guiColors_.background.get((options_.displayBackground_)));
addMMBackgroundListener(profileWin_);
profileWin_.setVisible(true);
}
@Override
public Rectangle getROI() throws MMScriptException {
// ROI values are given as x,y,w,h in individual one-member arrays (pointers in C++):
int[][] a = new int[4][1];
try {
core_.getROI(a[0], a[1], a[2], a[3]);
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
// Return as a single array with x,y,w,h:
return new Rectangle(a[0][0], a[1][0], a[2][0], a[3][0]);
}
private void calculateLineProfileData(ImagePlus imp) {
// generate line profile
Roi roi = imp.getRoi();
if (roi == null || !roi.isLine()) {
// if there is no line ROI, create one
Rectangle r = imp.getProcessor().getRoi();
int iWidth = r.width;
int iHeight = r.height;
int iXROI = r.x;
int iYROI = r.y;
if (roi == null) {
iXROI += iWidth / 2;
iYROI += iHeight / 2;
}
roi = new Line(iXROI - iWidth / 4, iYROI - iWidth / 4, iXROI
+ iWidth / 4, iYROI + iHeight / 4);
imp.setRoi(roi);
roi = imp.getRoi();
}
ImageProcessor ip = imp.getProcessor();
ip.setInterpolate(true);
Line line = (Line) roi;
if (lineProfileData_ == null) {
lineProfileData_ = new GraphData();
}
lineProfileData_.setData(line.getPixels());
}
@Override
public void setROI(Rectangle r) throws MMScriptException {
boolean liveRunning = false;
if (isLiveModeOn()) {
liveRunning = true;
enableLiveMode(false);
}
try {
core_.setROI(r.x, r.y, r.width, r.height);
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
}
private void setROI() {
ImagePlus curImage = WindowManager.getCurrentImage();
if (curImage == null) {
return;
}
Roi roi = curImage.getRoi();
try {
if (roi == null) {
// if there is no ROI, create one
Rectangle r = curImage.getProcessor().getRoi();
int iWidth = r.width;
int iHeight = r.height;
int iXROI = r.x;
int iYROI = r.y;
if (roi == null) {
iWidth /= 2;
iHeight /= 2;
iXROI += iWidth / 2;
iYROI += iHeight / 2;
}
curImage.setRoi(iXROI, iYROI, iWidth, iHeight);
roi = curImage.getRoi();
}
if (roi.getType() != Roi.RECTANGLE) {
handleError("ROI must be a rectangle.\nUse the ImageJ rectangle tool to draw the ROI.");
return;
}
Rectangle r = roi.getBounds();
// if we already had an ROI defined, correct for the offsets
Rectangle cameraR = getROI();
r.x += cameraR.x;
r.y += cameraR.y;
// Stop (and restart) live mode if it is running
setROI(r);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
private void clearROI() {
try {
boolean liveRunning = false;
if (isLiveModeOn()) {
liveRunning = true;
enableLiveMode(false);
}
core_.clearROI();
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
/**
* Returns instance of the core uManager object;
*/
@Override
public CMMCore getMMCore() {
return core_;
}
/**
* Returns singleton instance of MMStudioMainFrame
*/
public static MMStudioMainFrame getInstance() {
return gui_;
}
public MetadataPanel getMetadataPanel() {
return metadataPanel_;
}
public final void setExitStrategy(boolean closeOnExit) {
if (closeOnExit) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
else {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
@Override
public void saveConfigPresets() {
MicroscopeModel model = new MicroscopeModel();
try {
model.loadFromFile(sysConfigFile_);
model.createSetupConfigsFromHardware(core_);
model.createResolutionsFromHardware(core_);
File f = FileDialogs.save(this, "Save the configuration file", MM_CONFIG_FILE);
if (f != null) {
model.saveToFile(f.getAbsolutePath());
sysConfigFile_ = f.getAbsolutePath();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
configChanged_ = false;
setConfigSaveButtonStatus(configChanged_);
updateTitle();
}
} catch (MMConfigFileException e) {
ReportingUtils.showError(e);
}
}
protected void setConfigSaveButtonStatus(boolean changed) {
saveConfigButton_.setEnabled(changed);
}
public String getAcqDirectory() {
return openAcqDirectory_;
}
/**
* Get currently used configuration file
* @return - Path to currently used configuration file
*/
public String getSysConfigFile() {
return sysConfigFile_;
}
public void setAcqDirectory(String dir) {
openAcqDirectory_ = dir;
}
/**
* Open an existing acquisition directory and build viewer window.
*
*/
public void openAcquisitionData(boolean inRAM) {
// choose the directory
// --------------------
File f = FileDialogs.openDir(this, "Please select an image data set", MM_DATA_SET);
if (f != null) {
if (f.isDirectory()) {
openAcqDirectory_ = f.getAbsolutePath();
} else {
openAcqDirectory_ = f.getParent();
}
String acq = null;
try {
acq = openAcquisitionData(openAcqDirectory_, inRAM);
} catch (MMScriptException ex) {
ReportingUtils.showError(ex);
} finally {
try {
acqMgr_.closeAcquisition(acq);
} catch (MMScriptException ex) {
ReportingUtils.logError(ex);
}
}
}
}
@Override
public String openAcquisitionData(String dir, boolean inRAM, boolean show)
throws MMScriptException {
String rootDir = new File(dir).getAbsolutePath();
String name = new File(dir).getName();
rootDir = rootDir.substring(0, rootDir.length() - (name.length() + 1));
name = acqMgr_.getUniqueAcquisitionName(name);
acqMgr_.openAcquisition(name, rootDir, show, !inRAM, true);
try {
getAcquisition(name).initialize();
} catch (MMScriptException mex) {
acqMgr_.closeAcquisition(name);
throw (mex);
}
return name;
}
/**
* Opens an existing data set. Shows the acquisition in a window.
* @return The acquisition object.
*/
@Override
public String openAcquisitionData(String dir, boolean inRam) throws MMScriptException {
return openAcquisitionData(dir, inRam, true);
}
protected void zoomOut() {
ImageWindow curWin = WindowManager.getCurrentWindow();
if (curWin != null) {
ImageCanvas canvas = curWin.getCanvas();
Rectangle r = canvas.getBounds();
canvas.zoomOut(r.width / 2, r.height / 2);
VirtualAcquisitionDisplay vad = VirtualAcquisitionDisplay.getDisplay(curWin.getImagePlus());
if (vad != null) {
vad.storeWindowSizeAfterZoom(curWin);
vad.updateWindowTitleAndStatus();
}
}
}
protected void zoomIn() {
ImageWindow curWin = WindowManager.getCurrentWindow();
if (curWin != null) {
ImageCanvas canvas = curWin.getCanvas();
Rectangle r = canvas.getBounds();
canvas.zoomIn(r.width / 2, r.height / 2);
VirtualAcquisitionDisplay vad = VirtualAcquisitionDisplay.getDisplay(curWin.getImagePlus());
if (vad != null) {
vad.storeWindowSizeAfterZoom(curWin);
vad.updateWindowTitleAndStatus();
}
}
}
protected void changeBinning() {
try {
boolean liveRunning = false;
if (isLiveModeOn() ) {
liveRunning = true;
enableLiveMode(false);
}
if (isCameraAvailable()) {
Object item = comboBinning_.getSelectedItem();
if (item != null) {
core_.setProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning(), item.toString());
}
}
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
private void createPropertyEditor() {
if (propertyBrowser_ != null) {
propertyBrowser_.dispose();
}
propertyBrowser_ = new PropertyEditor();
propertyBrowser_.setGui(this);
propertyBrowser_.setVisible(true);
propertyBrowser_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
propertyBrowser_.setCore(core_);
}
private void createCalibrationListDlg() {
if (calibrationListDlg_ != null) {
calibrationListDlg_.dispose();
}
calibrationListDlg_ = new CalibrationListDlg(core_);
calibrationListDlg_.setVisible(true);
calibrationListDlg_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
calibrationListDlg_.setParentGUI(this);
}
public CalibrationListDlg getCalibrationListDlg() {
if (calibrationListDlg_ == null) {
createCalibrationListDlg();
}
return calibrationListDlg_;
}
private void createScriptPanel() {
if (scriptPanel_ == null) {
scriptPanel_ = new ScriptPanel(core_, options_, this);
scriptPanel_.insertScriptingObject(SCRIPT_CORE_OBJECT, core_);
scriptPanel_.insertScriptingObject(SCRIPT_ACQENG_OBJECT, engine_);
scriptPanel_.setParentGUI(this);
scriptPanel_.setBackground(guiColors_.background.get((options_.displayBackground_)));
addMMBackgroundListener(scriptPanel_);
}
}
/**
* Updates Status line in main window from cached values
*/
private void updateStaticInfoFromCache() {
String dimText = "Image info (from camera): " + staticInfo_.width_ + " X " + staticInfo_.height_ + " X "
+ staticInfo_.bytesPerPixel_ + ", Intensity range: " + staticInfo_.imageBitDepth_ + " bits";
dimText += ", " + TextUtils.FMT0.format(staticInfo_.pixSizeUm_ * 1000) + "nm/pix";
if (zStageLabel_.length() > 0) {
dimText += ", Z=" + TextUtils.FMT2.format(staticInfo_.zPos_) + "um";
}
if (xyStageLabel_.length() > 0) {
dimText += ", XY=(" + TextUtils.FMT2.format(staticInfo_.x_) + "," + TextUtils.FMT2.format(staticInfo_.y_) + ")um";
}
labelImageDimensions_.setText(dimText);
}
public void updateXYPos(double x, double y) {
staticInfo_.x_ = x;
staticInfo_.y_ = y;
updateStaticInfoFromCache();
}
public void updateZPos(double z) {
staticInfo_.zPos_ = z;
updateStaticInfoFromCache();
}
public void updateXYPosRelative(double x, double y) {
staticInfo_.x_ += x;
staticInfo_.y_ += y;
updateStaticInfoFromCache();
}
public void updateZPosRelative(double z) {
staticInfo_.zPos_ += z;
updateStaticInfoFromCache();
}
public void updateXYStagePosition(){
double x[] = new double[1];
double y[] = new double[1];
try {
if (xyStageLabel_.length() > 0)
core_.getXYPosition(xyStageLabel_, x, y);
} catch (Exception e) {
ReportingUtils.showError(e);
}
staticInfo_.x_ = x[0];
staticInfo_.y_ = y[0];
updateStaticInfoFromCache();
}
private void updatePixSizeUm (double pixSizeUm) {
staticInfo_.pixSizeUm_ = pixSizeUm;
updateStaticInfoFromCache();
}
private void updateStaticInfo() {
double zPos = 0.0;
double x[] = new double[1];
double y[] = new double[1];
try {
if (zStageLabel_.length() > 0) {
zPos = core_.getPosition(zStageLabel_);
}
if (xyStageLabel_.length() > 0) {
core_.getXYPosition(xyStageLabel_, x, y);
}
} catch (Exception e) {
handleException(e);
}
staticInfo_.width_ = core_.getImageWidth();
staticInfo_.height_ = core_.getImageHeight();
staticInfo_.bytesPerPixel_ = core_.getBytesPerPixel();
staticInfo_.imageBitDepth_ = core_.getImageBitDepth();
staticInfo_.pixSizeUm_ = core_.getPixelSizeUm();
staticInfo_.zPos_ = zPos;
staticInfo_.x_ = x[0];
staticInfo_.y_ = y[0];
updateStaticInfoFromCache();
}
public void toggleShutter() {
try {
if (!toggleShutterButton_.isEnabled())
return;
toggleShutterButton_.requestFocusInWindow();
if (toggleShutterButton_.getText().equals("Open")) {
setShutterButton(true);
core_.setShutterOpen(true);
} else {
core_.setShutterOpen(false);
setShutterButton(false);
}
} catch (Exception e1) {
ReportingUtils.showError(e1);
}
}
private void updateCenterAndDragListener() {
if (centerAndDragMenuItem_.isSelected()) {
centerAndDragListener_.start();
} else {
centerAndDragListener_.stop();
}
}
private void setShutterButton(boolean state) {
if (state) {
toggleShutterButton_.setText("Close");
} else {
toggleShutterButton_.setText("Open");
}
}
// //////////////////////////////////////////////////////////////////////////
// public interface available for scripting access
// //////////////////////////////////////////////////////////////////////////
@Override
public void snapSingleImage() {
doSnap();
}
public Object getPixels() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip != null) {
return ip.getProcessor().getPixels();
}
return null;
}
public void setPixels(Object obj) {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip == null) {
return;
}
ip.getProcessor().setPixels(obj);
}
public int getImageHeight() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip != null)
return ip.getHeight();
return 0;
}
public int getImageWidth() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip != null)
return ip.getWidth();
return 0;
}
public int getImageDepth() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip != null)
return ip.getBitDepth();
return 0;
}
public ImageProcessor getImageProcessor() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip == null)
return null;
return ip.getProcessor();
}
private boolean isCameraAvailable() {
return cameraLabel_.length() > 0;
}
/**
* Part of ScriptInterface API
* Opens the XYPositionList when it is not opened
* Adds the current position to the list (same as pressing the "Mark" button)
*/
@Override
public void markCurrentPosition() {
if (posListDlg_ == null) {
showXYPositionList();
}
if (posListDlg_ != null) {
posListDlg_.markPosition();
}
}
/**
* Implements ScriptInterface
*/
@Override
public AcqControlDlg getAcqDlg() {
return acqControlWin_;
}
/**
* Implements ScriptInterface
*/
@Override
public PositionListDlg getXYPosListDlg() {
if (posListDlg_ == null)
posListDlg_ = new PositionListDlg(core_, this, posList_, options_);
return posListDlg_;
}
/**
* Implements ScriptInterface
*/
@Override
public boolean isAcquisitionRunning() {
if (engine_ == null)
return false;
return engine_.isAcquisitionRunning();
}
/**
* Implements ScriptInterface
*/
@Override
public boolean versionLessThan(String version) throws MMScriptException {
try {
String[] v = MMVersion.VERSION_STRING.split(" ", 2);
String[] m = v[0].split("\\.", 3);
String[] v2 = version.split(" ", 2);
String[] m2 = v2[0].split("\\.", 3);
for (int i=0; i < 3; i++) {
if (Integer.parseInt(m[i]) < Integer.parseInt(m2[i])) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return true;
}
if (Integer.parseInt(m[i]) > Integer.parseInt(m2[i])) {
return false;
}
}
if (v2.length < 2 || v2[1].equals("") )
return false;
if (v.length < 2 ) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return true;
}
if (Integer.parseInt(v[1]) < Integer.parseInt(v2[1])) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return false;
}
return true;
} catch (Exception ex) {
throw new MMScriptException ("Format of version String should be \"a.b.c\"");
}
}
@Override
public boolean isLiveModeOn() {
return liveModeTimer_ != null && liveModeTimer_.isRunning();
}
public LiveModeTimer getLiveModeTimer() {
if (liveModeTimer_ == null) {
liveModeTimer_ = new LiveModeTimer();
}
return liveModeTimer_;
}
@Override
public void enableLiveMode(boolean enable) {
if (core_ == null) {
return;
}
if (enable == isLiveModeOn()) {
return;
}
if (enable) {
try {
if (core_.getCameraDevice().length() == 0) {
ReportingUtils.showError("No camera configured");
updateButtonsForLiveMode(false);
return;
}
if (liveModeTimer_ == null) {
liveModeTimer_ = new LiveModeTimer();
}
liveModeTimer_.begin();
callLiveModeListeners(enable);
} catch (Exception e) {
ReportingUtils.showError(e);
liveModeTimer_.stop();
callLiveModeListeners(false);
updateButtonsForLiveMode(false);
return;
}
} else {
liveModeTimer_.stop();
callLiveModeListeners(enable);
}
updateButtonsForLiveMode(enable);
}
public void updateButtonsForLiveMode(boolean enable) {
autoShutterCheckBox_.setEnabled(!enable);
if (core_.getAutoShutter()) {
toggleShutterButton_.setText(enable ? "Close" : "Open" );
}
snapButton_.setEnabled(!enable);
//toAlbumButton_.setEnabled(!enable);
liveButton_.setIcon(enable ? SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/cancel.png")
: SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/camera_go.png"));
liveButton_.setSelected(false);
liveButton_.setText(enable ? "Stop Live" : "Live");
}
public boolean getLiveMode() {
return isLiveModeOn();
}
public boolean updateImage() {
try {
if (isLiveModeOn()) {
enableLiveMode(false);
return true; // nothing to do, just show the last image
}
if (WindowManager.getCurrentWindow() == null) {
return false;
}
ImagePlus ip = WindowManager.getCurrentImage();
core_.snapImage();
Object img = core_.getImage();
ip.getProcessor().setPixels(img);
ip.updateAndRepaintWindow();
if (!isCurrentImageFormatSupported()) {
return false;
}
updateLineProfile();
} catch (Exception e) {
ReportingUtils.showError(e);
return false;
}
return true;
}
public boolean displayImage(final Object pixels) {
if (pixels instanceof TaggedImage) {
return displayTaggedImage((TaggedImage) pixels, true);
} else {
return displayImage(pixels, true);
}
}
public boolean displayImage(final Object pixels, boolean wait) {
checkSimpleAcquisition();
try {
int width = getAcquisition(SIMPLE_ACQ).getWidth();
int height = getAcquisition(SIMPLE_ACQ).getHeight();
int byteDepth = getAcquisition(SIMPLE_ACQ).getByteDepth();
TaggedImage ti = ImageUtils.makeTaggedImage(pixels, 0, 0, 0,0, width, height, byteDepth);
simpleDisplay_.getImageCache().putImage(ti);
simpleDisplay_.showImage(ti, wait);
return true;
} catch (Exception ex) {
ReportingUtils.showError(ex);
return false;
}
}
public boolean displayImageWithStatusLine(Object pixels, String statusLine) {
boolean ret = displayImage(pixels);
simpleDisplay_.displayStatusLine(statusLine);
return ret;
}
public void displayStatusLine(String statusLine) {
ImagePlus ip = WindowManager.getCurrentImage();
if (!(ip.getWindow() instanceof VirtualAcquisitionDisplay.DisplayWindow)) {
return;
}
VirtualAcquisitionDisplay.getDisplay(ip).displayStatusLine(statusLine);
}
private boolean isCurrentImageFormatSupported() {
boolean ret = false;
long channels = core_.getNumberOfComponents();
long bpp = core_.getBytesPerPixel();
if (channels > 1 && channels != 4 && bpp != 1) {
handleError("Unsupported image format.");
} else {
ret = true;
}
return ret;
}
public void doSnap() {
doSnap(false);
}
public void doSnap(final boolean album) {
if (core_.getCameraDevice().length() == 0) {
ReportingUtils.showError("No camera configured");
return;
}
BlockingQueue<TaggedImage> snapImageQueue =
new LinkedBlockingQueue<TaggedImage>();
try {
core_.snapImage();
long c = core_.getNumberOfCameraChannels();
runDisplayThread(snapImageQueue, new DisplayImageRoutine() {
@Override
public void show(final TaggedImage image) {
if (album) {
try {
addToAlbum(image);
} catch (MMScriptException ex) {
ReportingUtils.showError(ex);
}
} else {
displayImage(image);
}
}
});
for (int i = 0; i < c; ++i) {
TaggedImage img = core_.getTaggedImage(i);
img.tags.put("Channels", c);
snapImageQueue.put(img);
}
snapImageQueue.put(TaggedImageQueue.POISON);
if (simpleDisplay_ != null) {
ImagePlus imgp = simpleDisplay_.getImagePlus();
if (imgp != null) {
ImageWindow win = imgp.getWindow();
if (win != null) {
win.toFront();
}
}
}
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
}
/**
* Is this function still needed? It does some magic with tags. I found
* it to do harmful thing with tags when a Multi-Camera device is
* present (that issue is now fixed).
*/
public void normalizeTags(TaggedImage ti) {
if (ti != TaggedImageQueue.POISON) {
int channel = 0;
try {
if (ti.tags.has("ChannelIndex")) {
channel = MDUtils.getChannelIndex(ti.tags);
}
MDUtils.setChannelIndex(ti.tags, channel);
MDUtils.setPositionIndex(ti.tags, 0);
MDUtils.setSliceIndex(ti.tags, 0);
MDUtils.setFrameIndex(ti.tags, 0);
} catch (JSONException ex) {
ReportingUtils.logError(ex);
}
}
}
@Override
public boolean displayImage(TaggedImage ti) {
normalizeTags(ti);
return displayTaggedImage(ti, true);
}
private boolean displayTaggedImage(TaggedImage ti, boolean update) {
try {
checkSimpleAcquisition(ti);
setCursor(new Cursor(Cursor.WAIT_CURSOR));
ti.tags.put("Summary", getAcquisition(SIMPLE_ACQ).getSummaryMetadata());
addStagePositionToTags(ti);
addImage(SIMPLE_ACQ, ti, update, true);
} catch (Exception ex) {
ReportingUtils.logError(ex);
return false;
}
if (update) {
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
updateLineProfile();
}
return true;
}
public void addStagePositionToTags(TaggedImage ti) throws JSONException {
if (gui_.xyStageLabel_.length() > 0) {
ti.tags.put("XPositionUm", gui_.staticInfo_.x_);
ti.tags.put("YPositionUm", gui_.staticInfo_.y_);
}
if (gui_.zStageLabel_.length() > 0) {
ti.tags.put("ZPositionUm", gui_.staticInfo_.zPos_);
}
}
private void configureBinningCombo() throws Exception {
if (cameraLabel_.length() > 0) {
ActionListener[] listeners;
// binning combo
if (comboBinning_.getItemCount() > 0) {
comboBinning_.removeAllItems();
}
StrVector binSizes = core_.getAllowedPropertyValues(
cameraLabel_, MMCoreJ.getG_Keyword_Binning());
listeners = comboBinning_.getActionListeners();
for (int i = 0; i < listeners.length; i++) {
comboBinning_.removeActionListener(listeners[i]);
}
for (int i = 0; i < binSizes.size(); i++) {
comboBinning_.addItem(binSizes.get(i));
}
comboBinning_.setMaximumRowCount((int) binSizes.size());
if (binSizes.isEmpty()) {
comboBinning_.setEditable(true);
} else {
comboBinning_.setEditable(false);
}
for (int i = 0; i < listeners.length; i++) {
comboBinning_.addActionListener(listeners[i]);
}
}
}
public void initializeGUI() {
try {
// establish device roles
cameraLabel_ = core_.getCameraDevice();
shutterLabel_ = core_.getShutterDevice();
zStageLabel_ = core_.getFocusDevice();
xyStageLabel_ = core_.getXYStageDevice();
engine_.setZStageDevice(zStageLabel_);
configureBinningCombo();
// active shutter combo
try {
shutters_ = core_.getLoadedDevicesOfType(DeviceType.ShutterDevice);
} catch (Exception e) {
ReportingUtils.logError(e);
}
if (shutters_ != null) {
String items[] = new String[(int) shutters_.size()];
for (int i = 0; i < shutters_.size(); i++) {
items[i] = shutters_.get(i);
}
GUIUtils.replaceComboContents(shutterComboBox_, items);
String activeShutter = core_.getShutterDevice();
if (activeShutter != null) {
shutterComboBox_.setSelectedItem(activeShutter);
} else {
shutterComboBox_.setSelectedItem("");
}
}
// Autofocus
autofocusConfigureButton_.setEnabled(afMgr_.getDevice() != null);
autofocusNowButton_.setEnabled(afMgr_.getDevice() != null);
// Rebuild stage list in XY PositinList
if (posListDlg_ != null) {
posListDlg_.rebuildAxisList();
}
updateGUI(true);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
@Override
public String getVersion() {
return MMVersion.VERSION_STRING;
}
private void addPluginToMenu(final PluginItem plugin, Class<?> cl) {
// add plugin menu items
String toolTipDescription = "";
try {
// Get this static field from the class implementing MMPlugin.
toolTipDescription = (String) cl.getDeclaredField("tooltipDescription").get(null);
} catch (SecurityException e) {
ReportingUtils.logError(e);
toolTipDescription = "Description not available";
} catch (NoSuchFieldException e) {
toolTipDescription = "Description not available";
ReportingUtils.logMessage(cl.getName() + " fails to implement static String tooltipDescription.");
} catch (IllegalArgumentException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
GUIUtils.addMenuItem(pluginMenu_, plugin.menuItem, toolTipDescription,
new Runnable() {
public void run() {
ReportingUtils.logMessage("Plugin command: " + plugin.menuItem);
plugin.instantiate();
plugin.plugin.show();
}
});
pluginMenu_.validate();
menuBar_.validate();
}
public void updateGUI(boolean updateConfigPadStructure) {
updateGUI(updateConfigPadStructure, false);
}
public void updateGUI(boolean updateConfigPadStructure, boolean fromCache) {
try {
// establish device roles
cameraLabel_ = core_.getCameraDevice();
shutterLabel_ = core_.getShutterDevice();
zStageLabel_ = core_.getFocusDevice();
xyStageLabel_ = core_.getXYStageDevice();
afMgr_.refresh();
// camera settings
if (isCameraAvailable()) {
double exp = core_.getExposure();
textFieldExp_.setText(NumberUtils.doubleToDisplayString(exp));
configureBinningCombo();
String binSize;
if (fromCache) {
binSize = core_.getPropertyFromCache(cameraLabel_, MMCoreJ.getG_Keyword_Binning());
} else {
binSize = core_.getProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning());
}
GUIUtils.setComboSelection(comboBinning_, binSize);
}
if (liveModeTimer_ == null || !liveModeTimer_.isRunning()) {
autoShutterCheckBox_.setSelected(core_.getAutoShutter());
boolean shutterOpen = core_.getShutterOpen();
setShutterButton(shutterOpen);
if (autoShutterCheckBox_.isSelected()) {
toggleShutterButton_.setEnabled(false);
} else {
toggleShutterButton_.setEnabled(true);
}
}
// active shutter combo
if (shutters_ != null) {
String activeShutter = core_.getShutterDevice();
if (activeShutter != null) {
shutterComboBox_.setSelectedItem(activeShutter);
} else {
shutterComboBox_.setSelectedItem("");
}
}
// state devices
if (updateConfigPadStructure && (configPad_ != null)) {
configPad_.refreshStructure(fromCache);
// Needed to update read-only properties. May slow things down...
if (!fromCache)
core_.updateSystemStateCache();
}
// update Channel menus in Multi-dimensional acquisition dialog
updateChannelCombos();
// update list of pixel sizes in pixel size configuration window
if (calibrationListDlg_ != null) {
calibrationListDlg_.refreshCalibrations();
}
if (propertyBrowser_ != null) {
propertyBrowser_.refresh();
}
} catch (Exception e) {
ReportingUtils.logError(e);
}
updateStaticInfo();
updateTitle();
}
//TODO: Deprecated @Override
public boolean okToAcquire() {
return !isLiveModeOn();
}
//TODO: Deprecated @Override
public void stopAllActivity() {
if (this.acquisitionEngine2010 != null) {
this.acquisitionEngine2010.stop();
}
enableLiveMode(false);
}
/**
* Cleans up resources while shutting down
*
* @param calledByImageJ
* @return flag indicating success. Shut down should abort when flag is false
*/
private boolean cleanupOnClose(boolean calledByImageJ) {
// Save config presets if they were changed.
if (configChanged_) {
Object[] options = {"Yes", "No"};
int n = JOptionPane.showOptionDialog(null,
"Save Changed Configuration?", "Micro-Manager",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options, options[0]);
if (n == JOptionPane.YES_OPTION) {
saveConfigPresets();
// if the configChanged_ flag did not become false, the user
// must have cancelled the configuration saving and we should cancel
// quitting as well
if (configChanged_) {
return false;
}
}
}
if (liveModeTimer_ != null)
liveModeTimer_.stop();
// check needed to avoid deadlock
if (!calledByImageJ) {
if (!WindowManager.closeAllWindows()) {
core_.logMessage("Failed to close some windows");
}
}
if (profileWin_ != null) {
removeMMBackgroundListener(profileWin_);
profileWin_.dispose();
}
if (scriptPanel_ != null) {
removeMMBackgroundListener(scriptPanel_);
scriptPanel_.closePanel();
}
if (propertyBrowser_ != null) {
removeMMBackgroundListener(propertyBrowser_);
propertyBrowser_.dispose();
}
if (acqControlWin_ != null) {
removeMMBackgroundListener(acqControlWin_);
acqControlWin_.close();
}
if (engine_ != null) {
engine_.shutdown();
}
if (afMgr_ != null) {
afMgr_.closeOptionsDialog();
}
// dispose plugins
for (int i = 0; i < plugins_.size(); i++) {
MMPlugin plugin = plugins_.get(i).plugin;
if (plugin != null) {
plugin.dispose();
}
}
synchronized (shutdownLock_) {
try {
if (core_ != null) {
ReportingUtils.setCore(null);
core_.delete();
core_ = null;
}
} catch (Exception err) {
ReportingUtils.showError(err);
}
}
return true;
}
private void saveSettings() {
Rectangle r = this.getBounds();
mainPrefs_.putInt(MAIN_FRAME_X, r.x);
mainPrefs_.putInt(MAIN_FRAME_Y, r.y);
mainPrefs_.putInt(MAIN_FRAME_WIDTH, r.width);
mainPrefs_.putInt(MAIN_FRAME_HEIGHT, r.height);
mainPrefs_.putInt(MAIN_FRAME_DIVIDER_POS, this.splitPane_.getDividerLocation());
mainPrefs_.put(OPEN_ACQ_DIR, openAcqDirectory_);
mainPrefs_.put(MAIN_SAVE_METHOD,
ImageUtils.getImageStorageClass().getName());
// save field values from the main window
// NOTE: automatically restoring these values on startup may cause
// problems
mainPrefs_.put(MAIN_EXPOSURE, textFieldExp_.getText());
// NOTE: do not save auto shutter state
if (afMgr_ != null && afMgr_.getDevice() != null) {
mainPrefs_.put(AUTOFOCUS_DEVICE, afMgr_.getDevice().getDeviceName());
}
}
private void loadConfiguration() {
File f = FileDialogs.openFile(this, "Load a config file",MM_CONFIG_FILE);
if (f != null) {
sysConfigFile_ = f.getAbsolutePath();
configChanged_ = false;
setConfigSaveButtonStatus(configChanged_);
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
loadSystemConfiguration();
}
}
public synchronized boolean closeSequence(boolean calledByImageJ) {
if (!this.isRunning()) {
if (core_ != null) {
core_.logMessage("MMStudioMainFrame::closeSequence called while running_ is false");
}
return true;
}
if (engine_ != null && engine_.isAcquisitionRunning()) {
int result = JOptionPane.showConfirmDialog(
this,
"Acquisition in progress. Are you sure you want to exit and discard all data?",
"Micro-Manager", JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE);
if (result == JOptionPane.NO_OPTION) {
return false;
}
}
stopAllActivity();
try {
// Close all image windows associated with MM. Canceling saving of
// any of these should abort shutdown
if (!acqMgr_.closeAllImageWindows()) {
return false;
}
} catch (MMScriptException ex) {
// Not sure what to do here...
}
if (!cleanupOnClose(calledByImageJ)) {
return false;
}
running_ = false;
saveSettings();
try {
configPad_.saveSettings();
options_.saveSettings();
hotKeys_.saveSettings();
} catch (NullPointerException e) {
if (core_ != null)
this.logError(e);
}
// disposing sometimes hangs ImageJ!
// this.dispose();
if (options_.closeOnExit_) {
if (!runsAsPlugin_) {
System.exit(0);
} else {
ImageJ ij = IJ.getInstance();
if (ij != null) {
ij.quit();
}
}
} else {
this.dispose();
}
return true;
}
public void applyContrastSettings(ContrastSettings contrast8,
ContrastSettings contrast16) {
ImagePlus img = WindowManager.getCurrentImage();
if (img == null|| VirtualAcquisitionDisplay.getDisplay(img) == null )
return;
if (img.getBytesPerPixel() == 1)
VirtualAcquisitionDisplay.getDisplay(img).setChannelContrast(0,
contrast8.min, contrast8.max, contrast8.gamma);
else
VirtualAcquisitionDisplay.getDisplay(img).setChannelContrast(0,
contrast16.min, contrast16.max, contrast16.gamma);
}
//TODO: Deprecated @Override
public ContrastSettings getContrastSettings() {
ImagePlus img = WindowManager.getCurrentImage();
if (img == null || VirtualAcquisitionDisplay.getDisplay(img) == null )
return null;
return VirtualAcquisitionDisplay.getDisplay(img).getChannelContrastSettings(0);
}
public boolean is16bit() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip != null && ip.getProcessor() instanceof ShortProcessor) {
return true;
}
return false;
}
public boolean isRunning() {
return running_;
}
/**
* Executes the beanShell script. This script instance only supports
* commands directed to the core object.
*/
private void executeStartupScript() {
// execute startup script
File f = new File(startupScriptFile_);
if (startupScriptFile_.length() > 0 && f.exists()) {
WaitDialog waitDlg = new WaitDialog(
"Executing startup script, please wait...");
waitDlg.showDialog();
Interpreter interp = new Interpreter();
try {
// insert core object only
interp.set(SCRIPT_CORE_OBJECT, core_);
interp.set(SCRIPT_ACQENG_OBJECT, engine_);
interp.set(SCRIPT_GUI_OBJECT, this);
// read text file and evaluate
interp.eval(TextUtils.readTextFile(startupScriptFile_));
} catch (IOException exc) {
ReportingUtils.logError(exc, "Unable to read the startup script (" + startupScriptFile_ + ").");
} catch (EvalError exc) {
ReportingUtils.logError(exc);
} finally {
waitDlg.closeDialog();
}
} else {
if (startupScriptFile_.length() > 0)
ReportingUtils.logMessage("Startup script file ("+startupScriptFile_+") not present.");
}
}
/**
* Loads system configuration from the cfg file.
*/
private boolean loadSystemConfiguration() {
boolean result = true;
saveMRUConfigFiles();
final WaitDialog waitDlg = new WaitDialog(
"Loading system configuration, please wait...");
waitDlg.setAlwaysOnTop(true);
waitDlg.showDialog();
this.setEnabled(false);
try {
if (sysConfigFile_.length() > 0) {
GUIUtils.preventDisplayAdapterChangeExceptions();
core_.waitForSystem();
ignorePropertyChanges_ = true;
core_.loadSystemConfiguration(sysConfigFile_);
ignorePropertyChanges_ = false;
GUIUtils.preventDisplayAdapterChangeExceptions();
}
} catch (final Exception err) {
GUIUtils.preventDisplayAdapterChangeExceptions();
ReportingUtils.showError(err);
result = false;
} finally {
waitDlg.closeDialog();
}
setEnabled(true);
initializeGUI();
updateSwitchConfigurationMenu();
FileDialogs.storePath(MM_CONFIG_FILE, new File(sysConfigFile_));
return result;
}
private void saveMRUConfigFiles() {
if (0 < sysConfigFile_.length()) {
if (MRUConfigFiles_.contains(sysConfigFile_)) {
MRUConfigFiles_.remove(sysConfigFile_);
}
if (maxMRUCfgs_ <= MRUConfigFiles_.size()) {
MRUConfigFiles_.remove(maxMRUCfgs_ - 1);
}
MRUConfigFiles_.add(0, sysConfigFile_);
// save the MRU list to the preferences
for (Integer icfg = 0; icfg < MRUConfigFiles_.size(); ++icfg) {
String value = "";
if (null != MRUConfigFiles_.get(icfg)) {
value = MRUConfigFiles_.get(icfg).toString();
}
mainPrefs_.put(CFGFILE_ENTRY_BASE + icfg.toString(), value);
}
}
}
private void loadMRUConfigFiles() {
sysConfigFile_ = mainPrefs_.get(SYSTEM_CONFIG_FILE, sysConfigFile_);
// startupScriptFile_ = mainPrefs_.get(STARTUP_SCRIPT_FILE,
// startupScriptFile_);
MRUConfigFiles_ = new ArrayList<String>();
for (Integer icfg = 0; icfg < maxMRUCfgs_; ++icfg) {
String value = "";
value = mainPrefs_.get(CFGFILE_ENTRY_BASE + icfg.toString(), value);
if (0 < value.length()) {
File ruFile = new File(value);
if (ruFile.exists()) {
if (!MRUConfigFiles_.contains(value)) {
MRUConfigFiles_.add(value);
}
}
}
}
// initialize MRU list from old persistant data containing only SYSTEM_CONFIG_FILE
if (0 < sysConfigFile_.length()) {
if (!MRUConfigFiles_.contains(sysConfigFile_)) {
// in case persistant data is inconsistent
if (maxMRUCfgs_ <= MRUConfigFiles_.size()) {
MRUConfigFiles_.remove(maxMRUCfgs_ - 1);
}
MRUConfigFiles_.add(0, sysConfigFile_);
}
}
}
/**
* Opens Acquisition dialog.
*/
private void openAcqControlDialog() {
try {
if (acqControlWin_ == null) {
acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, this, options_);
}
if (acqControlWin_.isActive()) {
acqControlWin_.setTopPosition();
}
acqControlWin_.setVisible(true);
acqControlWin_.repaint();
// TODO: this call causes a strange exception the first time the
// dialog is created
// something to do with the order in which combo box creation is
// performed
// acqControlWin_.updateGroupsCombo();
} catch (Exception exc) {
ReportingUtils.showError(exc,
"\nAcquistion window failed to open due to invalid or corrupted settings.\n"
+ "Try resetting registry settings to factory defaults (Menu Tools|Options).");
}
}
/**
* Opens a dialog to record stage positions
*/
@Override
public void showXYPositionList() {
if (posListDlg_ == null) {
posListDlg_ = new PositionListDlg(core_, this, posList_, options_);
}
posListDlg_.setVisible(true);
}
private void updateChannelCombos() {
if (this.acqControlWin_ != null) {
this.acqControlWin_.updateChannelAndGroupCombo();
}
}
@Override
public void setConfigChanged(boolean status) {
configChanged_ = status;
setConfigSaveButtonStatus(configChanged_);
}
/**
* Returns the current background color
* @return current background color
*/
@Override
public Color getBackgroundColor() {
return guiColors_.background.get((options_.displayBackground_));
}
/*
* Changes background color of this window and all other MM windows
*/
@Override
public void setBackgroundStyle(String backgroundType) {
setBackground(guiColors_.background.get((backgroundType)));
paint(MMStudioMainFrame.this.getGraphics());
// sets background of all registered Components
for (Component comp:MMFrames_) {
if (comp != null)
comp.setBackground(guiColors_.background.get(backgroundType));
}
}
@Override
public String getBackgroundStyle() {
return options_.displayBackground_;
}
// //////////////////////////////////////////////////////////////////////////
// Scripting interface
// //////////////////////////////////////////////////////////////////////////
private class ExecuteAcq implements Runnable {
public ExecuteAcq() {
}
@Override
public void run() {
if (acqControlWin_ != null) {
acqControlWin_.runAcquisition();
}
}
}
private void testForAbortRequests() throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
}
}
/**
* @Deprecated - used to be in api/AcquisitionEngine
*/
public void startAcquisition() throws MMScriptException {
testForAbortRequests();
SwingUtilities.invokeLater(new ExecuteAcq());
}
@Override
public String runAcquisition() throws MMScriptException {
if (SwingUtilities.isEventDispatchThread()) {
throw new MMScriptException("Acquisition can not be run from this (EDT) thread");
}
testForAbortRequests();
if (acqControlWin_ != null) {
String name = acqControlWin_.runAcquisition();
try {
while (acqControlWin_.isAcquisitionRunning()) {
Thread.sleep(50);
}
} catch (InterruptedException e) {
ReportingUtils.showError(e);
}
return name;
} else {
throw new MMScriptException(
"Acquisition setup window must be open for this command to work.");
}
}
@Override
public String runAcquisition(String name, String root)
throws MMScriptException {
testForAbortRequests();
if (acqControlWin_ != null) {
String acqName = acqControlWin_.runAcquisition(name, root);
try {
while (acqControlWin_.isAcquisitionRunning()) {
Thread.sleep(100);
}
// ensure that the acquisition has finished.
// This does not seem to work, needs something better
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
boolean finished = false;
while (!finished) {
ImageCache imCache = acq.getImageCache();
if (imCache != null) {
if (imCache.isFinished()) {
finished = true;
} else {
Thread.sleep(100);
}
}
}
} catch (InterruptedException e) {
ReportingUtils.showError(e);
}
return acqName;
} else {
throw new MMScriptException(
"Acquisition setup window must be open for this command to work.");
}
}
/**
* @Deprecated used to be part of api
*/
public String runAcqusition(String name, String root) throws MMScriptException {
return runAcquisition(name, root);
}
/**
* Loads acquisition settings from file
* @param path file containing previously saved acquisition settings
* @throws MMScriptException
*/
@Override
public void loadAcquisition(String path) throws MMScriptException {
testForAbortRequests();
try {
engine_.shutdown();
// load protocol
if (acqControlWin_ != null) {
acqControlWin_.loadAcqSettingsFromFile(path);
}
} catch (Exception ex) {
throw new MMScriptException(ex.getMessage());
}
}
@Override
public void setPositionList(PositionList pl) throws MMScriptException {
testForAbortRequests();
// use serialization to clone the PositionList object
posList_ = pl; // PositionList.newInstance(pl);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (posListDlg_ != null)
posListDlg_.setPositionList(posList_);
if (engine_ != null)
engine_.setPositionList(posList_);
if (acqControlWin_ != null)
acqControlWin_.updateGUIContents();
}
});
}
@Override
public PositionList getPositionList() throws MMScriptException {
testForAbortRequests();
// use serialization to clone the PositionList object
return posList_; //PositionList.newInstance(posList_);
}
@Override
public void sleep(long ms) throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
scriptPanel_.sleep(ms);
}
}
@Override
public String getUniqueAcquisitionName(String stub) {
return acqMgr_.getUniqueAcquisitionName(stub);
}
//@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions) throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices,
nrPositions, true, false);
}
//@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices) throws MMScriptException {
openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0);
}
//@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions, boolean show)
throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, nrPositions, show, false);
}
//@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, boolean show)
throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, false);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions, boolean show, boolean save)
throws MMScriptException {
acqMgr_.openAcquisition(name, rootDir, show, save);
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.setDimensions(nrFrames, nrChannels, nrSlices, nrPositions);
}
//@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, boolean show, boolean virtual)
throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, virtual);
}
//@Override
public String createAcquisition(JSONObject summaryMetadata, boolean diskCached) {
return createAcquisition(summaryMetadata, diskCached, false);
}
@Override
public String createAcquisition(JSONObject summaryMetadata, boolean diskCached, boolean displayOff) {
return acqMgr_.createAcquisition(summaryMetadata, diskCached, engine_, displayOff);
}
//@Override
public void initializeSimpleAcquisition(String name, int width, int height,
int byteDepth, int bitDepth, int multiCamNumCh) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.setImagePhysicalDimensions(width, height, byteDepth, bitDepth, multiCamNumCh);
acq.initializeSimpleAcq();
}
@Override
public void initializeAcquisition(String name, int width, int height, int byteDepth, int bitDepth) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
//number of multi-cam cameras is set to 1 here for backwards compatibility
//might want to change this later
acq.setImagePhysicalDimensions(width, height, byteDepth, bitDepth, 1);
acq.initialize();
}
@Override
public int getAcquisitionImageWidth(String acqName) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getWidth();
}
@Override
public int getAcquisitionImageHeight(String acqName) throws MMScriptException{
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getHeight();
}
@Override
public int getAcquisitionImageBitDepth(String acqName) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getBitDepth();
}
@Override
public int getAcquisitionImageByteDepth(String acqName) throws MMScriptException{
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getByteDepth();
}
@Override public int getAcquisitionMultiCamNumChannels(String acqName) throws MMScriptException{
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getMultiCameraNumChannels();
}
@Override
public Boolean acquisitionExists(String name) {
return acqMgr_.acquisitionExists(name);
}
@Override
public void closeAcquisition(String name) throws MMScriptException {
acqMgr_.closeAcquisition(name);
}
/**
* @Deprecated use closeAcquisitionWindow instead
* @Deprecated - used to be in api/AcquisitionEngine
*/
public void closeAcquisitionImage5D(String acquisitionName) throws MMScriptException {
acqMgr_.closeImageWindow(acquisitionName);
}
@Override
public void closeAcquisitionWindow(String acquisitionName) throws MMScriptException {
acqMgr_.closeImageWindow(acquisitionName);
}
/**
* @Deprecated - used to be in api/AcquisitionEngine
* Since Burst and normal acquisition are now carried out by the same engine,
* loadBurstAcquistion simply calls loadAcquisition
* t
* @param path - path to file specifying acquisition settings
*/
public void loadBurstAcquisition(String path) throws MMScriptException {
this.loadAcquisition(path);
}
@Override
public void refreshGUI() {
updateGUI(true);
}
@Override
public void refreshGUIFromCache() {
updateGUI(true, true);
}
@Override
public void setAcquisitionProperty(String acqName, String propertyName,
String value) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
acq.setProperty(propertyName, value);
}
public void setAcquisitionSystemState(String acqName, JSONObject md) throws MMScriptException {
// acqMgr_.getAcquisition(acqName).setSystemState(md);
setAcquisitionSummary(acqName, md);
}
//@Override
public void setAcquisitionSummary(String acqName, JSONObject md) throws MMScriptException {
acqMgr_.getAcquisition(acqName).setSummaryProperties(md);
}
@Override
public void setImageProperty(String acqName, int frame, int channel,
int slice, String propName, String value) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
acq.setProperty(frame, channel, slice, propName, value);
}
@Override
public String getCurrentAlbum() {
return acqMgr_.getCurrentAlbum();
}
public String createNewAlbum() {
return acqMgr_.createNewAlbum();
}
public void appendImage(String name, TaggedImage taggedImg) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
int f = 1 + acq.getLastAcquiredFrame();
try {
MDUtils.setFrameIndex(taggedImg.tags, f);
} catch (JSONException e) {
throw new MMScriptException("Unable to set the frame index.");
}
acq.insertTaggedImage(taggedImg, f, 0, 0);
}
@Override
public void addToAlbum(TaggedImage taggedImg) throws MMScriptException {
addToAlbum(taggedImg, null);
}
public void addToAlbum(TaggedImage taggedImg, JSONObject displaySettings) throws MMScriptException {
normalizeTags(taggedImg);
acqMgr_.addToAlbum(taggedImg,displaySettings);
}
public void addImage(String name, Object img, int frame, int channel,
int slice) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.insertImage(img, frame, channel, slice);
}
//@Override
public void addImage(String name, TaggedImage taggedImg) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
if (!acq.isInitialized()) {
JSONObject tags = taggedImg.tags;
// initialize physical dimensions of the image
try {
int width = tags.getInt(MMTags.Image.WIDTH);
int height = tags.getInt(MMTags.Image.HEIGHT);
int byteDepth = MDUtils.getDepth(tags);
int bitDepth = tags.getInt(MMTags.Image.BIT_DEPTH);
initializeAcquisition(name, width, height, byteDepth, bitDepth);
} catch (JSONException e) {
throw new MMScriptException(e);
}
}
acq.insertImage(taggedImg);
}
@Override
/**
* The basic method for adding images to an existing data set.
* If the acquisition was not previously initialized, it will attempt to initialize it from the available image data
*/
public void addImageToAcquisition(String name, int frame, int channel, int slice, int position, TaggedImage taggedImg) throws MMScriptException {
// TODO: complete the tag set and initialize the acquisition
MMAcquisition acq = acqMgr_.getAcquisition(name);
// check position, for multi-position data set the number of declared positions should be at least 2
if (acq.getPositions() <= 1 && position > 0) {
throw new MMScriptException("The acquisition was open as a single position data set.\n"
+ "Open acqusition with two or more positions in order to crate a multi-position data set.");
}
// check position, for multi-position data set the number of declared positions should be at least 2
if (acq.getChannels() <= channel) {
throw new MMScriptException("This acquisition was opened with " + acq.getChannels() + " channels.\n"
+ "The channel number must not exceed declared number of positions.");
}
JSONObject tags = taggedImg.tags;
// if the acquisition was not previously initialized, set physical dimensions of the image
if (!acq.isInitialized()) {
// automatically initialize physical dimensions of the image
try {
int width = tags.getInt(MMTags.Image.WIDTH);
int height = tags.getInt(MMTags.Image.HEIGHT);
int byteDepth = MDUtils.getDepth(tags);
int bitDepth = byteDepth * 8;
if (tags.has(MMTags.Image.BIT_DEPTH))
bitDepth = tags.getInt(MMTags.Image.BIT_DEPTH);
initializeAcquisition(name, width, height, byteDepth, bitDepth);
} catch (JSONException e) {
throw new MMScriptException(e);
}
}
// create required coordinate tags
try {
tags.put(MMTags.Image.FRAME_INDEX, frame);
tags.put(MMTags.Image.FRAME, frame);
tags.put(MMTags.Image.CHANNEL_INDEX, channel);
tags.put(MMTags.Image.SLICE_INDEX, slice);
tags.put(MMTags.Image.POS_INDEX, position);
if (!tags.has(MMTags.Summary.SLICES_FIRST) && !tags.has(MMTags.Summary.TIME_FIRST)) {
// add default setting
tags.put(MMTags.Summary.SLICES_FIRST, true);
tags.put(MMTags.Summary.TIME_FIRST, false);
}
if (acq.getPositions() > 1) {
// if no position name is defined we need to insert a default one
if (tags.has(MMTags.Image.POS_NAME))
tags.put(MMTags.Image.POS_NAME, "Pos" + position);
}
// update frames if necessary
if (acq.getFrames() <= frame) {
acq.setProperty(MMTags.Summary.FRAMES, Integer.toString(frame+1));
}
} catch (JSONException e) {
throw new MMScriptException(e);
}
// System.out.println("Inserting frame: " + frame + ", channel: " + channel + ", slice: " + slice + ", pos: " + position);
acq.insertImage(taggedImg);
}
@Override
/**
* A quick way to implicitly snap an image and add it to the data set.
* Works in the same way as above.
*/
public void snapAndAddImage(String name, int frame, int channel, int slice, int position) throws MMScriptException {
TaggedImage ti;
try {
if (core_.isSequenceRunning()) {
ti = core_.getLastTaggedImage();
} else {
core_.snapImage();
ti = core_.getTaggedImage();
}
MDUtils.setChannelIndex(ti.tags, channel);
MDUtils.setFrameIndex(ti.tags, frame);
MDUtils.setSliceIndex(ti.tags, slice);
MDUtils.setPositionIndex(ti.tags, position);
MMAcquisition acq = acqMgr_.getAcquisition(name);
if (!acq.isInitialized()) {
long width = core_.getImageWidth();
long height = core_.getImageHeight();
long depth = core_.getBytesPerPixel();
long bitDepth = core_.getImageBitDepth();
int multiCamNumCh = (int) core_.getNumberOfCameraChannels();
acq.setImagePhysicalDimensions((int) width, (int) height, (int) depth, (int) bitDepth, multiCamNumCh);
acq.initialize();
}
if (acq.getPositions() > 1) {
MDUtils.setPositionName(ti.tags, "Pos" + position);
}
addImageToAcquisition(name, frame, channel, slice, position, ti);
} catch (Exception e) {
throw new MMScriptException(e);
}
}
//@Override
public void addImage(String name, TaggedImage img, boolean updateDisplay) throws MMScriptException {
acqMgr_.getAcquisition(name).insertImage(img, updateDisplay);
}
//@Override
public void addImage(String name, TaggedImage taggedImg,
boolean updateDisplay,
boolean waitForDisplay) throws MMScriptException {
acqMgr_.getAcquisition(name).insertImage(taggedImg, updateDisplay, waitForDisplay);
}
//@Override
public void addImage(String name, TaggedImage taggedImg, int frame, int channel,
int slice, int position) throws MMScriptException {
try {
acqMgr_.getAcquisition(name).insertImage(taggedImg, frame, channel, slice, position);
} catch (JSONException ex) {
ReportingUtils.showError(ex);
}
}
//@Override
public void addImage(String name, TaggedImage taggedImg, int frame, int channel,
int slice, int position, boolean updateDisplay) throws MMScriptException {
try {
acqMgr_.getAcquisition(name).insertImage(taggedImg, frame, channel, slice, position, updateDisplay);
} catch (JSONException ex) {
ReportingUtils.showError(ex);
}
}
//@Override
public void addImage(String name, TaggedImage taggedImg, int frame, int channel,
int slice, int position, boolean updateDisplay, boolean waitForDisplay) throws MMScriptException {
try {
acqMgr_.getAcquisition(name).insertImage(taggedImg, frame, channel, slice, position, updateDisplay, waitForDisplay);
} catch (JSONException ex) {
ReportingUtils.showError(ex);
}
}
/**
* Closes all acquisitions
*/
@Override
public void closeAllAcquisitions() {
acqMgr_.closeAll();
}
@Override
public String[] getAcquisitionNames()
{
return acqMgr_.getAcqusitionNames();
}
@Override
public MMAcquisition getAcquisition(String name) throws MMScriptException {
return acqMgr_.getAcquisition(name);
}
private class ScriptConsoleMessage implements Runnable {
String msg_;
public ScriptConsoleMessage(String text) {
msg_ = text;
}
@Override
public void run() {
if (scriptPanel_ != null)
scriptPanel_.message(msg_);
}
}
@Override
public void message(String text) throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
SwingUtilities.invokeLater(new ScriptConsoleMessage(text));
}
}
@Override
public void clearMessageWindow() throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
scriptPanel_.clearOutput();
}
}
public void clearOutput() throws MMScriptException {
clearMessageWindow();
}
public void clear() throws MMScriptException {
clearMessageWindow();
}
@Override
public void setChannelContrast(String title, int channel, int min, int max)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelContrast(channel, min, max);
}
@Override
public void setChannelName(String title, int channel, String name)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelName(channel, name);
}
@Override
public void setChannelColor(String title, int channel, Color color)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelColor(channel, color.getRGB());
}
@Override
public void setContrastBasedOnFrame(String title, int frame, int slice)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setContrastBasedOnFrame(frame, slice);
}
@Override
public void setStagePosition(double z) throws MMScriptException {
try {
core_.setPosition(core_.getFocusDevice(),z);
core_.waitForDevice(core_.getFocusDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
@Override
public void setRelativeStagePosition(double z) throws MMScriptException {
try {
core_.setRelativePosition(core_.getFocusDevice(), z);
core_.waitForDevice(core_.getFocusDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
@Override
public void setXYStagePosition(double x, double y) throws MMScriptException {
try {
core_.setXYPosition(core_.getXYStageDevice(), x, y);
core_.waitForDevice(core_.getXYStageDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
@Override
public void setRelativeXYStagePosition(double x, double y) throws MMScriptException {
try {
core_.setRelativeXYPosition(core_.getXYStageDevice(), x, y);
core_.waitForDevice(core_.getXYStageDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
@Override
public Point2D.Double getXYStagePosition() throws MMScriptException {
String stage = core_.getXYStageDevice();
if (stage.length() == 0) {
throw new MMScriptException("XY Stage device is not available");
}
double x[] = new double[1];
double y[] = new double[1];
try {
core_.getXYPosition(stage, x, y);
Point2D.Double pt = new Point2D.Double(x[0], y[0]);
return pt;
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
@Override
public String getXYStageName() {
return core_.getXYStageDevice();
}
@Override
public void setXYOrigin(double x, double y) throws MMScriptException {
String xyStage = core_.getXYStageDevice();
try {
core_.setAdapterOriginXY(xyStage, x, y);
} catch (Exception e) {
throw new MMScriptException(e);
}
}
public AcquisitionWrapperEngine getAcquisitionEngine() {
return engine_;
}
public String installPlugin(Class<?> cl) {
String className = cl.getSimpleName();
String msg = className + " module loaded.";
try {
for (PluginItem plugin : plugins_) {
if (plugin.className.contentEquals(className)) {
return className + " already loaded.";
}
}
PluginItem pi = new PluginItem();
pi.className = className;
try {
// Get this static field from the class implementing MMPlugin.
pi.menuItem = (String) cl.getDeclaredField("menuName").get(null);
} catch (SecurityException e) {
ReportingUtils.logError(e);
pi.menuItem = className;
} catch (NoSuchFieldException e) {
pi.menuItem = className;
ReportingUtils.logMessage(className + " fails to implement static String menuName.");
} catch (IllegalArgumentException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
if (pi.menuItem == null) {
pi.menuItem = className;
}
pi.menuItem = pi.menuItem.replace("_", " ");
pi.pluginClass = cl;
plugins_.add(pi);
final PluginItem pi2 = pi;
final Class<?> cl2 = cl;
SwingUtilities.invokeLater(
new Runnable() {
@Override
public void run() {
addPluginToMenu(pi2, cl2);
}
});
} catch (NoClassDefFoundError e) {
msg = className + " class definition not found.";
ReportingUtils.logError(e, msg);
}
return msg;
}
public String installPlugin(String className, String menuName) {
String msg = "installPlugin(String className, String menuName) is Deprecated. Use installPlugin(String className) instead.";
core_.logMessage(msg);
installPlugin(className);
return msg;
}
@Override
public String installPlugin(String className) {
try {
Class clazz = Class.forName(className);
return installPlugin(clazz);
} catch (ClassNotFoundException e) {
String msg = className + " plugin not found.";
ReportingUtils.logError(e, msg);
return msg;
}
}
@Override
public String installAutofocusPlugin(String className) {
try {
return installAutofocusPlugin(Class.forName(className));
} catch (ClassNotFoundException e) {
String msg = "Internal error: AF manager not instantiated.";
ReportingUtils.logError(e, msg);
return msg;
}
}
public String installAutofocusPlugin(Class<?> autofocus) {
String msg = autofocus.getSimpleName() + " module loaded.";
if (afMgr_ != null) {
afMgr_.setAFPluginClassName(autofocus.getSimpleName());
try {
afMgr_.refresh();
} catch (MMException e) {
msg = e.getMessage();
ReportingUtils.logError(e);
}
} else {
msg = "Internal error: AF manager not instantiated.";
}
return msg;
}
public CMMCore getCore() {
return core_;
}
@Override
public IAcquisitionEngine2010 getAcquisitionEngine2010() {
try {
acquisitionEngine2010LoadingThread.join();
if (acquisitionEngine2010 == null) {
acquisitionEngine2010 = (IAcquisitionEngine2010) acquisitionEngine2010Class.getConstructor(ScriptInterface.class).newInstance(this);
}
return acquisitionEngine2010;
} catch (Exception e) {
ReportingUtils.logError(e);
return null;
}
}
@Override
public void addImageProcessor(DataProcessor<TaggedImage> processor) {
System.out.println("Processor: "+processor.getClass().getSimpleName());
getAcquisitionEngine().addImageProcessor(processor);
}
@Override
public void removeImageProcessor(DataProcessor<TaggedImage> processor) {
getAcquisitionEngine().removeImageProcessor(processor);
}
@Override
public void setPause(boolean state) {
getAcquisitionEngine().setPause(state);
}
@Override
public boolean isPaused() {
return getAcquisitionEngine().isPaused();
}
@Override
public void attachRunnable(int frame, int position, int channel, int slice, Runnable runnable) {
getAcquisitionEngine().attachRunnable(frame, position, channel, slice, runnable);
}
@Override
public void clearRunnables() {
getAcquisitionEngine().clearRunnables();
}
@Override
public SequenceSettings getAcqusitionSettings() {
if (engine_ == null)
return new SequenceSettings();
return engine_.getSequenceSettings();
}
@Override
public String getAcquisitionPath() {
if (engine_ == null)
return null;
return engine_.getImageCache().getDiskLocation();
}
@Override
public void promptToSaveAcqusition(String name, boolean prompt) throws MMScriptException {
MMAcquisition acq = getAcquisition(name);
getAcquisition(name).promptToSave(prompt);
}
public void snapAndAddToImage5D() {
if (core_.getCameraDevice().length() == 0) {
ReportingUtils.showError("No camera configured");
return;
}
try {
if (this.isLiveModeOn()) {
copyFromLiveModeToAlbum(simpleDisplay_);
} else {
doSnap(true);
}
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
public void setAcquisitionEngine(AcquisitionWrapperEngine eng) {
engine_ = eng;
}
public void suspendLiveMode() {
liveModeSuspended_ = isLiveModeOn();
enableLiveMode(false);
}
public void resumeLiveMode() {
if (liveModeSuspended_) {
enableLiveMode(true);
}
}
@Override
public Autofocus getAutofocus() {
return afMgr_.getDevice();
}
@Override
public void showAutofocusDialog() {
if (afMgr_.getDevice() != null) {
afMgr_.showOptionsDialog();
}
}
@Override
public AutofocusManager getAutofocusManager() {
return afMgr_;
}
public void selectConfigGroup(String groupName) {
configPad_.setGroup(groupName);
}
public String regenerateDeviceList() {
Cursor oldc = Cursor.getDefaultCursor();
Cursor waitc = new Cursor(Cursor.WAIT_CURSOR);
setCursor(waitc);
StringBuffer resultFile = new StringBuffer();
MicroscopeModel.generateDeviceListFile(resultFile, core_);
//MicroscopeModel.generateDeviceListFile();
setCursor(oldc);
return resultFile.toString();
}
@Override
public void setImageSavingFormat(Class imageSavingClass) throws MMScriptException {
if (! (imageSavingClass.equals(TaggedImageStorageDiskDefault.class) ||
imageSavingClass.equals(TaggedImageStorageMultipageTiff.class))) {
throw new MMScriptException("Unrecognized saving class");
}
ImageUtils.setImageStorageClass(imageSavingClass);
if (acqControlWin_ != null) {
acqControlWin_.updateSavingTypeButtons();
}
}
private void loadPlugins() {
ArrayList<Class<?>> pluginClasses = new ArrayList<Class<?>>();
ArrayList<Class<?>> autofocusClasses = new ArrayList<Class<?>>();
List<Class<?>> classes;
try {
long t1 = System.currentTimeMillis();
classes = JavaUtils.findClasses(new File("mmplugins"), 2);
//System.out.println("findClasses: " + (System.currentTimeMillis() - t1));
//System.out.println(classes.size());
for (Class<?> clazz : classes) {
for (Class<?> iface : clazz.getInterfaces()) {
//core_.logMessage("interface found: " + iface.getName());
if (iface == MMPlugin.class) {
pluginClasses.add(clazz);
}
}
}
classes = JavaUtils.findClasses(new File("mmautofocus"), 2);
for (Class<?> clazz : classes) {
for (Class<?> iface : clazz.getInterfaces()) {
//core_.logMessage("interface found: " + iface.getName());
if (iface == Autofocus.class) {
autofocusClasses.add(clazz);
}
}
}
} catch (ClassNotFoundException e1) {
ReportingUtils.logError(e1);
}
for (Class<?> plugin : pluginClasses) {
try {
ReportingUtils.logMessage("Attempting to install plugin " + plugin.getName());
installPlugin(plugin);
} catch (Exception e) {
ReportingUtils.logError(e, "Failed to install the \"" + plugin.getName() + "\" plugin .");
}
}
for (Class<?> autofocus : autofocusClasses) {
try {
ReportingUtils.logMessage("Attempting to install autofocus plugin " + autofocus.getName());
installAutofocusPlugin(autofocus.getName());
} catch (Exception e) {
ReportingUtils.logError("Failed to install the \"" + autofocus.getName() + "\" autofocus plugin.");
}
}
}
@Override
public void logMessage(String msg) {
ReportingUtils.logMessage(msg);
}
@Override
public void showMessage(String msg) {
ReportingUtils.showMessage(msg);
}
@Override
public void logError(Exception e, String msg) {
ReportingUtils.logError(e, msg);
}
@Override
public void logError(Exception e) {
ReportingUtils.logError(e);
}
@Override
public void logError(String msg) {
ReportingUtils.logError(msg);
}
@Override
public void showError(Exception e, String msg) {
ReportingUtils.showError(e, msg);
}
@Override
public void showError(Exception e) {
ReportingUtils.showError(e);
}
@Override
public void showError(String msg) {
ReportingUtils.showError(msg);
}
private void runHardwareWizard() {
try {
if (configChanged_) {
Object[] options = {"Yes", "No"};
int n = JOptionPane.showOptionDialog(null,
"Save Changed Configuration?", "Micro-Manager",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options,
options[0]);
if (n == JOptionPane.YES_OPTION) {
saveConfigPresets();
}
configChanged_ = false;
}
boolean liveRunning = false;
if (isLiveModeOn()) {
liveRunning = true;
enableLiveMode(false);
}
// unload all devices before starting configurator
core_.reset();
GUIUtils.preventDisplayAdapterChangeExceptions();
// run Configurator
ConfiguratorDlg2 cfg2 = null;
try {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
cfg2 = new ConfiguratorDlg2(core_, sysConfigFile_);
} finally {
setCursor(Cursor.getDefaultCursor());
}
if (cfg2 == null)
{
ReportingUtils.showError("Failed to launch Hardware Configuration Wizard");
return;
}
cfg2.setVisible(true);
GUIUtils.preventDisplayAdapterChangeExceptions();
// re-initialize the system with the new configuration file
sysConfigFile_ = cfg2.getFileName();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
loadSystemConfiguration();
GUIUtils.preventDisplayAdapterChangeExceptions();
if (liveRunning) {
enableLiveMode(liveRunning);
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
private void autofocusNow() {
if (afMgr_.getDevice() != null) {
new Thread() {
@Override
public void run() {
try {
boolean lmo = isLiveModeOn();
if (lmo) {
enableLiveMode(false);
}
afMgr_.getDevice().fullFocus();
if (lmo) {
enableLiveMode(true);
}
} catch (MMException ex) {
ReportingUtils.logError(ex);
}
}
}.start(); // or any other method from Autofocus.java API
}
}
}
class BooleanLock extends Object {
private boolean value;
public BooleanLock(boolean initialValue) {
value = initialValue;
}
public BooleanLock() {
this(false);
}
public synchronized void setValue(boolean newValue) {
if (newValue != value) {
value = newValue;
notifyAll();
}
}
public synchronized boolean waitToSetTrue(long msTimeout)
throws InterruptedException {
boolean success = waitUntilFalse(msTimeout);
if (success) {
setValue(true);
}
return success;
}
public synchronized boolean waitToSetFalse(long msTimeout)
throws InterruptedException {
boolean success = waitUntilTrue(msTimeout);
if (success) {
setValue(false);
}
return success;
}
public synchronized boolean isTrue() {
return value;
}
public synchronized boolean isFalse() {
return !value;
}
public synchronized boolean waitUntilTrue(long msTimeout)
throws InterruptedException {
return waitUntilStateIs(true, msTimeout);
}
public synchronized boolean waitUntilFalse(long msTimeout)
throws InterruptedException {
return waitUntilStateIs(false, msTimeout);
}
public synchronized boolean waitUntilStateIs(
boolean state,
long msTimeout) throws InterruptedException {
if (msTimeout == 0L) {
while (value != state) {
wait();
}
return true;
}
long endTime = System.currentTimeMillis() + msTimeout;
long msRemaining = msTimeout;
while ((value != state) && (msRemaining > 0L)) {
wait(msRemaining);
msRemaining = endTime - System.currentTimeMillis();
}
return (value == state);
}
}
| Changed the plugin loaded so that it sorts menu names alphabetically. Partical implementation of ticket #690
git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@12828 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd
| mmstudio/src/org/micromanager/MMStudioMainFrame.java | Changed the plugin loaded so that it sorts menu names alphabetically. Partical implementation of ticket #690 | <ide><path>mstudio/src/org/micromanager/MMStudioMainFrame.java
<ide> import java.awt.dnd.DropTarget;
<ide> import java.awt.event.MouseAdapter;
<ide> import java.awt.event.MouseEvent;
<add>import java.text.Collator;
<ide> import java.util.Collections;
<add>import java.util.Comparator;
<ide> import java.util.concurrent.BlockingQueue;
<ide> import java.util.concurrent.LinkedBlockingQueue;
<ide>
<ide> return MMVersion.VERSION_STRING;
<ide> }
<ide>
<del> private void addPluginToMenu(final PluginItem plugin, Class<?> cl) {
<del> // add plugin menu items
<add> /**
<add> * Adds plugin items to the plugins menu
<add> * @param plugin - plugin to be added to the menu
<add> */
<add> private void addPluginToMenu(final PluginItem plugin) {
<add> Class<?> cl = plugin.pluginClass;
<ide> String toolTipDescription = "";
<ide> try {
<ide> // Get this static field from the class implementing MMPlugin.
<ide> return engine_;
<ide> }
<ide>
<add> /**
<add> * Helper class for plugin loader functions
<add> */
<add> private class PluginItemAndClass {
<add> private String msg_;
<add> private Class<?> cl_;
<add> private PluginItem pi_;
<add>
<add> public PluginItemAndClass(String msg, Class<?> cl, PluginItem pi) {
<add> msg_ = msg;
<add> cl_ = cl;
<add> pi_ = pi;
<add> }
<add> public Class<?> getItsClass () {return cl_;}
<add> public String getMessage() {return msg_;}
<add> public PluginItem getPluginItem() {return pi_;}
<add> }
<add>
<add> private class PluginItemAndClassComparator implements Comparator<PluginItemAndClass> {
<add> public int compare(PluginItemAndClass t1, PluginItemAndClass t2) {
<add> try {
<add> String m1 = t1.getPluginItem().menuItem;
<add> String m2 = t2.getPluginItem().menuItem;
<add> Collator collator = Collator.getInstance();
<add> collator.setStrength(Collator.PRIMARY);
<add> return collator.compare(m1, m2);
<add> } catch (NullPointerException npe) {
<add> ReportingUtils.logError("NullPointerException in PluginItemAndClassCopmarator");
<add> }
<add> return 0;
<add> }
<add> }
<add>
<ide> public String installPlugin(Class<?> cl) {
<add> PluginItemAndClass piac = declarePlugin(cl);
<add> final PluginItem pi = piac.getPluginItem();
<add> if (pi != null) {
<add> addPluginToMenuLater(pi);
<add> }
<add> String msg = piac.getMessage();
<add> if (msg != null) {
<add> return msg;
<add> }
<add> ReportingUtils.logError("In MMStudioMainFrame:installPlugin, msg was null");
<add> return piac.getMessage();
<add> }
<add>
<add> private PluginItemAndClass declarePlugin(Class<?> cl) {
<ide> String className = cl.getSimpleName();
<ide> String msg = className + " module loaded.";
<add> PluginItem pi = new PluginItem();
<ide> try {
<ide> for (PluginItem plugin : plugins_) {
<ide> if (plugin.className.contentEquals(className)) {
<del> return className + " already loaded.";
<del> }
<del> }
<del>
<del> PluginItem pi = new PluginItem();
<add> msg = className + " already loaded";
<add> PluginItemAndClass piac = new PluginItemAndClass(msg, cl, null);
<add> return piac;
<add> }
<add> }
<add>
<ide> pi.className = className;
<ide> try {
<ide> // Get this static field from the class implementing MMPlugin.
<ide> pi.menuItem = pi.menuItem.replace("_", " ");
<ide> pi.pluginClass = cl;
<ide> plugins_.add(pi);
<del> final PluginItem pi2 = pi;
<del> final Class<?> cl2 = cl;
<del> SwingUtilities.invokeLater(
<del> new Runnable() {
<del> @Override
<del> public void run() {
<del> addPluginToMenu(pi2, cl2);
<del> }
<del> });
<del>
<ide> } catch (NoClassDefFoundError e) {
<ide> msg = className + " class definition not found.";
<ide> ReportingUtils.logError(e, msg);
<del>
<del> }
<del>
<del> return msg;
<del>
<add> }
<add> PluginItemAndClass piac = new PluginItemAndClass(msg, cl, pi);
<add> return piac;
<add> }
<add>
<add>
<add> private void addPluginToMenuLater(final PluginItem pi) {
<add> SwingUtilities.invokeLater(
<add> new Runnable() {
<add> @Override
<add> public void run() {
<add> addPluginToMenu(pi);
<add> }
<add> });
<ide> }
<ide>
<ide> public String installPlugin(String className, String menuName) {
<ide>
<ide>
<ide>
<add> /**
<add> * Discovers Micro-Manager plugins and autofocus plugins at runtime
<add> * Adds these to the plugins menu
<add> */
<ide>
<ide> private void loadPlugins() {
<ide>
<ide> try {
<ide> long t1 = System.currentTimeMillis();
<ide> classes = JavaUtils.findClasses(new File("mmplugins"), 2);
<del> //System.out.println("findClasses: " + (System.currentTimeMillis() - t1));
<del> //System.out.println(classes.size());
<add>
<ide> for (Class<?> clazz : classes) {
<ide> for (Class<?> iface : clazz.getInterfaces()) {
<del> //core_.logMessage("interface found: " + iface.getName());
<ide> if (iface == MMPlugin.class) {
<ide> pluginClasses.add(clazz);
<ide> }
<ide> }
<del>
<ide> }
<ide>
<ide> classes = JavaUtils.findClasses(new File("mmautofocus"), 2);
<ide> ReportingUtils.logError(e1);
<ide> }
<ide>
<add> ArrayList<PluginItemAndClass> piacs = new ArrayList<PluginItemAndClass>();
<ide> for (Class<?> plugin : pluginClasses) {
<ide> try {
<ide> ReportingUtils.logMessage("Attempting to install plugin " + plugin.getName());
<del> installPlugin(plugin);
<add> PluginItemAndClass piac = declarePlugin(plugin);
<add> if (piac.getPluginItem() != null) {
<add> piacs.add(piac);
<add> }
<ide> } catch (Exception e) {
<ide> ReportingUtils.logError(e, "Failed to install the \"" + plugin.getName() + "\" plugin .");
<add> }
<add> }
<add> Collections.sort(piacs, new PluginItemAndClassComparator());
<add> for (PluginItemAndClass piac : piacs) {
<add> final PluginItem pi = piac.getPluginItem();
<add> if (pi != null) {
<add> addPluginToMenuLater(pi);
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 43a1b47f5594b2325c1b3ba1d22552c6f0be9005 | 0 | oakesville/mythling,oakesville/mythling,oakesville/mythling,oakesville/mythling | /**
* Copyright 2015 Donald Oakes
*
* 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.oakesville.mythling.util;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import org.json.JSONException;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.oakesville.mythling.BuildConfig;
import com.oakesville.mythling.R;
import com.oakesville.mythling.app.AppSettings;
import com.oakesville.mythling.app.Localizer;
import com.oakesville.mythling.media.Item;
import com.oakesville.mythling.media.Recording;
import com.oakesville.mythling.util.HttpHelper.AuthType;
public class ServiceFrontendPlayer implements FrontendPlayer {
private static final String TAG = ServiceFrontendPlayer.class.getSimpleName();
private AppSettings appSettings;
private Item item;
private String state;
public ServiceFrontendPlayer(AppSettings appSettings, Item item) {
this.appSettings = appSettings;
this.item = item;
}
public boolean checkIsPlaying() throws IOException, JSONException {
int timeout = 5000; // TODO: pref
state = null;
new StatusTask().execute();
while (state == null && timeout > 0) {
try {
Thread.sleep(100);
timeout -= 100;
} catch (InterruptedException ex) {
if (BuildConfig.DEBUG)
Log.e(TAG, ex.getMessage(), ex);
if (appSettings.isErrorReportingEnabled())
new Reporter(ex).send();
}
}
if (state == null)
throw new IOException(Localizer.getStringRes(R.string.error_frontend_status_) + appSettings.getFrontendServiceBaseUrl());
return !state.equals("idle");
}
public void play() {
new PlayItemTask().execute();
}
public void stop() {
new StopTask().execute();
}
private class StatusTask extends AsyncTask<URL, Integer, Long> {
private Exception ex;
protected Long doInBackground(URL... urls) {
try {
URL url = new URL(appSettings.getFrontendServiceBaseUrl() + "/Frontend/GetStatus");
HttpHelper downloader = new HttpHelper(new URL[]{url}, AuthType.None.toString(), appSettings.getPrefs());
String frontendStatusJson = new String(downloader.get(), "UTF-8");
state = new MythTvParser(appSettings, frontendStatusJson).parseFrontendStatus();
return 0L;
} catch (Exception ex) {
this.ex = ex;
if (BuildConfig.DEBUG)
Log.e(TAG, ex.getMessage(), ex);
if (appSettings.isErrorReportingEnabled())
new Reporter(ex).send();
return -1L;
}
}
protected void onPostExecute(Long result) {
if (result != 0L) {
if (ex != null)
Toast.makeText(appSettings.getAppContext(), ex.toString(), Toast.LENGTH_LONG).show();
}
}
}
private class PlayItemTask extends AsyncTask<URL, Integer, Long> {
private Exception ex;
protected Long doInBackground(URL... urls) {
try {
URL url = appSettings.getFrontendServiceBaseUrl();
if (item.isRecording()) {
// jump to recordings -- otherwise playback sometimes doesn't work
sendAction("TV Recording Playback");
Thread.sleep(500);
url = new URL(url + "/Frontend/PlayRecording?" + ((Recording) item).getChanIdStartTimeParams());
}
else if (item.isMusic())
throw new UnsupportedOperationException(Localizer.getStringRes(R.string.music_not_supported_by_svc_fe_player));
else
url = new URL(url + "/Frontend/PlayVideo?Id=" + item.getId());
HttpHelper poster = new HttpHelper(new URL[]{url}, AuthType.None.toString(), appSettings.getPrefs());
String resJson = new String(poster.post(), "UTF-8");
boolean res = new MythTvParser(appSettings, resJson).parseBool();
if (!res)
throw new ServiceException(Localizer.getStringRes(R.string.frontend_playback_failed_) + url);
return 0L;
} catch (Exception ex) {
this.ex = ex;
if (BuildConfig.DEBUG)
Log.e(TAG, ex.getMessage(), ex);
if (appSettings.isErrorReportingEnabled())
new Reporter(ex).send();
return -1L;
}
}
protected void onPostExecute(Long result) {
if (result != 0L) {
if (ex != null)
Toast.makeText(appSettings.getAppContext(), Localizer.getStringRes(R.string.frontend_playback_error_) + ex.toString(), Toast.LENGTH_LONG).show();
}
}
}
private class StopTask extends AsyncTask<URL, Integer, Long> {
private Exception ex;
protected Long doInBackground(URL... urls) {
try {
sendAction("STOPPLAYBACK");
Thread.sleep(250);
return 0L;
} catch (Exception ex) {
this.ex = ex;
if (BuildConfig.DEBUG)
Log.e(TAG, ex.getMessage(), ex);
if (appSettings.isErrorReportingEnabled())
new Reporter(ex).send();
return -1L;
}
}
protected void onPostExecute(Long result) {
if (result != 0L) {
if (ex != null)
Toast.makeText(appSettings.getAppContext(), Localizer.getStringRes(R.string.error_frontend_status_) + ex.toString(), Toast.LENGTH_LONG).show();
}
}
}
/**
* Perform a MythTV SendAction. Must be on background thread.
*/
private void sendAction(String action) throws IOException, JSONException {
URL url = new URL(appSettings.getFrontendServiceBaseUrl() + "/Frontend/SendAction?Action=" + URLEncoder.encode(action, "UTF-8"));
HttpHelper poster = new HttpHelper(new URL[]{url}, AuthType.None.toString(), appSettings.getPrefs());
String resJson = new String(poster.post(), "UTF-8");
boolean res = new MythTvParser(appSettings, resJson).parseBool();
if (!res)
throw new ServiceException(Localizer.getStringRes(R.string.error_performing_frontend_action_) + url);
}
}
| src/com/oakesville/mythling/util/ServiceFrontendPlayer.java | /**
* Copyright 2015 Donald Oakes
*
* 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.oakesville.mythling.util;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import org.json.JSONException;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.oakesville.mythling.BuildConfig;
import com.oakesville.mythling.R;
import com.oakesville.mythling.app.AppSettings;
import com.oakesville.mythling.app.Localizer;
import com.oakesville.mythling.media.Item;
import com.oakesville.mythling.media.Recording;
import com.oakesville.mythling.util.HttpHelper.AuthType;
public class ServiceFrontendPlayer implements FrontendPlayer {
private static final String TAG = ServiceFrontendPlayer.class.getSimpleName();
private AppSettings appSettings;
private Item item;
private String state;
public ServiceFrontendPlayer(AppSettings appSettings, Item item) {
this.appSettings = appSettings;
this.item = item;
}
public boolean checkIsPlaying() throws IOException, JSONException {
int timeout = 5000; // TODO: pref
state = null;
new StatusTask().execute();
while (state == null && timeout > 0) {
try {
Thread.sleep(100);
timeout -= 100;
} catch (InterruptedException ex) {
if (BuildConfig.DEBUG)
Log.e(TAG, ex.getMessage(), ex);
if (appSettings.isErrorReportingEnabled())
new Reporter(ex).send();
}
}
if (state == null)
throw new IOException(Localizer.getStringRes(R.string.error_frontend_status_) + appSettings.getFrontendServiceBaseUrl());
return !state.equals("idle");
}
public void play() {
new PlayItemTask().execute();
}
public void stop() {
new StopTask().execute();
}
private class StatusTask extends AsyncTask<URL, Integer, Long> {
private Exception ex;
protected Long doInBackground(URL... urls) {
try {
URL url = new URL(appSettings.getFrontendServiceBaseUrl() + "/Frontend/GetStatus");
HttpHelper downloader = new HttpHelper(new URL[]{url}, AuthType.None.toString(), appSettings.getPrefs());
String frontendStatusJson = new String(downloader.get(), "UTF-8");
state = new MythTvParser(appSettings, frontendStatusJson).parseFrontendStatus();
return 0L;
} catch (Exception ex) {
this.ex = ex;
if (BuildConfig.DEBUG)
Log.e(TAG, ex.getMessage(), ex);
if (appSettings.isErrorReportingEnabled())
new Reporter(ex).send();
return -1L;
}
}
protected void onPostExecute(Long result) {
if (result != 0L) {
if (ex != null)
Toast.makeText(appSettings.getAppContext(), ex.toString(), Toast.LENGTH_LONG).show();
}
}
}
private class PlayItemTask extends AsyncTask<URL, Integer, Long> {
private Exception ex;
protected Long doInBackground(URL... urls) {
try {
URL url = appSettings.getFrontendServiceBaseUrl();
if (item.isRecording()) {
// jump to recordings -- otherwise playback sometimes doesn't work
sendAction("TV Recording Playback");
Thread.sleep(500);
url = new URL(url + "/Frontend/PlayRecording?" + ((Recording) item).getChanIdStartTimeParams());
}
else if (item.isMusic())
throw new UnsupportedOperationException(Localizer.getStringRes(R.string.music_not_supported_by_svc_fe_player));
else
url = new URL(url + "/Frontend/PlayVideo?Id=" + item.getId());
HttpHelper poster = new HttpHelper(new URL[]{url}, AuthType.None.toString(), appSettings.getPrefs());
String resJson = new String(poster.post(), "UTF-8");
boolean res = new MythTvParser(appSettings, resJson).parseBool();
if (!res)
throw new ServiceException(Localizer.getStringRes(R.string.frontend_playback_failed_) + url);
return 0L;
} catch (Exception ex) {
this.ex = ex;
if (BuildConfig.DEBUG)
Log.e(TAG, ex.getMessage(), ex);
if (appSettings.isErrorReportingEnabled())
new Reporter(ex).send();
return -1L;
}
}
protected void onPostExecute(Long result) {
if (result != 0L) {
if (ex != null)
Toast.makeText(appSettings.getAppContext(), Localizer.getStringRes(R.string.frontend_playback_error_) + ex.toString(), Toast.LENGTH_LONG).show();
}
}
}
private class StopTask extends AsyncTask<URL, Integer, Long> {
private Exception ex;
protected Long doInBackground(URL... urls) {
try {
sendAction("STOPPLAYBACK");
Thread.sleep(250);
return 0L;
} catch (Exception ex) {
this.ex = ex;
if (BuildConfig.DEBUG)
Log.e(TAG, ex.getMessage(), ex);
if (appSettings.isErrorReportingEnabled())
new Reporter(ex).send();
return -1L;
}
}
protected void onPostExecute(Long result) {
if (result != 0L) {
if (ex != null)
Toast.makeText(appSettings.getAppContext(), Localizer.getStringRes(R.string.error_frontend_status_) + ex.toString(), Toast.LENGTH_LONG).show();
}
}
}
/**
* Must be on background thread.
*/
private void sendAction(String action) throws IOException, JSONException {
URL url = new URL(appSettings.getFrontendServiceBaseUrl() + "/Frontend/SendAction?Action=" + URLEncoder.encode(action, "UTF-8"));
HttpHelper poster = new HttpHelper(new URL[]{url}, AuthType.None.toString(), appSettings.getPrefs());
String resJson = new String(poster.post(), "UTF-8");
boolean res = new MythTvParser(appSettings, resJson).parseBool();
if (!res)
throw new ServiceException(Localizer.getStringRes(R.string.error_performing_frontend_action_) + url);
}
}
| Fix occasional frontend playback issues for recordings. | src/com/oakesville/mythling/util/ServiceFrontendPlayer.java | Fix occasional frontend playback issues for recordings. | <ide><path>rc/com/oakesville/mythling/util/ServiceFrontendPlayer.java
<ide> }
<ide>
<ide> /**
<del> * Must be on background thread.
<add> * Perform a MythTV SendAction. Must be on background thread.
<ide> */
<ide> private void sendAction(String action) throws IOException, JSONException {
<ide> URL url = new URL(appSettings.getFrontendServiceBaseUrl() + "/Frontend/SendAction?Action=" + URLEncoder.encode(action, "UTF-8")); |
|
JavaScript | mit | 83630bd0e3090cca4f7b1b6b35c20ae455f31da7 | 0 | Sosowski/Screeps_Custom,Sosowski/Screeps_Custom | var creep_trump = {
/** @param {Creep} creep **/
run: function(creep) {
if (creep.memory.building && creep.carry.energy == 0) {
delete creep.memory.building;
} else if (_.sum(creep.carry) == creep.carryCapacity && !creep.memory.building) {
creep.memory.building = true;
}
if (!creep.memory.building) {
if (creep.room.name != creep.memory.destination) {
creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
} else {
sources = creep.pos.findClosestByRange(FIND_SOURCES_ACTIVE);
if (sources) {
if (creep.harvest(sources) == ERR_NOT_IN_RANGE) {
creep.moveTo(sources);
}
}
}
} else {
if (creep.room.controller.level < 2) {
//Upgrade the controller
if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
creep.moveTo(creep.room.controller);
}
} else {
var targets = creep.pos.findClosestByRange(FIND_CONSTRUCTION_SITES);
if (targets) {
if (creep.build(targets) == ERR_NOT_IN_RANGE) {
creep.moveTo(targets);
}
} else {
var closestDamagedStructure = [];
closestDamagedStructure = creep.room.find(FIND_STRUCTURES, {
filter: (structure) => (structure.structureType != STRUCTURE_ROAD) && (structure.hits < 100000)
});
if (closestDamagedStructure.length > 0) {
closestDamagedStructure.sort(repairCompare);
creep.memory.structureTarget = closestDamagedStructure[0].id;
if (creep.repair(closestDamagedStructure[0]) == ERR_NOT_IN_RANGE) {
creep.moveTo(closestDamagedStructure[0], {
reusePath: 25,
maxRooms: 1
});
}
} else {
//America has been made great again.
if (Game.flags["WallThis"]) {
Game.flags["WallThis"].remove();
} else {
creep.suicide();
}
}
}
}
}
}
};
module.exports = creep_trump; | MainCode/creep.trump.js | var creep_trump = {
/** @param {Creep} creep **/
run: function(creep) {
if (creep.memory.building && creep.carry.energy == 0) {
delete creep.memory.building;
} else if (_.sum(creep.carry) == creep.carryCapacity && !creep.memory.building) {
creep.memory.building = true;
}
if (!creep.memory.building) {
if (creep.room.name != creep.memory.destination) {
creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
} else {
sources = creep.pos.findClosestByRange(FIND_SOURCES_ACTIVE);
if (sources) {
if (creep.harvest(sources) == ERR_NOT_IN_RANGE) {
creep.moveTo(sources);
}
}
}
} else {
var targets = creep.pos.findClosestByRange(FIND_CONSTRUCTION_SITES);
if (targets) {
if (creep.build(targets) == ERR_NOT_IN_RANGE) {
creep.moveTo(targets);
}
} else {
var closestDamagedStructure = [];
closestDamagedStructure = creep.room.find(FIND_STRUCTURES, {
filter: (structure) => (structure.structureType != STRUCTURE_ROAD) && (structure.hits < 100000)
});
if (closestDamagedStructure.length > 0) {
closestDamagedStructure.sort(repairCompare);
creep.memory.structureTarget = closestDamagedStructure[0].id;
if (creep.repair(closestDamagedStructure[0]) == ERR_NOT_IN_RANGE) {
creep.moveTo(closestDamagedStructure[0], {
reusePath: 25,
maxRooms: 1
});
}
} else {
//America has been made great again.
if (Game.flags["WallThis"]) {
Game.flags["WallThis"].remove();
} else {
creep.suicide();
}
}
}
}
}
};
module.exports = creep_trump; | Gotta make it stronger before greater
| MainCode/creep.trump.js | Gotta make it stronger before greater | <ide><path>ainCode/creep.trump.js
<ide> }
<ide> }
<ide> } else {
<del> var targets = creep.pos.findClosestByRange(FIND_CONSTRUCTION_SITES);
<del> if (targets) {
<del> if (creep.build(targets) == ERR_NOT_IN_RANGE) {
<del> creep.moveTo(targets);
<add> if (creep.room.controller.level < 2) {
<add> //Upgrade the controller
<add> if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
<add> creep.moveTo(creep.room.controller);
<ide> }
<ide> } else {
<del> var closestDamagedStructure = [];
<del> closestDamagedStructure = creep.room.find(FIND_STRUCTURES, {
<del> filter: (structure) => (structure.structureType != STRUCTURE_ROAD) && (structure.hits < 100000)
<del> });
<del>
<del> if (closestDamagedStructure.length > 0) {
<del> closestDamagedStructure.sort(repairCompare);
<del> creep.memory.structureTarget = closestDamagedStructure[0].id;
<del> if (creep.repair(closestDamagedStructure[0]) == ERR_NOT_IN_RANGE) {
<del> creep.moveTo(closestDamagedStructure[0], {
<del> reusePath: 25,
<del> maxRooms: 1
<del> });
<add> var targets = creep.pos.findClosestByRange(FIND_CONSTRUCTION_SITES);
<add> if (targets) {
<add> if (creep.build(targets) == ERR_NOT_IN_RANGE) {
<add> creep.moveTo(targets);
<ide> }
<ide> } else {
<del> //America has been made great again.
<del> if (Game.flags["WallThis"]) {
<del> Game.flags["WallThis"].remove();
<add> var closestDamagedStructure = [];
<add> closestDamagedStructure = creep.room.find(FIND_STRUCTURES, {
<add> filter: (structure) => (structure.structureType != STRUCTURE_ROAD) && (structure.hits < 100000)
<add> });
<add>
<add> if (closestDamagedStructure.length > 0) {
<add> closestDamagedStructure.sort(repairCompare);
<add> creep.memory.structureTarget = closestDamagedStructure[0].id;
<add> if (creep.repair(closestDamagedStructure[0]) == ERR_NOT_IN_RANGE) {
<add> creep.moveTo(closestDamagedStructure[0], {
<add> reusePath: 25,
<add> maxRooms: 1
<add> });
<add> }
<ide> } else {
<del> creep.suicide();
<add> //America has been made great again.
<add> if (Game.flags["WallThis"]) {
<add> Game.flags["WallThis"].remove();
<add> } else {
<add> creep.suicide();
<add> }
<ide> }
<ide> }
<ide> } |
|
Java | mit | ba63ad4a5e4950b5e80a387b22109e29db4adffa | 0 | D101F14/TinyVM,D101F14/TinyVM,D101F14/TinyVM | package dk.aau.d101f14.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
public class InformationCollector {
public static void main(String[] args) {
String errorText = "";
ArrayList<String> errorList = new ArrayList<String>();
HashMap<String,Integer> faultList = new HashMap<String,Integer>();
int normalTermination = 0;
int silentDataCorruption = 0;
int tinyVMNullReferenceException = 0;
int javaNullPointerException = 0;
int tinyVMOutOfMemoryException = 0;
int javaOutOfMemoryException = 0;
int tinyVMDivisionByZeroException = 0;
int tinyVMInvalidField = 0;
int javaArrayIndexOutOfBoundsException = 0;
int unknown = 0;
int masked = 0;
int correctRecovery = 0;
String pathToRootDirectoryForVM = args[0];
String pathToVMJarFile = args[1];
String pathToScript = args[2];
int numberOfTimesToRun = Integer.parseInt(args[3]);
String byteManPath = args[4];
int progress = 0;
int tempProgress = 0;
for(int i = 0; i < numberOfTimesToRun;i++){
ProcessBuilder pb = new ProcessBuilder("java", "-javaagent:"+byteManPath +"\\lib\\byteman.jar=script:"+pathToScript, "-jar", pathToVMJarFile, pathToRootDirectoryForVM);
pb.redirectErrorStream();
try {
tempProgress = i * 100 / numberOfTimesToRun;
if(tempProgress/5 > progress/5){
progress = tempProgress;
System.out.println(progress + "%");
}
Process p = pb.start();
p.waitFor();
String output = readString(p.getInputStream());
String flip = identifyFault(output);
String fault = "";
int count = 0;
if(p.exitValue() == returnValues.NORMAL.getCode()){
if(output.contains("0123456789") && output.contains("ROLLBACK")){
correctRecovery++;
fault = "Recovery";
errorList.add(fault+"\n"+output);
}else if(output.contains("0123456789") && output.contains("After instruction") && !output.contains("ROLLBACK")){
masked++;
fault = "Masked";
errorList.add("Masked:\n"+output);
}else if(output.contains("0123456789") && !output.contains("After instruction")){
normalTermination++;
fault = "Normal termination";
errorList.add("Normal termination:\n"+output);
}else{
silentDataCorruption++;
fault = "Silent data corruption";
errorList.add("Silent data corruption:\n"+output);
}
}else if(p.exitValue() == returnValues.JAVAFAULT.getCode()){
errorText = readString(p.getErrorStream());
if(errorText.contains("NullPointerException")){
javaNullPointerException++;
fault = "Java crash (Null pointer)";
errorList.add("Java crash (Null pointer):\n"+output+"\n"+errorText);
}else if(errorText.contains("ArrayIndexOutOfBoundsException")){
javaArrayIndexOutOfBoundsException++;
fault = "Java crash (Array index out of bounds)";
errorList.add("Java crash (Array index out of bounds):\n"+output+"\n"+errorText);
}else if(errorText.contains("OutOfMemoryException")){
javaOutOfMemoryException++;
fault = "Java crash (Out of memory)";
errorList.add("Java crash (Out of memory):\n"+output+"\n"+errorText);
}else{
unknown++;
fault = "Unknown";
errorList.add("Java crash (unknown):\n"+output+"\n"+errorText);
}
}else if(p.exitValue() == returnValues.NULLREF.getCode()){
tinyVMNullReferenceException++;
fault = "TinyVm unhandled exception (Null reference)";
errorList.add("TinyVm unhandled exception (Null reference):\n"+output);
}else if(p.exitValue() == returnValues.OUTOFMEM.getCode()){
tinyVMOutOfMemoryException++;
fault = "TinyVm unhandled exception (Out of memory)";
errorList.add("TinyVm unhandled exception (Out of memory):\n"+output);
}else if(p.exitValue() == returnValues.DIVBYZERO.getCode()){
tinyVMDivisionByZeroException++;
fault = "TinyVm unhandled exception (Division by zero)";
errorList.add("TinyVm unhandled exception (Division by zero):\n"+output);
}else if(p.exitValue() == returnValues.FIELD.getCode()){
tinyVMInvalidField++;
fault = "TinyVm undefined field access";
errorList.add("TinyVm undefined field access:\n"+output);
}
if(faultList.containsKey(flip+","+fault)){
count = faultList.get(flip+","+fault).intValue();
}
System.out.println(count);
faultList.put(flip+","+fault, new Integer(count++));
p.destroy();
} catch (Exception exp) {
exp.printStackTrace();
}
}
System.out.println("Output for the individual runs:");
for(int i = 0; i < errorList.size(); i++){
System.out.println("\nRun "+(i+1)+" - " + errorList.get(i));
}
System.out.println("\nTotal count of termination status:\n");
System.out.println(" Normal termination:\t\t\t " + normalTermination);
System.out.println(" Recovery:\t\t\t\t " + correctRecovery);
System.out.println(" Masked:\t\t\t\t " + masked);
System.out.println(" Silent Data Corruption:\t\t " + silentDataCorruption);
System.out.println("(TinyVM) Null Reference Exception:\t\t " + tinyVMNullReferenceException);
System.out.println("(Java) Null Pointer Exception:\t\t " + javaNullPointerException);
System.out.println("(TinyVM) Out Of Memory Exception:\t\t " + tinyVMOutOfMemoryException);
System.out.println("(Java) Out Of Memory Exception:\t\t " + javaOutOfMemoryException);
System.out.println("(TinyVM) Division By Zero Exception:\t\t " + tinyVMDivisionByZeroException);
System.out.println("(TinyVM) Invalid Field:\t\t\t\t " + tinyVMInvalidField);
System.out.println("(Java) Array Index Out Of Bounds Exception:\t " + javaArrayIndexOutOfBoundsException);
System.out.println("(Java) Unknown:\t\t\t\t " + unknown);
String os = "\nTermination by bitflip on the Operand Stack:\n";
String os_r = "\nTermination by bitflip on the Operand Stack R:\n";
String pc = "\nTermination by bitflip in the Program Counter:\n";
String pc_r = "\nTermination by bitflip on the Program Counter R:\n";
String lh = "\nTermination by bitflip in the Local Heap:\n";
String lh_r = "\nTermination by bitflip in the Local Heap R:\n";
String lv = "\nTermination by bitflip in the Local Variables:\n";
String lv_r = "\nTermination by bitflip in the Local Variables R:\n";
for(Entry<String, Integer> entry : faultList.entrySet()){
String[] split = entry.getKey().split(",");
String flip = split[0];
String fault = split[1];
switch(flip){
case "OS":
os += "\t"+fault+": "+entry.getValue().intValue() + "\n";
break;
case "OS_R":
os_r += "\t"+fault+": "+entry.getValue().intValue() + "\n";
break;
case "PC":
pc += "\t"+fault+": "+entry.getValue().intValue() + "\n";
break;
case "PC_R":
pc_r += "\t"+fault+": "+entry.getValue().intValue() + "\n";
break;
case "LH":
lh += "\t"+fault+": "+entry.getValue().intValue() + "\n";
break;
case "LH_R":
lh_r += "\t"+fault+": "+entry.getValue().intValue() + "\n";
break;
case "LV":
lv += "\t"+fault+": "+entry.getValue().intValue() + "\n";
break;
case "LV_R":
lv_r += "\t"+fault+": "+entry.getValue().intValue() + "\n";
break;
default:
break;
}
}
System.out.println(os + os_r + pc + pc_r + lh + lh_r + lv + lv_r);
}
private static String readString(InputStream is){
StringBuilder sb = new StringBuilder(64);
int value = -1;
try {
while ((value = is.read()) != -1) {
sb.append((char)value);
}
} catch (IOException exp) {
exp.printStackTrace();
sb.append(exp.getMessage());
}
return sb.toString();
}
private static String identifyFault(String text){
if(text.contains("After instruction") && text.contains("OS") && !text.contains("OS_R")){
return "OS";
}else if(text.contains("After instruction") && text.contains("OS_R")){
return "OS_R";
}else if(text.contains("After instruction") && text.contains("Program Counter") && !text.contains("Program Counter R")){
return "PC";
}else if(text.contains("After instruction") && text.contains("Program Counter R")){
return "PC_R";
}else if(text.contains("After instruction") && text.contains("Local Heap") && !text.contains("Local Heap R")){
return "LH";
}else if(text.contains("After instruction") && text.contains("Local Heap R")){
return "LH_R";
}else if(text.contains("After instruction") && text.contains("Local Variables") && !text.contains("Local Variables R")){
return "LV";
}else if(text.contains("After instruction") && text.contains("Local Variables R")){
return "LV_R";
}
return "";
}
public enum returnValues{
NORMAL(0),JAVAFAULT(1),NULLREF(2),OUTOFMEM(3),DIVBYZERO(4),FIELD(5);
private int errorCode;
private returnValues(int id){
errorCode = id;
}
public int getCode(){
return errorCode;
}
}
}
| src/dk/aau/d101f14/test/InformationCollector.java | package dk.aau.d101f14.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class InformationCollector {
public static void main(String[] args) {
String errorText = "";
ArrayList<String> errorList = new ArrayList<String>();
int normalTermination = 0;
int silentDataCorruption = 0;
int tinyVMNullReferenceException = 0;
int javaNullPointerException = 0;
int tinyVMOutOfMemoryException = 0;
int javaOutOfMemoryException = 0;
int tinyVMDivisionByZeroException = 0;
int tinyVMInvalidField = 0;
int javaArrayIndexOutOfBoundsException = 0;
int unknown = 0;
int masked = 0;
int correctRecovery = 0;
String pathToRootDirectoryForVM = args[0];
String pathToVMJarFile = args[1];
String pathToScript = args[2];
int numberOfTimesToRun = Integer.parseInt(args[3]);
String byteManPath = args[4];
int progress = 0;
int tempProgress = 0;
for(int i = 0; i < numberOfTimesToRun;i++){
ProcessBuilder pb = new ProcessBuilder("java", "-javaagent:"+byteManPath +"\\lib\\byteman.jar=script:"+pathToScript, "-jar", pathToVMJarFile, pathToRootDirectoryForVM);
pb.redirectErrorStream();
try {
tempProgress = i * 100 / numberOfTimesToRun;
if(tempProgress/5 > progress/5){
progress = tempProgress;
System.out.println(progress + "%");
}
Process p = pb.start();
p.waitFor();
if(p.exitValue() == returnValues.NORMAL.getCode()){
String text = readString(p.getInputStream());
if(text.contains("0123456789") && text.contains("ROLLBACK")){
correctRecovery++;
errorList.add("Recovery:\n"+text);
}else if(text.contains("0123456789") && text.contains("After instruction") && !text.contains("ROLLBACK")){
masked++;
errorList.add("Masked:\n"+text);
}else if(text.contains("0123456789") && !text.contains("After instruction")){
normalTermination++;
errorList.add("Normal termination:\n"+text);
}else{
silentDataCorruption++;
errorList.add("Silent data corruption:\n"+text);
}
}else if(p.exitValue() == returnValues.JAVAFAULT.getCode()){
errorText = readString(p.getErrorStream());
if(errorText.contains("NullPointerException")){
javaNullPointerException++;
errorList.add("Java crash (Null pointer):\n"+readString(p.getInputStream())+"\n"+errorText);
}else if(errorText.contains("ArrayIndexOutOfBoundsException")){
javaArrayIndexOutOfBoundsException++;
errorList.add("Java crash (Array index out of bounds):\n"+readString(p.getInputStream())+"\n"+errorText);
}else if(errorText.contains("OutOfMemoryException")){
javaOutOfMemoryException++;
errorList.add("Java crash (Out of memory):\n"+readString(p.getInputStream())+"\n"+errorText);
}else{
unknown++;
errorList.add("Java crash (unknown):\n"+readString(p.getInputStream())+"\n"+errorText);
}
}else if(p.exitValue() == returnValues.NULLREF.getCode()){
tinyVMNullReferenceException++;
errorList.add("TinyVm unhandled exception (Null reference):\n"+readString(p.getInputStream()));
}else if(p.exitValue() == returnValues.OUTOFMEM.getCode()){
tinyVMOutOfMemoryException++;
errorList.add("TinyVm unhandled exception (Out of memory):\n"+readString(p.getInputStream()));
}else if(p.exitValue() == returnValues.DIVBYZERO.getCode()){
tinyVMDivisionByZeroException++;
errorList.add("TinyVm unhandled exception (Division by zero):\n"+readString(p.getInputStream()));
}else if(p.exitValue() == returnValues.FIELD.getCode()){
tinyVMInvalidField++;
errorList.add("TinyVm undefined field access:\n"+readString(p.getInputStream()));
}
p.destroy();
} catch (Exception exp) {
exp.printStackTrace();
}
}
System.out.println("Output for the individual runs:");
for(int i = 0; i < errorList.size(); i++){
System.out.println("\nRun "+(i+1)+" - " + errorList.get(i));
}
System.out.println("\nTotal count of termination status:\n");
System.out.println(" Normal termination:\t\t\t " + normalTermination);
System.out.println(" Recovery:\t\t\t\t " + correctRecovery);
System.out.println(" Masked:\t\t\t\t " + masked);
System.out.println(" Silent Data Corruption:\t\t " + silentDataCorruption);
System.out.println("(TinyVM) Null Reference Exception:\t\t " + tinyVMNullReferenceException);
System.out.println("(Java) Null Pointer Exception:\t\t " + javaNullPointerException);
System.out.println("(TinyVM) Out Of Memory Exception:\t\t " + tinyVMOutOfMemoryException);
System.out.println("(Java) Out Of Memory Exception:\t\t " + javaOutOfMemoryException);
System.out.println("(TinyVM) Division By Zero Exception:\t\t " + tinyVMDivisionByZeroException);
System.out.println("(TinyVM) Invalid Field:\t\t\t\t " + tinyVMInvalidField);
System.out.println("(Java) Array Index Out Of Bounds Exception:\t " + javaArrayIndexOutOfBoundsException);
System.out.println("(Java) Unknown:\t\t\t\t " + unknown);
}
private static String readString(InputStream is){
StringBuilder sb = new StringBuilder(64);
int value = -1;
try {
while ((value = is.read()) != -1) {
sb.append((char)value);
}
} catch (IOException exp) {
exp.printStackTrace();
sb.append(exp.getMessage());
}
return sb.toString();
}
public enum returnValues{
NORMAL(0),JAVAFAULT(1),NULLREF(2),OUTOFMEM(3),DIVBYZERO(4),FIELD(5);
private int errorCode;
private returnValues(int id){
errorCode = id;
}
public int getCode(){
return errorCode;
}
}
}
| Update InformationCollector to log fault and type counts
| src/dk/aau/d101f14/test/InformationCollector.java | Update InformationCollector to log fault and type counts | <ide><path>rc/dk/aau/d101f14/test/InformationCollector.java
<ide> import java.io.IOException;
<ide> import java.io.InputStream;
<ide> import java.util.ArrayList;
<add>import java.util.HashMap;
<add>import java.util.Map.Entry;
<ide>
<ide> public class InformationCollector {
<ide>
<ide> public static void main(String[] args) {
<ide> String errorText = "";
<ide> ArrayList<String> errorList = new ArrayList<String>();
<add> HashMap<String,Integer> faultList = new HashMap<String,Integer>();
<ide> int normalTermination = 0;
<ide> int silentDataCorruption = 0;
<ide> int tinyVMNullReferenceException = 0;
<ide>
<ide> p.waitFor();
<ide>
<add> String output = readString(p.getInputStream());
<add> String flip = identifyFault(output);
<add> String fault = "";
<add> int count = 0;
<add>
<ide> if(p.exitValue() == returnValues.NORMAL.getCode()){
<del> String text = readString(p.getInputStream());
<del>
<del> if(text.contains("0123456789") && text.contains("ROLLBACK")){
<add> if(output.contains("0123456789") && output.contains("ROLLBACK")){
<ide> correctRecovery++;
<del> errorList.add("Recovery:\n"+text);
<del> }else if(text.contains("0123456789") && text.contains("After instruction") && !text.contains("ROLLBACK")){
<add> fault = "Recovery";
<add> errorList.add(fault+"\n"+output);
<add> }else if(output.contains("0123456789") && output.contains("After instruction") && !output.contains("ROLLBACK")){
<ide> masked++;
<del> errorList.add("Masked:\n"+text);
<del> }else if(text.contains("0123456789") && !text.contains("After instruction")){
<add> fault = "Masked";
<add> errorList.add("Masked:\n"+output);
<add> }else if(output.contains("0123456789") && !output.contains("After instruction")){
<ide> normalTermination++;
<del> errorList.add("Normal termination:\n"+text);
<add> fault = "Normal termination";
<add> errorList.add("Normal termination:\n"+output);
<ide> }else{
<ide> silentDataCorruption++;
<del> errorList.add("Silent data corruption:\n"+text);
<add> fault = "Silent data corruption";
<add> errorList.add("Silent data corruption:\n"+output);
<ide> }
<ide> }else if(p.exitValue() == returnValues.JAVAFAULT.getCode()){
<ide> errorText = readString(p.getErrorStream());
<ide>
<ide> if(errorText.contains("NullPointerException")){
<ide> javaNullPointerException++;
<del> errorList.add("Java crash (Null pointer):\n"+readString(p.getInputStream())+"\n"+errorText);
<add> fault = "Java crash (Null pointer)";
<add> errorList.add("Java crash (Null pointer):\n"+output+"\n"+errorText);
<ide> }else if(errorText.contains("ArrayIndexOutOfBoundsException")){
<ide> javaArrayIndexOutOfBoundsException++;
<del> errorList.add("Java crash (Array index out of bounds):\n"+readString(p.getInputStream())+"\n"+errorText);
<add> fault = "Java crash (Array index out of bounds)";
<add> errorList.add("Java crash (Array index out of bounds):\n"+output+"\n"+errorText);
<ide> }else if(errorText.contains("OutOfMemoryException")){
<ide> javaOutOfMemoryException++;
<del> errorList.add("Java crash (Out of memory):\n"+readString(p.getInputStream())+"\n"+errorText);
<add> fault = "Java crash (Out of memory)";
<add> errorList.add("Java crash (Out of memory):\n"+output+"\n"+errorText);
<ide> }else{
<ide> unknown++;
<del> errorList.add("Java crash (unknown):\n"+readString(p.getInputStream())+"\n"+errorText);
<add> fault = "Unknown";
<add> errorList.add("Java crash (unknown):\n"+output+"\n"+errorText);
<ide> }
<ide> }else if(p.exitValue() == returnValues.NULLREF.getCode()){
<ide> tinyVMNullReferenceException++;
<del> errorList.add("TinyVm unhandled exception (Null reference):\n"+readString(p.getInputStream()));
<add> fault = "TinyVm unhandled exception (Null reference)";
<add> errorList.add("TinyVm unhandled exception (Null reference):\n"+output);
<ide> }else if(p.exitValue() == returnValues.OUTOFMEM.getCode()){
<ide> tinyVMOutOfMemoryException++;
<del> errorList.add("TinyVm unhandled exception (Out of memory):\n"+readString(p.getInputStream()));
<add> fault = "TinyVm unhandled exception (Out of memory)";
<add> errorList.add("TinyVm unhandled exception (Out of memory):\n"+output);
<ide> }else if(p.exitValue() == returnValues.DIVBYZERO.getCode()){
<ide> tinyVMDivisionByZeroException++;
<del> errorList.add("TinyVm unhandled exception (Division by zero):\n"+readString(p.getInputStream()));
<add> fault = "TinyVm unhandled exception (Division by zero)";
<add> errorList.add("TinyVm unhandled exception (Division by zero):\n"+output);
<ide> }else if(p.exitValue() == returnValues.FIELD.getCode()){
<ide> tinyVMInvalidField++;
<del> errorList.add("TinyVm undefined field access:\n"+readString(p.getInputStream()));
<add> fault = "TinyVm undefined field access";
<add> errorList.add("TinyVm undefined field access:\n"+output);
<ide> }
<add>
<add>
<add> if(faultList.containsKey(flip+","+fault)){
<add> count = faultList.get(flip+","+fault).intValue();
<add> }
<add> System.out.println(count);
<add> faultList.put(flip+","+fault, new Integer(count++));
<add>
<ide> p.destroy();
<ide> } catch (Exception exp) {
<ide> exp.printStackTrace();
<ide> System.out.println("(TinyVM) Division By Zero Exception:\t\t " + tinyVMDivisionByZeroException);
<ide> System.out.println("(TinyVM) Invalid Field:\t\t\t\t " + tinyVMInvalidField);
<ide> System.out.println("(Java) Array Index Out Of Bounds Exception:\t " + javaArrayIndexOutOfBoundsException);
<del> System.out.println("(Java) Unknown:\t\t\t\t " + unknown);
<add> System.out.println("(Java) Unknown:\t\t\t\t " + unknown);
<add>
<add>
<add> String os = "\nTermination by bitflip on the Operand Stack:\n";
<add> String os_r = "\nTermination by bitflip on the Operand Stack R:\n";
<add> String pc = "\nTermination by bitflip in the Program Counter:\n";
<add> String pc_r = "\nTermination by bitflip on the Program Counter R:\n";
<add> String lh = "\nTermination by bitflip in the Local Heap:\n";
<add> String lh_r = "\nTermination by bitflip in the Local Heap R:\n";
<add> String lv = "\nTermination by bitflip in the Local Variables:\n";
<add> String lv_r = "\nTermination by bitflip in the Local Variables R:\n";
<add>
<add> for(Entry<String, Integer> entry : faultList.entrySet()){
<add>
<add> String[] split = entry.getKey().split(",");
<add>
<add> String flip = split[0];
<add> String fault = split[1];
<add>
<add> switch(flip){
<add> case "OS":
<add> os += "\t"+fault+": "+entry.getValue().intValue() + "\n";
<add> break;
<add> case "OS_R":
<add> os_r += "\t"+fault+": "+entry.getValue().intValue() + "\n";
<add> break;
<add> case "PC":
<add> pc += "\t"+fault+": "+entry.getValue().intValue() + "\n";
<add> break;
<add> case "PC_R":
<add> pc_r += "\t"+fault+": "+entry.getValue().intValue() + "\n";
<add> break;
<add> case "LH":
<add> lh += "\t"+fault+": "+entry.getValue().intValue() + "\n";
<add> break;
<add> case "LH_R":
<add> lh_r += "\t"+fault+": "+entry.getValue().intValue() + "\n";
<add> break;
<add> case "LV":
<add> lv += "\t"+fault+": "+entry.getValue().intValue() + "\n";
<add> break;
<add> case "LV_R":
<add> lv_r += "\t"+fault+": "+entry.getValue().intValue() + "\n";
<add> break;
<add> default:
<add> break;
<add> }
<add> }
<add> System.out.println(os + os_r + pc + pc_r + lh + lh_r + lv + lv_r);
<ide> }
<ide>
<ide> private static String readString(InputStream is){
<ide> return sb.toString();
<ide> }
<ide>
<add> private static String identifyFault(String text){
<add>
<add> if(text.contains("After instruction") && text.contains("OS") && !text.contains("OS_R")){
<add> return "OS";
<add> }else if(text.contains("After instruction") && text.contains("OS_R")){
<add> return "OS_R";
<add> }else if(text.contains("After instruction") && text.contains("Program Counter") && !text.contains("Program Counter R")){
<add> return "PC";
<add> }else if(text.contains("After instruction") && text.contains("Program Counter R")){
<add> return "PC_R";
<add> }else if(text.contains("After instruction") && text.contains("Local Heap") && !text.contains("Local Heap R")){
<add> return "LH";
<add> }else if(text.contains("After instruction") && text.contains("Local Heap R")){
<add> return "LH_R";
<add> }else if(text.contains("After instruction") && text.contains("Local Variables") && !text.contains("Local Variables R")){
<add> return "LV";
<add> }else if(text.contains("After instruction") && text.contains("Local Variables R")){
<add> return "LV_R";
<add> }
<add>
<add> return "";
<add> }
<add>
<ide>
<ide> public enum returnValues{
<ide> NORMAL(0),JAVAFAULT(1),NULLREF(2),OUTOFMEM(3),DIVBYZERO(4),FIELD(5); |
|
JavaScript | mit | f52b4009bbcf4339090c74622fd7a6be50688603 | 0 | PonteIneptique/arethusa,PonteIneptique/arethusa,Masoumeh/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,latin-language-toolkit/arethusa,fbaumgardt/arethusa,fbaumgardt/arethusa,latin-language-toolkit/arethusa,Masoumeh/arethusa,alpheios-project/arethusa | 'use strict';
/* A newable factory to handle xml files using the Perseus Treebank Schema
*
* The constructor functions takes a configuration object (that typically
* contains a resource object for this service).
*
*/
angular.module('arethusa').factory('TreebankRetriever', [
'configurator',
'documentStore',
'retrieverHelper',
'idHandler',
function (configurator, documentStore, retrieverHelper, idHandler) {
function xmlTokenToState(docId, token, sentenceId, artificials) {
// One could formalize this to real rules that are configurable...
//
// Remember that attributes of the converted xml are prefixed with underscore
var obj = aC.token(token._form, sentenceId);
obj.morphology = {
lemma: token._lemma,
postag: token._postag
};
obj.relation = {};
var relation = token._relation;
obj.relation.label = (relation && relation !== 'nil') ? relation : '';
var gloss = token._gloss;
if (gloss) {
obj.morphology.gloss = gloss;
}
var sg = token._sg;
if (sg && !sg.match(/^\s*$/)) {
obj.sg = { ancestors: sg.split(' ') };
}
if (token._artificial) {
obj.artificial = true;
obj.type = token._artificial;
}
if (aU.isTerminatingPunctuation(obj.string)) {
obj.terminator = true;
}
var intId = xmlTokenId(token, sentenceId);
retrieverHelper.generateId(obj, intId, token._id, docId);
createHead(obj, token, artificials);
return obj;
}
function createHead(stateToken, xmlToken, artificials) {
var head = xmlToken._head;
if (angular.isDefined(head) && head !== "") {
var newHead = {};
var artHead = artificials[head];
newHead.id = artHead ? artHead : idHandler.getId(head, stateToken.sentenceId);
stateToken.head = newHead;
}
}
function xmlTokenId(token, sentenceId) {
if (token._artificial) {
return padWithSentenceId(token._insertion_id, sentenceId);
} else {
return idHandler.getId(token._id, sentenceId);
}
}
// This is for backwards compatibility - we still might encounter documents, which
// stored the insertion id without the sentence id. This is a little hacky but a
// must have.
function padWithSentenceId(id, sentenceId) {
return (id.match(/-/)) ? id : idHandler.padIdWithSId(id, sentenceId);
}
function extractArtificial(memo, token, sentenceId) {
if (token._artificial) {
memo[token._id] = padWithSentenceId(token._insertion_id, sentenceId);
}
}
function xmlSentenceToState(docId, words, id, cite) {
var tokens = {};
var artificials = arethusaUtil.inject({}, words, function(memo, token, i) {
extractArtificial(memo, token, id);
});
angular.forEach(words, function (xmlToken, i) {
var token = xmlTokenToState(docId, xmlToken, id, artificials);
tokens[token.id] = token;
});
return aC.sentence(id, tokens, cite);
}
function parseDocument(json, docId) {
var sentences = arethusaUtil.toAry(json.treebank.sentence);
return arethusaUtil.inject([], sentences, function (memo, sentence, k) {
var cite = extractCiteInfo(sentence);
var words = arethusaUtil.toAry(sentence.word);
memo.push(xmlSentenceToState(docId, words, sentence._id, cite));
});
}
// Try to support the new as well as the old schema for now
function extractCiteInfo(sentence) {
var cite = sentence._cite;
if (cite) {
return cite;
} else {
var docId = sentence._document_id;
var subdoc = sentence._subdoc;
if (subdoc) {
return docId + ':' + subdoc;
} else {
return docId;
}
}
}
function findAdditionalConfInfo(json) {
var linkInfo = json.treebank.link;
var links = linkInfo ? arethusaUtil.toAry(linkInfo) : [];
var confs = arethusaUtil.inject({}, links, function(memo, link) {
memo[link._title] = link._href;
});
var format = json.treebank._format;
if (format) {
// For backwards compatibility to older days
if (format == 'aldt') {
format = 'aldt2' + json.treebank['_xml:lang'];
}
confs.fullFile = format;
}
return confs;
}
return function (conf) {
var self = this;
var resource = configurator.provideResource(conf.resource);
var docId = conf.docIdentifier;
this.preselections = retrieverHelper.getPreselections(conf);
this.parse = function(xml, callback) {
var json = arethusaUtil.xml2json(xml);
var moreConf = findAdditionalConfInfo(json);
documentStore.addDocument(docId, new aC.doc(xml, json, moreConf));
callback(parseDocument(json, docId));
};
this.get = function (callback) {
resource.get().then(function (res) {
self.parse(res.data, callback);
});
};
};
}
]);
| app/js/arethusa/treebank_retriever.js | 'use strict';
/* A newable factory to handle xml files using the Perseus Treebank Schema
*
* The constructor functions takes a configuration object (that typically
* contains a resource object for this service).
*
*/
angular.module('arethusa').factory('TreebankRetriever', [
'configurator',
'documentStore',
'retrieverHelper',
'idHandler',
function (configurator, documentStore, retrieverHelper, idHandler) {
function xmlTokenToState(docId, token, sentenceId, artificials) {
// One could formalize this to real rules that are configurable...
//
// Remember that attributes of the converted xml are prefixed with underscore
var obj = aC.token(token._form, sentenceId);
obj.morphology = {
lemma: token._lemma,
postag: token._postag
};
obj.relation = {};
var relation = token._relation;
obj.relation.label = (relation && relation !== 'nil') ? relation : '';
var gloss = token._gloss;
if (gloss) {
obj.morphology.gloss = gloss;
}
var sg = token._sg;
if (sg && !sg.match(/^\s*$/)) {
obj.sg = { ancestors: sg.split(' ') };
}
if (token._artificial) {
obj.artificial = true;
obj.type = token._artificial;
}
if (aU.isTerminatingPunctuation(obj.string)) {
obj.terminator = true;
}
var intId = xmlTokenId(token, sentenceId);
retrieverHelper.generateId(obj, intId, token._id, docId);
createHead(obj, token, artificials);
return obj;
}
function createHead(stateToken, xmlToken, artificials) {
var head = xmlToken._head;
if (angular.isDefined(head) && head !== "") {
var newHead = {};
var artHead = artificials[head];
newHead.id = artHead ? artHead : idHandler.getId(head, stateToken.sentenceId);
stateToken.head = newHead;
}
}
function xmlTokenId(token, sentenceId) {
if (token._artificial) {
return padWithSentenceId(token._insertion_id, sentenceId);
} else {
return idHandler.getId(token._id, sentenceId);
}
}
// This is for backwards compatibility - we still might encounter documents, which
// stored the insertion id without the sentence id. This is a little hacky but a
// must have.
function padWithSentenceId(id, sentenceId) {
return (id.match(/-/)) ? id : idHandler.padIdWithSId(id, sentenceId);
}
function extractArtificial(memo, token, sentenceId) {
if (token._artificial) {
memo[token._id] = padWithSentenceId(token._insertion_id, sentenceId);
}
}
function xmlSentenceToState(docId, words, id, cite) {
var tokens = {};
var artificials = arethusaUtil.inject({}, words, function(memo, token, i) {
extractArtificial(memo, token, id);
});
angular.forEach(words, function (xmlToken, i) {
var token = xmlTokenToState(docId, xmlToken, id, artificials);
tokens[token.id] = token;
});
return aC.sentence(id, tokens, cite);
}
function parseDocument(json, docId) {
var sentences = arethusaUtil.toAry(json.treebank.sentence);
return arethusaUtil.inject([], sentences, function (memo, sentence, k) {
var cite = extractCiteInfo(sentence);
var words = arethusaUtil.toAry(sentence.word);
memo.push(xmlSentenceToState(docId, words, sentence._id, cite));
});
}
// Try to support the new as well as the old schema for now
function extractCiteInfo(sentence) {
var cite = sentence._cite;
if (cite) {
return cite;
} else {
var docId = sentence._document_id;
var subdoc = sentence._subdoc;
if (subdoc) {
return docId + ':' + subdoc;
} else {
return docId;
}
}
}
function findAdditionalConfInfo(json) {
var linkInfo = json.treebank.link;
var links = linkInfo ? arethusaUtil.toAry(linkInfo) : [];
var confs = arethusaUtil.inject({}, links, function(memo, link) {
memo[link._title] = link._href;
});
var format = json.treebank._format;
if (format) {
// For backwards compatibility to older days
if (format == 'aldt') {
format = 'aldt2' + json.treebank['_xml:lang'];
}
confs.fullFile = format;
}
return confs;
}
return function (conf) {
var self = this;
var resource = configurator.provideResource(conf.resource);
var docId = conf.docIdentifier;
this.preselections = retrieverHelper.getPreselections(conf);
this.get = function (callback) {
resource.get().then(function (res) {
var xml = res.data;
var json = arethusaUtil.xml2json(res.data);
var moreConf = findAdditionalConfInfo(json);
documentStore.addDocument(docId, new aC.doc(xml, json, moreConf));
callback(parseDocument(json, docId));
});
};
};
}
]);
| Extract public parse function in TreebankRetriever
| app/js/arethusa/treebank_retriever.js | Extract public parse function in TreebankRetriever | <ide><path>pp/js/arethusa/treebank_retriever.js
<ide> return confs;
<ide> }
<ide>
<add>
<add>
<ide> return function (conf) {
<ide> var self = this;
<ide> var resource = configurator.provideResource(conf.resource);
<ide>
<ide> this.preselections = retrieverHelper.getPreselections(conf);
<ide>
<add> this.parse = function(xml, callback) {
<add> var json = arethusaUtil.xml2json(xml);
<add> var moreConf = findAdditionalConfInfo(json);
<add>
<add> documentStore.addDocument(docId, new aC.doc(xml, json, moreConf));
<add> callback(parseDocument(json, docId));
<add> };
<add>
<ide> this.get = function (callback) {
<ide> resource.get().then(function (res) {
<del> var xml = res.data;
<del> var json = arethusaUtil.xml2json(res.data);
<del> var moreConf = findAdditionalConfInfo(json);
<del>
<del> documentStore.addDocument(docId, new aC.doc(xml, json, moreConf));
<del> callback(parseDocument(json, docId));
<add> self.parse(res.data, callback);
<ide> });
<ide> };
<ide> }; |
|
Java | bsd-2-clause | dd333044c5ca9b10ce98e6935dc213d2b12c88c2 | 0 | highsource/aufzugswaechter,highsource/aufzugswaechter | package org.hisrc.azw.email.controller;
import java.io.IOException;
import java.text.MessageFormat;
import javax.inject.Inject;
import org.apache.commons.lang3.Validate;
import org.hisrc.azw.email.FacilityStateChangedEventEmailSubscriptionService;
import org.hisrc.azw.recaptcha.RecaptchaValidator;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmailSubscriptionController {
private FacilityStateChangedEventEmailSubscriptionService emailSubscriptionService;
public FacilityStateChangedEventEmailSubscriptionService getEmailSubscriptionService() {
return emailSubscriptionService;
}
@Inject
public void setEmailSubscriptionService(
FacilityStateChangedEventEmailSubscriptionService emailSubscriptionService) {
this.emailSubscriptionService = emailSubscriptionService;
}
private RecaptchaValidator recaptchaValidator;
public RecaptchaValidator getRecaptchaValidator() {
return recaptchaValidator;
}
@Inject
public void setRecaptchaValidator(RecaptchaValidator recaptchaValidator) {
this.recaptchaValidator = recaptchaValidator;
}
@CrossOrigin(origins = { "*" })
@RequestMapping(value = "/facilities/subscriptions/email/{email}/", method = RequestMethod.PUT)
@ResponseBody
public void subscribe(@PathVariable(value = "email") String email,
@RequestParam(name = "token", required = true) String token) {
Validate.notNull(email);
Validate.notNull(token);
try {
if (getRecaptchaValidator().isValid(token)) {
getEmailSubscriptionService().subscribeForAllFacilities(email);
} else {
throw new IllegalArgumentException(MessageFormat.format("Invalid token: [{0}].", token));
}
} catch (IOException ioex) {
throw new IllegalArgumentException(MessageFormat.format("Invalid token: [{0}].", token), ioex);
}
}
@CrossOrigin(origins = { "*" })
@RequestMapping(value = "/facilities/{equipmentnumber}/subscriptions/email/{email}/", method = RequestMethod.PUT)
@ResponseBody
public void subscribe(@PathVariable(value = "equipmentnumber") Long equipmentnumber,
@PathVariable(value = "email") String email,
@RequestParam(name = "token", required = true) String token) {
Validate.notNull(equipmentnumber);
Validate.notNull(email);
Validate.notNull(token);
try {
if (getRecaptchaValidator().isValid(token)) {
getEmailSubscriptionService().subscribeForFacility(equipmentnumber, email);
} else {
throw new IllegalArgumentException(MessageFormat.format("Invalid token: [{0}].", token));
}
} catch (IOException ioex) {
throw new IllegalArgumentException(MessageFormat.format("Invalid token: [{0}].", token), ioex);
}
}
}
| web/src/main/java/org/hisrc/azw/email/controller/EmailSubscriptionController.java | package org.hisrc.azw.email.controller;
import java.io.IOException;
import java.text.MessageFormat;
import javax.inject.Inject;
import org.apache.commons.lang3.Validate;
import org.hisrc.azw.email.FacilityStateChangedEventEmailSubscriptionService;
import org.hisrc.azw.recaptcha.RecaptchaValidator;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmailSubscriptionController {
private FacilityStateChangedEventEmailSubscriptionService emailSubscriptionService;
public FacilityStateChangedEventEmailSubscriptionService getEmailSubscriptionService() {
return emailSubscriptionService;
}
@Inject
public void setEmailSubscriptionService(
FacilityStateChangedEventEmailSubscriptionService emailSubscriptionService) {
this.emailSubscriptionService = emailSubscriptionService;
}
private RecaptchaValidator recaptchaValidator;
public RecaptchaValidator getRecaptchaValidator() {
return recaptchaValidator;
}
@Inject
public void setRecaptchaValidator(RecaptchaValidator recaptchaValidator) {
this.recaptchaValidator = recaptchaValidator;
}
@CrossOrigin(origins = { "*" })
@RequestMapping(value = "/facilities/subscriptions/email/{email}", method = RequestMethod.PUT)
@ResponseBody
public void subscribe(@PathVariable(value = "email") String email,
@RequestParam(name = "token", required = true) String token) {
Validate.notNull(email);
Validate.notNull(token);
try {
if (getRecaptchaValidator().isValid(token)) {
getEmailSubscriptionService().subscribeForAllFacilities(email);
} else {
throw new IllegalArgumentException(MessageFormat.format("Invalid token: [{0}].", token));
}
} catch (IOException ioex) {
throw new IllegalArgumentException(MessageFormat.format("Invalid token: [{0}].", token), ioex);
}
}
@CrossOrigin(origins = { "*" })
@RequestMapping(value = "/facilities/{equipmentnumber}/subscriptions/email/{email}", method = RequestMethod.PUT)
@ResponseBody
public void subscribe(@PathVariable(value = "equipmentnumber") Long equipmentnumber,
@PathVariable(value = "equipmentnumber") String email,
@RequestParam(name = "token", required = true) String token) {
Validate.notNull(equipmentnumber);
Validate.notNull(email);
Validate.notNull(token);
try {
if (getRecaptchaValidator().isValid(token)) {
getEmailSubscriptionService().subscribeForFacility(equipmentnumber, email);
} else {
throw new IllegalArgumentException(MessageFormat.format("Invalid token: [{0}].", token));
}
} catch (IOException ioex) {
throw new IllegalArgumentException(MessageFormat.format("Invalid token: [{0}].", token), ioex);
}
}
}
| Fixed E-Mail truncation
| web/src/main/java/org/hisrc/azw/email/controller/EmailSubscriptionController.java | Fixed E-Mail truncation | <ide><path>eb/src/main/java/org/hisrc/azw/email/controller/EmailSubscriptionController.java
<ide> }
<ide>
<ide> @CrossOrigin(origins = { "*" })
<del> @RequestMapping(value = "/facilities/subscriptions/email/{email}", method = RequestMethod.PUT)
<add> @RequestMapping(value = "/facilities/subscriptions/email/{email}/", method = RequestMethod.PUT)
<ide> @ResponseBody
<ide> public void subscribe(@PathVariable(value = "email") String email,
<ide> @RequestParam(name = "token", required = true) String token) {
<ide> }
<ide>
<ide> @CrossOrigin(origins = { "*" })
<del> @RequestMapping(value = "/facilities/{equipmentnumber}/subscriptions/email/{email}", method = RequestMethod.PUT)
<add> @RequestMapping(value = "/facilities/{equipmentnumber}/subscriptions/email/{email}/", method = RequestMethod.PUT)
<ide> @ResponseBody
<ide> public void subscribe(@PathVariable(value = "equipmentnumber") Long equipmentnumber,
<del> @PathVariable(value = "equipmentnumber") String email,
<add> @PathVariable(value = "email") String email,
<ide> @RequestParam(name = "token", required = true) String token) {
<ide> Validate.notNull(equipmentnumber);
<ide> Validate.notNull(email); |
|
Java | agpl-3.0 | f19aadb939e2d32e246c8b6a17a087029d1e7834 | 0 | subshare/subshare,subshare/subshare,subshare/subshare | package org.subshare.test;
import static co.codewizards.cloudstore.core.oio.OioFileFactory.*;
import static co.codewizards.cloudstore.core.util.AssertUtil.*;
import static org.assertj.core.api.Assertions.*;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import mockit.Invocation;
import mockit.Mock;
import mockit.MockUp;
import mockit.integration.junit4.JMockit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.subshare.core.dto.CollisionDto;
import org.subshare.core.dto.HistoFrameDto;
import org.subshare.core.dto.PlainHistoCryptoRepoFileDto;
import org.subshare.core.dto.PlainHistoCryptoRepoFileDtoTreeNode;
import org.subshare.core.repo.histo.HistoExporter;
import org.subshare.core.repo.histo.HistoExporterImpl;
import org.subshare.core.repo.local.CollisionFilter;
import org.subshare.core.repo.local.HistoFrameFilter;
import org.subshare.core.repo.local.PlainHistoCryptoRepoFileFilter;
import org.subshare.core.repo.local.SsLocalRepoMetaData;
import org.subshare.core.repo.sync.SsRepoToRepoSync;
import org.subshare.local.UserRepoKeyPublicKeyHelper;
import org.subshare.local.persistence.UserRepoKeyPublicKey;
import co.codewizards.cloudstore.core.dto.Uid;
import co.codewizards.cloudstore.core.objectfactory.ObjectFactory;
import co.codewizards.cloudstore.core.oio.File;
import co.codewizards.cloudstore.core.progress.ProgressMonitor;
import co.codewizards.cloudstore.core.repo.local.LocalRepoManager;
import co.codewizards.cloudstore.core.repo.sync.RepoToRepoSync;
import co.codewizards.cloudstore.core.util.IOUtil;
@RunWith(JMockit.class)
public class CollisionRepoToRepoSyncIT extends AbstractRepoToRepoSyncIT {
private static final Logger logger = LoggerFactory.getLogger(CollisionRepoToRepoSyncIT.class);
@Override
public void before() throws Exception {
super.before();
new MockUp<UserRepoKeyPublicKeyHelper>() {
@Mock
void createUserIdentities(UserRepoKeyPublicKey userRepoKeyPublicKey) {
// Our mock should do nothing, because we don't have a real UserRegistry here.
}
};
new MockUp<ObjectFactory>() {
@Mock
<T> T create(Invocation invocation, Class<T> clazz, Class<?>[] parameterTypes, Object ... parameters) {
if (RepoToRepoSync.class.isAssignableFrom(clazz)) {
return clazz.cast(new MockSsRepoToRepoSync((File) parameters[0], (URL) parameters[1]));
}
return invocation.proceed();
}
};
}
@Override
public void after() throws Exception {
for (RepoToRepoSyncCoordinator coordinator : repoToRepoSyncCoordinators)
coordinator.close();
repoToRepoSyncCoordinators.clear();
super.after();
}
/**
* Mocking the {@link SsRepoToRepoSync} does not work - for whatever reason - hence, this
* class is a "manual" mock which is introduced into Subshare using a mocked {@link ObjectFactory}.
*/
private static class MockSsRepoToRepoSync extends SsRepoToRepoSync {
protected MockSsRepoToRepoSync(File localRoot, URL remoteRoot) {
super(localRoot, remoteRoot);
}
@Override
protected void syncUp(ProgressMonitor monitor) {
RepoToRepoSyncCoordinator coordinator = repoToRepoSyncCoordinatorThreadLocal.get();
if (coordinator != null && ! coordinator.waitWhileSyncUpFrozen())
return;
super.syncUp(monitor);
if (coordinator != null)
coordinator.setSyncUpDone(true);
}
@Override
protected void syncDown(boolean fromRepoLocalSync, ProgressMonitor monitor) {
RepoToRepoSyncCoordinator coordinator = repoToRepoSyncCoordinatorThreadLocal.get();
if (coordinator != null && ! coordinator.waitWhileSyncDownFrozen())
return;
super.syncDown(fromRepoLocalSync, monitor);
if (coordinator != null)
coordinator.setSyncDownDone(true);
}
}
private class RepoToRepoSyncCoordinator {
private final Logger logger = LoggerFactory.getLogger(CollisionRepoToRepoSyncIT.RepoToRepoSyncCoordinator.class);
private boolean syncUpFrozen = true;
private boolean syncUpDone;
private boolean syncDownFrozen = true;
private boolean syncDownDone;
private Throwable error;
private boolean closed;
public RepoToRepoSyncCoordinator() {
repoToRepoSyncCoordinators.add(this);
}
protected synchronized boolean isSyncUpFrozen() {
return syncUpFrozen;
}
protected synchronized void setSyncUpFrozen(boolean value) {
logger.info("setSyncUpFrozen: value={}", value);
this.syncUpFrozen = value;
notifyAll();
}
protected synchronized boolean isSyncDownFrozen() {
return syncDownFrozen;
}
protected synchronized void setSyncDownFrozen(boolean value) {
logger.info("setSyncDownFrozen: value={}", value);
this.syncDownFrozen = value;
notifyAll();
}
protected synchronized boolean isSyncUpDone() {
return syncUpDone;
}
protected synchronized void setSyncUpDone(boolean value) {
logger.info("setSyncUpDone: value={}", value);
this.syncUpDone = value;
notifyAll();
}
protected synchronized boolean isSyncDownDone() {
return syncDownDone;
}
protected synchronized void setSyncDownDone(boolean value) {
logger.info("setSyncDownDone: value={}", value);
this.syncDownDone = value;
notifyAll();
}
public synchronized boolean waitWhileSyncUpFrozen() {
while (isSyncUpFrozen()) {
logger.info("waitWhileSyncUpFrozen: Waiting...");
try {
wait(30000);
} catch (InterruptedException e) {
logger.error("waitWhileSyncUpFrozen: " + e, e);
return false;
}
throwErrorIfNeeded();
}
setSyncUpFrozen(true);
logger.info("waitWhileSyncUpFrozen: Continuing!");
return true;
}
public synchronized boolean waitWhileSyncDownFrozen() {
while (isSyncDownFrozen()) {
logger.info("waitWhileSyncDownFrozen: Waiting...");
try {
wait(30000);
} catch (InterruptedException e) {
logger.error("waitWhileSyncDownFrozen: " + e, e);
return false;
}
throwErrorIfNeeded();
}
setSyncDownFrozen(true);
logger.info("waitWhileSyncDownFrozen: Continuing!");
return true;
}
public synchronized boolean waitForSyncUpDone() {
while (! isSyncUpDone()) {
logger.info("waitForSyncUpDone: Waiting...");
try {
wait(30000);
} catch (InterruptedException e) {
logger.error("waitForSyncUpDone: " + e, e);
return false;
}
throwErrorIfNeeded();
}
setSyncUpDone(false);
logger.info("waitForSyncUpDone: Continuing!");
return true;
}
public synchronized boolean waitForSyncDownDone() {
while (! isSyncDownDone()) {
logger.info("waitForSyncDownDone: Waiting...");
try {
wait(30000);
} catch (InterruptedException e) {
logger.error("waitForSyncDownDone: " + e, e);
return false;
}
throwErrorIfNeeded();
}
setSyncDownDone(false);
logger.info("waitForSyncDownDone: Continuing!");
return true;
}
public synchronized Throwable getError() {
return error;
}
public synchronized void setError(Throwable error) {
this.error = error;
notifyAll();
}
public void throwErrorIfNeeded() {
Throwable error = getError();
if (error != null) {
if (error instanceof Error)
throw (Error) error;
throw new RuntimeException(error);
}
}
public synchronized boolean isClosed() {
return closed;
}
public synchronized void close() {
closed = true;
if (error == null)
error = new RuntimeException("CLOSED!");
notifyAll();
}
}
private static final ThreadLocal<RepoToRepoSyncCoordinator> repoToRepoSyncCoordinatorThreadLocal = new ThreadLocal<RepoToRepoSyncCoordinator>() {
@Override
public RepoToRepoSyncCoordinator get() {
RepoToRepoSyncCoordinator result = super.get();
if (result != null && result.isClosed())
return null;
return result;
}
};
private final List<RepoToRepoSyncCoordinator> repoToRepoSyncCoordinators = new ArrayList<RepoToRepoSyncCoordinator>();
/**
* Two clients simultaneously create a file with the same name in the same directory.
* <p>
* The 1st client syncs completely, first. Then the 2nd client syncs completely. Thus,
* the collision happens during the down-sync on the 2nd client.
*
* @see #newVsNewFileCollisionOnServer()
*/
@Test
public void newFileVsNewFileCollisionOnClient() throws Exception {
prepareLocalAndDestinationRepo();
File file1 = createFile(localSrcRoot, "2", "new-file");
createFileWithRandomContent(file1);
modifyFile_append(file1, 111);
File file2 = createFile(localDestRoot, "2", "new-file");
createFileWithRandomContent(file2);
modifyFile_append(file2, 222);
SsLocalRepoMetaData localRepoMetaData = (SsLocalRepoMetaData) localRepoManagerLocal.getLocalRepoMetaData();
Collection<CollisionDto> collisionDtos = localRepoMetaData.getCollisionDtos(new CollisionFilter());
assertThat(collisionDtos).isEmpty();
syncFromLocalSrcToRemote();
syncFromRemoteToLocalDest(false); // should up-sync its own version
syncFromLocalSrcToRemote(); // should down-sync the change from dest-repo
assertDirectoriesAreEqualRecursively(
(remotePathPrefix2Plain.isEmpty() ? getLocalRootWithPathPrefix() : createFile(getLocalRootWithPathPrefix(), remotePathPrefix2Plain)),
localDestRoot);
// Verify that *both* versions are in the history.
List<PlainHistoCryptoRepoFileDto> plainHistoCryptoRepoFileDtos = getPlainHistoCryptoRepoFileDtos(localRepoManagerLocal, file1);
assertThat(plainHistoCryptoRepoFileDtos).hasSize(2);
// Verify that the older one is the previous version of the newer one (the list is sorted by timestamp).
// Since the collision happens on the client, they are consecutive (rather than forked siblings of the same previous version).
assertThat(plainHistoCryptoRepoFileDtos.get(0).getHistoCryptoRepoFileDto().getHistoCryptoRepoFileId())
.isEqualTo(plainHistoCryptoRepoFileDtos.get(1).getHistoCryptoRepoFileDto().getPreviousHistoCryptoRepoFileId());
// Verify that the 2nd version (with 222 at the end) is the current one.
int lastByte1 = getLastByte(file1);
assertThat(lastByte1).isEqualTo(222);
int lastByte2 = getLastByte(file2);
assertThat(lastByte2).isEqualTo(222);
// Export both versions of the file and assert that
// - the current file is identical to the last one
// - and the first one ends on 111.
File tempDir0 = createTempDirectory(getClass().getSimpleName() + '.');
File tempDir1 = createTempDirectory(getClass().getSimpleName() + '.');
try (HistoExporter histoExporter = HistoExporterImpl.createHistoExporter(localSrcRoot);) {
histoExporter.exportFile(
plainHistoCryptoRepoFileDtos.get(0).getHistoCryptoRepoFileDto().getHistoCryptoRepoFileId(), tempDir0);
histoExporter.exportFile(
plainHistoCryptoRepoFileDtos.get(1).getHistoCryptoRepoFileDto().getHistoCryptoRepoFileId(), tempDir1);
}
File histoFile0 = createFile(tempDir0, "new-file");
File histoFile1 = createFile(tempDir1, "new-file");
assertThat(IOUtil.compareFiles(histoFile1, file1)).isTrue();
assertThat(IOUtil.compareFiles(histoFile0, histoFile1)).isFalse();
int lastByteOfHistoFile0 = getLastByte(histoFile0);
assertThat(lastByteOfHistoFile0).isEqualTo(111);
collisionDtos = localRepoMetaData.getCollisionDtos(new CollisionFilter());
assertThat(collisionDtos).hasSize(1);
}
/**
* Two clients simultaneously modify the same file.
*/
@Test
public void modifiedFileVsModifiedFileCollisionOnClient() throws Exception {
prepareLocalAndDestinationRepo();
File file1 = createFile(localSrcRoot, "2", "a");
assertThat(file1.getIoFile()).isFile();
modifyFile_append(file1, 111);
File file2 = createFile(localDestRoot, "2", "a");
assertThat(file2.getIoFile()).isFile();
modifyFile_append(file2, 222);
SsLocalRepoMetaData localRepoMetaData = (SsLocalRepoMetaData) localRepoManagerLocal.getLocalRepoMetaData();
Collection<CollisionDto> collisionDtos = localRepoMetaData.getCollisionDtos(new CollisionFilter());
assertThat(collisionDtos).isEmpty();
syncFromLocalSrcToRemote();
syncFromRemoteToLocalDest(false); // should up-sync its own version
syncFromLocalSrcToRemote(); // should down-sync the change from dest-repo
assertDirectoriesAreEqualRecursively(
(remotePathPrefix2Plain.isEmpty() ? getLocalRootWithPathPrefix() : createFile(getLocalRootWithPathPrefix(), remotePathPrefix2Plain)),
localDestRoot);
// Verify that *both* versions are in the history.
List<PlainHistoCryptoRepoFileDto> plainHistoCryptoRepoFileDtos = getPlainHistoCryptoRepoFileDtos(localRepoManagerLocal, file1);
assertThat(plainHistoCryptoRepoFileDtos).hasSize(3);
// Verify that the older one is the previous version of the newer one (the list is sorted by timestamp).
// Since the collision happens on the client, they are consecutive (rather than forked siblings of the same previous version).
assertThat(plainHistoCryptoRepoFileDtos.get(0).getHistoCryptoRepoFileDto().getHistoCryptoRepoFileId())
.isEqualTo(plainHistoCryptoRepoFileDtos.get(1).getHistoCryptoRepoFileDto().getPreviousHistoCryptoRepoFileId());
assertThat(plainHistoCryptoRepoFileDtos.get(1).getHistoCryptoRepoFileDto().getHistoCryptoRepoFileId())
.isEqualTo(plainHistoCryptoRepoFileDtos.get(2).getHistoCryptoRepoFileDto().getPreviousHistoCryptoRepoFileId());
// Verify that the 2nd version (with 222 at the end) is the current one.
int lastByte1 = getLastByte(file1);
assertThat(lastByte1).isEqualTo(222);
int lastByte2 = getLastByte(file2);
assertThat(lastByte2).isEqualTo(222);
// Export both versions of the file and assert that
// - the current file is identical to the last one
// - and the first one ends on 111.
File tempDir1 = createTempDirectory(getClass().getSimpleName() + '.');
File tempDir2 = createTempDirectory(getClass().getSimpleName() + '.');
try (HistoExporter histoExporter = HistoExporterImpl.createHistoExporter(localSrcRoot);) {
histoExporter.exportFile(
plainHistoCryptoRepoFileDtos.get(1).getHistoCryptoRepoFileDto().getHistoCryptoRepoFileId(), tempDir1);
histoExporter.exportFile(
plainHistoCryptoRepoFileDtos.get(2).getHistoCryptoRepoFileDto().getHistoCryptoRepoFileId(), tempDir2);
}
File histoFile1 = createFile(tempDir1, "a");
File histoFile2 = createFile(tempDir2, "a");
// IOUtil.copyFile(file1, tempDir2.createFile("a.current"));
assertThat(IOUtil.compareFiles(histoFile2, file1)).isTrue();
assertThat(IOUtil.compareFiles(histoFile1, histoFile2)).isFalse();
int lastByteOfHistoFile1 = getLastByte(histoFile1);
assertThat(lastByteOfHistoFile1).isEqualTo(111);
collisionDtos = localRepoMetaData.getCollisionDtos(new CollisionFilter());
assertThat(collisionDtos).hasSize(1);
}
private void modifyFile_append(File file, int byteToAppend) throws IOException {
try (OutputStream out = file.createOutputStream(true)) { // append
out.write(byteToAppend);
}
}
// /**
// * The first client deletes the file, uploads to the server, the 2nd client modifies it
// * and then syncs.
// */
// @Test
// public void deletedFileVsModifiedFileCollisionOnClient() throws Exception {
//
// }
//
// /**
// * The first client modifies the file, uploads to the server, the 2nd client deletes it
// * and then syncs.
// */
// @Test
// public void modifiedFileVsDeletedFileCollisionOnClient() throws Exception {
//
// }
/**
* Two clients simultaneously create a file with the same name in the same directory.
* <p>
* In contrast to {@link #newVsNewFileCollisionOnClient()}, both clients first sync-down,
* see no change on the server and then sync-up really causing two different
* {@code CryptoRepoFile} objects for the same file.
* <p>
* The collision thus happens and is detected during a following down-sync at a later time.
*
* @see #newVsNewFileCollisionOnClient()
*/
@Test
public void newFileVsNewFileCollisionOnServer() throws Exception {
prepareLocalAndDestinationRepo();
File file1 = createFile(localSrcRoot, "2", "new-file");
createFileWithRandomContent(file1);
modifyFile_append(file1, 111);
File file2 = createFile(localDestRoot, "2", "new-file");
createFileWithRandomContent(file2);
modifyFile_append(file2, 222);
SsLocalRepoMetaData localRepoMetaData = (SsLocalRepoMetaData) localRepoManagerLocal.getLocalRepoMetaData();
Collection<CollisionDto> collisionDtos = localRepoMetaData.getCollisionDtos(new CollisionFilter());
assertThat(collisionDtos).isEmpty();
RepoToRepoSyncCoordinator syncFromLocalSrcToRemoteCoordinator = new RepoToRepoSyncCoordinator();
SyncFromLocalSrcToRemoteThread syncFromLocalSrcToRemoteThread = new SyncFromLocalSrcToRemoteThread(syncFromLocalSrcToRemoteCoordinator);
syncFromLocalSrcToRemoteThread.start();
// should collide and up-sync its own version in parallel
RepoToRepoSyncCoordinator syncFromRemoteToLocalDestCoordinator = new RepoToRepoSyncCoordinator();
SyncFromRemoteToLocalDestThread syncFromRemoteToLocalDestThread = new SyncFromRemoteToLocalDestThread(syncFromRemoteToLocalDestCoordinator);
syncFromRemoteToLocalDestThread.start();
System.out.println("************************************************************");
// Thread.sleep(30000);
System.out.println("************************************************************");
// Both threads are waiting *before* down-syncing now. We allow them both to continue:
syncFromLocalSrcToRemoteCoordinator.setSyncDownFrozen(false);
syncFromRemoteToLocalDestCoordinator.setSyncDownFrozen(false);
// Then we wait until they're done down-syncing.
syncFromLocalSrcToRemoteCoordinator.waitForSyncDownDone();
syncFromRemoteToLocalDestCoordinator.waitForSyncDownDone();
System.out.println("*****************");
// Thread.sleep(60000);
System.out.println("*****************");
// Now they're waiting *before* up-syncing. We continue the up-sync, thus, now.
syncFromLocalSrcToRemoteCoordinator.setSyncUpFrozen(false);
syncFromRemoteToLocalDestCoordinator.setSyncUpFrozen(false);
// Again, we wait here until they're done (this time, up-syncing).
syncFromLocalSrcToRemoteCoordinator.waitForSyncUpDone();
syncFromRemoteToLocalDestCoordinator.waitForSyncUpDone();
System.out.println("*****************");
// Thread.sleep(60000);
System.out.println("*****************");
// Again, they're waiting for down-sync's green light => go!
syncFromLocalSrcToRemoteCoordinator.setSyncDownFrozen(false);
syncFromRemoteToLocalDestCoordinator.setSyncDownFrozen(false);
// ...wait until they're done.
syncFromLocalSrcToRemoteCoordinator.waitForSyncDownDone();
syncFromRemoteToLocalDestCoordinator.waitForSyncDownDone();
System.out.println("************************************************************");
// Thread.sleep(60000);
System.out.println("************************************************************");
// syncFromLocalSrcToRemote(); // should down-sync the change from dest-repo
assertDirectoriesAreEqualRecursively(
(remotePathPrefix2Plain.isEmpty() ? getLocalRootWithPathPrefix() : createFile(getLocalRootWithPathPrefix(), remotePathPrefix2Plain)),
localDestRoot);
// Verify that *both* versions are in the history.
List<PlainHistoCryptoRepoFileDto> plainHistoCryptoRepoFileDtos = getPlainHistoCryptoRepoFileDtos(localRepoManagerLocal, file1);
assertThat(plainHistoCryptoRepoFileDtos).hasSize(2);
// Both new versions should have the same previous version, because the collision happened on the server.
Set<Uid> previousHistoCryptoRepoFileIds = new HashSet<>();
for (PlainHistoCryptoRepoFileDto phcrfDto : plainHistoCryptoRepoFileDtos)
previousHistoCryptoRepoFileIds.add(phcrfDto.getHistoCryptoRepoFileDto().getPreviousHistoCryptoRepoFileId());
assertThat(previousHistoCryptoRepoFileIds).hasSize(1);
// Verify that the 2nd version (with 222 at the end) is the current one.
int lastByte1 = getLastByte(file1);
assertThat(lastByte1).isEqualTo(222);
int lastByte2 = getLastByte(file2);
assertThat(lastByte2).isEqualTo(222);
// Export both versions of the file and assert that
// - the current file is identical to the last one
// - and the first one ends on 111.
File tempDir0 = createTempDirectory(getClass().getSimpleName() + '.');
File tempDir1 = createTempDirectory(getClass().getSimpleName() + '.');
try (HistoExporter histoExporter = HistoExporterImpl.createHistoExporter(localSrcRoot);) {
histoExporter.exportFile(
plainHistoCryptoRepoFileDtos.get(0).getHistoCryptoRepoFileDto().getHistoCryptoRepoFileId(), tempDir0);
histoExporter.exportFile(
plainHistoCryptoRepoFileDtos.get(1).getHistoCryptoRepoFileDto().getHistoCryptoRepoFileId(), tempDir1);
}
File histoFile0 = createFile(tempDir0, "new-file");
File histoFile1 = createFile(tempDir1, "new-file");
assertThat(IOUtil.compareFiles(histoFile1, file1)).isTrue();
assertThat(IOUtil.compareFiles(histoFile0, histoFile1)).isFalse();
int lastByteOfHistoFile0 = getLastByte(histoFile0);
assertThat(lastByteOfHistoFile0).isEqualTo(111);
collisionDtos = localRepoMetaData.getCollisionDtos(new CollisionFilter());
assertThat(collisionDtos).hasSize(1);
}
private class SyncFromLocalSrcToRemoteThread extends Thread {
private final Logger logger = LoggerFactory.getLogger(SyncFromLocalSrcToRemoteThread.class);
private final RepoToRepoSyncCoordinator coordinator;
public SyncFromLocalSrcToRemoteThread(RepoToRepoSyncCoordinator coordinator) {
this.coordinator = assertNotNull("coordinator", coordinator);
repoToRepoSyncCoordinatorThreadLocal.set(coordinator);
}
@Override
public void run() {
try {
syncFromLocalSrcToRemote();
} catch (Throwable e) {
logger.error("run: " + e, e);
coordinator.setError(e);
}
}
}
private class SyncFromRemoteToLocalDestThread extends Thread {
private final Logger logger = LoggerFactory.getLogger(SyncFromRemoteToLocalDestThread.class);
private final RepoToRepoSyncCoordinator coordinator;
public SyncFromRemoteToLocalDestThread(RepoToRepoSyncCoordinator coordinator) {
this.coordinator = assertNotNull("coordinator", coordinator);
repoToRepoSyncCoordinatorThreadLocal.set(coordinator);
}
@Override
public void run() {
try {
syncFromRemoteToLocalDest(false);
} catch (Throwable e) {
logger.error("run: " + e, e);
coordinator.setError(e);
}
}
}
// /**
// * Two clients simultaneously modify the same file.
// */
// @Test
// public void modifiedFileVsModifiedFileCollisionOnServer() throws Exception {
//
// }
//
// /**
// * The first client deletes the file, uploads to the server, the 2nd client modifies it
// * and then syncs.
// */
// @Test
// public void deletedFileVsModifiedFileCollisionOnServer() throws Exception {
//
// }
//
// /**
// * The first client modifies the file, uploads to the server, the 2nd client deletes it
// * and then syncs.
// */
// @Test
// public void modifiedFileVsDeletedFileCollisionOnServer() throws Exception {
//
// }
// TODO add file-type-change-collisions (e.g. from directory to file)
protected void prepareLocalAndDestinationRepo() throws Exception {
createLocalSourceAndRemoteRepo();
populateLocalSourceRepo();
syncFromLocalSrcToRemote();
determineRemotePathPrefix2Encrypted();
createLocalDestinationRepo();
syncFromRemoteToLocalDest();
}
private int getLastByte(File file) throws IOException {
try (RandomAccessFile raf = new RandomAccessFile(file.getIoFile(), "r")) {
raf.seek(raf.length() - 1);
int result = raf.read();
assertThat(result).isGreaterThanOrEqualTo(0);
return result;
}
}
private List<PlainHistoCryptoRepoFileDto> getPlainHistoCryptoRepoFileDtos(LocalRepoManager localRepoManager, File file) throws IOException {
final String path = "/" + localRepoManager.getLocalRoot().relativize(file).replace('\\', '/');
SsLocalRepoMetaData localRepoMetaData = (SsLocalRepoMetaData) localRepoManagerLocal.getLocalRepoMetaData();
List<PlainHistoCryptoRepoFileDto> result = new ArrayList<>();
// TODO need to extend the filter with a path! Do this when extending the UI to show a history in every folder-detail-pane.
// The current implementation is very inefficient - but we have only small test data, anyway ;-)
Collection<HistoFrameDto> histoFrameDtos = localRepoMetaData.getHistoFrameDtos(new HistoFrameFilter());
for (HistoFrameDto histoFrameDto : histoFrameDtos) {
PlainHistoCryptoRepoFileFilter filter = new PlainHistoCryptoRepoFileFilter();
filter.setHistoFrameId(histoFrameDto.getHistoFrameId());
filter.setFillParents(true);
Collection<PlainHistoCryptoRepoFileDto> plainHistoCryptoRepoFileDtos = localRepoMetaData.getPlainHistoCryptoRepoFileDtos(filter);
PlainHistoCryptoRepoFileDtoTreeNode rootNode = PlainHistoCryptoRepoFileDtoTreeNode.createTree(plainHistoCryptoRepoFileDtos);
for (PlainHistoCryptoRepoFileDtoTreeNode node : rootNode) {
if (path.equals(node.getPath()))
result.add(node.getPlainHistoCryptoRepoFileDto());
}
}
Collections.sort(result, new Comparator<PlainHistoCryptoRepoFileDto>() {
@Override
public int compare(PlainHistoCryptoRepoFileDto o1, PlainHistoCryptoRepoFileDto o2) {
Date signatureCreated1 = o1.getHistoCryptoRepoFileDto().getSignature().getSignatureCreated();
Date signatureCreated2 = o2.getHistoCryptoRepoFileDto().getSignature().getSignatureCreated();
return signatureCreated1.compareTo(signatureCreated2);
}
});
return result;
}
}
| org.subshare/org.subshare.test/src/test/java/org/subshare/test/CollisionRepoToRepoSyncIT.java | package org.subshare.test;
import static co.codewizards.cloudstore.core.oio.OioFileFactory.*;
import static co.codewizards.cloudstore.core.util.AssertUtil.*;
import static org.assertj.core.api.Assertions.*;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import mockit.Invocation;
import mockit.Mock;
import mockit.MockUp;
import mockit.integration.junit4.JMockit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.subshare.core.dto.CollisionDto;
import org.subshare.core.dto.HistoFrameDto;
import org.subshare.core.dto.PlainHistoCryptoRepoFileDto;
import org.subshare.core.dto.PlainHistoCryptoRepoFileDtoTreeNode;
import org.subshare.core.repo.histo.HistoExporter;
import org.subshare.core.repo.histo.HistoExporterImpl;
import org.subshare.core.repo.local.CollisionFilter;
import org.subshare.core.repo.local.HistoFrameFilter;
import org.subshare.core.repo.local.PlainHistoCryptoRepoFileFilter;
import org.subshare.core.repo.local.SsLocalRepoMetaData;
import org.subshare.core.repo.sync.SsRepoToRepoSync;
import org.subshare.local.UserRepoKeyPublicKeyHelper;
import org.subshare.local.persistence.UserRepoKeyPublicKey;
import co.codewizards.cloudstore.core.dto.Uid;
import co.codewizards.cloudstore.core.objectfactory.ObjectFactory;
import co.codewizards.cloudstore.core.oio.File;
import co.codewizards.cloudstore.core.progress.ProgressMonitor;
import co.codewizards.cloudstore.core.repo.local.LocalRepoManager;
import co.codewizards.cloudstore.core.repo.sync.RepoToRepoSync;
import co.codewizards.cloudstore.core.util.IOUtil;
@RunWith(JMockit.class)
public class CollisionRepoToRepoSyncIT extends AbstractRepoToRepoSyncIT {
private static final Logger logger = LoggerFactory.getLogger(CollisionRepoToRepoSyncIT.class);
@Override
public void before() throws Exception {
super.before();
new MockUp<UserRepoKeyPublicKeyHelper>() {
@Mock
void createUserIdentities(UserRepoKeyPublicKey userRepoKeyPublicKey) {
// Our mock should do nothing, because we don't have a real UserRegistry here.
}
};
new MockUp<ObjectFactory>() {
@Mock
<T> T create(Invocation invocation, Class<T> clazz, Class<?>[] parameterTypes, Object ... parameters) {
if (RepoToRepoSync.class.isAssignableFrom(clazz)) {
return clazz.cast(new MockSsRepoToRepoSync((File) parameters[0], (URL) parameters[1]));
}
return invocation.proceed();
}
};
// new MockUp<SsRepoToRepoSync>() {
// @Mock
// void syncUp(Invocation invocation, ProgressMonitor monitor) {
// System.out.println(">>>>>>>>>>>>> syncUp >>>>>>>>>>>>>>>>>");
//// RepoToRepoSyncCoordinator coordinator = repoToRepoSyncCoordinatorThreadLocal.get();
//// if (coordinator != null && ! coordinator.waitWhileSyncUpFrozen())
//// return;
//
// invocation.proceed();
//
//// if (coordinator != null)
//// coordinator.setSyncUpDone(true);
// }
//
// @Mock
// void syncDown(Invocation invocation, boolean fromRepoLocalSync, ProgressMonitor monitor) {
// System.out.println(">>>>>>>>>>>>> syncDown >>>>>>>>>>>>>>>>>");
//// RepoToRepoSyncCoordinator coordinator = repoToRepoSyncCoordinatorThreadLocal.get();
//// if (coordinator != null && ! coordinator.waitWhileSyncDownFrozen())
//// return;
//
// invocation.proceed();
//
//// if (coordinator != null)
//// coordinator.setSyncDownDone(true);
// }
// };
}
private static class MockSsRepoToRepoSync extends SsRepoToRepoSync {
protected MockSsRepoToRepoSync(File localRoot, URL remoteRoot) {
super(localRoot, remoteRoot);
}
@Override
protected void syncUp(ProgressMonitor monitor) {
RepoToRepoSyncCoordinator coordinator = repoToRepoSyncCoordinatorThreadLocal.get();
if (coordinator != null && ! coordinator.waitWhileSyncUpFrozen())
return;
super.syncUp(monitor);
if (coordinator != null)
coordinator.setSyncUpDone(true);
}
@Override
protected void syncDown(boolean fromRepoLocalSync, ProgressMonitor monitor) {
RepoToRepoSyncCoordinator coordinator = repoToRepoSyncCoordinatorThreadLocal.get();
if (coordinator != null && ! coordinator.waitWhileSyncDownFrozen())
return;
super.syncDown(fromRepoLocalSync, monitor);
if (coordinator != null)
coordinator.setSyncDownDone(true);
}
}
private static class RepoToRepoSyncCoordinator {
private static final Logger logger = LoggerFactory.getLogger(CollisionRepoToRepoSyncIT.RepoToRepoSyncCoordinator.class);
private boolean syncUpFrozen = true;
private boolean syncUpDone;
private boolean syncDownFrozen = true;
private boolean syncDownDone;
private Throwable error;
protected synchronized boolean isSyncUpFrozen() {
return syncUpFrozen;
}
protected synchronized void setSyncUpFrozen(boolean value) {
logger.info("setSyncUpFrozen: value={}", value);
this.syncUpFrozen = value;
notifyAll();
}
protected synchronized boolean isSyncDownFrozen() {
return syncDownFrozen;
}
protected synchronized void setSyncDownFrozen(boolean value) {
logger.info("setSyncDownFrozen: value={}", value);
this.syncDownFrozen = value;
notifyAll();
}
protected synchronized boolean isSyncUpDone() {
return syncUpDone;
}
protected synchronized void setSyncUpDone(boolean value) {
logger.info("setSyncUpDone: value={}", value);
this.syncUpDone = value;
notifyAll();
}
protected synchronized boolean isSyncDownDone() {
return syncDownDone;
}
protected synchronized void setSyncDownDone(boolean value) {
logger.info("setSyncDownDone: value={}", value);
this.syncDownDone = value;
notifyAll();
}
public synchronized boolean waitWhileSyncUpFrozen() {
while (isSyncUpFrozen()) {
logger.info("waitWhileSyncUpFrozen: Waiting...");
try {
wait(30000);
} catch (InterruptedException e) {
logger.error("waitWhileSyncUpFrozen: " + e, e);
return false;
}
throwErrorIfNeeded();
}
setSyncUpFrozen(true);
logger.info("waitWhileSyncUpFrozen: Continuing!");
return true;
}
public synchronized boolean waitWhileSyncDownFrozen() {
while (isSyncDownFrozen()) {
logger.info("waitWhileSyncDownFrozen: Waiting...");
try {
wait(30000);
} catch (InterruptedException e) {
logger.error("waitWhileSyncDownFrozen: " + e, e);
return false;
}
throwErrorIfNeeded();
}
setSyncDownFrozen(true);
logger.info("waitWhileSyncDownFrozen: Continuing!");
return true;
}
public synchronized boolean waitForSyncUpDone() {
while (! isSyncUpDone()) {
logger.info("waitForSyncUpDone: Waiting...");
try {
wait(30000);
} catch (InterruptedException e) {
logger.error("waitForSyncUpDone: " + e, e);
return false;
}
throwErrorIfNeeded();
}
setSyncUpDone(false);
logger.info("waitForSyncUpDone: Continuing!");
return true;
}
public synchronized boolean waitForSyncDownDone() {
while (! isSyncDownDone()) {
logger.info("waitForSyncDownDone: Waiting...");
try {
wait(30000);
} catch (InterruptedException e) {
logger.error("waitForSyncDownDone: " + e, e);
return false;
}
throwErrorIfNeeded();
}
setSyncDownDone(false);
logger.info("waitForSyncDownDone: Continuing!");
return true;
}
public synchronized Throwable getError() {
return error;
}
public synchronized void setError(Throwable error) {
this.error = error;
notifyAll();
}
public void throwErrorIfNeeded() {
Throwable error = getError();
if (error != null) {
if (error instanceof Error)
throw (Error) error;
throw new RuntimeException(error);
}
}
}
private static final ThreadLocal<RepoToRepoSyncCoordinator> repoToRepoSyncCoordinatorThreadLocal = new ThreadLocal<>();
/**
* Two clients simultaneously create a file with the same name in the same directory.
* <p>
* The 1st client syncs completely, first. Then the 2nd client syncs completely. Thus,
* the collision happens during the down-sync on the 2nd client.
*
* @see #newVsNewFileCollisionOnServer()
*/
@Test
public void newFileVsNewFileCollisionOnClient() throws Exception {
prepareLocalAndDestinationRepo();
File file1 = createFile(localSrcRoot, "2", "new-file");
createFileWithRandomContent(file1);
modifyFile_append(file1, 111);
File file2 = createFile(localDestRoot, "2", "new-file");
createFileWithRandomContent(file2);
modifyFile_append(file2, 222);
SsLocalRepoMetaData localRepoMetaData = (SsLocalRepoMetaData) localRepoManagerLocal.getLocalRepoMetaData();
Collection<CollisionDto> collisionDtos = localRepoMetaData.getCollisionDtos(new CollisionFilter());
assertThat(collisionDtos).isEmpty();
syncFromLocalSrcToRemote();
syncFromRemoteToLocalDest(false); // should up-sync its own version
syncFromLocalSrcToRemote(); // should down-sync the change from dest-repo
assertDirectoriesAreEqualRecursively(
(remotePathPrefix2Plain.isEmpty() ? getLocalRootWithPathPrefix() : createFile(getLocalRootWithPathPrefix(), remotePathPrefix2Plain)),
localDestRoot);
// Verify that *both* versions are in the history.
List<PlainHistoCryptoRepoFileDto> plainHistoCryptoRepoFileDtos = getPlainHistoCryptoRepoFileDtos(localRepoManagerLocal, file1);
assertThat(plainHistoCryptoRepoFileDtos).hasSize(2);
// Verify that the older one is the previous version of the newer one (the list is sorted by timestamp).
// Since the collision happens on the client, they are consecutive (rather than forked siblings of the same previous version).
assertThat(plainHistoCryptoRepoFileDtos.get(0).getHistoCryptoRepoFileDto().getHistoCryptoRepoFileId())
.isEqualTo(plainHistoCryptoRepoFileDtos.get(1).getHistoCryptoRepoFileDto().getPreviousHistoCryptoRepoFileId());
// Verify that the 2nd version (with 222 at the end) is the current one.
int lastByte1 = getLastByte(file1);
assertThat(lastByte1).isEqualTo(222);
int lastByte2 = getLastByte(file2);
assertThat(lastByte2).isEqualTo(222);
// Export both versions of the file and assert that
// - the current file is identical to the last one
// - and the first one ends on 111.
File tempDir0 = createTempDirectory(getClass().getSimpleName() + '.');
File tempDir1 = createTempDirectory(getClass().getSimpleName() + '.');
try (HistoExporter histoExporter = HistoExporterImpl.createHistoExporter(localSrcRoot);) {
histoExporter.exportFile(
plainHistoCryptoRepoFileDtos.get(0).getHistoCryptoRepoFileDto().getHistoCryptoRepoFileId(), tempDir0);
histoExporter.exportFile(
plainHistoCryptoRepoFileDtos.get(1).getHistoCryptoRepoFileDto().getHistoCryptoRepoFileId(), tempDir1);
}
File histoFile0 = createFile(tempDir0, "new-file");
File histoFile1 = createFile(tempDir1, "new-file");
assertThat(IOUtil.compareFiles(histoFile1, file1)).isTrue();
assertThat(IOUtil.compareFiles(histoFile0, histoFile1)).isFalse();
int lastByteOfHistoFile0 = getLastByte(histoFile0);
assertThat(lastByteOfHistoFile0).isEqualTo(111);
collisionDtos = localRepoMetaData.getCollisionDtos(new CollisionFilter());
assertThat(collisionDtos).hasSize(1);
}
/**
* Two clients simultaneously modify the same file.
*/
@Test
public void modifiedFileVsModifiedFileCollisionOnClient() throws Exception {
prepareLocalAndDestinationRepo();
File file1 = createFile(localSrcRoot, "2", "a");
assertThat(file1.getIoFile()).isFile();
modifyFile_append(file1, 111);
File file2 = createFile(localDestRoot, "2", "a");
assertThat(file2.getIoFile()).isFile();
modifyFile_append(file2, 222);
SsLocalRepoMetaData localRepoMetaData = (SsLocalRepoMetaData) localRepoManagerLocal.getLocalRepoMetaData();
Collection<CollisionDto> collisionDtos = localRepoMetaData.getCollisionDtos(new CollisionFilter());
assertThat(collisionDtos).isEmpty();
syncFromLocalSrcToRemote();
syncFromRemoteToLocalDest(false); // should up-sync its own version
syncFromLocalSrcToRemote(); // should down-sync the change from dest-repo
assertDirectoriesAreEqualRecursively(
(remotePathPrefix2Plain.isEmpty() ? getLocalRootWithPathPrefix() : createFile(getLocalRootWithPathPrefix(), remotePathPrefix2Plain)),
localDestRoot);
// Verify that *both* versions are in the history.
List<PlainHistoCryptoRepoFileDto> plainHistoCryptoRepoFileDtos = getPlainHistoCryptoRepoFileDtos(localRepoManagerLocal, file1);
assertThat(plainHistoCryptoRepoFileDtos).hasSize(3);
// Verify that the older one is the previous version of the newer one (the list is sorted by timestamp).
// Since the collision happens on the client, they are consecutive (rather than forked siblings of the same previous version).
assertThat(plainHistoCryptoRepoFileDtos.get(0).getHistoCryptoRepoFileDto().getHistoCryptoRepoFileId())
.isEqualTo(plainHistoCryptoRepoFileDtos.get(1).getHistoCryptoRepoFileDto().getPreviousHistoCryptoRepoFileId());
assertThat(plainHistoCryptoRepoFileDtos.get(1).getHistoCryptoRepoFileDto().getHistoCryptoRepoFileId())
.isEqualTo(plainHistoCryptoRepoFileDtos.get(2).getHistoCryptoRepoFileDto().getPreviousHistoCryptoRepoFileId());
// Verify that the 2nd version (with 222 at the end) is the current one.
int lastByte1 = getLastByte(file1);
assertThat(lastByte1).isEqualTo(222);
int lastByte2 = getLastByte(file2);
assertThat(lastByte2).isEqualTo(222);
// Export both versions of the file and assert that
// - the current file is identical to the last one
// - and the first one ends on 111.
File tempDir1 = createTempDirectory(getClass().getSimpleName() + '.');
File tempDir2 = createTempDirectory(getClass().getSimpleName() + '.');
try (HistoExporter histoExporter = HistoExporterImpl.createHistoExporter(localSrcRoot);) {
histoExporter.exportFile(
plainHistoCryptoRepoFileDtos.get(1).getHistoCryptoRepoFileDto().getHistoCryptoRepoFileId(), tempDir1);
histoExporter.exportFile(
plainHistoCryptoRepoFileDtos.get(2).getHistoCryptoRepoFileDto().getHistoCryptoRepoFileId(), tempDir2);
}
File histoFile1 = createFile(tempDir1, "a");
File histoFile2 = createFile(tempDir2, "a");
// IOUtil.copyFile(file1, tempDir2.createFile("a.current"));
assertThat(IOUtil.compareFiles(histoFile2, file1)).isTrue();
assertThat(IOUtil.compareFiles(histoFile1, histoFile2)).isFalse();
int lastByteOfHistoFile1 = getLastByte(histoFile1);
assertThat(lastByteOfHistoFile1).isEqualTo(111);
collisionDtos = localRepoMetaData.getCollisionDtos(new CollisionFilter());
assertThat(collisionDtos).hasSize(1);
}
private void modifyFile_append(File file, int byteToAppend) throws IOException {
try (OutputStream out = file.createOutputStream(true)) { // append
out.write(byteToAppend);
}
}
// /**
// * The first client deletes the file, uploads to the server, the 2nd client modifies it
// * and then syncs.
// */
// @Test
// public void deletedFileVsModifiedFileCollisionOnClient() throws Exception {
//
// }
//
// /**
// * The first client modifies the file, uploads to the server, the 2nd client deletes it
// * and then syncs.
// */
// @Test
// public void modifiedFileVsDeletedFileCollisionOnClient() throws Exception {
//
// }
/**
* Two clients simultaneously create a file with the same name in the same directory.
* <p>
* In contrast to {@link #newVsNewFileCollisionOnClient()}, both clients first sync-down,
* see no change on the server and then sync-up really causing two different
* {@code CryptoRepoFile} objects for the same file.
* <p>
* The collision thus happens and is detected during a following down-sync at a later time.
*
* @see #newVsNewFileCollisionOnClient()
*/
@Test
public void newFileVsNewFileCollisionOnServer() throws Exception {
prepareLocalAndDestinationRepo();
File file1 = createFile(localSrcRoot, "2", "new-file");
createFileWithRandomContent(file1);
modifyFile_append(file1, 111);
File file2 = createFile(localDestRoot, "2", "new-file");
createFileWithRandomContent(file2);
modifyFile_append(file2, 222);
SsLocalRepoMetaData localRepoMetaData = (SsLocalRepoMetaData) localRepoManagerLocal.getLocalRepoMetaData();
Collection<CollisionDto> collisionDtos = localRepoMetaData.getCollisionDtos(new CollisionFilter());
assertThat(collisionDtos).isEmpty();
RepoToRepoSyncCoordinator syncFromLocalSrcToRemoteCoordinator = new RepoToRepoSyncCoordinator();
SyncFromLocalSrcToRemoteThread syncFromLocalSrcToRemoteThread = new SyncFromLocalSrcToRemoteThread(syncFromLocalSrcToRemoteCoordinator);
syncFromLocalSrcToRemoteThread.start();
// should collide and up-sync its own version in parallel
RepoToRepoSyncCoordinator syncFromRemoteToLocalDestCoordinator = new RepoToRepoSyncCoordinator();
SyncFromRemoteToLocalDestThread syncFromRemoteToLocalDestThread = new SyncFromRemoteToLocalDestThread(syncFromRemoteToLocalDestCoordinator);
syncFromRemoteToLocalDestThread.start();
System.out.println("************************************************************");
// Thread.sleep(30000);
System.out.println("************************************************************");
// Both threads are waiting *before* down-syncing now. We allow them both to continue:
syncFromLocalSrcToRemoteCoordinator.setSyncDownFrozen(false);
syncFromRemoteToLocalDestCoordinator.setSyncDownFrozen(false);
// Then we wait until they're done down-syncing.
syncFromLocalSrcToRemoteCoordinator.waitForSyncDownDone();
syncFromRemoteToLocalDestCoordinator.waitForSyncDownDone();
System.out.println("*****************");
// Thread.sleep(60000);
System.out.println("*****************");
// Now they're waiting *before* up-syncing. We continue the up-sync, thus, now.
syncFromLocalSrcToRemoteCoordinator.setSyncUpFrozen(false);
syncFromRemoteToLocalDestCoordinator.setSyncUpFrozen(false);
// Again, we wait here until they're done (this time, up-syncing).
syncFromLocalSrcToRemoteCoordinator.waitForSyncUpDone();
syncFromRemoteToLocalDestCoordinator.waitForSyncUpDone();
System.out.println("*****************");
// Thread.sleep(60000);
System.out.println("*****************");
// Again, they're waiting for down-sync's green light => go!
syncFromLocalSrcToRemoteCoordinator.setSyncDownFrozen(false);
syncFromRemoteToLocalDestCoordinator.setSyncDownFrozen(false);
// ...wait until they're done.
syncFromLocalSrcToRemoteCoordinator.waitForSyncDownDone();
syncFromRemoteToLocalDestCoordinator.waitForSyncDownDone();
System.out.println("************************************************************");
// Thread.sleep(60000);
System.out.println("************************************************************");
// syncFromLocalSrcToRemote(); // should down-sync the change from dest-repo
assertDirectoriesAreEqualRecursively(
(remotePathPrefix2Plain.isEmpty() ? getLocalRootWithPathPrefix() : createFile(getLocalRootWithPathPrefix(), remotePathPrefix2Plain)),
localDestRoot);
// Verify that *both* versions are in the history.
List<PlainHistoCryptoRepoFileDto> plainHistoCryptoRepoFileDtos = getPlainHistoCryptoRepoFileDtos(localRepoManagerLocal, file1);
assertThat(plainHistoCryptoRepoFileDtos).hasSize(2);
// Both new versions should have the same previous version, because the collision happened on the server.
Set<Uid> previousHistoCryptoRepoFileIds = new HashSet<>();
for (PlainHistoCryptoRepoFileDto phcrfDto : plainHistoCryptoRepoFileDtos)
previousHistoCryptoRepoFileIds.add(phcrfDto.getHistoCryptoRepoFileDto().getPreviousHistoCryptoRepoFileId());
assertThat(previousHistoCryptoRepoFileIds).hasSize(1);
// Verify that the 2nd version (with 222 at the end) is the current one.
int lastByte1 = getLastByte(file1);
assertThat(lastByte1).isEqualTo(222);
int lastByte2 = getLastByte(file2);
assertThat(lastByte2).isEqualTo(222);
// Export both versions of the file and assert that
// - the current file is identical to the last one
// - and the first one ends on 111.
File tempDir0 = createTempDirectory(getClass().getSimpleName() + '.');
File tempDir1 = createTempDirectory(getClass().getSimpleName() + '.');
try (HistoExporter histoExporter = HistoExporterImpl.createHistoExporter(localSrcRoot);) {
histoExporter.exportFile(
plainHistoCryptoRepoFileDtos.get(0).getHistoCryptoRepoFileDto().getHistoCryptoRepoFileId(), tempDir0);
histoExporter.exportFile(
plainHistoCryptoRepoFileDtos.get(1).getHistoCryptoRepoFileDto().getHistoCryptoRepoFileId(), tempDir1);
}
File histoFile0 = createFile(tempDir0, "new-file");
File histoFile1 = createFile(tempDir1, "new-file");
assertThat(IOUtil.compareFiles(histoFile1, file1)).isTrue();
assertThat(IOUtil.compareFiles(histoFile0, histoFile1)).isFalse();
int lastByteOfHistoFile0 = getLastByte(histoFile0);
assertThat(lastByteOfHistoFile0).isEqualTo(111);
collisionDtos = localRepoMetaData.getCollisionDtos(new CollisionFilter());
assertThat(collisionDtos).hasSize(1);
}
private class SyncFromLocalSrcToRemoteThread extends Thread {
private final Logger logger = LoggerFactory.getLogger(SyncFromLocalSrcToRemoteThread.class);
private final RepoToRepoSyncCoordinator coordinator;
public SyncFromLocalSrcToRemoteThread(RepoToRepoSyncCoordinator coordinator) {
this.coordinator = assertNotNull("coordinator", coordinator);
repoToRepoSyncCoordinatorThreadLocal.set(coordinator);
}
@Override
public void run() {
try {
syncFromLocalSrcToRemote();
} catch (Throwable e) {
logger.error("run: " + e, e);
coordinator.setError(e);
}
}
}
private class SyncFromRemoteToLocalDestThread extends Thread {
private final Logger logger = LoggerFactory.getLogger(SyncFromRemoteToLocalDestThread.class);
private final RepoToRepoSyncCoordinator coordinator;
public SyncFromRemoteToLocalDestThread(RepoToRepoSyncCoordinator coordinator) {
this.coordinator = assertNotNull("coordinator", coordinator);
repoToRepoSyncCoordinatorThreadLocal.set(coordinator);
}
@Override
public void run() {
try {
syncFromRemoteToLocalDest(false);
} catch (Throwable e) {
logger.error("run: " + e, e);
coordinator.setError(e);
}
}
}
// /**
// * Two clients simultaneously modify the same file.
// */
// @Test
// public void modifiedFileVsModifiedFileCollisionOnServer() throws Exception {
//
// }
//
// /**
// * The first client deletes the file, uploads to the server, the 2nd client modifies it
// * and then syncs.
// */
// @Test
// public void deletedFileVsModifiedFileCollisionOnServer() throws Exception {
//
// }
//
// /**
// * The first client modifies the file, uploads to the server, the 2nd client deletes it
// * and then syncs.
// */
// @Test
// public void modifiedFileVsDeletedFileCollisionOnServer() throws Exception {
//
// }
// TODO add file-type-change-collisions (e.g. from directory to file)
protected void prepareLocalAndDestinationRepo() throws Exception {
createLocalSourceAndRemoteRepo();
populateLocalSourceRepo();
syncFromLocalSrcToRemote();
determineRemotePathPrefix2Encrypted();
createLocalDestinationRepo();
syncFromRemoteToLocalDest();
}
private int getLastByte(File file) throws IOException {
try (RandomAccessFile raf = new RandomAccessFile(file.getIoFile(), "r")) {
raf.seek(raf.length() - 1);
int result = raf.read();
assertThat(result).isGreaterThanOrEqualTo(0);
return result;
}
}
private List<PlainHistoCryptoRepoFileDto> getPlainHistoCryptoRepoFileDtos(LocalRepoManager localRepoManager, File file) throws IOException {
final String path = "/" + localRepoManager.getLocalRoot().relativize(file).replace('\\', '/');
SsLocalRepoMetaData localRepoMetaData = (SsLocalRepoMetaData) localRepoManagerLocal.getLocalRepoMetaData();
List<PlainHistoCryptoRepoFileDto> result = new ArrayList<>();
// TODO need to extend the filter with a path! Do this when extending the UI to show a history in every folder-detail-pane.
// The current implementation is very inefficient - but we have only small test data, anyway ;-)
Collection<HistoFrameDto> histoFrameDtos = localRepoMetaData.getHistoFrameDtos(new HistoFrameFilter());
for (HistoFrameDto histoFrameDto : histoFrameDtos) {
PlainHistoCryptoRepoFileFilter filter = new PlainHistoCryptoRepoFileFilter();
filter.setHistoFrameId(histoFrameDto.getHistoFrameId());
filter.setFillParents(true);
Collection<PlainHistoCryptoRepoFileDto> plainHistoCryptoRepoFileDtos = localRepoMetaData.getPlainHistoCryptoRepoFileDtos(filter);
PlainHistoCryptoRepoFileDtoTreeNode rootNode = PlainHistoCryptoRepoFileDtoTreeNode.createTree(plainHistoCryptoRepoFileDtos);
for (PlainHistoCryptoRepoFileDtoTreeNode node : rootNode) {
if (path.equals(node.getPath()))
result.add(node.getPlainHistoCryptoRepoFileDto());
}
}
Collections.sort(result, new Comparator<PlainHistoCryptoRepoFileDto>() {
@Override
public int compare(PlainHistoCryptoRepoFileDto o1, PlainHistoCryptoRepoFileDto o2) {
Date signatureCreated1 = o1.getHistoCryptoRepoFileDto().getSignature().getSignatureCreated();
Date signatureCreated2 = o2.getHistoCryptoRepoFileDto().getSignature().getSignatureCreated();
return signatureCreated1.compareTo(signatureCreated2);
}
});
return result;
}
}
| Fixed one test leaking RepoToRepoSyncCoordinator into following test.
| org.subshare/org.subshare.test/src/test/java/org/subshare/test/CollisionRepoToRepoSyncIT.java | Fixed one test leaking RepoToRepoSyncCoordinator into following test. | <ide><path>rg.subshare/org.subshare.test/src/test/java/org/subshare/test/CollisionRepoToRepoSyncIT.java
<ide> return invocation.proceed();
<ide> }
<ide> };
<del>
<del>// new MockUp<SsRepoToRepoSync>() {
<del>// @Mock
<del>// void syncUp(Invocation invocation, ProgressMonitor monitor) {
<del>// System.out.println(">>>>>>>>>>>>> syncUp >>>>>>>>>>>>>>>>>");
<del>//// RepoToRepoSyncCoordinator coordinator = repoToRepoSyncCoordinatorThreadLocal.get();
<del>//// if (coordinator != null && ! coordinator.waitWhileSyncUpFrozen())
<del>//// return;
<del>//
<del>// invocation.proceed();
<del>//
<del>//// if (coordinator != null)
<del>//// coordinator.setSyncUpDone(true);
<del>// }
<del>//
<del>// @Mock
<del>// void syncDown(Invocation invocation, boolean fromRepoLocalSync, ProgressMonitor monitor) {
<del>// System.out.println(">>>>>>>>>>>>> syncDown >>>>>>>>>>>>>>>>>");
<del>//// RepoToRepoSyncCoordinator coordinator = repoToRepoSyncCoordinatorThreadLocal.get();
<del>//// if (coordinator != null && ! coordinator.waitWhileSyncDownFrozen())
<del>//// return;
<del>//
<del>// invocation.proceed();
<del>//
<del>//// if (coordinator != null)
<del>//// coordinator.setSyncDownDone(true);
<del>// }
<del>// };
<del> }
<del>
<add> }
<add>
<add> @Override
<add> public void after() throws Exception {
<add> for (RepoToRepoSyncCoordinator coordinator : repoToRepoSyncCoordinators)
<add> coordinator.close();
<add>
<add> repoToRepoSyncCoordinators.clear();
<add> super.after();
<add> }
<add>
<add> /**
<add> * Mocking the {@link SsRepoToRepoSync} does not work - for whatever reason - hence, this
<add> * class is a "manual" mock which is introduced into Subshare using a mocked {@link ObjectFactory}.
<add> */
<ide> private static class MockSsRepoToRepoSync extends SsRepoToRepoSync {
<ide>
<ide> protected MockSsRepoToRepoSync(File localRoot, URL remoteRoot) {
<ide> }
<ide> }
<ide>
<del> private static class RepoToRepoSyncCoordinator {
<del> private static final Logger logger = LoggerFactory.getLogger(CollisionRepoToRepoSyncIT.RepoToRepoSyncCoordinator.class);
<add> private class RepoToRepoSyncCoordinator {
<add> private final Logger logger = LoggerFactory.getLogger(CollisionRepoToRepoSyncIT.RepoToRepoSyncCoordinator.class);
<ide>
<ide> private boolean syncUpFrozen = true;
<ide> private boolean syncUpDone;
<ide> private boolean syncDownDone;
<ide>
<ide> private Throwable error;
<add>
<add> private boolean closed;
<add>
<add> public RepoToRepoSyncCoordinator() {
<add> repoToRepoSyncCoordinators.add(this);
<add> }
<ide>
<ide> protected synchronized boolean isSyncUpFrozen() {
<ide> return syncUpFrozen;
<ide> throw new RuntimeException(error);
<ide> }
<ide> }
<del> }
<del>
<del> private static final ThreadLocal<RepoToRepoSyncCoordinator> repoToRepoSyncCoordinatorThreadLocal = new ThreadLocal<>();
<add>
<add> public synchronized boolean isClosed() {
<add> return closed;
<add> }
<add>
<add> public synchronized void close() {
<add> closed = true;
<add>
<add> if (error == null)
<add> error = new RuntimeException("CLOSED!");
<add>
<add> notifyAll();
<add> }
<add> }
<add>
<add> private static final ThreadLocal<RepoToRepoSyncCoordinator> repoToRepoSyncCoordinatorThreadLocal = new ThreadLocal<RepoToRepoSyncCoordinator>() {
<add> @Override
<add> public RepoToRepoSyncCoordinator get() {
<add> RepoToRepoSyncCoordinator result = super.get();
<add> if (result != null && result.isClosed())
<add> return null;
<add>
<add> return result;
<add> }
<add> };
<add> private final List<RepoToRepoSyncCoordinator> repoToRepoSyncCoordinators = new ArrayList<RepoToRepoSyncCoordinator>();
<ide>
<ide> /**
<ide> * Two clients simultaneously create a file with the same name in the same directory. |
|
Java | mit | b7de5a26dcca8d01e291f363f19ed828a02decc2 | 0 | InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service | package org.innovateuk.ifs.project.status.security;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.innovateuk.ifs.commons.error.exception.ForbiddenActionException;
import org.innovateuk.ifs.commons.security.PermissionRule;
import org.innovateuk.ifs.commons.security.PermissionRules;
import org.innovateuk.ifs.project.ProjectService;
import org.innovateuk.ifs.project.resource.ProjectPartnerStatusResource;
import org.innovateuk.ifs.project.resource.ProjectTeamStatusResource;
import org.innovateuk.ifs.project.resource.ProjectUserResource;
import org.innovateuk.ifs.project.sections.ProjectSetupSectionAccessibilityHelper;
import org.innovateuk.ifs.project.sections.SectionAccess;
import org.innovateuk.ifs.user.resource.OrganisationResource;
import org.innovateuk.ifs.user.resource.UserResource;
import org.innovateuk.ifs.user.resource.UserRoleType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
import static org.innovateuk.ifs.project.sections.SectionAccess.ACCESSIBLE;
import static org.innovateuk.ifs.util.CollectionFunctions.simpleFindFirst;
/**
* Permission checker around the access to various sections within the Project Setup process
*/
@PermissionRules
@Component
public class ProjectSetupSectionsPermissionRules {
private static final Log LOG = LogFactory.getLog(ProjectSetupSectionsPermissionRules.class);
@Autowired
private ProjectService projectService;
private ProjectSetupSectionPartnerAccessorSupplier accessorSupplier = new ProjectSetupSectionPartnerAccessorSupplier();
@PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required")
public boolean partnerCanAccessProjectDetailsSection(Long projectId, UserResource user) {
return doSectionCheck(projectId, user, ProjectSetupSectionAccessibilityHelper::canAccessProjectDetailsSection);
}
@PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " +
"section when their Companies House details are complete or not required, and the Project Details have been submitted")
public boolean partnerCanAccessMonitoringOfficerSection(Long projectId, UserResource user) {
return doSectionCheck(projectId, user, ProjectSetupSectionAccessibilityHelper::canAccessMonitoringOfficerSection);
}
@PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " +
"section when their Companies House details are complete or not required, and they have a Finance Contact " +
"available for their Organisation")
public boolean partnerCanAccessBankDetailsSection(Long projectId, UserResource user) {
return doSectionCheck(projectId, user, ProjectSetupSectionAccessibilityHelper::canAccessBankDetailsSection);
}
@PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " +
" when their Companies House details are complete or not required, and the Project Details have been submitted")
public boolean partnerCanAccessFinanceChecksSection(Long projectId, UserResource user) {
return doSectionCheck(projectId, user, ProjectSetupSectionAccessibilityHelper::canAccessFinanceChecksSection);
}
@PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " +
"section when their Companies House details are complete or not required, the Project Details have been submitted, " +
"and the Organisation's Bank Details have been approved or queried")
public boolean partnerCanAccessSpendProfileSection(Long projectId, UserResource user) {
return doSectionCheck(projectId, user, ProjectSetupSectionAccessibilityHelper::canAccessSpendProfileSection);
}
@PermissionRule(value = "ACCESS_COMPANIES_HOUSE_SECTION", description = "A partner can access the Companies House " +
"section if their Organisation is a business type (i.e. if Companies House details are required)")
public boolean partnerCanAccessCompaniesHouseSection(Long projectId, UserResource user) {
return doSectionCheck(projectId, user, ProjectSetupSectionAccessibilityHelper::canAccessCompaniesHouseSection);
}
@PermissionRule(value = "ACCESS_OTHER_DOCUMENTS_SECTION", description = "A partner can access the Other Documents " +
"section if their Organisation is a business type (i.e. if Companies House details are required)")
public boolean partnerCanAccessOtherDocumentsSection(Long projectId, UserResource user) {
return doSectionCheck(projectId, user, ProjectSetupSectionAccessibilityHelper::canAccessOtherDocumentsSection);
}
@PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " +
"section when all other sections are complete and a Grant Offer Letter has been generated by the internal team")
public boolean partnerCanAccessGrantOfferLetterSection(Long projectId, UserResource user) {
return doSectionCheck(projectId, user, ProjectSetupSectionAccessibilityHelper::canAccessGrantOfferLetterSection);
}
@PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document")
public boolean leadPartnerAccess(Long projectId, UserResource user) {
return projectService.isUserLeadPartner(projectId, user.getId());
}
@PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete")
public boolean userCanMarkSpendProfileIncomplete(Long projectId, UserResource user) {
List<ProjectUserResource> projectLeadPartners = projectService.getLeadPartners(projectId);
Optional<ProjectUserResource> returnedProjectUser = simpleFindFirst(projectLeadPartners, projectUserResource -> projectUserResource.getUser().equals(user.getId()));
return returnedProjectUser.isPresent();
}
private boolean doSectionCheck(Long projectId, UserResource user, BiFunction<ProjectSetupSectionAccessibilityHelper, OrganisationResource, SectionAccess> sectionCheckFn) {
List<ProjectUserResource> projectUsers = projectService.getProjectUsersForProject(projectId);
Optional<ProjectUserResource> projectUser = simpleFindFirst(projectUsers, pu ->
user.getId().equals(pu.getUser()) && UserRoleType.PARTNER.getName().equals(pu.getRoleName()));
return projectUser.map(pu -> {
ProjectTeamStatusResource teamStatus;
try {
teamStatus = projectService.getProjectTeamStatus(projectId, Optional.of(user.getId()));
} catch (ForbiddenActionException e) {
LOG.error("User " + user.getId() + " is not a Partner on an Organisation for Project " + projectId + ". Denying access to Project Setup");
return false;
}
ProjectPartnerStatusResource partnerStatusForUser = teamStatus.getPartnerStatusForOrganisation(pu.getOrganisation()).get();
ProjectSetupSectionAccessibilityHelper sectionAccessor = accessorSupplier.apply(teamStatus);
OrganisationResource organisation = new OrganisationResource();
organisation.setId(partnerStatusForUser.getOrganisationId());
organisation.setOrganisationType(partnerStatusForUser.getOrganisationType().getOrganisationTypeId());
return sectionCheckFn.apply(sectionAccessor, organisation) == ACCESSIBLE;
}).orElseGet(() -> {
LOG.error("User " + user.getId() + " is not a Partner on an Organisation for Project " + projectId + ". Denying access to Project Setup");
return false;
});
}
public class ProjectSetupSectionPartnerAccessorSupplier implements Function<ProjectTeamStatusResource, ProjectSetupSectionAccessibilityHelper> {
@Override
public ProjectSetupSectionAccessibilityHelper apply(ProjectTeamStatusResource teamStatus) {
return new ProjectSetupSectionAccessibilityHelper(teamStatus);
}
}
}
| ifs-web-service/ifs-project-setup-service/src/main/java/org/innovateuk/ifs/project/status/security/ProjectSetupSectionsPermissionRules.java | package org.innovateuk.ifs.project.status.security;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.innovateuk.ifs.commons.error.exception.ForbiddenActionException;
import org.innovateuk.ifs.commons.security.PermissionRule;
import org.innovateuk.ifs.commons.security.PermissionRules;
import org.innovateuk.ifs.project.ProjectService;
import org.innovateuk.ifs.project.resource.ProjectPartnerStatusResource;
import org.innovateuk.ifs.project.resource.ProjectTeamStatusResource;
import org.innovateuk.ifs.project.resource.ProjectUserResource;
import org.innovateuk.ifs.project.sections.ProjectSetupSectionAccessibilityHelper;
import org.innovateuk.ifs.project.sections.SectionAccess;
import org.innovateuk.ifs.user.resource.OrganisationResource;
import org.innovateuk.ifs.user.resource.UserResource;
import org.innovateuk.ifs.user.resource.UserRoleType;
import org.innovateuk.ifs.utils.AuthorisationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
import static org.innovateuk.ifs.project.sections.SectionAccess.ACCESSIBLE;
import static org.innovateuk.ifs.util.CollectionFunctions.simpleFindFirst;
/**
* Permission checker around the access to various sections within the Project Setup process
*/
@PermissionRules
@Component
public class ProjectSetupSectionsPermissionRules {
private static final Log LOG = LogFactory.getLog(ProjectSetupSectionsPermissionRules.class);
@Autowired
AuthorisationUtil authorisationUtil;
@Autowired
private ProjectService projectService;
private ProjectSetupSectionPartnerAccessorSupplier accessorSupplier = new ProjectSetupSectionPartnerAccessorSupplier();
@PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required")
public boolean partnerCanAccessProjectDetailsSection(Long projectId, UserResource user) {
return doSectionCheck(projectId, user, ProjectSetupSectionAccessibilityHelper::canAccessProjectDetailsSection);
}
@PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " +
"section when their Companies House details are complete or not required, and the Project Details have been submitted")
public boolean partnerCanAccessMonitoringOfficerSection(Long projectId, UserResource user) {
return doSectionCheck(projectId, user, ProjectSetupSectionAccessibilityHelper::canAccessMonitoringOfficerSection);
}
@PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " +
"section when their Companies House details are complete or not required, and they have a Finance Contact " +
"available for their Organisation")
public boolean partnerCanAccessBankDetailsSection(Long projectId, UserResource user) {
return doSectionCheck(projectId, user, ProjectSetupSectionAccessibilityHelper::canAccessBankDetailsSection);
}
@PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " +
" when their Companies House details are complete or not required, and the Project Details have been submitted")
public boolean partnerCanAccessFinanceChecksSection(Long projectId, UserResource user) {
return doSectionCheck(projectId, user, ProjectSetupSectionAccessibilityHelper::canAccessFinanceChecksSection);
}
@PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " +
"section when their Companies House details are complete or not required, the Project Details have been submitted, " +
"and the Organisation's Bank Details have been approved or queried")
public boolean partnerCanAccessSpendProfileSection(Long projectId, UserResource user) {
return doSectionCheck(projectId, user, ProjectSetupSectionAccessibilityHelper::canAccessSpendProfileSection);
}
@PermissionRule(value = "ACCESS_COMPANIES_HOUSE_SECTION", description = "A partner can access the Companies House " +
"section if their Organisation is a business type (i.e. if Companies House details are required)")
public boolean partnerCanAccessCompaniesHouseSection(Long projectId, UserResource user) {
return doSectionCheck(projectId, user, ProjectSetupSectionAccessibilityHelper::canAccessCompaniesHouseSection);
}
@PermissionRule(value = "ACCESS_OTHER_DOCUMENTS_SECTION", description = "A partner can access the Other Documents " +
"section if their Organisation is a business type (i.e. if Companies House details are required)")
public boolean partnerCanAccessOtherDocumentsSection(Long projectId, UserResource user) {
return doSectionCheck(projectId, user, ProjectSetupSectionAccessibilityHelper::canAccessOtherDocumentsSection);
}
@PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " +
"section when all other sections are complete and a Grant Offer Letter has been generated by the internal team")
public boolean partnerCanAccessGrantOfferLetterSection(Long projectId, UserResource user) {
return doSectionCheck(projectId, user, ProjectSetupSectionAccessibilityHelper::canAccessGrantOfferLetterSection);
}
@PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document")
public boolean leadPartnerAccess(Long projectId, UserResource user) {
return projectService.isUserLeadPartner(projectId, user.getId());
}
@PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete")
public boolean userCanMarkSpendProfileIncomplete(Long projectId, UserResource user) {
List<ProjectUserResource> projectLeadPartners = projectService.getLeadPartners(projectId);
Optional<ProjectUserResource> returnedProjectUser = simpleFindFirst(projectLeadPartners, projectUserResource -> projectUserResource.getUser().equals(user.getId()));
return returnedProjectUser.isPresent();
}
private boolean doSectionCheck(Long projectId, UserResource user, BiFunction<ProjectSetupSectionAccessibilityHelper, OrganisationResource, SectionAccess> sectionCheckFn) {
List<ProjectUserResource> projectUsers = projectService.getProjectUsersForProject(projectId);
Optional<ProjectUserResource> projectUser = simpleFindFirst(projectUsers, pu ->
user.getId().equals(pu.getUser()) && UserRoleType.PARTNER.getName().equals(pu.getRoleName()));
return projectUser.map(pu -> {
ProjectTeamStatusResource teamStatus;
if(!authorisationUtil.userIsPartnerInOrganisationForProject(projectId, pu.getOrganisation(), user.getId())) {
LOG.warn("User " + user.getId() + " is not a Partner on an Organisation for Project " + projectId + ". Denying access to Project Setup");
return false;
}
teamStatus = projectService.getProjectTeamStatus(projectId, Optional.of(user.getId()));
ProjectPartnerStatusResource partnerStatusForUser = teamStatus.getPartnerStatusForOrganisation(pu.getOrganisation()).get();
ProjectSetupSectionAccessibilityHelper sectionAccessor = accessorSupplier.apply(teamStatus);
OrganisationResource organisation = new OrganisationResource();
organisation.setId(partnerStatusForUser.getOrganisationId());
organisation.setOrganisationType(partnerStatusForUser.getOrganisationType().getOrganisationTypeId());
return sectionCheckFn.apply(sectionAccessor, organisation) == ACCESSIBLE;
}).orElseGet(() -> {
LOG.error("User " + user.getId() + " is not a Partner on an Organisation for Project " + projectId + ". Denying access to Project Setup");
return false;
});
}
public class ProjectSetupSectionPartnerAccessorSupplier implements Function<ProjectTeamStatusResource, ProjectSetupSectionAccessibilityHelper> {
@Override
public ProjectSetupSectionAccessibilityHelper apply(ProjectTeamStatusResource teamStatus) {
return new ProjectSetupSectionAccessibilityHelper(teamStatus);
}
}
}
| INFUND-9065 revert check that is not needed.
| ifs-web-service/ifs-project-setup-service/src/main/java/org/innovateuk/ifs/project/status/security/ProjectSetupSectionsPermissionRules.java | INFUND-9065 revert check that is not needed. | <ide><path>fs-web-service/ifs-project-setup-service/src/main/java/org/innovateuk/ifs/project/status/security/ProjectSetupSectionsPermissionRules.java
<ide> import org.innovateuk.ifs.user.resource.OrganisationResource;
<ide> import org.innovateuk.ifs.user.resource.UserResource;
<ide> import org.innovateuk.ifs.user.resource.UserRoleType;
<del>import org.innovateuk.ifs.utils.AuthorisationUtil;
<ide> import org.springframework.beans.factory.annotation.Autowired;
<ide> import org.springframework.stereotype.Component;
<ide>
<ide> public class ProjectSetupSectionsPermissionRules {
<ide>
<ide> private static final Log LOG = LogFactory.getLog(ProjectSetupSectionsPermissionRules.class);
<del>
<del> @Autowired
<del> AuthorisationUtil authorisationUtil;
<ide>
<ide> @Autowired
<ide> private ProjectService projectService;
<ide>
<ide> ProjectTeamStatusResource teamStatus;
<ide>
<del> if(!authorisationUtil.userIsPartnerInOrganisationForProject(projectId, pu.getOrganisation(), user.getId())) {
<del> LOG.warn("User " + user.getId() + " is not a Partner on an Organisation for Project " + projectId + ". Denying access to Project Setup");
<add> try {
<add> teamStatus = projectService.getProjectTeamStatus(projectId, Optional.of(user.getId()));
<add> } catch (ForbiddenActionException e) {
<add> LOG.error("User " + user.getId() + " is not a Partner on an Organisation for Project " + projectId + ". Denying access to Project Setup");
<ide> return false;
<ide> }
<del>
<del> teamStatus = projectService.getProjectTeamStatus(projectId, Optional.of(user.getId()));
<ide>
<ide> ProjectPartnerStatusResource partnerStatusForUser = teamStatus.getPartnerStatusForOrganisation(pu.getOrganisation()).get();
<ide> |
|
JavaScript | mit | c5b3290cd3707bb947be42a920f4c4b04c93bc76 | 0 | teamco/anthill_layout,teamco/anthill_layout,teamco/anthill_layout,teamco/anthill_layout | /**
* Created with RubyMine.
* User: teamco
* Date: 3/7/14
* Time: 7:39 PM
*/
define([
'plugins/preferences/preferences'
], function defineWidgetPreferences(BasePreferences) {
/**
* Define prefs
* @class WidgetPreferences
* @extends Renderer
* @extends BasePreferences
* @constructor
*/
var WidgetPreferences = function WidgetPreferences() {
};
return WidgetPreferences.extend('WidgetPreferences', {
/**
* @type {{
* title: {type: string, disabled: boolean, value},
* description: {type: string, disabled: boolean, value},
* widgetUrl: {type: string, disabled: boolean, value},
* onClickOpenUrl: {type: string, disabled: boolean, value},
* overlapping: {type: string, disabled: boolean, checked: boolean},
* alwaysOnTop: {type: string, disabled: boolean, checked: boolean},
* statistics: {type: string, disabled: boolean, checked: boolean},
* setLayerUp: {type: string, disabled: boolean, group: string, events: array},
* setLayerDown: {type: string, disabled: boolean, group: string, events: array},
* stretchWidth: {type: string, disabled: boolean, group: string, events: array},
* stretchHeight: {type: string, disabled: boolean, group: string, events: array}
* }}
*/
defaultPrefs: {
title: {
type: 'text',
disabled: false,
value: undefined,
visible: true
},
description: {
type: 'textarea',
disabled: false,
value: undefined,
visible: true
},
widgetUrl: {
type: 'textarea',
disabled: true,
value: undefined,
visible: true
},
onClickOpenUrl: {
type: 'textarea',
disabled: false,
value: undefined,
visible: true
},
overlapping: {
type: 'checkbox',
disabled: false,
checked: false,
visible: true
},
statistics: {
type: 'checkbox',
disabled: false,
checked: false,
visible: true
},
alwaysOnTop: {
type: 'checkbox',
disabled: false,
checked: false,
visible: true
},
setLayerUp: {
type: 'event',
disabled: false,
group: 'layer',
events: ['click'],
visible: true
},
setLayerDown: {
type: 'event',
disabled: false,
group: 'layer',
events: ['click'],
visible: true
},
stretchWidth: {
type: 'checkbox',
disabled: false,
checked: false,
visible: true
},
stretchHeight: {
type: 'checkbox',
disabled: false,
checked: false,
visible: true
},
stickToLeft: {
type: 'event',
disabled: false,
group: 'stick',
events: ['click'],
visible: true
},
stickToTop: {
type: 'event',
disabled: false,
group: 'stick',
events: ['click'],
visible: true
},
stickToCenter: {
type: 'event',
disabled: false,
group: 'stick',
events: ['click'],
visible: true
},
stickToBottom: {
type: 'event',
disabled: false,
group: 'stick',
events: ['click'],
visible: true
},
stickToRight: {
type: 'event',
disabled: false,
group: 'stick',
events: ['click'],
visible: true
}
},
/**
* Render prefs data
* @member WidgetPreferences
* @param data
*/
renderBasePrefsData: function renderBasePrefsData(data) {
/**
* Render form element
* @param {{}} hash
* @param {string} title
* @private
* @return {Array}
*/
function _renderForm(hash, title) {
/**
* Define dom nodes
* @type {Array}
*/
var nodes = [];
for (var index in hash) {
if (hash.hasOwnProperty(index)) {
/**
* Define text
* @type {string}
*/
var text = index.replace(title.toLowerCase(), '').
toPoint().
humanize();
/**
* Define node
*/
var node = hash[index];
/**
* Define placeholder text
* @type {string}
*/
var placeholder = 'Enter ' + text,
$element;
if (node.type === 'event') {
/**
* Get text field
* @type {*[]}
*/
$element = this.renderEventLink({
name: index,
title: text.trim(),
group: node.group || index,
disabled: node.disabled,
events: node.events,
visible: node.visible
});
}
if (node.type === 'text') {
/**
* Get text field
* @type {*[]}
*/
$element = this.renderTextField({
name: index,
text: text.trim(),
placeholder: placeholder,
value: node.value,
disabled: node.disabled,
visible: node.visible
});
}
if (node.type === 'checkbox') {
/**
* Get checkbox
* @type {*[]}
*/
$element = this.renderCheckbox({
name: index,
text: text.trim(),
checked: node.value,
value: node.value,
disabled: node.disabled,
visible: node.visible
});
}
if (node.type === 'textarea') {
/**
* Get text field
* @type {*[]}
*/
$element = this.renderTextArea({
name: index,
text: text.trim(),
placeholder: placeholder,
value: node.value,
disabled: node.disabled,
visible: node.visible
});
}
if (node.type === 'combobox') {
/**
* Define selected item
* @type {string}
*/
var selected = node.value;
/**
* Get text field
* @type {*[]}
*/
$element = this.renderCombobox(
node.list,
(selected.length === 0 ? node.list[0].value : selected),
text.trim(),
index,
undefined,
node.visible
);
}
nodes.push(
$('<li />').
addClass([node.type, node.visible ? '' : 'hidden'].join(' ')).
append($element)
);
}
}
return nodes;
}
/**
* Render node
* @param type
* @param prefs
* @param {string} title
* @param {boolean} [isOpened]
* @returns {*|jQuery}
* @private
*/
function _renderNode(type, prefs, title, isOpened) {
/**
* Define css class
* @type {string}
*/
var open = isOpened ? 'open' : undefined;
return $('<li />').append(
$('<fieldset />').append(
$('<legend />').addClass(open).text(title).
on('click.toggle', this.toggleFieldset.bind(this)).attr({
title: title
}),
$('<ul />').addClass(type).append(
_renderForm.bind(this)(prefs, title)
)
)
).addClass('auto');
}
/**
* Merge prefs
* @param defaults
* @param prefs
* @param {boolean} condition
* @returns {{}}
* @private
*/
function _mergePrefs(defaults, prefs, condition) {
var merge = {}, hash = {}, partition;
$.extend(true, hash, defaults, prefs);
for (var index in hash) {
if (hash.hasOwnProperty(index)) {
partition = condition ?
defaults.hasOwnProperty(index) :
!defaults.hasOwnProperty(index);
if (partition) {
merge[index] = hash[index];
}
}
}
return merge;
}
this.$.append(
this.renderInteractions([
_renderNode.bind(this)(
'default',
_mergePrefs(this.defaultPrefs, data, true),
'Widget'
),
_renderNode.bind(this)(
'content',
_mergePrefs(this.defaultPrefs, data, false),
this.view.scope.constructor.name,
true
)
])
);
},
/**
* Render Interactions
* @member WidgetPreferences
* @param {Array} nodes
* @returns {*}
*/
renderInteractions: function renderInteractions(nodes) {
/**
* Define controller
* @type {*}
*/
var controller = this.view.controller;
/**
* Define interactions container
* @type {*|jQuery}
*/
var $ul = $('<ul />').addClass('interactions');
/**
* Define dom prefs
*/
var column = controller.getDOMPreferences('column'),
row = controller.getDOMPreferences('row'),
width = controller.getDOMPreferences('relWidth'),
height = controller.getDOMPreferences('relHeight');
nodes.push(
$('<li />').append(
$('<fieldset />').append(
$('<legend />').text('Interactions').
on('click.toggle', this.toggleFieldset.bind(this)).attr({
title: 'Interactions'
}),
$ul.append([
this.renderPrefs('Column', column),
this.renderPrefs('Width', width),
this.renderPrefs('Row', row),
this.renderPrefs('Height', height)
])
)
).addClass('auto')
);
return nodes;
},
/**
* Render move
* @member WidgetPreferences
* @param {string} side
* @param value
* @returns {*|jQuery}
*/
renderPrefs: function renderPrefs(side, value) {
/**
* Define move
* @type {*[]}
*/
var $move = this.renderTextField({
name: side.toLowerCase(),
text: side,
placeholder: side,
value: value,
disabled: true,
visible: true
});
return $('<li />').append($move);
}
}, BasePreferences.prototype);
}); | app/assets/javascripts/scripts/plugins/preferences/widget.preferences.js | /**
* Created with RubyMine.
* User: teamco
* Date: 3/7/14
* Time: 7:39 PM
*/
define([
'plugins/preferences/preferences'
], function defineWidgetPreferences(BasePreferences) {
/**
* Define prefs
* @class WidgetPreferences
* @extends Renderer
* @extends BasePreferences
* @constructor
*/
var WidgetPreferences = function WidgetPreferences() {
};
return WidgetPreferences.extend('WidgetPreferences', {
/**
* @type {{
* title: {type: string, disabled: boolean, value},
* description: {type: string, disabled: boolean, value},
* widgetUrl: {type: string, disabled: boolean, value},
* onClickOpenUrl: {type: string, disabled: boolean, value},
* overlapping: {type: string, disabled: boolean, checked: boolean},
* alwaysOnTop: {type: string, disabled: boolean, checked: boolean},
* statistics: {type: string, disabled: boolean, checked: boolean},
* setLayerUp: {type: string, disabled: boolean, group: string, events: array},
* setLayerDown: {type: string, disabled: boolean, group: string, events: array},
* stretchWidth: {type: string, disabled: boolean, group: string, events: array},
* stretchHeight: {type: string, disabled: boolean, group: string, events: array}
* }}
*/
defaultPrefs: {
title: {
type: 'text',
disabled: false,
value: undefined,
visible: true
},
description: {
type: 'textarea',
disabled: false,
value: undefined,
visible: true
},
widgetUrl: {
type: 'textarea',
disabled: true,
value: undefined,
visible: true
},
onClickOpenUrl: {
type: 'textarea',
disabled: false,
value: undefined,
visible: true
},
overlapping: {
type: 'checkbox',
disabled: false,
checked: false,
visible: true
},
statistics: {
type: 'checkbox',
disabled: false,
checked: false,
visible: true
},
alwaysOnTop: {
type: 'checkbox',
disabled: false,
checked: false,
visible: true
},
setLayerUp: {
type: 'event',
disabled: false,
group: 'layer',
events: ['click'],
visible: true
},
setLayerDown: {
type: 'event',
disabled: false,
group: 'layer',
events: ['click'],
visible: true
},
stretchWidth: {
type: 'checkbox',
disabled: false,
checked: false,
visible: true
},
stretchHeight: {
type: 'checkbox',
disabled: false,
checked: false,
visible: true
},
stickToLeft: {
type: 'event',
disabled: false,
group: 'stick',
events: ['click'],
visible: true
},
stickToTop: {
type: 'event',
disabled: false,
group: 'stick',
events: ['click'],
visible: true
},
stickToCenter: {
type: 'event',
disabled: false,
group: 'stick',
events: ['click'],
visible: true
},
stickToBottom: {
type: 'event',
disabled: false,
group: 'stick',
events: ['click'],
visible: true
},
stickToRight: {
type: 'event',
disabled: false,
group: 'stick',
events: ['click'],
visible: true
}
},
/**
* Render prefs data
* @member WidgetPreferences
* @param data
*/
renderBasePrefsData: function renderBasePrefsData(data) {
/**
* Render form element
* @param {{}} hash
* @param {string} title
* @private
* @return {Array}
*/
function _renderForm(hash, title) {
/**
* Define dom nodes
* @type {Array}
*/
var nodes = [];
for (var index in hash) {
if (hash.hasOwnProperty(index)) {
/**
* Define text
* @type {string}
*/
var text = index.replace(title.toLowerCase(), '').toPoint().humanize();
/**
* Define node
*/
var node = hash[index];
/**
* Define placeholder text
* @type {string}
*/
var placeholder = 'Enter ' + text,
$element;
if (node.type === 'event') {
/**
* Get text field
* @type {*[]}
*/
$element = this.renderEventLink({
name: index,
title: text.trim(),
group: node.group || index,
disabled: node.disabled,
events: node.events,
visible: node.visible
});
}
if (node.type === 'text') {
/**
* Get text field
* @type {*[]}
*/
$element = this.renderTextField({
name: index,
text: text.trim(),
placeholder: placeholder,
value: node.value,
disabled: node.disabled,
visible: node.visible
});
}
if (node.type === 'checkbox') {
/**
* Get checkbox
* @type {*[]}
*/
$element = this.renderCheckbox({
name: index,
text: text.trim(),
checked: node.value,
value: node.value,
disabled: node.disabled,
visible: node.visible
});
}
if (node.type === 'textarea') {
/**
* Get text field
* @type {*[]}
*/
$element = this.renderTextArea({
name: index,
text: text.trim(),
placeholder: placeholder,
value: node.value,
disabled: node.disabled,
visible: node.visible
});
}
if (node.type === 'combobox') {
/**
* Define selected item
* @type {string}
*/
var selected = node.value;
/**
* Get text field
* @type {*[]}
*/
$element = this.renderCombobox(
node.list,
(selected.length === 0 ? node.list[0].value : selected),
text.trim(),
index,
undefined,
node.visible
);
}
nodes.push(
$('<li />').
addClass([node.type, node.visible ? '' : 'hidden'].join(' ')).
append($element)
);
}
}
return nodes;
}
/**
* Render node
* @param type
* @param prefs
* @param {string} title
* @param {boolean} [isOpened]
* @returns {*|jQuery}
* @private
*/
function _renderNode(type, prefs, title, isOpened) {
/**
* Define css class
* @type {string}
*/
var open = isOpened ? 'open' : undefined;
return $('<li />').append(
$('<fieldset />').append(
$('<legend />').addClass(open).text(title).
on('click.toggle', this.toggleFieldset.bind(this)).attr({
title: title
}),
$('<ul />').addClass(type).append(
_renderForm.bind(this)(prefs, title)
)
)
).addClass('auto');
}
/**
* Merge prefs
* @param defaults
* @param prefs
* @param {boolean} condition
* @returns {{}}
* @private
*/
function _mergePrefs(defaults, prefs, condition) {
var merge = {}, hash = {}, partition;
$.extend(true, hash, defaults, prefs);
for (var index in hash) {
if (hash.hasOwnProperty(index)) {
partition = condition ?
defaults.hasOwnProperty(index) :
!defaults.hasOwnProperty(index);
if (partition) {
merge[index] = hash[index];
}
}
}
return merge;
}
this.$.append(
this.renderInteractions([
_renderNode.bind(this)(
'default',
_mergePrefs(this.defaultPrefs, data, true),
'Widget'
),
_renderNode.bind(this)(
'content',
_mergePrefs(this.defaultPrefs, data, false),
this.view.scope.constructor.name,
true
)
])
);
},
/**
* Render Interactions
* @member WidgetPreferences
* @param {Array} nodes
* @returns {*}
*/
renderInteractions: function renderInteractions(nodes) {
/**
* Define controller
* @type {*}
*/
var controller = this.view.controller;
/**
* Define interactions container
* @type {*|jQuery}
*/
var $ul = $('<ul />').addClass('interactions');
/**
* Define dom prefs
*/
var column = controller.getDOMPreferences('column'),
row = controller.getDOMPreferences('row'),
width = controller.getDOMPreferences('relWidth'),
height = controller.getDOMPreferences('relHeight');
nodes.push(
$('<li />').append(
$('<fieldset />').append(
$('<legend />').text('Interactions').
on('click.toggle', this.toggleFieldset.bind(this)).attr({
title: 'Interactions'
}),
$ul.append([
this.renderPrefs('Column', column),
this.renderPrefs('Width', width),
this.renderPrefs('Row', row),
this.renderPrefs('Height', height)
])
)
).addClass('auto')
);
return nodes;
},
/**
* Render move
* @member WidgetPreferences
* @param {string} side
* @param value
* @returns {*|jQuery}
*/
renderPrefs: function renderPrefs(side, value) {
/**
* Define move
* @type {*[]}
*/
var $move = this.renderTextField({
name: side.toLowerCase(),
text: side,
placeholder: side,
value: value,
disabled: true,
visible: true
});
return $('<li />').append($move);
}
}, BasePreferences.prototype);
}); | fix code
| app/assets/javascripts/scripts/plugins/preferences/widget.preferences.js | fix code | <ide><path>pp/assets/javascripts/scripts/plugins/preferences/widget.preferences.js
<ide> * Define text
<ide> * @type {string}
<ide> */
<del> var text = index.replace(title.toLowerCase(), '').toPoint().humanize();
<add> var text = index.replace(title.toLowerCase(), '').
<add> toPoint().
<add> humanize();
<ide>
<ide> /**
<ide> * Define node |
|
Java | apache-2.0 | bb1a0a759e821871b266663e8dfdf860067b467c | 0 | apache/isis,estatio/isis,sanderginn/isis,howepeng/isis,estatio/isis,niv0/isis,kidaa/isis,peridotperiod/isis,howepeng/isis,sanderginn/isis,apache/isis,estatio/isis,oscarbou/isis,apache/isis,incodehq/isis,kidaa/isis,apache/isis,kidaa/isis,niv0/isis,sanderginn/isis,oscarbou/isis,howepeng/isis,niv0/isis,incodehq/isis,apache/isis,peridotperiod/isis,sanderginn/isis,kidaa/isis,peridotperiod/isis,incodehq/isis,oscarbou/isis,niv0/isis,estatio/isis,apache/isis,incodehq/isis,howepeng/isis,peridotperiod/isis,oscarbou/isis | package org.nakedobjects.viewer.skylark.metal;
import org.nakedobjects.object.Naked;
import org.nakedobjects.object.control.Consent;
import org.nakedobjects.viewer.skylark.Bounds;
import org.nakedobjects.viewer.skylark.Canvas;
import org.nakedobjects.viewer.skylark.Click;
import org.nakedobjects.viewer.skylark.Content;
import org.nakedobjects.viewer.skylark.ContentDrag;
import org.nakedobjects.viewer.skylark.Drag;
import org.nakedobjects.viewer.skylark.DragStart;
import org.nakedobjects.viewer.skylark.InternalDrag;
import org.nakedobjects.viewer.skylark.Location;
import org.nakedobjects.viewer.skylark.MenuOptionSet;
import org.nakedobjects.viewer.skylark.Padding;
import org.nakedobjects.viewer.skylark.Size;
import org.nakedobjects.viewer.skylark.UserAction;
import org.nakedobjects.viewer.skylark.View;
import org.nakedobjects.viewer.skylark.ViewAreaType;
import org.nakedobjects.viewer.skylark.ViewAxis;
import org.nakedobjects.viewer.skylark.ViewDrag;
import org.nakedobjects.viewer.skylark.ViewSpecification;
import org.nakedobjects.viewer.skylark.ViewState;
import org.nakedobjects.viewer.skylark.Viewer;
import org.nakedobjects.viewer.skylark.Workspace;
public abstract class AbstractControlView implements View {
protected final UserAction action;
private Location location;
private final View parent;
private Size size;
public AbstractControlView(UserAction action, View target) {
this.action = action;
this.parent = target;
}
public void addView(View view) {}
public boolean canChangeValue() {
return false;
}
public boolean canFocus() {
return true;
}
public boolean contains(View view) {
return false;
}
public void contentMenuOptions(MenuOptionSet menuOptions) {}
public String debugDetails() {
return null;
}
public void dispose() {}
public void drag(InternalDrag drag) {}
public void dragCancel(InternalDrag drag) {}
public View dragFrom(Location location) {
return null;
}
public void dragIn(ContentDrag drag) {}
public void dragOut(ContentDrag drag) {}
public Drag dragStart(DragStart drag) {
return null;
}
public void dragTo(InternalDrag drag) {}
public void draw(Canvas canvas) {}
public void drop(ContentDrag drag) {}
public void drop(ViewDrag drag) {}
public void editComplete() {}
public void entered() {
// getViewManager().clearStatus();
View target = getParent();
Consent disabled = action.disabled(target);
if (disabled.isVetoed()) {
getViewManager().setStatus(action.getName(target) + " - " + disabled.getReason());
} else {
getViewManager().setStatus(action.getName(target) + " - " + action.getDescription(target));
}
}
public void enteredSubview() {}
public void exited() {
getViewManager().clearStatus();
}
public void exitedSubview() {}
public void firstClick(Click click) {
View target = getParent().getView();
if (action.disabled(target).isAllowed()) {
markDamaged();
getViewManager().saveCurrentFieldEntry();
action.execute(target.getWorkspace(), target, getLocation());
}
}
public void focusLost() {}
public void focusRecieved() {}
public Location getAbsoluteLocation() {
return null;
}
public int getBaseline() {
return 0;
}
public Bounds getBounds() {
return new Bounds(location, size);
}
public Content getContent() {
return null;
}
public int getId() {
return 0;
}
public Location getLocation() {
return new Location(location);
}
public Padding getPadding() {
return null;
}
public View getParent() {
return parent;
}
public Size getSize() {
return new Size(size);
}
public ViewSpecification getSpecification() {
return null;
}
public ViewState getState() {
return null;
}
public View[] getSubviews() {
return new View[0];
}
public View getView() {
return this;
}
public ViewAxis getViewAxis() {
return null;
}
public Viewer getViewManager() {
return Viewer.getInstance();
}
public Workspace getWorkspace() {
return null;
}
public boolean hasFocus() {
return false;
}
public View identify(Location location) {
return this;
}
public void invalidateContent() {}
public void invalidateLayout() {}
public void keyPressed(int keyCode, int modifiers) {}
public void keyReleased(int keyCode, int modifiers) {}
public void keyTyped(char keyCode) {}
public void layout() {}
public void limitBoundsWithin(Bounds bounds) {}
public void markDamaged() {}
public void markDamaged(Bounds bounds) {}
public void mouseMoved(Location location) {}
public void objectActionResult(Naked result, Location at) {}
public View pickupContent(Location location) {
return null;
}
public View pickupView(Location location) {
return null;
}
public void print(Canvas canvas) {}
public void refresh() {}
public void removeView(View view) {}
public void replaceView(View toReplace, View replacement) {}
public void secondClick(Click click) {}
public void setBounds(Bounds bounds) {}
public void setLocation(Location point) {
this.location = point;
}
public void setParent(View view) {}
public void setRequiredSize(Size size) {}
public void setSize(Size size) {
this.size = size;
}
public void setView(View view) {}
public View subviewFor(Location location) {
return null;
}
public void thirdClick(Click click) {}
public void update(Naked object) {}
public void updateView() {}
public ViewAreaType viewAreaType(Location mouseLocation) {
return null;
}
public void viewMenuOptions(MenuOptionSet menuOptions) {}
}
/*
* Naked Objects - a framework that exposes behaviourally complete business objects directly to the
* user. Copyright (C) 2000 - 2005 Naked Objects Group Ltd
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*
* The authors can be contacted via www.nakedobjects.org (the registered address of Naked Objects
* Group is Kingsway House, 123 Goldworth Road, Woking GU21 1NR, UK).
*/ | viewer-skylark/src/org/nakedobjects/viewer/skylark/metal/AbstractControlView.java | package org.nakedobjects.viewer.skylark.metal;
import org.nakedobjects.object.Naked;
import org.nakedobjects.object.control.Consent;
import org.nakedobjects.viewer.skylark.Bounds;
import org.nakedobjects.viewer.skylark.Canvas;
import org.nakedobjects.viewer.skylark.Click;
import org.nakedobjects.viewer.skylark.Content;
import org.nakedobjects.viewer.skylark.ContentDrag;
import org.nakedobjects.viewer.skylark.Drag;
import org.nakedobjects.viewer.skylark.DragStart;
import org.nakedobjects.viewer.skylark.InternalDrag;
import org.nakedobjects.viewer.skylark.Location;
import org.nakedobjects.viewer.skylark.MenuOptionSet;
import org.nakedobjects.viewer.skylark.Padding;
import org.nakedobjects.viewer.skylark.Size;
import org.nakedobjects.viewer.skylark.UserAction;
import org.nakedobjects.viewer.skylark.View;
import org.nakedobjects.viewer.skylark.ViewAreaType;
import org.nakedobjects.viewer.skylark.ViewAxis;
import org.nakedobjects.viewer.skylark.ViewDrag;
import org.nakedobjects.viewer.skylark.ViewSpecification;
import org.nakedobjects.viewer.skylark.ViewState;
import org.nakedobjects.viewer.skylark.Viewer;
import org.nakedobjects.viewer.skylark.Workspace;
public abstract class AbstractControlView implements View {
protected final UserAction action;
private Location location;
private final View parent;
private Size size;
public AbstractControlView(UserAction action, View target) {
this.action = action;
this.parent = target;
}
public void addView(View view) {}
public boolean canChangeValue() {
return false;
}
public boolean canFocus() {
return true;
}
public boolean contains(View view) {
return false;
}
public void contentMenuOptions(MenuOptionSet menuOptions) {}
public String debugDetails() {
return null;
}
public void dispose() {}
public void drag(InternalDrag drag) {}
public void dragCancel(InternalDrag drag) {}
public View dragFrom(Location location) {
return null;
}
public void dragIn(ContentDrag drag) {}
public void dragOut(ContentDrag drag) {}
public Drag dragStart(DragStart drag) {
return null;
}
public void dragTo(InternalDrag drag) {}
public void draw(Canvas canvas) {}
public void drop(ContentDrag drag) {}
public void drop(ViewDrag drag) {}
public void editComplete() {}
public void entered() {
// getViewManager().clearStatus();
View target = getParent();
Consent disabled = action.disabled(target);
if (disabled.isVetoed()) {
getViewManager().setStatus(action.getName(target) + " - " + disabled.getReason());
} else {
getViewManager().setStatus(action.getName(target) + " - " + action.getDescription(target));
}
}
public void enteredSubview() {}
public void exited() {
getViewManager().clearStatus();
}
public void exitedSubview() {}
public void firstClick(Click click) {
View target = getParent();
if (action.disabled(target).isAllowed()) {
markDamaged();
getViewManager().saveCurrentFieldEntry();
action.execute(target.getWorkspace(), target, getLocation());
}
}
public void focusLost() {}
public void focusRecieved() {}
public Location getAbsoluteLocation() {
return null;
}
public int getBaseline() {
return 0;
}
public Bounds getBounds() {
return new Bounds(location, size);
}
public Content getContent() {
return null;
}
public int getId() {
return 0;
}
public Location getLocation() {
return new Location(location);
}
public Padding getPadding() {
return null;
}
public View getParent() {
return parent;
}
public Size getSize() {
return new Size(size);
}
public ViewSpecification getSpecification() {
return null;
}
public ViewState getState() {
return null;
}
public View[] getSubviews() {
return new View[0];
}
public View getView() {
return this;
}
public ViewAxis getViewAxis() {
return null;
}
public Viewer getViewManager() {
return Viewer.getInstance();
}
public Workspace getWorkspace() {
return null;
}
public boolean hasFocus() {
return false;
}
public View identify(Location location) {
return this;
}
public void invalidateContent() {}
public void invalidateLayout() {}
public void keyPressed(int keyCode, int modifiers) {}
public void keyReleased(int keyCode, int modifiers) {}
public void keyTyped(char keyCode) {}
public void layout() {}
public void limitBoundsWithin(Bounds bounds) {}
public void markDamaged() {}
public void markDamaged(Bounds bounds) {}
public void mouseMoved(Location location) {}
public void objectActionResult(Naked result, Location at) {}
public View pickupContent(Location location) {
return null;
}
public View pickupView(Location location) {
return null;
}
public void print(Canvas canvas) {}
public void refresh() {}
public void removeView(View view) {}
public void replaceView(View toReplace, View replacement) {}
public void secondClick(Click click) {}
public void setBounds(Bounds bounds) {}
public void setLocation(Location point) {
this.location = point;
}
public void setParent(View view) {}
public void setRequiredSize(Size size) {}
public void setSize(Size size) {
this.size = size;
}
public void setView(View view) {}
public View subviewFor(Location location) {
return null;
}
public void thirdClick(Click click) {}
public void update(Naked object) {}
public void updateView() {}
public ViewAreaType viewAreaType(Location mouseLocation) {
return null;
}
public void viewMenuOptions(MenuOptionSet menuOptions) {}
}
/*
* Naked Objects - a framework that exposes behaviourally complete business objects directly to the
* user. Copyright (C) 2000 - 2005 Naked Objects Group Ltd
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*
* The authors can be contacted via www.nakedobjects.org (the registered address of Naked Objects
* Group is Kingsway House, 123 Goldworth Road, Woking GU21 1NR, UK).
*/ | Controls (windows control and buttons) now use the outermost decorator as a view reference, ensuring the execute method of the action knows the real target view.
git-svn-id: 3f09329b2f6451ddff3637e937fd5de689f72c1f@1007443 13f79535-47bb-0310-9956-ffa450edef68
| viewer-skylark/src/org/nakedobjects/viewer/skylark/metal/AbstractControlView.java | Controls (windows control and buttons) now use the outermost decorator as a view reference, ensuring the execute method of the action knows the real target view. | <ide><path>iewer-skylark/src/org/nakedobjects/viewer/skylark/metal/AbstractControlView.java
<ide> public void exitedSubview() {}
<ide>
<ide> public void firstClick(Click click) {
<del> View target = getParent();
<add> View target = getParent().getView();
<ide> if (action.disabled(target).isAllowed()) {
<ide> markDamaged();
<ide> getViewManager().saveCurrentFieldEntry(); |
|
JavaScript | mit | 652ad6a9751906f6b543e48741e60ebd0e5026c2 | 0 | crossroads/shared.goodcity,crossroads/shared.goodcity | import Ember from "ember";
import AjaxPromise from './../utils/ajax-promise';
export default Ember.ArrayController.extend({
sortProperties: ["date"],
sortAscending: true,
messagesUtil: Ember.inject.service("messages"),
nextNotification: function() {
//retrieveNotification is not implemented here because it needs to call itself
return this.retrieveNotification();
}.property("[]"),
retrieveNotification: function(index) {
// not sure why but model.firstObject is undefined when there's one notification
var notification = this.get("model")[index || 0];
if (!notification) {
return null;
}
this.setRoute(notification);
// if current url matches notification view action url then dismiss notification
var router = this.get("target");
var currentUrl = router.get("url");
var actionUrl = router.generate.apply(router, notification.route);
if (currentUrl === actionUrl) {
this.removeObject(notification);
return this.retrieveNotification(index);
}
return notification;
},
itemImageUrl: function() {
var itemId = this.get("nextNotification.item_id");
return itemId ? this.store.getById("item", itemId).get("displayImageUrl") : null;
}.property("nextNotification"),
showItemImage: Ember.computed.notEmpty("itemImageUrl"),
senderImageUrl: function() {
var notification = this.get("nextNotification");
if (!notification) { return null; }
return this.store.getById("user", notification.author_id).get("displayImageUrl");
}.property("nextNotification"),
setRoute: function(notification) {
switch (notification.category) {
case "message":
notification.route = this.get("messagesUtil").getRoute(notification);
break;
case "new_offer":
case "incoming_call":
var routeName = this.get("session.isDonorApp") ? "offer" : "review_offer";
notification.route = [routeName, notification.offer_id];
break;
case "call_answered":
notification.route = ["offer.donor_messages", notification.offer_id];
break;
}
},
acceptCall: function(notification) {
new AjaxPromise("/twilio_inbound/accept_call", "GET", this.get('session.authToken'), { donor_id: notification.author_id })
},
actions: {
view: function() {
var notification = this.get("nextNotification");
this.removeObject(notification);
if (notification.category === "incoming_call") {
this.acceptCall(notification);
}
this.transitionToRoute.apply(this, notification.route);
}
}
});
| app/controllers/notifications.js | import Ember from "ember";
import AjaxPromise from './../utils/ajax-promise';
export default Ember.ArrayController.extend({
sortProperties: ["date"],
sortAscending: true,
messagesUtil: Ember.inject.service("messages"),
nextNotification: function() {
//retrieveNotification is not implemented here because it needs to call itself
return this.retrieveNotification();
}.property("[]"),
retrieveNotification: function(index) {
// not sure why but model.firstObject is undefined when there's one notification
var notification = this.get("model")[index || 0];
if (!notification) {
return null;
}
this.setRoute(notification);
// if current url matches notification view action url then dismiss notification
var router = this.get("target");
var currentUrl = router.get("url");
var actionUrl = router.generate.apply(router, notification.route);
if (currentUrl === actionUrl) {
this.removeObject(notification);
return this.retrieveNotification(index);
}
return notification;
},
itemImageUrl: function() {
var itemId = this.get("nextNotification.item_id");
return itemId ? this.store.getById("item", itemId).get("displayImageUrl") : null;
}.property("nextNotification"),
showItemImage: Ember.computed.notEmpty("itemImageUrl"),
senderImageUrl: function() {
var notification = this.get("nextNotification");
if (!notification) { return null; }
return this.store.getById("user", notification.author_id).get("displayImageUrl");
}.property("nextNotification"),
setRoute: function(notification) {
switch (notification.category) {
case "message":
notification.route = this.get("messagesUtil").getRoute(notification);
break;
case "new_offer":
case "incoming_call":
var routeName = this.get("session.isDonorApp") ? "offer" : "review_offer";
notification.route = [routeName, notification.offer_id];
break;
case "call_answered":
notification.route = ["offer.donor_messages", notification.offer_id];
break;
}
},
acceptCall: function(notification) {
new AjaxPromise("/twilio/accept_call", "GET", this.get('session.authToken'), { donor_id: notification.author_id })
},
actions: {
view: function() {
var notification = this.get("nextNotification");
this.removeObject(notification);
if (notification.category === "incoming_call") {
this.acceptCall(notification);
}
this.transitionToRoute.apply(this, notification.route);
}
}
});
| update twilio-call accept notification path
| app/controllers/notifications.js | update twilio-call accept notification path | <ide><path>pp/controllers/notifications.js
<ide> },
<ide>
<ide> acceptCall: function(notification) {
<del> new AjaxPromise("/twilio/accept_call", "GET", this.get('session.authToken'), { donor_id: notification.author_id })
<add> new AjaxPromise("/twilio_inbound/accept_call", "GET", this.get('session.authToken'), { donor_id: notification.author_id })
<ide> },
<ide>
<ide> actions: { |
|
Java | apache-2.0 | 7460d90a67bd9724d8fdac839c384bf36cbbce37 | 0 | tbrooks8/netty,andsel/netty,fengjiachun/netty,bryce-anderson/netty,ngocdaothanh/netty,jchambers/netty,fengjiachun/netty,mikkokar/netty,gerdriesselmann/netty,idelpivnitskiy/netty,NiteshKant/netty,KatsuraKKKK/netty,johnou/netty,louxiu/netty,skyao/netty,ejona86/netty,mikkokar/netty,gerdriesselmann/netty,louxiu/netty,ejona86/netty,carl-mastrangelo/netty,johnou/netty,carl-mastrangelo/netty,louxiu/netty,fenik17/netty,KatsuraKKKK/netty,andsel/netty,Apache9/netty,fengjiachun/netty,artgon/netty,carl-mastrangelo/netty,gerdriesselmann/netty,skyao/netty,zer0se7en/netty,zer0se7en/netty,idelpivnitskiy/netty,gerdriesselmann/netty,Squarespace/netty,netty/netty,skyao/netty,cnoldtree/netty,jchambers/netty,ngocdaothanh/netty,artgon/netty,idelpivnitskiy/netty,KatsuraKKKK/netty,tbrooks8/netty,netty/netty,Spikhalskiy/netty,KatsuraKKKK/netty,skyao/netty,louxiu/netty,Apache9/netty,doom369/netty,bryce-anderson/netty,ngocdaothanh/netty,cnoldtree/netty,Apache9/netty,carl-mastrangelo/netty,NiteshKant/netty,jchambers/netty,tbrooks8/netty,Squarespace/netty,NiteshKant/netty,gerdriesselmann/netty,idelpivnitskiy/netty,doom369/netty,bryce-anderson/netty,doom369/netty,zer0se7en/netty,Squarespace/netty,doom369/netty,KatsuraKKKK/netty,andsel/netty,bryce-anderson/netty,artgon/netty,tbrooks8/netty,netty/netty,ejona86/netty,fenik17/netty,fengjiachun/netty,zer0se7en/netty,idelpivnitskiy/netty,Squarespace/netty,NiteshKant/netty,cnoldtree/netty,Spikhalskiy/netty,Apache9/netty,fengjiachun/netty,carl-mastrangelo/netty,netty/netty,Spikhalskiy/netty,ngocdaothanh/netty,ejona86/netty,mikkokar/netty,netty/netty,Squarespace/netty,zer0se7en/netty,jchambers/netty,skyao/netty,bryce-anderson/netty,mikkokar/netty,tbrooks8/netty,andsel/netty,fenik17/netty,ejona86/netty,louxiu/netty,cnoldtree/netty,fenik17/netty,doom369/netty,artgon/netty,ngocdaothanh/netty,johnou/netty,artgon/netty,Spikhalskiy/netty,Apache9/netty,Spikhalskiy/netty,johnou/netty,andsel/netty,cnoldtree/netty,fenik17/netty,mikkokar/netty,NiteshKant/netty,jchambers/netty,johnou/netty | /*
* Copyright 2012 The Netty Project
*
* The Netty 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 io.netty.handler.timeout;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.Channel.Unsafe;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOutboundBuffer;
import io.netty.channel.ChannelPromise;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* Triggers an {@link IdleStateEvent} when a {@link Channel} has not performed
* read, write, or both operation for a while.
*
* <h3>Supported idle states</h3>
* <table border="1">
* <tr>
* <th>Property</th><th>Meaning</th>
* </tr>
* <tr>
* <td>{@code readerIdleTime}</td>
* <td>an {@link IdleStateEvent} whose state is {@link IdleState#READER_IDLE}
* will be triggered when no read was performed for the specified period of
* time. Specify {@code 0} to disable.</td>
* </tr>
* <tr>
* <td>{@code writerIdleTime}</td>
* <td>an {@link IdleStateEvent} whose state is {@link IdleState#WRITER_IDLE}
* will be triggered when no write was performed for the specified period of
* time. Specify {@code 0} to disable.</td>
* </tr>
* <tr>
* <td>{@code allIdleTime}</td>
* <td>an {@link IdleStateEvent} whose state is {@link IdleState#ALL_IDLE}
* will be triggered when neither read nor write was performed for the
* specified period of time. Specify {@code 0} to disable.</td>
* </tr>
* </table>
*
* <pre>
* // An example that sends a ping message when there is no outbound traffic
* // for 30 seconds. The connection is closed when there is no inbound traffic
* // for 60 seconds.
*
* public class MyChannelInitializer extends {@link ChannelInitializer}<{@link Channel}> {
* {@code @Override}
* public void initChannel({@link Channel} channel) {
* channel.pipeline().addLast("idleStateHandler", new {@link IdleStateHandler}(60, 30, 0));
* channel.pipeline().addLast("myHandler", new MyHandler());
* }
* }
*
* // Handler should handle the {@link IdleStateEvent} triggered by {@link IdleStateHandler}.
* public class MyHandler extends {@link ChannelDuplexHandler} {
* {@code @Override}
* public void userEventTriggered({@link ChannelHandlerContext} ctx, {@link Object} evt) throws {@link Exception} {
* if (evt instanceof {@link IdleStateEvent}) {
* {@link IdleStateEvent} e = ({@link IdleStateEvent}) evt;
* if (e.state() == {@link IdleState}.READER_IDLE) {
* ctx.close();
* } else if (e.state() == {@link IdleState}.WRITER_IDLE) {
* ctx.writeAndFlush(new PingMessage());
* }
* }
* }
* }
*
* {@link ServerBootstrap} bootstrap = ...;
* ...
* bootstrap.childHandler(new MyChannelInitializer());
* ...
* </pre>
*
* @see ReadTimeoutHandler
* @see WriteTimeoutHandler
*/
public class IdleStateHandler extends ChannelDuplexHandler {
private static final long MIN_TIMEOUT_NANOS = TimeUnit.MILLISECONDS.toNanos(1);
// Not create a new ChannelFutureListener per write operation to reduce GC pressure.
private final ChannelFutureListener writeListener = new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
lastWriteTime = ticksInNanos();
firstWriterIdleEvent = firstAllIdleEvent = true;
}
};
private final boolean observeOutput;
private final long readerIdleTimeNanos;
private final long writerIdleTimeNanos;
private final long allIdleTimeNanos;
private ScheduledFuture<?> readerIdleTimeout;
private long lastReadTime;
private boolean firstReaderIdleEvent = true;
private ScheduledFuture<?> writerIdleTimeout;
private long lastWriteTime;
private boolean firstWriterIdleEvent = true;
private ScheduledFuture<?> allIdleTimeout;
private boolean firstAllIdleEvent = true;
private byte state; // 0 - none, 1 - initialized, 2 - destroyed
private boolean reading;
private long lastChangeCheckTimeStamp;
private int lastMessageHashCode;
private long lastPendingWriteBytes;
/**
* Creates a new instance firing {@link IdleStateEvent}s.
*
* @param readerIdleTimeSeconds
* an {@link IdleStateEvent} whose state is {@link IdleState#READER_IDLE}
* will be triggered when no read was performed for the specified
* period of time. Specify {@code 0} to disable.
* @param writerIdleTimeSeconds
* an {@link IdleStateEvent} whose state is {@link IdleState#WRITER_IDLE}
* will be triggered when no write was performed for the specified
* period of time. Specify {@code 0} to disable.
* @param allIdleTimeSeconds
* an {@link IdleStateEvent} whose state is {@link IdleState#ALL_IDLE}
* will be triggered when neither read nor write was performed for
* the specified period of time. Specify {@code 0} to disable.
*/
public IdleStateHandler(
int readerIdleTimeSeconds,
int writerIdleTimeSeconds,
int allIdleTimeSeconds) {
this(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds,
TimeUnit.SECONDS);
}
/**
* @see #IdleStateHandler(boolean, long, long, long, TimeUnit)
*/
public IdleStateHandler(
long readerIdleTime, long writerIdleTime, long allIdleTime,
TimeUnit unit) {
this(false, readerIdleTime, writerIdleTime, allIdleTime, unit);
}
/**
* Creates a new instance firing {@link IdleStateEvent}s.
*
* @param observeOutput
* whether or not the consumption of {@code bytes} should be taken into
* consideration when assessing write idleness. The default is {@code false}.
* @param readerIdleTime
* an {@link IdleStateEvent} whose state is {@link IdleState#READER_IDLE}
* will be triggered when no read was performed for the specified
* period of time. Specify {@code 0} to disable.
* @param writerIdleTime
* an {@link IdleStateEvent} whose state is {@link IdleState#WRITER_IDLE}
* will be triggered when no write was performed for the specified
* period of time. Specify {@code 0} to disable.
* @param allIdleTime
* an {@link IdleStateEvent} whose state is {@link IdleState#ALL_IDLE}
* will be triggered when neither read nor write was performed for
* the specified period of time. Specify {@code 0} to disable.
* @param unit
* the {@link TimeUnit} of {@code readerIdleTime},
* {@code writeIdleTime}, and {@code allIdleTime}
*/
public IdleStateHandler(boolean observeOutput,
long readerIdleTime, long writerIdleTime, long allIdleTime,
TimeUnit unit) {
if (unit == null) {
throw new NullPointerException("unit");
}
this.observeOutput = observeOutput;
if (readerIdleTime <= 0) {
readerIdleTimeNanos = 0;
} else {
readerIdleTimeNanos = Math.max(unit.toNanos(readerIdleTime), MIN_TIMEOUT_NANOS);
}
if (writerIdleTime <= 0) {
writerIdleTimeNanos = 0;
} else {
writerIdleTimeNanos = Math.max(unit.toNanos(writerIdleTime), MIN_TIMEOUT_NANOS);
}
if (allIdleTime <= 0) {
allIdleTimeNanos = 0;
} else {
allIdleTimeNanos = Math.max(unit.toNanos(allIdleTime), MIN_TIMEOUT_NANOS);
}
}
/**
* Return the readerIdleTime that was given when instance this class in milliseconds.
*
*/
public long getReaderIdleTimeInMillis() {
return TimeUnit.NANOSECONDS.toMillis(readerIdleTimeNanos);
}
/**
* Return the writerIdleTime that was given when instance this class in milliseconds.
*
*/
public long getWriterIdleTimeInMillis() {
return TimeUnit.NANOSECONDS.toMillis(writerIdleTimeNanos);
}
/**
* Return the allIdleTime that was given when instance this class in milliseconds.
*
*/
public long getAllIdleTimeInMillis() {
return TimeUnit.NANOSECONDS.toMillis(allIdleTimeNanos);
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
if (ctx.channel().isActive() && ctx.channel().isRegistered()) {
// channelActive() event has been fired already, which means this.channelActive() will
// not be invoked. We have to initialize here instead.
initialize(ctx);
} else {
// channelActive() event has not been fired yet. this.channelActive() will be invoked
// and initialization will occur there.
}
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
destroy();
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
// Initialize early if channel is active already.
if (ctx.channel().isActive()) {
initialize(ctx);
}
super.channelRegistered(ctx);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// This method will be invoked only if this handler was added
// before channelActive() event is fired. If a user adds this handler
// after the channelActive() event, initialize() will be called by beforeAdd().
initialize(ctx);
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
destroy();
super.channelInactive(ctx);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (readerIdleTimeNanos > 0 || allIdleTimeNanos > 0) {
reading = true;
firstReaderIdleEvent = firstAllIdleEvent = true;
}
ctx.fireChannelRead(msg);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
if ((readerIdleTimeNanos > 0 || allIdleTimeNanos > 0) && reading) {
lastReadTime = ticksInNanos();
reading = false;
}
ctx.fireChannelReadComplete();
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
// Allow writing with void promise if handler is only configured for read timeout events.
if (writerIdleTimeNanos > 0 || allIdleTimeNanos > 0) {
ctx.write(msg, promise.unvoid()).addListener(writeListener);
} else {
ctx.write(msg, promise);
}
}
private void initialize(ChannelHandlerContext ctx) {
// Avoid the case where destroy() is called before scheduling timeouts.
// See: https://github.com/netty/netty/issues/143
switch (state) {
case 1:
case 2:
return;
}
state = 1;
initOutputChanged(ctx);
lastReadTime = lastWriteTime = ticksInNanos();
if (readerIdleTimeNanos > 0) {
readerIdleTimeout = schedule(ctx, new ReaderIdleTimeoutTask(ctx),
readerIdleTimeNanos, TimeUnit.NANOSECONDS);
}
if (writerIdleTimeNanos > 0) {
writerIdleTimeout = schedule(ctx, new WriterIdleTimeoutTask(ctx),
writerIdleTimeNanos, TimeUnit.NANOSECONDS);
}
if (allIdleTimeNanos > 0) {
allIdleTimeout = schedule(ctx, new AllIdleTimeoutTask(ctx),
allIdleTimeNanos, TimeUnit.NANOSECONDS);
}
}
/**
* This method is visible for testing!
*/
long ticksInNanos() {
return System.nanoTime();
}
/**
* This method is visible for testing!
*/
ScheduledFuture<?> schedule(ChannelHandlerContext ctx, Runnable task, long delay, TimeUnit unit) {
return ctx.executor().schedule(task, delay, unit);
}
private void destroy() {
state = 2;
if (readerIdleTimeout != null) {
readerIdleTimeout.cancel(false);
readerIdleTimeout = null;
}
if (writerIdleTimeout != null) {
writerIdleTimeout.cancel(false);
writerIdleTimeout = null;
}
if (allIdleTimeout != null) {
allIdleTimeout.cancel(false);
allIdleTimeout = null;
}
}
/**
* Is called when an {@link IdleStateEvent} should be fired. This implementation calls
* {@link ChannelHandlerContext#fireUserEventTriggered(Object)}.
*/
protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
ctx.fireUserEventTriggered(evt);
}
/**
* Returns a {@link IdleStateEvent}.
*/
protected IdleStateEvent newIdleStateEvent(IdleState state, boolean first) {
switch (state) {
case ALL_IDLE:
return first ? IdleStateEvent.FIRST_ALL_IDLE_STATE_EVENT : IdleStateEvent.ALL_IDLE_STATE_EVENT;
case READER_IDLE:
return first ? IdleStateEvent.FIRST_READER_IDLE_STATE_EVENT : IdleStateEvent.READER_IDLE_STATE_EVENT;
case WRITER_IDLE:
return first ? IdleStateEvent.FIRST_WRITER_IDLE_STATE_EVENT : IdleStateEvent.WRITER_IDLE_STATE_EVENT;
default:
throw new IllegalArgumentException("Unhandled: state=" + state + ", first=" + first);
}
}
/**
* @see #hasOutputChanged(ChannelHandlerContext, boolean)
*/
private void initOutputChanged(ChannelHandlerContext ctx) {
if (observeOutput) {
Channel channel = ctx.channel();
Unsafe unsafe = channel.unsafe();
ChannelOutboundBuffer buf = unsafe.outboundBuffer();
if (buf != null) {
lastMessageHashCode = System.identityHashCode(buf.current());
lastPendingWriteBytes = buf.totalPendingWriteBytes();
}
}
}
/**
* Returns {@code true} if and only if the {@link IdleStateHandler} was constructed
* with {@link #observeOutput} enabled and there has been an observed change in the
* {@link ChannelOutboundBuffer} between two consecutive calls of this method.
*
* https://github.com/netty/netty/issues/6150
*/
private boolean hasOutputChanged(ChannelHandlerContext ctx, boolean first) {
if (observeOutput) {
// We can take this shortcut if the ChannelPromises that got passed into write()
// appear to complete. It indicates "change" on message level and we simply assume
// that there's change happening on byte level. If the user doesn't observe channel
// writability events then they'll eventually OOME and there's clearly a different
// problem and idleness is least of their concerns.
if (lastChangeCheckTimeStamp != lastWriteTime) {
lastChangeCheckTimeStamp = lastWriteTime;
// But this applies only if it's the non-first call.
if (!first) {
return true;
}
}
Channel channel = ctx.channel();
Unsafe unsafe = channel.unsafe();
ChannelOutboundBuffer buf = unsafe.outboundBuffer();
if (buf != null) {
int messageHashCode = System.identityHashCode(buf.current());
long pendingWriteBytes = buf.totalPendingWriteBytes();
if (messageHashCode != lastMessageHashCode || pendingWriteBytes != lastPendingWriteBytes) {
lastMessageHashCode = messageHashCode;
lastPendingWriteBytes = pendingWriteBytes;
if (!first) {
return true;
}
}
}
}
return false;
}
private abstract static class AbstractIdleTask implements Runnable {
private final ChannelHandlerContext ctx;
AbstractIdleTask(ChannelHandlerContext ctx) {
this.ctx = ctx;
}
@Override
public void run() {
if (!ctx.channel().isOpen()) {
return;
}
run(ctx);
}
protected abstract void run(ChannelHandlerContext ctx);
}
private final class ReaderIdleTimeoutTask extends AbstractIdleTask {
ReaderIdleTimeoutTask(ChannelHandlerContext ctx) {
super(ctx);
}
@Override
protected void run(ChannelHandlerContext ctx) {
long nextDelay = readerIdleTimeNanos;
if (!reading) {
nextDelay -= ticksInNanos() - lastReadTime;
}
if (nextDelay <= 0) {
// Reader is idle - set a new timeout and notify the callback.
readerIdleTimeout = schedule(ctx, this, readerIdleTimeNanos, TimeUnit.NANOSECONDS);
boolean first = firstReaderIdleEvent;
firstReaderIdleEvent = false;
try {
IdleStateEvent event = newIdleStateEvent(IdleState.READER_IDLE, first);
channelIdle(ctx, event);
} catch (Throwable t) {
ctx.fireExceptionCaught(t);
}
} else {
// Read occurred before the timeout - set a new timeout with shorter delay.
readerIdleTimeout = schedule(ctx, this, nextDelay, TimeUnit.NANOSECONDS);
}
}
}
private final class WriterIdleTimeoutTask extends AbstractIdleTask {
WriterIdleTimeoutTask(ChannelHandlerContext ctx) {
super(ctx);
}
@Override
protected void run(ChannelHandlerContext ctx) {
long lastWriteTime = IdleStateHandler.this.lastWriteTime;
long nextDelay = writerIdleTimeNanos - (ticksInNanos() - lastWriteTime);
if (nextDelay <= 0) {
// Writer is idle - set a new timeout and notify the callback.
writerIdleTimeout = schedule(ctx, this, writerIdleTimeNanos, TimeUnit.NANOSECONDS);
boolean first = firstWriterIdleEvent;
firstWriterIdleEvent = false;
try {
if (hasOutputChanged(ctx, first)) {
return;
}
IdleStateEvent event = newIdleStateEvent(IdleState.WRITER_IDLE, first);
channelIdle(ctx, event);
} catch (Throwable t) {
ctx.fireExceptionCaught(t);
}
} else {
// Write occurred before the timeout - set a new timeout with shorter delay.
writerIdleTimeout = schedule(ctx, this, nextDelay, TimeUnit.NANOSECONDS);
}
}
}
private final class AllIdleTimeoutTask extends AbstractIdleTask {
AllIdleTimeoutTask(ChannelHandlerContext ctx) {
super(ctx);
}
@Override
protected void run(ChannelHandlerContext ctx) {
long nextDelay = allIdleTimeNanos;
if (!reading) {
nextDelay -= ticksInNanos() - Math.max(lastReadTime, lastWriteTime);
}
if (nextDelay <= 0) {
// Both reader and writer are idle - set a new timeout and
// notify the callback.
allIdleTimeout = schedule(ctx, this, allIdleTimeNanos, TimeUnit.NANOSECONDS);
boolean first = firstAllIdleEvent;
firstAllIdleEvent = false;
try {
if (hasOutputChanged(ctx, first)) {
return;
}
IdleStateEvent event = newIdleStateEvent(IdleState.ALL_IDLE, first);
channelIdle(ctx, event);
} catch (Throwable t) {
ctx.fireExceptionCaught(t);
}
} else {
// Either read or write occurred before the timeout - set a new
// timeout with shorter delay.
allIdleTimeout = schedule(ctx, this, nextDelay, TimeUnit.NANOSECONDS);
}
}
}
}
| handler/src/main/java/io/netty/handler/timeout/IdleStateHandler.java | /*
* Copyright 2012 The Netty Project
*
* The Netty 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 io.netty.handler.timeout;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.Channel.Unsafe;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOutboundBuffer;
import io.netty.channel.ChannelPromise;
import io.netty.util.concurrent.EventExecutor;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* Triggers an {@link IdleStateEvent} when a {@link Channel} has not performed
* read, write, or both operation for a while.
*
* <h3>Supported idle states</h3>
* <table border="1">
* <tr>
* <th>Property</th><th>Meaning</th>
* </tr>
* <tr>
* <td>{@code readerIdleTime}</td>
* <td>an {@link IdleStateEvent} whose state is {@link IdleState#READER_IDLE}
* will be triggered when no read was performed for the specified period of
* time. Specify {@code 0} to disable.</td>
* </tr>
* <tr>
* <td>{@code writerIdleTime}</td>
* <td>an {@link IdleStateEvent} whose state is {@link IdleState#WRITER_IDLE}
* will be triggered when no write was performed for the specified period of
* time. Specify {@code 0} to disable.</td>
* </tr>
* <tr>
* <td>{@code allIdleTime}</td>
* <td>an {@link IdleStateEvent} whose state is {@link IdleState#ALL_IDLE}
* will be triggered when neither read nor write was performed for the
* specified period of time. Specify {@code 0} to disable.</td>
* </tr>
* </table>
*
* <pre>
* // An example that sends a ping message when there is no outbound traffic
* // for 30 seconds. The connection is closed when there is no inbound traffic
* // for 60 seconds.
*
* public class MyChannelInitializer extends {@link ChannelInitializer}<{@link Channel}> {
* {@code @Override}
* public void initChannel({@link Channel} channel) {
* channel.pipeline().addLast("idleStateHandler", new {@link IdleStateHandler}(60, 30, 0));
* channel.pipeline().addLast("myHandler", new MyHandler());
* }
* }
*
* // Handler should handle the {@link IdleStateEvent} triggered by {@link IdleStateHandler}.
* public class MyHandler extends {@link ChannelDuplexHandler} {
* {@code @Override}
* public void userEventTriggered({@link ChannelHandlerContext} ctx, {@link Object} evt) throws {@link Exception} {
* if (evt instanceof {@link IdleStateEvent}) {
* {@link IdleStateEvent} e = ({@link IdleStateEvent}) evt;
* if (e.state() == {@link IdleState}.READER_IDLE) {
* ctx.close();
* } else if (e.state() == {@link IdleState}.WRITER_IDLE) {
* ctx.writeAndFlush(new PingMessage());
* }
* }
* }
* }
*
* {@link ServerBootstrap} bootstrap = ...;
* ...
* bootstrap.childHandler(new MyChannelInitializer());
* ...
* </pre>
*
* @see ReadTimeoutHandler
* @see WriteTimeoutHandler
*/
public class IdleStateHandler extends ChannelDuplexHandler {
private static final long MIN_TIMEOUT_NANOS = TimeUnit.MILLISECONDS.toNanos(1);
// Not create a new ChannelFutureListener per write operation to reduce GC pressure.
private final ChannelFutureListener writeListener = new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
lastWriteTime = ticksInNanos();
firstWriterIdleEvent = firstAllIdleEvent = true;
}
};
private final boolean observeOutput;
private final long readerIdleTimeNanos;
private final long writerIdleTimeNanos;
private final long allIdleTimeNanos;
private ScheduledFuture<?> readerIdleTimeout;
private long lastReadTime;
private boolean firstReaderIdleEvent = true;
private ScheduledFuture<?> writerIdleTimeout;
private long lastWriteTime;
private boolean firstWriterIdleEvent = true;
private ScheduledFuture<?> allIdleTimeout;
private boolean firstAllIdleEvent = true;
private byte state; // 0 - none, 1 - initialized, 2 - destroyed
private boolean reading;
private long lastChangeCheckTimeStamp;
private int lastMessageHashCode;
private long lastPendingWriteBytes;
/**
* Creates a new instance firing {@link IdleStateEvent}s.
*
* @param readerIdleTimeSeconds
* an {@link IdleStateEvent} whose state is {@link IdleState#READER_IDLE}
* will be triggered when no read was performed for the specified
* period of time. Specify {@code 0} to disable.
* @param writerIdleTimeSeconds
* an {@link IdleStateEvent} whose state is {@link IdleState#WRITER_IDLE}
* will be triggered when no write was performed for the specified
* period of time. Specify {@code 0} to disable.
* @param allIdleTimeSeconds
* an {@link IdleStateEvent} whose state is {@link IdleState#ALL_IDLE}
* will be triggered when neither read nor write was performed for
* the specified period of time. Specify {@code 0} to disable.
*/
public IdleStateHandler(
int readerIdleTimeSeconds,
int writerIdleTimeSeconds,
int allIdleTimeSeconds) {
this(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds,
TimeUnit.SECONDS);
}
/**
* @see #IdleStateHandler(boolean, long, long, long, TimeUnit)
*/
public IdleStateHandler(
long readerIdleTime, long writerIdleTime, long allIdleTime,
TimeUnit unit) {
this(false, readerIdleTime, writerIdleTime, allIdleTime, unit);
}
/**
* Creates a new instance firing {@link IdleStateEvent}s.
*
* @param observeOutput
* whether or not the consumption of {@code bytes} should be taken into
* consideration when assessing write idleness. The default is {@code false}.
* @param readerIdleTime
* an {@link IdleStateEvent} whose state is {@link IdleState#READER_IDLE}
* will be triggered when no read was performed for the specified
* period of time. Specify {@code 0} to disable.
* @param writerIdleTime
* an {@link IdleStateEvent} whose state is {@link IdleState#WRITER_IDLE}
* will be triggered when no write was performed for the specified
* period of time. Specify {@code 0} to disable.
* @param allIdleTime
* an {@link IdleStateEvent} whose state is {@link IdleState#ALL_IDLE}
* will be triggered when neither read nor write was performed for
* the specified period of time. Specify {@code 0} to disable.
* @param unit
* the {@link TimeUnit} of {@code readerIdleTime},
* {@code writeIdleTime}, and {@code allIdleTime}
*/
public IdleStateHandler(boolean observeOutput,
long readerIdleTime, long writerIdleTime, long allIdleTime,
TimeUnit unit) {
if (unit == null) {
throw new NullPointerException("unit");
}
this.observeOutput = observeOutput;
if (readerIdleTime <= 0) {
readerIdleTimeNanos = 0;
} else {
readerIdleTimeNanos = Math.max(unit.toNanos(readerIdleTime), MIN_TIMEOUT_NANOS);
}
if (writerIdleTime <= 0) {
writerIdleTimeNanos = 0;
} else {
writerIdleTimeNanos = Math.max(unit.toNanos(writerIdleTime), MIN_TIMEOUT_NANOS);
}
if (allIdleTime <= 0) {
allIdleTimeNanos = 0;
} else {
allIdleTimeNanos = Math.max(unit.toNanos(allIdleTime), MIN_TIMEOUT_NANOS);
}
}
/**
* Return the readerIdleTime that was given when instance this class in milliseconds.
*
*/
public long getReaderIdleTimeInMillis() {
return TimeUnit.NANOSECONDS.toMillis(readerIdleTimeNanos);
}
/**
* Return the writerIdleTime that was given when instance this class in milliseconds.
*
*/
public long getWriterIdleTimeInMillis() {
return TimeUnit.NANOSECONDS.toMillis(writerIdleTimeNanos);
}
/**
* Return the allIdleTime that was given when instance this class in milliseconds.
*
*/
public long getAllIdleTimeInMillis() {
return TimeUnit.NANOSECONDS.toMillis(allIdleTimeNanos);
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
if (ctx.channel().isActive() && ctx.channel().isRegistered()) {
// channelActive() event has been fired already, which means this.channelActive() will
// not be invoked. We have to initialize here instead.
initialize(ctx);
} else {
// channelActive() event has not been fired yet. this.channelActive() will be invoked
// and initialization will occur there.
}
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
destroy();
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
// Initialize early if channel is active already.
if (ctx.channel().isActive()) {
initialize(ctx);
}
super.channelRegistered(ctx);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// This method will be invoked only if this handler was added
// before channelActive() event is fired. If a user adds this handler
// after the channelActive() event, initialize() will be called by beforeAdd().
initialize(ctx);
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
destroy();
super.channelInactive(ctx);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (readerIdleTimeNanos > 0 || allIdleTimeNanos > 0) {
reading = true;
firstReaderIdleEvent = firstAllIdleEvent = true;
}
ctx.fireChannelRead(msg);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
if ((readerIdleTimeNanos > 0 || allIdleTimeNanos > 0) && reading) {
lastReadTime = ticksInNanos();
reading = false;
}
ctx.fireChannelReadComplete();
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
// Allow writing with void promise if handler is only configured for read timeout events.
if (writerIdleTimeNanos > 0 || allIdleTimeNanos > 0) {
ChannelPromise unvoid = promise.unvoid();
unvoid.addListener(writeListener);
ctx.write(msg, unvoid);
} else {
ctx.write(msg, promise);
}
}
private void initialize(ChannelHandlerContext ctx) {
// Avoid the case where destroy() is called before scheduling timeouts.
// See: https://github.com/netty/netty/issues/143
switch (state) {
case 1:
case 2:
return;
}
state = 1;
initOutputChanged(ctx);
lastReadTime = lastWriteTime = ticksInNanos();
if (readerIdleTimeNanos > 0) {
readerIdleTimeout = schedule(ctx, new ReaderIdleTimeoutTask(ctx),
readerIdleTimeNanos, TimeUnit.NANOSECONDS);
}
if (writerIdleTimeNanos > 0) {
writerIdleTimeout = schedule(ctx, new WriterIdleTimeoutTask(ctx),
writerIdleTimeNanos, TimeUnit.NANOSECONDS);
}
if (allIdleTimeNanos > 0) {
allIdleTimeout = schedule(ctx, new AllIdleTimeoutTask(ctx),
allIdleTimeNanos, TimeUnit.NANOSECONDS);
}
}
/**
* This method is visible for testing!
*/
long ticksInNanos() {
return System.nanoTime();
}
/**
* This method is visible for testing!
*/
ScheduledFuture<?> schedule(ChannelHandlerContext ctx, Runnable task, long delay, TimeUnit unit) {
return ctx.executor().schedule(task, delay, unit);
}
private void destroy() {
state = 2;
if (readerIdleTimeout != null) {
readerIdleTimeout.cancel(false);
readerIdleTimeout = null;
}
if (writerIdleTimeout != null) {
writerIdleTimeout.cancel(false);
writerIdleTimeout = null;
}
if (allIdleTimeout != null) {
allIdleTimeout.cancel(false);
allIdleTimeout = null;
}
}
/**
* Is called when an {@link IdleStateEvent} should be fired. This implementation calls
* {@link ChannelHandlerContext#fireUserEventTriggered(Object)}.
*/
protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
ctx.fireUserEventTriggered(evt);
}
/**
* Returns a {@link IdleStateEvent}.
*/
protected IdleStateEvent newIdleStateEvent(IdleState state, boolean first) {
switch (state) {
case ALL_IDLE:
return first ? IdleStateEvent.FIRST_ALL_IDLE_STATE_EVENT : IdleStateEvent.ALL_IDLE_STATE_EVENT;
case READER_IDLE:
return first ? IdleStateEvent.FIRST_READER_IDLE_STATE_EVENT : IdleStateEvent.READER_IDLE_STATE_EVENT;
case WRITER_IDLE:
return first ? IdleStateEvent.FIRST_WRITER_IDLE_STATE_EVENT : IdleStateEvent.WRITER_IDLE_STATE_EVENT;
default:
throw new IllegalArgumentException("Unhandled: state=" + state + ", first=" + first);
}
}
/**
* @see #hasOutputChanged(ChannelHandlerContext, boolean)
*/
private void initOutputChanged(ChannelHandlerContext ctx) {
if (observeOutput) {
Channel channel = ctx.channel();
Unsafe unsafe = channel.unsafe();
ChannelOutboundBuffer buf = unsafe.outboundBuffer();
if (buf != null) {
lastMessageHashCode = System.identityHashCode(buf.current());
lastPendingWriteBytes = buf.totalPendingWriteBytes();
}
}
}
/**
* Returns {@code true} if and only if the {@link IdleStateHandler} was constructed
* with {@link #observeOutput} enabled and there has been an observed change in the
* {@link ChannelOutboundBuffer} between two consecutive calls of this method.
*
* https://github.com/netty/netty/issues/6150
*/
private boolean hasOutputChanged(ChannelHandlerContext ctx, boolean first) {
if (observeOutput) {
// We can take this shortcut if the ChannelPromises that got passed into write()
// appear to complete. It indicates "change" on message level and we simply assume
// that there's change happening on byte level. If the user doesn't observe channel
// writability events then they'll eventually OOME and there's clearly a different
// problem and idleness is least of their concerns.
if (lastChangeCheckTimeStamp != lastWriteTime) {
lastChangeCheckTimeStamp = lastWriteTime;
// But this applies only if it's the non-first call.
if (!first) {
return true;
}
}
Channel channel = ctx.channel();
Unsafe unsafe = channel.unsafe();
ChannelOutboundBuffer buf = unsafe.outboundBuffer();
if (buf != null) {
int messageHashCode = System.identityHashCode(buf.current());
long pendingWriteBytes = buf.totalPendingWriteBytes();
if (messageHashCode != lastMessageHashCode || pendingWriteBytes != lastPendingWriteBytes) {
lastMessageHashCode = messageHashCode;
lastPendingWriteBytes = pendingWriteBytes;
if (!first) {
return true;
}
}
}
}
return false;
}
private abstract static class AbstractIdleTask implements Runnable {
private final ChannelHandlerContext ctx;
AbstractIdleTask(ChannelHandlerContext ctx) {
this.ctx = ctx;
}
@Override
public void run() {
if (!ctx.channel().isOpen()) {
return;
}
run(ctx);
}
protected abstract void run(ChannelHandlerContext ctx);
}
private final class ReaderIdleTimeoutTask extends AbstractIdleTask {
ReaderIdleTimeoutTask(ChannelHandlerContext ctx) {
super(ctx);
}
@Override
protected void run(ChannelHandlerContext ctx) {
long nextDelay = readerIdleTimeNanos;
if (!reading) {
nextDelay -= ticksInNanos() - lastReadTime;
}
if (nextDelay <= 0) {
// Reader is idle - set a new timeout and notify the callback.
readerIdleTimeout = schedule(ctx, this, readerIdleTimeNanos, TimeUnit.NANOSECONDS);
boolean first = firstReaderIdleEvent;
firstReaderIdleEvent = false;
try {
IdleStateEvent event = newIdleStateEvent(IdleState.READER_IDLE, first);
channelIdle(ctx, event);
} catch (Throwable t) {
ctx.fireExceptionCaught(t);
}
} else {
// Read occurred before the timeout - set a new timeout with shorter delay.
readerIdleTimeout = schedule(ctx, this, nextDelay, TimeUnit.NANOSECONDS);
}
}
}
private final class WriterIdleTimeoutTask extends AbstractIdleTask {
WriterIdleTimeoutTask(ChannelHandlerContext ctx) {
super(ctx);
}
@Override
protected void run(ChannelHandlerContext ctx) {
long lastWriteTime = IdleStateHandler.this.lastWriteTime;
long nextDelay = writerIdleTimeNanos - (ticksInNanos() - lastWriteTime);
if (nextDelay <= 0) {
// Writer is idle - set a new timeout and notify the callback.
writerIdleTimeout = schedule(ctx, this, writerIdleTimeNanos, TimeUnit.NANOSECONDS);
boolean first = firstWriterIdleEvent;
firstWriterIdleEvent = false;
try {
if (hasOutputChanged(ctx, first)) {
return;
}
IdleStateEvent event = newIdleStateEvent(IdleState.WRITER_IDLE, first);
channelIdle(ctx, event);
} catch (Throwable t) {
ctx.fireExceptionCaught(t);
}
} else {
// Write occurred before the timeout - set a new timeout with shorter delay.
writerIdleTimeout = schedule(ctx, this, nextDelay, TimeUnit.NANOSECONDS);
}
}
}
private final class AllIdleTimeoutTask extends AbstractIdleTask {
AllIdleTimeoutTask(ChannelHandlerContext ctx) {
super(ctx);
}
@Override
protected void run(ChannelHandlerContext ctx) {
long nextDelay = allIdleTimeNanos;
if (!reading) {
nextDelay -= ticksInNanos() - Math.max(lastReadTime, lastWriteTime);
}
if (nextDelay <= 0) {
// Both reader and writer are idle - set a new timeout and
// notify the callback.
allIdleTimeout = schedule(ctx, this, allIdleTimeNanos, TimeUnit.NANOSECONDS);
boolean first = firstAllIdleEvent;
firstAllIdleEvent = false;
try {
if (hasOutputChanged(ctx, first)) {
return;
}
IdleStateEvent event = newIdleStateEvent(IdleState.ALL_IDLE, first);
channelIdle(ctx, event);
} catch (Throwable t) {
ctx.fireExceptionCaught(t);
}
} else {
// Either read or write occurred before the timeout - set a new
// timeout with shorter delay.
allIdleTimeout = schedule(ctx, this, nextDelay, TimeUnit.NANOSECONDS);
}
}
}
}
| Add listener to returned Future rather than passed in Promise
Motivation
It's cleaner to add listeners to returned Futures rather than provided Promises because the latter can have strange side effects in terms of listeners firing and called methods returning. Adding listeners preemtively may yield also to more OPS than necessary when there's an Exception in the to be called method.
Modifications
Add listener to returned ChannelFuture rather than given ChannelPromise
Result
Cleaner completion and exception handling
| handler/src/main/java/io/netty/handler/timeout/IdleStateHandler.java | Add listener to returned Future rather than passed in Promise | <ide><path>andler/src/main/java/io/netty/handler/timeout/IdleStateHandler.java
<ide> import io.netty.channel.ChannelInitializer;
<ide> import io.netty.channel.ChannelOutboundBuffer;
<ide> import io.netty.channel.ChannelPromise;
<del>import io.netty.util.concurrent.EventExecutor;
<ide>
<ide> import java.util.concurrent.ScheduledFuture;
<ide> import java.util.concurrent.TimeUnit;
<ide> public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
<ide> // Allow writing with void promise if handler is only configured for read timeout events.
<ide> if (writerIdleTimeNanos > 0 || allIdleTimeNanos > 0) {
<del> ChannelPromise unvoid = promise.unvoid();
<del> unvoid.addListener(writeListener);
<del> ctx.write(msg, unvoid);
<add> ctx.write(msg, promise.unvoid()).addListener(writeListener);
<ide> } else {
<ide> ctx.write(msg, promise);
<ide> } |
|
JavaScript | mit | c9774cb33b9c3e262acd88db50caff6030681a29 | 0 | mihailgaberov/es6-bingo-game,mihailgaberov/es6-bingo-game | /**
* Created by Mihail on 8/15/2016.
*/
'use strict';
import App from '../src/app';
import { expect, assert } from 'chai';
import sinon from 'sinon';
describe('Bingo App', () => {
let appBingo = new App();
it('Should set the url for loading the configs', () => {
expect(appBingo.confUrl).to.not.be.undefined;
expect(appBingo.confUrl).to.be.a('string');
});
it('Should set the title of the application', () => {
expect(appBingo.confUrl).to.be.a('string');
expect(appBingo.title).to.equal('Bingo Bigul');
});
it("Should call the callback when get the configs", function () {
let callback = sinon.spy();
let proxy = appBingo.loadConfigs(callback);
proxy();
assert(callback.called);
});
it('Should initialize the CardGenerator to start the app', () => {
expect(appBingo.hasOwnProperty(appBingo.cardGen)).not.to.be.undefined;
});
it('Should initialize the CardDrawer to start the app', () => {
expect(appBingo.hasOwnProperty(appBingo.CardDrawer)).not.to.be.undefined;
});
}); | test/app.spec.js | /**
* Created by Mihail on 8/15/2016.
*/
'use strict';
import App from '../src/app';
import { expect, assert } from 'chai';
import sinon from 'sinon';
describe('Bingo App', () => {
let appBingo = new App();
it('Should set the url for loading the configs', () => {
expect(appBingo.confUrl).to.not.be.undefined;
expect(appBingo.confUrl).to.be.a('string');
});
it('Should set the title of the application', () => {
expect(appBingo.confUrl).to.be.a('string');
expect(appBingo.title).to.equal('Bingo game');
});
it("Should call the callback when get the configs", function () {
let callback = sinon.spy();
let proxy = appBingo.loadConfigs(callback);
proxy();
assert(callback.called);
});
it('Should initialize the CardGenerator to start the app', () => {
expect(appBingo.hasOwnProperty(appBingo.cardGen)).not.to.be.undefined;
});
it('Should initialize the CardDrawer to start the app', () => {
expect(appBingo.hasOwnProperty(appBingo.CardDrawer)).not.to.be.undefined;
});
}); | Fixed unit test for the app title.
| test/app.spec.js | Fixed unit test for the app title. | <ide><path>est/app.spec.js
<ide>
<ide> it('Should set the title of the application', () => {
<ide> expect(appBingo.confUrl).to.be.a('string');
<del> expect(appBingo.title).to.equal('Bingo game');
<add> expect(appBingo.title).to.equal('Bingo Bigul');
<ide> });
<ide>
<ide> it("Should call the callback when get the configs", function () { |
|
Java | apache-2.0 | e0b25205dbb612737470fcab7389b718fc1004d6 | 0 | trifork/erjang,trifork/erjang,csae1152/erjang,trifork/erjang,trifork/erjang,trifork/erjang,csae1152/erjang,csae1152/erjang,trifork/erjang,csae1152/erjang,csae1152/erjang,trifork/erjang | /**
* This file is part of Erjang - A JVM-based Erlang VM
*
* Copyright (c) 2009 by Trifork
*
* 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 erjang.beam;
import static erjang.beam.CodeAtoms.ERLANG_ATOM;
import static erjang.beam.CodeAtoms.FALSE_ATOM;
import static erjang.beam.CodeAtoms.TRUE_ATOM;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import kilim.Pausable;
import kilim.analysis.ClassInfo;
import kilim.analysis.ClassWeaver;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.Method;
import com.trifork.clj_ds.IPersistentCollection;
import erjang.EAtom;
import erjang.EBinMatchState;
import erjang.EBinary;
import erjang.EBitString;
import erjang.EBitStringBuilder;
import erjang.ECons;
import erjang.EDouble;
import erjang.EFun;
import erjang.EInteger;
import erjang.EBig;
import erjang.EInternalPID;
import erjang.EList;
import erjang.EModuleManager;
import erjang.ENil;
import erjang.ENumber;
import erjang.EObject;
import erjang.EOutputStream;
import erjang.EPID;
import erjang.EPort;
import erjang.EProc;
import erjang.ERT;
import erjang.ERef;
import erjang.ESeq;
import erjang.ESmall;
import erjang.EString;
import erjang.ETuple;
import erjang.ETuple2;
import erjang.ErlangException;
import erjang.Export;
import erjang.FunID;
import erjang.Import;
import erjang.LocalFunID;
import erjang.Module;
import erjang.beam.Arg.Kind;
import erjang.beam.ModuleAnalyzer.FunInfo;
import erjang.beam.repr.ExtFun;
import erjang.beam.repr.Insn;
import erjang.m.erlang.ErlBif;
/**
*
*/
public class CompilerVisitor implements ModuleVisitor, Opcodes {
public static boolean PARANOIA_MODE = false;
// a select ins with up to this many cases that are all
// atom values is just encoded as an if-then-else-etc.
public static final int ATOM_SELECT_IF_ELSE_LIMIT = 4;
EAtom am_source = EAtom.intern("source");
ECons atts = ERT.NIL;
ECons compile_info = ERT.NIL;
String source = null;
private Set<String> exported = new HashSet<String>();
private final ClassVisitor cv;
private EAtom module_name;
private Type self_type;
private static final EObject ATOM_field_flags = EAtom.intern("field_flags");
private static final EObject ATOM_start = EAtom.intern("start");
static final String[] PAUSABLE_EX = new String[] { Type.getType(
Pausable.class).getInternalName() };
static final Type EBINMATCHSTATE_TYPE = Type.getType(EBinMatchState.class);
static final Type EBINSTRINGBUILDER_TYPE = Type
.getType(EBitStringBuilder.class);
static final Type ERLANG_EXCEPTION_TYPE = Type
.getType(ErlangException.class);
static final Type ERT_TYPE = Type.getType(ERT.class);
static final Type EINTEGER_TYPE = Type.getType(EInteger.class);
static final Type ESTRING_TYPE = Type.getType(EString.class);
static final Type ECOMPILEDMODULE_TYPE = Type.getType(ECompiledModule.class);
/**
*
*/
static final String ECOMPILEDMODULE_NAME = ECOMPILEDMODULE_TYPE.getInternalName();
static final Type ENUMBER_TYPE = Type.getType(ENumber.class);
static final Type EOBJECT_TYPE = Type.getType(EObject.class);
static final String EOBJECT_DESC = EOBJECT_TYPE.getDescriptor();
static final Type EPROC_TYPE = Type.getType(EProc.class);
static final String EPROC_NAME = EPROC_TYPE.getInternalName();
static final String EPROC_DESC = EPROC_TYPE.getDescriptor();
static final Type ESMALL_TYPE = Type.getType(ESmall.class);
static final String ESMALL_NAME = ESMALL_TYPE.getInternalName();
static final Type EEXCEPTION_TYPE = Type.getType(ErlangException.class);
static final String EEXCEPTION_DESC = EEXCEPTION_TYPE.getDescriptor();
/**/
static final String GO_DESC = "(" + EPROC_TYPE.getDescriptor() + ")"
+ EOBJECT_DESC;
static final Type EDOUBLE_TYPE = Type.getType(EDouble.class);
static final Type EBIG_TYPE = Type.getType(EBig.class);
static final Type ENIL_TYPE = Type.getType(ENil.class);
static final Type EATOM_TYPE = Type.getType(EAtom.class);
static final Type ETUPLE_TYPE = Type.getType(ETuple.class);
static final Type EBINARY_TYPE = Type.getType(EBinary.class);
static final Type EBITSTRING_TYPE = Type.getType(EBitString.class);
static final Type EBITSTRINGBUILDER_TYPE = Type
.getType(EBitStringBuilder.class);
static final Type ECONS_TYPE = Type.getType(ECons.class);
static final Type ESEQ_TYPE = Type.getType(ESeq.class);
static final Type ELIST_TYPE = Type.getType(EList.class);
static final Type EFUN_TYPE = Type.getType(EFun.class);
/**
*
*/
static final String EFUN_NAME = EFUN_TYPE.getInternalName();
static final String EOBJECT_NAME = EOBJECT_TYPE.getInternalName();
static final String ETUPLE_NAME = ETUPLE_TYPE.getInternalName();
static final String ERT_NAME = ERT_TYPE.getInternalName();
static final String EDOUBLE_NAME = EDOUBLE_TYPE.getInternalName();
static final String EBIG_NAME = EBIG_TYPE.getInternalName();
static final String EINTEGER_NAME = EINTEGER_TYPE.getInternalName();
static final String ENIL_NAME = ENIL_TYPE.getInternalName();
static final String ESEQ_NAME = ESEQ_TYPE.getInternalName();
static final String ETUPLE_DESC = ETUPLE_TYPE.getDescriptor();
static final String EATOM_DESC = EATOM_TYPE.getDescriptor();
static final String ECONS_DESC = ECONS_TYPE.getDescriptor();
static final String ESEQ_DESC = ESEQ_TYPE.getDescriptor();
/**
*
*/
static final String EFUN_DESCRIPTOR = EFUN_TYPE.getDescriptor();
static final Type EPID_TYPE = Type.getType(EPID.class);
static final Type EPORT_TYPE = Type.getType(EPort.class);
static final Type EMATCHSTATE_TYPE = Type.getType(EBinMatchState.class);
static final Type MODULE_ANN_TYPE = Type.getType(Module.class);
static final Type IMPORT_ANN_TYPE = Type.getType(Import.class);
static final Type EXPORT_ANN_TYPE = Type.getType(Export.class);
private final ClassRepo classRepo;
/**
* @param classRepo
*
*/
public CompilerVisitor(ClassVisitor cv, ClassRepo classRepo) {
this.cv = cv;
this.classRepo = classRepo;
}
/*
* (non-Javadoc)
*
* @see erjang.beam.ModuleVisitor#visitModule(erjang.EAtom)
*/
@Override
public void visitModule(EAtom name) {
this.module_name = name;
this.self_type = Type.getType("L" + getInternalClassName() + ";");
cv.visit(V1_6, ACC_PUBLIC, self_type.getInternalName(), null,
ECOMPILEDMODULE_NAME, null);
add_module_annotation(cv);
}
private void add_module_annotation(ClassVisitor cv) {
AnnotationVisitor av = cv.visitAnnotation(MODULE_ANN_TYPE
.getDescriptor(), true);
av.visit("value", getModuleName());
av.visitEnd();
}
public String getInternalClassName() {
String moduleName = getModuleName();
return Compiler.moduleClassName(moduleName);
}
/**
* @return
*/
private String getModuleName() {
return module_name.getName();
}
Map<EObject, String> constants = new HashMap<EObject, String>();
/*
* (non-Javadoc)
*
* @see erjang.beam.ModuleVisitor#visitAttribute(erjang.EAtom,
* erjang.EObject)
*/
@Override
public void visitAttribute(EAtom att, EObject value) {
atts = atts.cons(ETuple2.make(att, value));
}
@Override
public void visitCompile(EAtom att, EObject value) {
EString string;
if (att == am_source && (string = value.testString()) != null) {
source = string.stringValue();
}
compile_info = compile_info.cons(ETuple2.make(att, value));
}
String source() {
if (source == null) {
return module_name.getName() + ".erl";
} else {
int idx = source.lastIndexOf('/');
if (idx == -1) {
return source;
} else {
return source.substring(idx+1);
}
}
}
/*
* (non-Javadoc)
*
* @see erjang.beam.ModuleVisitor#visitEnd()
*/
@Override
public void visitEnd() {
cv.visitSource(source(), null);
// wow, this is where we generate <clinit>
for (Map.Entry<String, ExtFun> ent : imported.entrySet()) {
String field_name = ent.getKey();
ExtFun f = ent.getValue();
FieldVisitor fv = cv.visitField(ACC_STATIC, ent.getKey(), "L"
+ EFUN_NAME + f.arity + ";", null, null);
EFun.ensure(f.arity);
AnnotationVisitor av = fv.visitAnnotation(IMPORT_ANN_TYPE
.getDescriptor(), true);
av.visit("module", f.mod.getName());
av.visit("fun", f.fun.getName());
av.visit("arity", f.arity);
av.visitEnd();
fv.visitEnd();
}
generate_classinit();
cv.visitEnd();
}
/**
*
*/
private void generate_classinit() {
MethodVisitor mv = cv.visitMethod(ACC_STATIC | ACC_PRIVATE, "<clinit>",
"()V", null, null);
mv.visitCode();
for (Map.Entry<String, String> ent : funs.entrySet()) {
String field = ent.getKey();
String clazz = ent.getValue();
mv.visitTypeInsn(NEW, clazz);
mv.visitInsn(DUP);
mv.visitMethodInsn(INVOKESPECIAL, clazz, "<init>", "()V");
mv.visitFieldInsn(PUTSTATIC, self_type.getInternalName(), field,
"L" + funt.get(field) + ";");
}
for (Map.Entry<EObject, String> ent : constants.entrySet()) {
EObject term = ent.getKey();
term.emit_const(mv);
mv.visitFieldInsn(Opcodes.PUTSTATIC, self_type.getInternalName(),
ent.getValue(), Type.getType(term.getClass())
.getDescriptor());
}
cv.visitField(ACC_STATIC|ACC_PRIVATE,
"attributes", ESEQ_TYPE.getDescriptor(), null, null);
atts.emit_const(mv);
mv.visitFieldInsn(Opcodes.PUTSTATIC, self_type.getInternalName(),
"attributes", ESEQ_TYPE.getDescriptor());
cv.visitField(ACC_STATIC|ACC_PRIVATE,
"compile", ESEQ_TYPE.getDescriptor(), null, null);
compile_info.emit_const(mv);
mv.visitFieldInsn(Opcodes.PUTSTATIC, self_type.getInternalName(),
"compile", ESEQ_TYPE.getDescriptor());
if (this.module_md5 != null) {
cv.visitField(ACC_STATIC, "module_md5", EBINARY_TYPE.getDescriptor(), null, null);
module_md5.emit_const(mv);
mv.visitFieldInsn(PUTSTATIC, self_type.getInternalName(), "module_md5", EBINARY_TYPE.getDescriptor());
}
mv.visitInsn(RETURN);
mv.visitMaxs(200, 10);
mv.visitEnd();
// make the method module_name
mv = cv.visitMethod(ACC_PROTECTED, "module_name",
"()Ljava/lang/String;", null, null);
mv.visitCode();
mv.visitLdcInsn(this.module_name.getName());
mv.visitInsn(ARETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
// make the method attributes
mv = cv.visitMethod(ACC_PROTECTED, "attributes",
"()" + ESEQ_TYPE.getDescriptor(), null, null);
mv.visitCode();
mv.visitFieldInsn(Opcodes.GETSTATIC, self_type.getInternalName(), "attributes",
ESEQ_TYPE.getDescriptor());
mv.visitInsn(ARETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
// make the method attributes
mv = cv.visitMethod(ACC_PROTECTED, "compile",
"()" + ESEQ_TYPE.getDescriptor(), null, null);
mv.visitCode();
mv.visitFieldInsn(Opcodes.GETSTATIC, self_type.getInternalName(), "compile",
ESEQ_TYPE.getDescriptor());
mv.visitInsn(ARETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
// make default constructor
mv = cv.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, ECOMPILEDMODULE_NAME, "<init>", "()V");
mv.visitInsn(RETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
mv = cv.visitMethod(ACC_PUBLIC, "registerImportsAndExports", "()V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, ECOMPILEDMODULE_NAME, "registerImportsAndExports", "()V");
for (Lambda l : lambdas_xx.values() ) {
mv.visitTypeInsn(NEW, Type.getInternalName(LocalFunID.class));
mv.visitInsn(DUP);
module_name.emit_const(mv);
l.fun.emit_const(mv);
push_int(mv, l.arity);
push_int(mv, l.old_index);
push_int(mv, l.index);
push_int(mv, l.old_uniq);
mv.visitFieldInsn(GETSTATIC, self_type.getInternalName(), "module_md5", EBINARY_TYPE.getDescriptor());
mv.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(LocalFunID.class), "<init>",
"("+EATOM_DESC+EATOM_DESC+"IIII"+EBINARY_TYPE.getDescriptor()+")V"
);
mv.visitInsn(DUP);
cv.visitField(ACC_STATIC, anon_fun_name(l), Type.getDescriptor(LocalFunID.class), null, null).visitEnd();
mv.visitFieldInsn(PUTSTATIC, self_type.getInternalName(), anon_fun_name(l), Type.getDescriptor(LocalFunID.class));
String mname = EUtil.getJavaName(l.fun, l.arity-l.freevars);
String outer_name = self_type.getInternalName();
String inner_name = "FN_" + mname;
String full_inner_name = outer_name + "$" + inner_name;
mv.visitLdcInsn(full_inner_name.replace('/', '.'));
mv.visitMethodInsn(INVOKESTATIC, Type.getInternalName(Class.class), "forName",
"(Ljava/lang/String;)Ljava/lang/Class;");
mv.visitMethodInsn(INVOKESTATIC, Type.getInternalName(EModuleManager.class), "register_lambda",
"(" + Type.getDescriptor(LocalFunID.class)
+ Type.getDescriptor(Class.class) + ")V");
}
mv.visitInsn(RETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
}
public static String anon_fun_name(Lambda l) {
return "lambda_"+l.index+"_"+l.old_index+"_"+l.old_uniq;
}
private void push_int(MethodVisitor mv, int val) {
if (val == -1) {
mv.visitInsn(ICONST_M1);
} else if (val >= 0 && val <= 5) {
mv.visitInsn(ICONST_0+val);
} else {
mv.visitLdcInsn(new Integer(val));
}
}
/*
* (non-Javadoc)
*
* @see erjang.beam.ModuleVisitor#visitExport(erjang.EAtom, int, int)
*/
@Override
public void visitExport(EAtom name, int arity, int entry) {
exported.add(EUtil.getJavaName(name, arity));
}
boolean isExported(EAtom name, int arity) {
return exported.contains(EUtil.getJavaName(name, arity));
}
@Override
public void declareFunction(EAtom fun, int arity, int label) {
/* ignore */
}
@Override
public FunctionVisitor visitFunction(EAtom name, int arity, int startLabel) {
return new ASMFunctionAdapter(name, arity, startLabel);
}
Map<FunID, Lambda> lambdas_xx = new TreeMap<FunID, Lambda>();
Map<String, String> funs = new HashMap<String, String>();
Map<String, String> funt = new HashMap<String, String>();
Set<String> non_pausable_methods = new HashSet<String>();
public EBinary module_md5;
private static final String SEQ_CONS_SIG = "(" + EOBJECT_DESC + ")"
+ ESEQ_DESC;
private static final String FUNC_INFO_SIG = "(" + EATOM_DESC + EATOM_DESC + ESEQ_DESC +")"
+ EOBJECT_DESC;
private static final String ERT_CONS_SIG = "(" + EOBJECT_DESC + EOBJECT_DESC + ")"
+ ECONS_TYPE.getDescriptor();
private static final String TEST_FUN_SIG ="(" + EOBJECT_DESC + EFUN_DESCRIPTOR + ")V";
class ASMFunctionAdapter implements FunctionVisitor2 {
private final EAtom fun_name;
private final int arity;
private final int startLabel;
Map<Integer, Label> labels = new TreeMap<Integer, Label>();
Map<Integer, Label> ex_handler_labels = new TreeMap<Integer, Label>();
Set<Integer> label_inserted = new TreeSet<Integer>();
List<EXHandler> ex_handlers = new ArrayList<EXHandler>();
EXHandler activeExceptionHandler;
BeamExceptionHandler active_beam_exh;
private boolean isTailRecursive;
private MethodVisitor mv;
private int[] xregs;
private int[] yregs;
private int[] fpregs;
private Label start;
private Label end;
private int scratch_reg;
private int bit_string_builder;
private int bit_string_matcher;
private int bit_string_save;
private FunInfo funInfo;
private Collection<Integer> deadBlocks;
Label getLabel(int i) {
if (i <= 0)
throw new Error();
Label l = labels.get(i);
if (l == null) {
labels.put(i, l = new Label());
}
return l;
}
Label getExceptionHandlerLabel(BeamExceptionHandler exh) {
int i = exh.getHandlerLabel();
Label l = ex_handler_labels.get(i);
if (l == null) {
ex_handler_labels.put(i, l = new Label());
}
return l;
}
/**
* @param name
* @param arity
* @param startLabel
* @param isTailRecursive
*/
public ASMFunctionAdapter(EAtom name, int arity, int startLabel) {
this.fun_name = name;
this.arity = arity;
this.startLabel = startLabel;
}
@Override
public void visitMaxs(Collection<Integer> x_regs, int y_count, int fp_count,
boolean isTailRecursive, Collection<Integer> dead_blocks) {
FunID me = new FunID(module_name, fun_name, arity);
this.funInfo = funInfos.get(me);
this.isTailRecursive = isTailRecursive;
this.deadBlocks = dead_blocks;
Lambda lambda = get_lambda_freevars(fun_name, arity);
final int freevars =
lambda == null
? 0
: lambda.freevars;
int real_arity = arity-freevars;
String javaName = EUtil.getJavaName(fun_name, real_arity);
String signature = EUtil.getSignature(arity, true);
mv = cv.visitMethod(ACC_STATIC | ACC_PUBLIC, javaName, signature,
null, funInfo.is_pausable ? PAUSABLE_EX : null);
if (!funInfo.is_pausable) {
non_pausable_methods.add(javaName);
}
this.start = new Label();
this.end = new Label();
mv.visitCode();
allocate_regs_to_locals(x_regs, y_count, fp_count);
mv.visitLabel(start);
mv.visitJumpInsn(GOTO, getLabel(startLabel));
}
/*
* (non-Javadoc)
*
* @see erjang.beam.FunctionVisitor#visitEnd()
*/
@Override
public void visitEnd() {
adjust_exception_handlers(null, false);
mv.visitLabel(end);
for (EXHandler h : ex_handlers) {
if (! label_inserted.contains(h.handler_beam_label))
throw new InternalError("Exception handler not inserted: "+h.handler_beam_label);
if (deadBlocks.contains(h.handler_beam_label)) {
continue;
}
mv.visitTryCatchBlock(h.begin, h.end, h.target,
Type.getType(ErlangException.class).getInternalName());
}
mv.visitMaxs(20, scratch_reg + 3);
mv.visitEnd();
int arity_plus = arity;
Lambda lambda = get_lambda_freevars(fun_name, arity_plus);
final int freevars =
lambda == null
? 0
: lambda.freevars;
int real_arity = arity_plus-freevars;
String mname = EUtil.getJavaName(fun_name, real_arity);
String outer_name = self_type.getInternalName();
String inner_name = "FN_" + mname;
String full_inner_name = outer_name + "$" + inner_name;
boolean make_fun = false;
boolean is_exported = isExported(fun_name, arity);
if (lambda != null) {
CompilerVisitor.this.module_md5 = lambda.uniq;
make_fun = true;
} else {
if (funInfo.is_called_locally_in_nontail_position)
generate_invoke_call_self();
if (funInfo.is_called_locally_in_tail_position)
generate_tail_call_self(full_inner_name);
if (funInfo.mustHaveFun()) {
FieldVisitor fv = cv.visitField(ACC_STATIC | ACC_FINAL, mname,
"L" + full_inner_name + ";", null, null);
EFun.ensure(arity);
if (is_exported) {
if (ModuleAnalyzer.log.isLoggable(Level.FINE))
ModuleAnalyzer.log.fine("export " + module_name + ":"
+ fun_name + "/" + arity);
AnnotationVisitor an = fv.visitAnnotation(EXPORT_ANN_TYPE
.getDescriptor(), true);
an.visit("module", module_name.getName());
an.visit("fun", fun_name.getName());
an.visit("arity", new Integer(arity));
an.visitEnd();
}
fv.visitEnd();
funs.put(mname, full_inner_name);
funt.put(mname, full_inner_name);
EFun.ensure(arity);
make_fun = true;
}
}
if (make_fun) {
cv.visitInnerClass(full_inner_name, outer_name, inner_name,
ACC_STATIC);
byte[] data = CompilerVisitor.make_invoker(module_name.getName(), fun_name.getName(), self_type, mname, mname,
arity, true, is_exported, lambda, EOBJECT_TYPE, funInfo.may_return_tail_marker, funInfo.is_pausable|funInfo.call_is_pausable);
ClassWeaver w = new ClassWeaver(data, new Compiler.ErjangDetector(
self_type.getInternalName(), non_pausable_methods));
w.weave();
if (w.getClassInfos().size() == 0) { // Class did not need weaving
try {
classRepo.store(full_inner_name, data);
} catch (IOException e) {
e.printStackTrace();
}
} else {
for (ClassInfo ci : w.getClassInfos()) {
try {
// System.out.println("> storing "+ci.className);
String iname = ci.className.replace('.', '/');
classRepo.store(iname, ci.bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
private void ensure_exception_handler_in_place() {
adjust_exception_handlers(active_beam_exh, false);
}
private void adjust_exception_handlers(BeamExceptionHandler exh, boolean expectChange) {
int desiredLabel = exh==null ? -1
: exh.getHandlerLabel();
int actualLabel = activeExceptionHandler==null ? -1
: activeExceptionHandler.handler_beam_label;
if (expectChange) assert(actualLabel != desiredLabel);
if (actualLabel != desiredLabel) {
// Terminate the old handler block:
if (activeExceptionHandler != null) {
mv.visitLabel(activeExceptionHandler.end);
activeExceptionHandler = null;
}
//...and begin a new if necessary:
if (exh != null) {
EXHandler h = new EXHandler();
h.begin = new Label();
h.end = new Label();
h.target = getExceptionHandlerLabel(exh);
h.handler_beam_label = exh.getHandlerLabel();
h.beam_exh = exh;
ex_handlers.add(h);
mv.visitLabel(h.begin);
// mv.visitInsn(NOP); // To avoid potentially-empty exception block; Kilim can't handle those.
activeExceptionHandler = h;
}
}
}
/**
*
*/
private void generate_invoke_call_self() {
boolean pausable = funInfo.is_pausable || funInfo.call_is_pausable;
String javaName = EUtil.getJavaName(fun_name, arity);
String signature = EUtil.getSignature(arity, true);
mv = cv.visitMethod(ACC_STATIC, javaName + "$call", signature,
null, pausable ? PAUSABLE_EX : null);
mv.visitCode();
if (!pausable) {
non_pausable_methods.add(javaName + "$call");
}
// if (isTailRecursive) {
mv.visitVarInsn(ALOAD, 0);
for (int i = 0; i < arity; i++) {
mv.visitVarInsn(ALOAD, i + 1);
}
mv.visitMethodInsn(INVOKESTATIC, self_type.getInternalName(),
javaName, EUtil.getSignature(arity, true));
if (funInfo.may_return_tail_marker) {
mv.visitVarInsn(ASTORE, arity + 1);
Label done = new Label();
Label loop = new Label();
mv.visitLabel(loop);
mv.visitVarInsn(ALOAD, arity + 1);
if (EProc.TAIL_MARKER == null) {
mv.visitJumpInsn(IFNONNULL, done);
} else {
mv.visitFieldInsn(GETSTATIC, EPROC_NAME, "TAIL_MARKER",
EOBJECT_DESC);
mv.visitJumpInsn(IF_ACMPNE, done);
}
// load proc
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, EPROC_NAME, "tail", EFUN_DESCRIPTOR);
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKEVIRTUAL, EFUN_NAME, (pausable ? "go" : "go2"), GO_DESC);
mv.visitVarInsn(ASTORE, arity + 1);
mv.visitJumpInsn(GOTO, loop);
mv.visitLabel(done);
mv.visitVarInsn(ALOAD, arity + 1);
}
mv.visitInsn(ARETURN);
mv.visitMaxs(arity + 2, arity + 2);
mv.visitEnd();
}
/**
* @param full_inner_name TODO
*
*/
private void generate_tail_call_self(String full_inner_name) {
String javaName = EUtil.getJavaName(fun_name, arity);
String signature = EUtil.getSignature(arity, true);
mv = cv.visitMethod(ACC_STATIC, javaName + "$tail", signature,
null, null);
mv.visitCode();
// if (isTailRecursive) {
for (int i = 0; i < arity; i++) {
mv.visitVarInsn(ALOAD, 0);
mv.visitVarInsn(ALOAD, i + 1);
mv
.visitFieldInsn(PUTFIELD, EPROC_NAME, "arg" + i,
EOBJECT_DESC);
}
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETSTATIC, self_type.getInternalName(), javaName,
"L" + full_inner_name + ";");
mv.visitFieldInsn(PUTFIELD, EPROC_NAME, "tail", EFUN_DESCRIPTOR);
if (EProc.TAIL_MARKER == null) {
mv.visitInsn(ACONST_NULL);
} else {
mv.visitFieldInsn(GETSTATIC, EPROC_NAME, "TAIL_MARKER",
EOBJECT_DESC);
}
/*
* } else { for (int i = 0; i < arity + 1; i++) {
* mv.visitVarInsn(ALOAD, i); }
*
* mv.visitMethodInsn(INVOKESTATIC, self_type.getInternalName(),
* javaName, signature); }
*/
mv.visitInsn(ARETURN);
mv.visitMaxs(arity + 2, arity + 2);
mv.visitEnd();
}
/**
* @param xCount
* @param yCount
* @param fpCount
*/
private void allocate_regs_to_locals(Collection<Integer> xRegs, int yCount, int fpCount) {
int max_y = yCount;
int max_f = fpCount;
int local = 1;
Integer[] xxregs = xRegs.toArray(new Integer[xRegs.size()]);
if (xxregs.length > 0) {
Arrays.sort(xxregs);
Integer biggest_used = xxregs[ xxregs.length - 1 ];
xregs = new int[biggest_used+1];
for (int i = 0; i < xxregs.length; i++) {
xregs[xxregs[i]] = i+local;
}
local += xxregs.length;
}
yregs = new int[max_y];
for (int i = 0; i < max_y; i++) {
// mv.visitLocalVariable("Y" + i, EOBJECT_DESCRIPTOR,
// null, start, end, local);
yregs[i] = local;
local += 1;
}
fpregs = new int[max_f];
for (int i = 0; i < max_f; i++) {
// mv.visitLocalVariable("F" + i,
// Type.DOUBLE_TYPE.getDescriptor(), null, start, end,
// local);
fpregs[i] = local;
local += 2;
}
this.bit_string_builder = local++;
this.bit_string_matcher = local++;
this.bit_string_save = local++;
this.scratch_reg = local;
}
/*
* (non-Javadoc)
*
* @see erjang.beam.FunctionVisitor#visitLabeledBlock(int)
*/
@Override
public BlockVisitor visitLabeledBlock(int label) {
Label blockLabel = getLabel(label);
mv.visitLabel(blockLabel);
label_inserted.add(label);
// mv.visitLineNumber(label & 0x7fff, blockLabel);
return new ASMBlockVisitor(label);
}
class ASMBlockVisitor implements BlockVisitor2 {
final int beam_label;
public ASMBlockVisitor(int beam_label) {this.beam_label=beam_label;}
@Override
public void visitBegin(BeamExceptionHandler exh) {
active_beam_exh = exh;
if (exh==null || (exh.getHandlerLabel() != beam_label)) {
adjust_exception_handlers(exh, false);
mv.visitInsn(NOP);
}
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitBSAdd(erjang.beam.Arg[],
* erjang.beam.Arg)
*/
@Override
public void visitBSAdd(Arg in1, Arg in2, int scale, Arg out) {
push(in1, Type.INT_TYPE);
push_scaled(in2, scale);
mv.visitInsn(IADD);
pop(out, Type.INT_TYPE);
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitBS(erjang.beam.BeamOpcode,
* erjang.beam.Arg)
*/
@Override
public void visitBS(BeamOpcode opcode, Arg arg, Arg imm) {
switch (opcode) {
case bs_save2:
case bs_restore2:
push(arg, EOBJECT_TYPE);
if (imm.value == ATOM_start) {
String methName =
(opcode == BeamOpcode.bs_restore2)
? "bs_restore2_start" : "bs_save2_start";
mv.visitMethodInsn(INVOKESTATIC, EBINMATCHSTATE_TYPE.getInternalName(), methName, "("+EOBJECT_DESC+")V");
} else {
push(imm, Type.INT_TYPE);
mv.visitMethodInsn(INVOKESTATIC, EBINMATCHSTATE_TYPE.getInternalName(), opcode.name(), "("+EOBJECT_DESC+"I)V");
}
return;
case bs_context_to_binary:
push(arg, EOBJECT_TYPE);
mv.visitMethodInsn(INVOKESTATIC, EBINMATCHSTATE_TYPE
.getInternalName(), "bs_context_to_binary", "(" +EOBJECT_DESC + ")" + EOBJECT_DESC);
pop(arg, EOBJECT_TYPE);
return;
case bs_utf8_size:
push(arg, EOBJECT_TYPE);
mv.visitMethodInsn(INVOKESTATIC, EBINSTRINGBUILDER_TYPE.getInternalName(), "bs_utf8_size",
"(" + EOBJECT_DESC +")" + ESMALL_TYPE.getDescriptor());
pop(imm, ESMALL_TYPE);
return;
case bs_utf16_size:
push(arg, EOBJECT_TYPE);
mv.visitMethodInsn(INVOKESTATIC, EBINSTRINGBUILDER_TYPE.getInternalName(), "bs_utf16_size",
"(" + EOBJECT_DESC +")" + ESMALL_TYPE.getDescriptor());
pop(imm, ESMALL_TYPE);
return;
}
throw new Error("unhandled: " + opcode);
}
@Override
public void visitInitWritable(Arg size, Arg out) {
push(size, EOBJECT_TYPE);
mv.visitMethodInsn(INVOKESTATIC,
EBITSTRINGBUILDER_TYPE.getInternalName(), "bs_init_writable",
"("+EOBJECT_DESC+")"+EBITSTRINGBUILDER_TYPE.getDescriptor());
mv.visitInsn(DUP);
mv.visitVarInsn(ASTORE, bit_string_builder);
mv.visitMethodInsn(INVOKEVIRTUAL, EBITSTRINGBUILDER_TYPE
.getInternalName(), "bitstring", "()"
+ EBITSTRING_TYPE.getDescriptor());
pop(out, EBITSTRING_TYPE);
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitInitBitString(erjang.EObject,
* erjang.beam.Arg, erjang.beam.Arg)
*/
@Override
public void visitInitBitString(Arg size, int flags, Arg out, boolean unit_is_bits) {
push(size, Type.INT_TYPE);
mv.visitLdcInsn(new Integer(flags));
String methodName = unit_is_bits? "bs_initBits" : "bs_init";
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, methodName, "(II)"
+ EBITSTRINGBUILDER_TYPE.getDescriptor());
mv.visitInsn(DUP);
mv.visitVarInsn(ASTORE, bit_string_builder);
mv.visitMethodInsn(INVOKEVIRTUAL, EBITSTRINGBUILDER_TYPE
.getInternalName(), "bitstring", "()"
+ EBITSTRING_TYPE.getDescriptor());
pop(out, EBITSTRING_TYPE);
return;
}
@Override
public void visitBitStringAppend(BeamOpcode opcode, int label, Arg extra_size, Arg src, int unit, int flags, Arg dst) {
push(src, EOBJECT_TYPE);
push(extra_size, Type.INT_TYPE);
push_int(unit);
push_int(flags);
mv.visitMethodInsn(INVOKESTATIC, EBITSTRINGBUILDER_TYPE.getInternalName(),
opcode.name(), "("+ EOBJECT_DESC +"III)"+EBITSTRINGBUILDER_TYPE.getDescriptor());
mv.visitInsn(DUP);
mv.visitVarInsn(ASTORE, bit_string_builder);
mv.visitMethodInsn(INVOKEVIRTUAL, EBITSTRINGBUILDER_TYPE
.getInternalName(), "bitstring", "()"
+ EBITSTRING_TYPE.getDescriptor());
pop(dst, EBITSTRING_TYPE);
return;
}
/*
* (non-Javadoc)
*
* @see
* erjang.beam.BlockVisitor2#visitBitStringPut(erjang.beam.BeamOpcode
* , erjang.EObject)
*/
@Override
public void visitBitStringPut(BeamOpcode opcode, Arg arg, Arg size,
int unit, int flags)
{
switch (opcode) {
case bs_put_string:
mv.visitVarInsn(ALOAD, bit_string_builder);
push(arg, ESTRING_TYPE);
mv.visitMethodInsn(INVOKEVIRTUAL, EBITSTRINGBUILDER_TYPE
.getInternalName(), "put_string", "("
+ ESTRING_TYPE.getDescriptor() + ")V");
return;
case bs_put_integer:
mv.visitVarInsn(ALOAD, bit_string_builder);
push(arg, EINTEGER_TYPE);
push_scaled(size, unit);
push_int(flags);
mv.visitMethodInsn(INVOKEVIRTUAL, EBITSTRINGBUILDER_TYPE
.getInternalName(), "put_integer", "("
+ EOBJECT_DESC + "II)V");
return;
case bs_put_float:
mv.visitVarInsn(ALOAD, bit_string_builder);
push(arg, EDOUBLE_TYPE);
push_scaled(size, unit);
push_int(flags);
mv.visitMethodInsn(INVOKEVIRTUAL, EBITSTRINGBUILDER_TYPE
.getInternalName(), "put_float", "("+EOBJECT_DESC+"II)V");
return;
case bs_put_utf8:
mv.visitVarInsn(ALOAD, bit_string_builder);
push(arg, EINTEGER_TYPE);
push_int(flags);
mv.visitMethodInsn(INVOKEVIRTUAL, EBITSTRINGBUILDER_TYPE
.getInternalName(), "put_utf8", "("+EOBJECT_DESC+"I)V");
return;
case bs_put_utf16:
mv.visitVarInsn(ALOAD, bit_string_builder);
push(arg, EINTEGER_TYPE);
push_int(flags);
mv.visitMethodInsn(INVOKEVIRTUAL, EBITSTRINGBUILDER_TYPE
.getInternalName(), "put_utf16", "("+EOBJECT_DESC+"I)V");
return;
case bs_put_utf32:
mv.visitVarInsn(ALOAD, bit_string_builder);
push(arg, EINTEGER_TYPE);
push_int(flags);
mv.visitMethodInsn(INVOKEVIRTUAL, EBITSTRINGBUILDER_TYPE
.getInternalName(), "put_utf32", "("+EOBJECT_DESC+"I)V");
return;
case bs_put_binary:
mv.visitVarInsn(ALOAD, bit_string_builder);
push(arg, EBITSTRING_TYPE);
if (size.kind == Kind.IMMEDIATE &&
size.value.equals(EAtom.intern("all")))
push_int(-1);
else
push_scaled(size, unit);
push_int(flags);
mv.visitMethodInsn(INVOKEVIRTUAL, EBITSTRINGBUILDER_TYPE
.getInternalName(), "put_bitstring", "("
+ EOBJECT_TYPE.getDescriptor() + "II)V");
return;
}
throw new Error("unhandled: " + opcode);
}
@Override
public void visitBitStringTest(BeamOpcode test, int failLabel, Arg in, int intg, Arg dst) {
switch (test) {
case bs_start_match2: {
push(in, EOBJECT_TYPE);
push_int(intg); // Slots
mv.visitMethodInsn(INVOKESTATIC, EBINMATCHSTATE_TYPE
.getInternalName(), test.name(), "(" + EOBJECT_DESC
+ "I)" + EMATCHSTATE_TYPE.getDescriptor());
mv.visitInsn(DUP);
mv.visitVarInsn(ASTORE, bit_string_matcher);
mv.visitJumpInsn(IFNULL, getLabel(failLabel));
mv.visitVarInsn(ALOAD, bit_string_matcher);
pop(dst, EBINMATCHSTATE_TYPE);
return;
}
/* {test,bs_get_utf8,{f,6},[{x,0},1,
{field_flags,[...,unsigned,big]},{x,1}]}. */
case bs_get_utf8:
case bs_get_utf16:
case bs_get_utf32: {
push(in, EBINMATCHSTATE_TYPE);
push_int(intg); // Flags
mv.visitMethodInsn(INVOKEVIRTUAL, EBINMATCHSTATE_TYPE
.getInternalName(), test.name(), "(I)I");
mv.visitInsn(DUP);
mv.visitVarInsn(ISTORE, scratch_reg);
mv.visitJumpInsn(IFLT, getLabel(failLabel));
mv.visitVarInsn(ILOAD, scratch_reg);
emit_box(Type.INT_TYPE, ESMALL_TYPE);
pop(dst, ESMALL_TYPE);
return;
}
default:
throw new Error("unhandled bit string test: " + test);
}
}
@Override
public void visitBitStringTest(BeamOpcode test, int failLabel, Arg in, EBitString bin) {
switch (test) {
case bs_match_string: {
push(in, EBINMATCHSTATE_TYPE);
push_immediate(bin, EBITSTRING_TYPE);
mv.visitMethodInsn(INVOKEVIRTUAL, EBINMATCHSTATE_TYPE
.getInternalName(), test.name(), "("
+ EBITSTRING_TYPE.getDescriptor() + ")"
+ EBITSTRING_TYPE);
mv.visitJumpInsn(IFNULL, getLabel(failLabel));
return;
}
default:
throw new Error("unhandled bit string test: " + test);
}
}
@Override
public void visitBitStringTest(BeamOpcode test, int failLabel, Arg in, Arg bits, int unit, int flags) {
switch (test) {
case bs_skip_bits2: {
// {test,bs_skip_bits2, {f,39},
// [{x,1},{x,0},8,{field_flags,0}]}
push(in, EBINMATCHSTATE_TYPE);
push(bits, EINTEGER_TYPE);
push_int(unit); // TODO: Scale here instead?
push_int(flags);
mv.visitMethodInsn(INVOKEVIRTUAL, EBINMATCHSTATE_TYPE
.getInternalName(), test.name(), "(" + EOBJECT_DESC
+ "II)" + EOBJECT_DESC);
mv.visitJumpInsn(IFNULL, getLabel(failLabel));
return;
}
default:
throw new Error("unhandled bit string test: " + test);
}
}
@Override
public void visitLine(int line) {
Label here = new Label();
mv.visitLabel(here);
mv.visitLineNumber(line, here);
}
@Override
public void visitBitStringTest(BeamOpcode test, int failLabel, Arg in, Arg bits, int unit, int flags, Arg dst) {
switch (test) {
case bs_get_binary2: {
push(in, EBINMATCHSTATE_TYPE);
push(bits, EOBJECT_TYPE); //TODO: scale by unit, handling 'all'
push_int(flags);
mv.visitMethodInsn(INVOKEVIRTUAL, EBINMATCHSTATE_TYPE
.getInternalName(), test.name(), "(" + EOBJECT_DESC
+ "I)" + EBITSTRING_TYPE);
mv.visitInsn(DUP);
mv.visitVarInsn(ASTORE, scratch_reg);
mv.visitJumpInsn(IFNULL, getLabel(failLabel));
mv.visitVarInsn(ALOAD, scratch_reg);
pop(dst, EBITSTRING_TYPE);
return;
}
// {test,bs_get_integer2,{f,348},[{x,3},4,{integer,32},1,{field_flags,0},{x,4}]}
case bs_get_integer2: {
push(in, EBINMATCHSTATE_TYPE);
push(bits, Type.INT_TYPE);
push_int(unit);
push_int(flags);
mv.visitMethodInsn(INVOKEVIRTUAL, EBINMATCHSTATE_TYPE
.getInternalName(), test.name(), "(III)"
+ EINTEGER_TYPE.getDescriptor());
mv.visitInsn(DUP);
mv.visitVarInsn(ASTORE, scratch_reg);
mv.visitJumpInsn(IFNULL, getLabel(failLabel));
mv.visitVarInsn(ALOAD, scratch_reg);
pop(dst, EOBJECT_TYPE);
return;
}
case bs_get_float2: {
push(in, EBINMATCHSTATE_TYPE);
push(bits, Type.INT_TYPE);
push_int(unit);
push_int(flags);
mv.visitMethodInsn(INVOKEVIRTUAL, EBINMATCHSTATE_TYPE
.getInternalName(), test.name(), "(III)"
+ EDOUBLE_TYPE.getDescriptor());
mv.visitInsn(DUP);
mv.visitVarInsn(ASTORE, scratch_reg);
mv.visitJumpInsn(IFNULL, getLabel(failLabel));
mv.visitVarInsn(ALOAD, scratch_reg);
pop(dst, EOBJECT_TYPE);
return;
}
default:
throw new Error("unhandled bit string test: " + test);
}
}
@Override
public void visitBitStringTest(BeamOpcode test, int failLabel, Arg in, int intg) {
// case bs_test_tail2: // intg == expected bits left
// case bs_test_unit: // intg == unit
// case bs_skip_utfXX: // intg == flags
push(in, EBINMATCHSTATE_TYPE);
push_int(intg);
mv.visitMethodInsn(INVOKEVIRTUAL, EBINMATCHSTATE_TYPE
.getInternalName(), test.name(), "(I)Z");
mv.visitJumpInsn(IFEQ, getLabel(failLabel));
return;
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitInsn(erjang.beam.BeamOpcode,
* int, erjang.beam.Arg[], erjang.beam.Arg)
*/
@Override
public void visitInsn(BeamOpcode opcode, int failLabel, Arg[] in,
Arg ex) {
if (opcode == BeamOpcode.raise) {
push(in[0], EOBJECT_TYPE);
push(in[1], EOBJECT_TYPE);
// raise will actually throw (if successful)
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "raise", "("
+ EOBJECT_DESC + EOBJECT_DESC + ")"
+ EOBJECT_DESC);
mv.visitInsn(ARETURN);
return;
}
throw new Error("unhandled: " + opcode);
}
/**
*
*/
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitInsn(erjang.beam.BeamOpcode,
* int, erjang.beam.Arg[], erjang.beam.Arg,
* java.lang.reflect.Method)
*/
public void visitDecrement(Arg src, Arg out) {
push(src, src.type);
mv.visitMethodInsn(INVOKEVIRTUAL, EOBJECT_NAME, "dec", "()"+ENUMBER_TYPE.getDescriptor());
pop(out, EOBJECT_TYPE);
};
@Override
public void visitIncrement(Arg src, Arg out) {
push(src, src.type);
mv.visitMethodInsn(INVOKEVIRTUAL, EOBJECT_NAME, "inc", "()"+ENUMBER_TYPE.getDescriptor());
pop(out, EOBJECT_TYPE);
return;
}
@Override
public void visitInsn(BeamOpcode opcode, int failLabel, Arg[] in,
Arg out, BuiltInFunction bif) {
ensure_exception_handler_in_place();
switch (opcode) {
case bif0:
case bif1:
case bif2:
case gc_bif1:
case gc_bif2:
case gc_bif3:
case fadd:
case fsub:
case fmul:
case fdiv:
Type[] parameterTypes = bif.getArgumentTypes();
push(in, parameterTypes, bif.isVirtual());
mv.visitMethodInsn(bif.isVirtual() ? INVOKEVIRTUAL : INVOKESTATIC, bif.owner
.getInternalName(), bif.getName(), bif
.getDescriptor());
if (failLabel != 0) {
// guard
// dup result for test
if (out != null) {
pop(out, bif.getReturnType());
push(out, bif.getReturnType());
}
if (bif.getReturnType().getSort() == Type.BOOLEAN) {
mv.visitJumpInsn(IFEQ, getLabel(failLabel));
} else {
if (bif.getReturnType().getSort() != Type.OBJECT)
throw new Error(
"guards must return object type - "
+ bif);
mv.visitJumpInsn(IFNULL, getLabel(failLabel));
}
} else {
if (PARANOIA_MODE && bif.getReturnType().getSort() == Type.OBJECT) {
// Expect non-guards to return non-null.
mv.visitInsn(DUP);
mv.visitLdcInsn(bif.toString());
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME,
"paranoiaCheck", "(Lerjang/EObject;Ljava/lang/String;)V");
}
pop(out, bif.getReturnType());
}
return;
}
throw new Error();
}
public void visitUnreachablePoint() {
// mv.visitLdcInsn("Reached unreachable point.");
// mv.visitInsn(DUP);
// mv.visitMethodInsn(INVOKESPECIAL, "java/lang/RuntimeException", "<init>", "(Ljava/lang/String;)V");
// mv.visitInsn(ATHROW);
}
public void visitCatchBlockStart(BeamOpcode opcode, int label, Arg out, BeamExceptionHandler exh) {
switch (opcode) {
case K_try:
case K_catch: {
active_beam_exh = exh;
return;
}
}
}
public void visitCatchBlockEnd(BeamOpcode opcode, Arg out, BeamExceptionHandler exh) {
active_beam_exh = exh.getParent();
adjust_exception_handlers(active_beam_exh, false);
switch (opcode) {
case try_end: {
} break;
case catch_end: {
// Insert exception decoding sequence:
Label after = new Label();
mv.visitJumpInsn(GOTO, after);
mv.visitLabel(getExceptionHandlerLabel(exh));
// Remember the exception value:
mv.visitInsn(DUP);
mv.visitVarInsn(ALOAD, 0);
mv.visitInsn(SWAP);
mv.visitFieldInsn(PUTFIELD, EPROC_NAME,
"last_exception", EEXCEPTION_DESC);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME,
"decode_exception2", "("
+ ERLANG_EXCEPTION_TYPE.getDescriptor()
+ ")" + EOBJECT_DESC);
mv.visitVarInsn(ASTORE, xregs[0]);
mv.visitLabel(after);
} break;
case try_case: {
mv.visitLabel(getExceptionHandlerLabel(exh));
// Remember the exception value:
mv.visitInsn(DUP);
mv.visitVarInsn(ALOAD, 0);
mv.visitInsn(SWAP);
mv.visitFieldInsn(PUTFIELD, EPROC_NAME,
"last_exception", EEXCEPTION_DESC);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME,
"decode_exception3", "("
+ ERLANG_EXCEPTION_TYPE.getDescriptor()
+ ")" + getTubleType(3).getDescriptor());
mv.visitInsn(DUP);
mv.visitFieldInsn(GETFIELD, ETUPLE_NAME + 3, "elem1",
EOBJECT_DESC);
mv.visitVarInsn(ASTORE, xregs[0]);
mv.visitInsn(DUP);
mv.visitFieldInsn(GETFIELD, ETUPLE_NAME + 3, "elem2",
EOBJECT_DESC);
mv.visitVarInsn(ASTORE, xregs[1]);
mv.visitFieldInsn(GETFIELD, ETUPLE_NAME + 3, "elem3",
EOBJECT_DESC);
mv.visitVarInsn(ASTORE, xregs[2]);
} break;
}
}
/**
* @param out
* @return
*/
private int var_index(Arg out) {
switch (out.kind) {
case X:
return xregs[out.no];
case Y:
return yregs[out.no];
case F:
return fpregs[out.no];
}
throw new Error();
}
/**
* @param out
* @param stack_type
*/
private void pop(Arg out, Type stack_type) {
if (out == null) {
if (stack_type != null
&& Type.DOUBLE_TYPE.equals(stack_type)) {
mv.visitInsn(POP2);
} else {
mv.visitInsn(POP);
}
return;
}
if (stack_type == Type.DOUBLE_TYPE
&& (out.kind == Kind.X || out.kind == Kind.Y)) {
emit_convert(
stack_type,
stack_type == Type.DOUBLE_TYPE ? EDOUBLE_TYPE
: (stack_type == Type.INT_TYPE ? EINTEGER_TYPE
: EOBJECT_TYPE));
}
if (out.kind == Kind.X || out.kind == Kind.Y) {
if (out.type == Type.INT_TYPE
|| out.type == Type.BOOLEAN_TYPE
|| (out.type == null && stack_type == Type.INT_TYPE)
|| (out.type == null && stack_type == Type.BOOLEAN_TYPE)) {
mv.visitVarInsn(ISTORE, var_index(out));
} else {
mv.visitVarInsn(ASTORE, var_index(out));
}
} else if (out.kind == Kind.F) {
if (!stack_type.equals(Type.DOUBLE_TYPE)) {
emit_convert(stack_type, Type.DOUBLE_TYPE);
}
mv.visitVarInsn(DSTORE, var_index(out));
} else {
throw new Error();
}
}
/**
* @param type
* @param stackType
*/
private void emit_convert(Type from_type, Type to_type) {
if (from_type.equals(to_type))
return;
if (from_type.getSort() == Type.OBJECT
&& to_type.getSort() == Type.OBJECT) {
return;
}
if (to_type.getSort() == Type.OBJECT) {
emit_box(from_type, to_type);
} else {
emit_unbox(from_type, to_type);
}
}
/**
* @param fromType
* @param toType
*/
private void emit_unbox(Type fromType, Type toType) {
if (toType.equals(Type.INT_TYPE)) {
if (fromType.equals(ESMALL_TYPE)) {
mv.visitFieldInsn(GETFIELD, ESMALL_NAME, "value", "I");
return;
}
}
if (toType.equals(Type.DOUBLE_TYPE)) {
if (fromType.equals(EDOUBLE_TYPE)) {
mv.visitFieldInsn(GETFIELD, EDOUBLE_NAME, "value", "D");
return;
}
}
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "unboxTo"
+ primTypeName(toType), "(" + fromType.getDescriptor()
+ ")" + toType.getDescriptor());
}
/**
* @param toType
* @return
*/
private String primTypeName(Type typ) {
switch (typ.getSort()) {
case Type.DOUBLE:
return "Double";
case Type.INT:
return "Int";
case Type.BOOLEAN:
return "Atom";
default:
throw new Error();
}
}
/**
* @param fromType
* @param toType
*/
private void emit_box(Type fromType, Type toType) {
if (fromType.equals(Type.INT_TYPE)
&& toType.getSort() == Type.OBJECT) {
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "box", "(I)"
+ ESMALL_TYPE.getDescriptor());
} else if (fromType.equals(Type.DOUBLE_TYPE)
&& toType.getSort() == Type.OBJECT) {
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "box", "(D)"
+ EDOUBLE_TYPE.getDescriptor());
} else if (fromType.equals(Type.BOOLEAN_TYPE)
&& toType.getSort() == Type.OBJECT) {
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "box", "(Z)"
+ EATOM_TYPE.getDescriptor());
} else {
throw new Error("cannot box " + fromType + " -> " + toType);
}
}
/**
* @param in
* @param parameterTypes
*/
private void push(Arg[] in, Type[] parameterTypes, boolean isVirtual) {
int off = 0;
if (isVirtual) {
push(in[0], EOBJECT_TYPE);
off = 1;
}
if (in.length == parameterTypes.length - 1
&& EPROC_TYPE.equals(parameterTypes[0])) {
mv.visitVarInsn(ALOAD, 0);
}
for (int i = 0; i < in.length-off; i++) {
Arg arg = in[i+off];
Type pt = parameterTypes[i];
push(arg, pt);
}
}
private void push_scaled(Arg value, int factor) {
if (value.kind == Kind.IMMEDIATE &&
value.value instanceof ESmall)
{
ESmall sm = (ESmall)value.value;
mv.visitLdcInsn(new Integer(factor * sm.intValue()));
} else {
push(value, Type.INT_TYPE);
push_int(factor);
mv.visitInsn(IMUL);
}
}
/**
* @param arg
* @param class1
*/
private void push(Arg value, Type stack_type) {
Type t = value.type;
if (value.kind == Kind.X || value.kind == Kind.Y) {
if (value.type == Type.INT_TYPE
|| value.type == Type.BOOLEAN_TYPE) {
// throw new Error("should not happen");
mv.visitVarInsn(ILOAD, var_index(value));
} else {
mv.visitVarInsn(ALOAD, var_index(value));
}
} else if (value.kind == Kind.F) {
mv.visitVarInsn(DLOAD, var_index(value));
} else if (value.kind == Kind.IMMEDIATE) {
t = push_immediate(value.value, stack_type);
} else {
throw new Error();
}
if (t != null && !t.equals(stack_type)) {
emit_convert(t, stack_type);
}
}
/**
* @param value
* @param stack_type
*/
private Type push_immediate(EObject value, Type stack_type) {
if (value == ERT.NIL) {
mv.visitFieldInsn(GETSTATIC, ERT_NAME, "NIL", ENIL_TYPE
.getDescriptor());
return ENIL_TYPE;
}
if (value == ERT.TRUE) {
mv.visitFieldInsn(GETSTATIC, ERT_NAME, "TRUE", EATOM_DESC);
return EATOM_TYPE;
}
if (value == ERT.FALSE) {
mv.visitFieldInsn(GETSTATIC, ERT_NAME, "FALSE", EATOM_DESC);
return EATOM_TYPE;
}
// Handle conversions to primitive Java types:
if (stack_type.getSort() != Type.OBJECT) {
if (value instanceof ESmall) {
mv.visitLdcInsn(new Integer(value.asInt()));
return Type.INT_TYPE;
} else if (value instanceof EBig && stack_type.getSort() == Type.DOUBLE) {
push_immediate(value, EBIG_TYPE);
mv.visitMethodInsn(INVOKEVIRTUAL, EBIG_NAME, "doubleValue", "()D");
return Type.DOUBLE_TYPE;
} else if (value instanceof EDouble) {
mv.visitLdcInsn(new Double(((EDouble) value).value));
return Type.DOUBLE_TYPE;
} else if (value == TRUE_ATOM) {
mv.visitInsn(ICONST_1);
return Type.BOOLEAN_TYPE;
} else if (value == FALSE_ATOM) {
mv.visitInsn(ICONST_0);
return Type.BOOLEAN_TYPE;
}
if (value instanceof ETuple2) {
ETuple2 t2 = (ETuple2) value;
if (t2.elm(1) == ATOM_field_flags) {
push_int(t2.elem2.asInt());
return Type.INT_TYPE;
}
}
throw new Error("cannot convert " + value + " as "
+ stack_type);
}
String known = constants.get(value);
if (known == null) {
Type type = Type.getType(value.getClass());
String cn = getConstantName(value, constants.size());
constants.put(value, known = cn);
cv.visitField(ACC_STATIC, known, type.getDescriptor(),
null, null);
// System.err.println(constants);
}
if (known != null) {
Type type = Type.getType(value.getClass());
mv.visitFieldInsn(GETSTATIC, self_type.getInternalName(),
known, type.getDescriptor());
return type;
}
throw new Error("cannot push " + value + " as " + stack_type);
// return Type.getType(value.getClass());
}
/**
* @param value
* @param size
* @return
*/
private String getConstantName(EObject value, int size) {
if (value instanceof EAtom)
return "atom_" + EUtil.toJavaIdentifier((EAtom) value);
if (value instanceof ENumber)
return EUtil.toJavaIdentifier("num_"
+ value.toString().replace('.', '_').replace('-',
'_'));
if (value instanceof EString)
return "str_" + size;
else
return "cst_" + size;
}
/*
* (non-Javadoc)
*
* @see
* erjang.beam.BlockVisitor2#visitReceive(erjang.beam.BeamOpcode,
* int, erjang.beam.Arg)
*/
@Override
public void visitReceive(BeamOpcode opcode, int blockLabel, Arg out) {
switch (opcode) {
case loop_rec:
ensure_exception_handler_in_place();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "loop_rec",
"(" + EPROC_TYPE.getDescriptor() + ")"
+ EOBJECT_DESC);
mv.visitInsn(DUP);
pop(out, EOBJECT_TYPE);
mv.visitJumpInsn(IFNULL, getLabel(blockLabel));
return;
}
throw new Error();
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitInsn(erjang.beam.BeamOpcode,
* erjang.beam.Arg[], erjang.beam.Arg)
*/
@Override
public void visitInsn(BeamOpcode opcode, Arg[] in, Arg out) {
switch (opcode) {
case put_list:
push(in[0], EOBJECT_TYPE);
push(in[1], EOBJECT_TYPE);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "cons", ERT_CONS_SIG);
pop(out, ECONS_TYPE);
return;
case call_fun:
case i_call_fun_last: {
ensure_exception_handler_in_place();
boolean is_tail = opcode == BeamOpcode.i_call_fun_last;
int nargs = in.length - 1;
push(in[nargs], EOBJECT_TYPE);
mv.visitInsn(DUP);
String funtype = EFUN_NAME + nargs;
mv.visitMethodInsn(INVOKESTATIC, funtype, "cast", "("
+ EOBJECT_DESC + ")L" + funtype + ";");
mv.visitInsn(DUP_X1);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "test_fun", TEST_FUN_SIG);
mv.visitVarInsn(ALOAD, 0); // load proc
for (int i = 0; i < nargs; i++) {
push(in[i], EOBJECT_TYPE);
}
mv.visitMethodInsn(INVOKEVIRTUAL, funtype,
is_tail ? "invoke_tail" : "invoke",
EUtil.getSignature(nargs, true));
if (is_tail) {
mv.visitInsn(ARETURN);
} else {
pop(out, EOBJECT_TYPE);
}
return;
}
}//switch
throw new Error();
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitInsn(erjang.beam.BeamOpcode)
*/
@Override
public void visitInsn(BeamOpcode insn) {
switch (insn) {
case if_end:
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "if_end", EUtil
.getSignature(0, false));
mv.visitInsn(ARETURN);
return;
case timeout:
mv.visitVarInsn(ALOAD, 0);
mv
.visitMethodInsn(INVOKESTATIC, ERT_NAME, "timeout",
"("+EPROC_DESC+")V");
return;
case remove_message:
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME,
"remove_message", "(" + EPROC_TYPE.getDescriptor()
+ ")V");
return;
}
throw new Error();
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitInsn(erjang.beam.BeamOpcode,
* int, erjang.beam.Arg)
*/
@Override
public void visitInsn(BeamOpcode opcode, int val, Arg out) {
switch (opcode) {
case put_tuple:
mv.visitTypeInsn(NEW, out.type.getInternalName());
mv.visitInsn(DUP);
mv.visitMethodInsn(INVOKESPECIAL, out.type
.getInternalName(), "<init>", "()V");
pop(out, out.type);
return;
case wait_timeout: {
mv.visitVarInsn(ALOAD, 0);
push(out, EOBJECT_TYPE);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "wait_timeout",
"(" + EPROC_TYPE.getDescriptor()
+ EOBJECT_TYPE.getDescriptor() + ")Z");
mv.visitJumpInsn(IFNE, getLabel(val));
return;
}
case loop_rec_end:
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "loop_rec_end",
"(" + EPROC_TYPE.getDescriptor() + ")V");
mv.visitJumpInsn(GOTO, getLabel(val));
return;
case wait: {
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "wait",
"(" + EPROC_TYPE.getDescriptor() + ")V");
mv.visitJumpInsn(GOTO, getLabel(val));
return;
}
}
throw new Error("unhandled: " + opcode);
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitInsn(erjang.beam.BeamOpcode,
* erjang.beam.Arg, erjang.beam.Arg, int)
*/
@Override
public void visitInsn(BeamOpcode opcode, Arg val, Arg out, int pos) {
if (opcode == BeamOpcode.put) {
push(out, out.type);
push(val, EOBJECT_TYPE);
mv.visitFieldInsn(PUTFIELD, out.type.getInternalName(),
"elem" + pos, EOBJECT_DESC);
return;
} else if (opcode == BeamOpcode.get_tuple_element) {
int known_arity = get_known_arity(val.type);
if (known_arity >= pos+1) {
push(val, val.type);
mv.visitFieldInsn(GETFIELD, val.type.getInternalName(),
"elem" + (pos + 1), EOBJECT_DESC);
} else {
push(val, val.type);
mv.visitTypeInsn(CHECKCAST, ETUPLE_NAME);
push_int(pos + 1);
mv.visitMethodInsn(INVOKEVIRTUAL, ETUPLE_NAME, "elm",
"(I)" + EOBJECT_DESC);
}
pop(out, EOBJECT_TYPE);
return;
} else if (opcode == BeamOpcode.set_tuple_element) {
push(out, out.type);
if (get_known_arity(out.type) < 0)
mv.visitTypeInsn(CHECKCAST, ETUPLE_NAME);
push_int(pos + 1);
push(val, val.type);
mv.visitMethodInsn(INVOKEVIRTUAL, ETUPLE_NAME, "set", "(I"
+ EOBJECT_DESC + ")V");
return;
}
throw new Error();
}
/**
* @param type
* @return -1 if non-ETuple; arity [#elements] otherwise
*/
private int get_known_arity(Type type) {
String in = type.getInternalName();
if (in.startsWith(ETUPLE_NAME)) {
int pfx_len = ETUPLE_NAME.length();
if (in.length() == pfx_len) {
return 0;
}
try {
String arity = in.substring(pfx_len);
return Integer.parseInt(arity);
} catch (NumberFormatException e) {
return 0;
}
}
// not a tuple
return -1;
}
/**
* @param pos
*/
private void push_int(int pos) {
if (pos >= -1 && pos <= 5) {
mv.visitInsn(ICONST_0 + pos);
} else {
mv.visitLdcInsn(new Integer(pos));
}
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitTest(erjang.beam.BeamOpcode,
* int, erjang.beam.Arg, java.lang.reflect.Method)
*/
@Override
public void visitInsn(BeamOpcode test, int failLabel, Arg arg1,
org.objectweb.asm.commons.Method bif) {
throw new Error();
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor#visitEnd()
*/
@Override
public void visitEnd() {
// skip //
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor#visitInsn(erjang.beam.BeamOpcode,
* erjang.ETuple)
*/
@Override
public void visitInsn(Insn insn) {
throw new Error();
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitInsn(erjang.beam.BeamOpcode,
* erjang.beam.Arg)
*/
@Override
public void visitInsn(BeamOpcode opcode, Arg arg) {
switch (opcode) {
case K_return:
push(arg, EOBJECT_TYPE);
mv.visitInsn(ARETURN);
return;
case init:
push_immediate(ERT.NIL, ENIL_TYPE);
pop(arg, ENIL_TYPE);
return;
case try_case_end:
push(arg, EOBJECT_TYPE);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "try_case_end",
EUtil.getSignature(1, false));
mv.visitInsn(ARETURN);
return;
case case_end:
push(arg, EOBJECT_TYPE);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "case_end",
EUtil.getSignature(1, false));
mv.visitInsn(ARETURN);
return;
case badmatch:
push(arg, EOBJECT_TYPE);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "badmatch",
EUtil.getSignature(1, false));
mv.visitInsn(ARETURN);
return;
}
throw new Error("unhandled " + opcode);
}
public void visitInsn(BeamOpcode opcode, ExtFun f) {
switch (opcode) {
case func_info:
push_immediate(f.mod, EATOM_TYPE);
push_immediate(f.fun, EATOM_TYPE);
push_immediate(ERT.NIL, ENIL_TYPE);
for (int i=f.arity-1; i>=0; i--) {
push(new Arg(Kind.X, i), EOBJECT_TYPE);
mv.visitMethodInsn(INVOKEVIRTUAL, ESEQ_NAME, "cons", SEQ_CONS_SIG);
}
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "func_info", FUNC_INFO_SIG);
mv.visitInsn(ARETURN);
return;
}//switch
throw new Error("unhandled " + opcode);
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitTest(erjang.beam.BeamOpcode,
* int, erjang.beam.Arg)
*/
@Override
public void visitTest(BeamOpcode test, int failLabel, Arg arg1,
Type out) {
Method test_bif = get_test_bif(test, arg1.type);
// System.err.println(test_bif);
push(arg1, arg1.type);
mv.visitMethodInsn(INVOKEVIRTUAL, EOBJECT_NAME, test_bif
.getName(), test_bif.getDescriptor());
Type returnType = test_bif.getReturnType();
if (failLabel != 0) {
// guard
if (returnType.getSort() != Type.OBJECT)
throw new Error("guards must return object type: "
+ test_bif);
// dup result for test
if (arg1 != null) {
mv.visitInsn(DUP);
mv.visitVarInsn(ASTORE, scratch_reg);
}
mv.visitJumpInsn(IFNULL, getLabel(failLabel));
if (arg1 != null) {
mv.visitVarInsn(ALOAD, scratch_reg);
pop(arg1, returnType);
}
} else {
pop(arg1, returnType);
}
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitTest(erjang.beam.BeamOpcode,
* int, erjang.beam.Arg, int, org.objectweb.asm.Type)
*/
@Override
public void visitTest(BeamOpcode test, int failLabel, Arg arg,
int arity, Type tupleType) {
switch (test) {
case test_arity: {
Type tt = getTubleType(arity);
if (tt.equals(arg.type)) {
// do nothing //
} else {
push(arg, EOBJECT_TYPE);
mv.visitMethodInsn(INVOKESTATIC, tt.getInternalName(),
"cast", "(" + arg.type.getDescriptor() + ")"
+ tt.getDescriptor());
mv.visitInsn(DUP);
mv.visitVarInsn(ASTORE, scratch_reg);
mv.visitJumpInsn(IFNULL, getLabel(failLabel));
mv.visitVarInsn(ALOAD, scratch_reg);
pop(arg, getTubleType(arity));
}
return;
}
}//switch
throw new Error("unhandled " + test);
}
@Override
public void visitTest(BeamOpcode test, int failLabel, Arg arg,
Arg arity, Type funType) {
switch (test) {
case is_function2:
// push object to test
push(arg, EOBJECT_TYPE);
// push arity
push(arity, Type.INT_TYPE);
// call object.testFunction2(nargs)
mv.visitMethodInsn(INVOKEVIRTUAL, EOBJECT_NAME,
"testFunction2", "(I)" + EFUN_DESCRIPTOR);
mv.visitInsn(DUP);
mv.visitVarInsn(ASTORE, scratch_reg);
mv.visitJumpInsn(IFNULL, getLabel(failLabel));
mv.visitVarInsn(ALOAD, scratch_reg);
pop(arg, funType);
return;
}
throw new Error("unhandled " + test);
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitTest(erjang.beam.BeamOpcode,
* int, erjang.beam.Arg[], erjang.beam.Arg, org.objectweb.asm.Type)
*/
@Override
public void visitTest(BeamOpcode test, int failLabel, Arg[] args,
Type outType) {
switch (test) {
case is_eq_exact:
{
if (args[0].kind==Kind.IMMEDIATE && args[0].value.equalsExactly(ESmall.ZERO)) {
push(args[1], EOBJECT_TYPE);
mv.visitMethodInsn(INVOKEVIRTUAL, EOBJECT_NAME, "is_zero",
"()Z");
mv.visitJumpInsn(IFEQ, getLabel(failLabel));
return;
}
if (args[1].kind==Kind.IMMEDIATE && args[1].value.equalsExactly(ESmall.ZERO)) {
push(args[0], EOBJECT_TYPE);
mv.visitMethodInsn(INVOKEVIRTUAL, EOBJECT_NAME, "is_zero",
"()Z");
mv.visitJumpInsn(IFEQ, getLabel(failLabel));
return;
}
}
case is_ne_exact:
case is_ne:
case is_eq:
{
// if arg[0] is object type, and arg[1] is not, then swap args.
if (args[0].type.equals(EOBJECT_TYPE) && !args[1].type.equals(EOBJECT_TYPE)) {
Arg t = args[0];
args[0] = args[1];
args[1] = t;
}
}
case is_lt:
case is_ge:
{
// this particular case can be coded as a java instruction instruction
if ((test == BeamOpcode.is_eq_exact || test == BeamOpcode.is_eq)
&& (args[0].type.equals(EATOM_TYPE) || args[1].type
.equals(EATOM_TYPE))) {
push(args[0], EOBJECT_TYPE);
push(args[1], EOBJECT_TYPE);
mv.visitJumpInsn(IF_ACMPNE, getLabel(failLabel));
return;
}
for (int i = 0; i < args.length; i++) {
push(args[i], EOBJECT_TYPE);
}
mv.visitMethodInsn(INVOKEVIRTUAL, EOBJECT_NAME,
test.name(), "(" + EOBJECT_DESC + ")Z");
if (failLabel != 0) {
mv.visitJumpInsn(IFEQ, getLabel(failLabel));
} else {
throw new Error("test with no fail label?");
}
//
if (test == BeamOpcode.is_eq_exact && !Type.VOID_TYPE.equals(outType)) {
if (args[0].type.equals(EOBJECT_TYPE) && args[0].kind.isReg()) {
push(args[1], outType);
args[0].type = outType;
pop(args[0], outType);
} else if (args[1].type.equals(EOBJECT_TYPE) && args[1].kind.isReg()) {
push(args[0], outType);
args[1].type = outType;
pop(args[1], outType);
}
}
return;
}
}
throw new Error("unhandled " + test);
}
/**
* @param test
* @return
*/
private String test2name(BeamOpcode test) {
return test.name();
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitInsn(erjang.beam.BeamOpcode,
* erjang.beam.Arg, erjang.beam.Arg)
*/
@Override
public void visitInsn(BeamOpcode opcode, Arg arg1, Arg arg2) {
switch (opcode) {
case fconv:
case move:
case fmove:
if (arg1.kind == Kind.F) {
push(arg1, Type.DOUBLE_TYPE);
if (arg2.kind == Kind.F) {
pop(arg2, Type.DOUBLE_TYPE);
} else {
emit_convert(Type.DOUBLE_TYPE, EDOUBLE_TYPE);
pop(arg2, EDOUBLE_TYPE);
}
} else {
if (arg2.kind == Kind.F) {
push(arg1, Type.DOUBLE_TYPE);
pop(arg2, Type.DOUBLE_TYPE);
} else {
push(arg1, arg1.type);
pop(arg2, arg1.type);
}
}
break;
default:
throw new Error("unhandled: " + opcode);
}
}
/**
* @param test
* @param args
* @return
*/
private Method get_test_bif(BeamOpcode test, Type type) {
if (!type.getInternalName().startsWith("erjang/E")) {
throw new Error("expecting EObject");
}
switch (test) {
case is_nonempty_list:
return IS_NONEMPTY_LIST_TEST;
case is_nil:
return IS_NIL_TEST;
case is_boolean:
return IS_BOOLEAN_TEST;
case is_number:
return IS_NUMBER_TEST;
case is_float:
return IS_FLOAT_TEST;
case is_atom:
return IS_ATOM_TEST;
case is_list:
return IS_LIST_TEST;
case is_tuple:
return IS_TUPLE_TEST;
case is_integer:
return IS_INTEGER_TEST;
case is_binary:
return IS_BINARY_TEST;
case is_bitstr:
return IS_BITSTRING_TEST;
case is_pid:
return IS_PID_TEST;
case is_port:
return IS_PORT_TEST;
case is_reference:
return IS_REFERENCE_TEST;
case is_function:
return IS_FUNCTION_TEST;
case is_function2:
return IS_FUNCTION2_TEST;
}
throw new Error("unhandled " + test);
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitInsn(erjang.beam.BeamOpcode,
* erjang.beam.Arg[])
*/
@Override
public void visitInsn(BeamOpcode opcode, Arg[] ys) {
if (opcode == BeamOpcode.allocate_zero
|| opcode == BeamOpcode.allocate_heap_zero) {
mv.visitFieldInsn(GETSTATIC, ERT_NAME, "NIL", ENIL_TYPE
.getDescriptor());
for (int i = 0; i < ys.length; i++) {
if (i != (ys.length - 1))
mv.visitInsn(DUP);
mv.visitInsn(NOP);
pop(ys[i], ENIL_TYPE);
}
return;
} else if (opcode == BeamOpcode.get_list) {
push(ys[0], ECONS_TYPE);
mv.visitInsn(DUP);
mv.visitMethodInsn(INVOKEVIRTUAL, ECONS_TYPE
.getInternalName(), "head", "()" + EOBJECT_DESC);
pop(ys[1], EOBJECT_TYPE);
mv.visitMethodInsn(INVOKEVIRTUAL, ECONS_TYPE
.getInternalName(), "tail", "()" + EOBJECT_DESC);
pop(ys[2], EOBJECT_TYPE);
return;
}
ensure_exception_handler_in_place();
if (opcode == BeamOpcode.apply || opcode == BeamOpcode.apply_last) {
int arity = ys.length-2;
push(ys[ys.length-2], EOBJECT_TYPE); // push mod
push(ys[ys.length-1], EOBJECT_TYPE); // push fun
push_int(arity); // push arity
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "resolve_fun", "("+EOBJECT_DESC+EOBJECT_DESC+"I)"+EFUN_DESCRIPTOR);
String funtype = EFUN_NAME + arity;
mv.visitMethodInsn(INVOKESTATIC, funtype, "cast", "("
+ EOBJECT_DESC + ")L" + funtype + ";");
mv.visitVarInsn(ALOAD, 0); // push eproc
int loops = 0;
for (int i = 0; i <= ys.length-3; i++) {
push(ys[i], EOBJECT_TYPE);
loops += 1;
}
if (loops != arity) {
// invariant for above complicated loop logic.
throw new InternalError("bad args here");
}
boolean is_tail = opcode == BeamOpcode.apply_last;
if (is_tail) {
mv.visitMethodInsn(INVOKEVIRTUAL, funtype, "invoke_tail", EUtil
.getSignature(arity, true));
mv.visitInsn(ARETURN);
} else {
mv.visitMethodInsn(INVOKEVIRTUAL, funtype,
"invoke", EUtil
.getSignature(arity, true));
mv.visitVarInsn(ASTORE, xregs[0]);
}
return;
} else if (opcode == BeamOpcode.send) {
mv.visitVarInsn(ALOAD, 0);
for (int i = 0; i < ys.length; i++) {
push(ys[i], EOBJECT_TYPE);
}
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "send", EUtil
.getSignature(ys.length, true));
mv.visitVarInsn(ASTORE, xregs[0]);
return;
}
throw new Error("unhandled:" + opcode);
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitInsn(erjang.beam.BeamOpcode,
* erjang.beam.ExtFunc, int)
*/
@Override
public void visitInsn(BeamOpcode opcode, ExtFun efun,
Arg[] freevars, int index, int old_index, EBinary uniq, int old_uniq) {
ensure_exception_handler_in_place();
if (opcode == BeamOpcode.make_fun2) {
CompilerVisitor.this.register_lambda(efun.fun, efun.arity,
freevars.length, index, old_index, uniq, old_uniq);
String inner = EUtil.getFunClassName(self_type, efun, freevars.length);
mv.visitTypeInsn(NEW, inner);
mv.visitInsn(DUP);
// load proc
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKEVIRTUAL, EPROC_NAME, "self_handle", "()" + Type.getDescriptor(EInternalPID.class));
// String funtype = EFUN_NAME + efun.no;
for (int i = 0; i < freevars.length; i++) {
push(freevars[i], EOBJECT_TYPE);
}
StringBuilder sb = new StringBuilder("(");
sb.append(EPID_TYPE.getDescriptor());
for (int i = 0; i < freevars.length; i++) {
sb.append(EOBJECT_DESC);
}
sb.append(")V");
// sb.append("L").append(funtype).append(";");
String gen_fun_desc = sb.toString();
mv.visitMethodInsn(INVOKESPECIAL, inner, "<init>",
gen_fun_desc);
mv.visitVarInsn(ASTORE, xregs[0]);
return;
}
throw new Error();
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitSelectValue(erjang.beam.Arg,
* int, erjang.beam.Arg[], int[])
*/
@Override
public void visitSelectValue(Arg in, int failLabel, Arg[] values,
int[] targets) {
boolean all_small_ints = true;
for (int i = 0; i < values.length; i++) {
if (!(values[i].value instanceof ESmall)) {
all_small_ints = false;
break;
}
}
if (all_small_ints) {
int[] ivals = new int[values.length];
Label[] label = new Label[values.length];
for (int i = 0; i < values.length; i++) {
ivals[i] = values[i].value.asInt();
label[i] = getLabel(targets[i]);
}
push(in, Type.INT_TYPE);
sort(ivals, label);
mv.visitLookupSwitchInsn(getLabel(failLabel), ivals, label);
return;
}
if (values.length < ATOM_SELECT_IF_ELSE_LIMIT) {
boolean all_atoms = true;
for (int i = 0; i < values.length; i++) {
if (!(values[i].value instanceof EAtom)) {
all_atoms = false;
break;
}
}
if (all_atoms) {
for (int i = 0; i < values.length; i++) {
push(in, in.type);
push(values[i], values[i].type);
mv.visitJumpInsn(IF_ACMPEQ, getLabel(targets[i]));
}
mv.visitJumpInsn(GOTO, getLabel(failLabel));
return;
}
}
class Case implements Comparable<Case> {
final Arg arg;
final Label label;
/**
* @param arg
* @param label2
*/
public Case(Arg arg, Label label) {
this.arg = arg;
this.label = label;
}
EObject value() {
return arg.value;
}
/*
* (non-Javadoc)
*
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(Case o) {
int h = hashCode();
int ho = o.hashCode();
if (h < ho)
return -1;
if (h > ho)
return 1;
return value().erlangCompareTo(o.value());
}
}
Map<Integer, List<Case>> cases = new TreeMap<Integer, List<Case>>();
for (int i = 0; i < values.length; i++) {
int hash = values[i].value.hashCode();
List<Case> c = cases.get(hash);
if (c == null) {
cases.put(hash, c = new ArrayList<Case>());
}
c.add(new Case(values[i], getLabel(targets[i])));
}
int[] hashes = new int[cases.size()];
Label[] tests = new Label[cases.size()];
List<Case>[] idx_cases = new List[cases.size()];
int idx = 0;
for (Map.Entry<Integer, List<Case>> c : cases.entrySet()) {
hashes[idx] = c.getKey();
idx_cases[idx] = c.getValue();
tests[idx++] = new Label();
}
push(in, EOBJECT_TYPE);
mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object",
"hashCode", "()I");
mv.visitLookupSwitchInsn(getLabel(failLabel), hashes, tests);
for (int i = 0; i < idx_cases.length; i++) {
mv.visitLabel(tests[i]);
for (Case c : idx_cases[i]) {
Arg val_j = c.arg;
Label target_j = c.label;
if (val_j.type.equals(EATOM_TYPE)) {
push(in, in.type);
push(val_j, val_j.type);
mv.visitJumpInsn(IF_ACMPEQ, target_j);
} else {
if (in.type == val_j.type) {
push(in, in.type);
push(val_j, val_j.type);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME,
"eq", "(" + in.type.getDescriptor()
+ in.type.getDescriptor()
+ ")Z");
} else {
push(in, EOBJECT_TYPE);
push(val_j, EOBJECT_TYPE);
mv.visitMethodInsn(INVOKEVIRTUAL,
"java/lang/Object", "equals",
"(Ljava/lang/Object;)Z");
}
mv.visitJumpInsn(IFNE, target_j);
}
}
mv.visitJumpInsn(GOTO, getLabel(failLabel));
}
}
/**
* @param ivals
* @param label
*/
private int[] sort(int[] ivals, Label[] label) {
Label[] orig_labels = label.clone();
int[] orig_ivals = ivals.clone();
int[] res = new int[ivals.length];
Arrays.sort(ivals);
next_val: for (int i = 0; i < ivals.length; i++) {
int find = ivals[i];
for (int p = 0; p < orig_ivals.length; p++) {
int was = orig_ivals[p];
if (find == was) {
res[p] = i;
label[i] = orig_labels[p];
continue next_val;
}
}
}
return res;
}
/** class that we use to sort the labels for select_arity switch */
class TupleArityLabel implements Comparable<TupleArityLabel> {
Label cast_label = new Label();
Label target;
int arity;
public TupleArityLabel(int arity, Label target) {
this.arity = arity;
this.target = target;
}
@Override
public int compareTo(TupleArityLabel o) {
if (this.arity < o.arity)
return -1;
if (this.arity == o.arity)
return 0;
return 1;
}
}
/** Switch based on arity of incoming <code>in</code> tuple value. */
@Override
public void visitSelectTuple(Arg in, int failLabel, int[] arities,
int[] targets) {
push(in, ETUPLE_TYPE);
//if (in.type == null) {
mv.visitTypeInsn(CHECKCAST, ETUPLE_NAME);
//}
mv.visitMethodInsn(INVOKEVIRTUAL, ETUPLE_NAME, "arity", "()I");
TupleArityLabel[] cases = new TupleArityLabel[targets.length];
for (int i = 0; i < targets.length; i++) {
cases[i] = new TupleArityLabel(arities[i], getLabel(targets[i]));
}
Arrays.sort(cases);
Label[] casts = new Label[cases.length];
int[] values = new int[cases.length];
for (int i = 0; i < cases.length; i++) {
values[i] = cases[i].arity;
casts[i] = cases[i].cast_label;
}
mv.visitLookupSwitchInsn(getLabel(failLabel), values, casts);
for (int i = 0; i < cases.length; i++) {
mv.visitLabel(cases[i].cast_label);
// NOTE: unfortunately, we have to use a cast here. There
// is no real way around it, except maybe make some
// special ETuple methods for small tuple sizes?
// that is an option for future optimization of pattern match.
push(in, ETUPLE_TYPE);
mv.visitTypeInsn(CHECKCAST, getTubleType(cases[i].arity).getInternalName());
pop(in, getTubleType(cases[i].arity));
mv.visitJumpInsn(GOTO, cases[i].target);
}
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitJump(int)
*/
@Override
public void visitJump(int label) {
mv.visitJumpInsn(GOTO, getLabel(label));
}
/**
* @param i
* @return
*/
private Type getTubleType(int i) {
return Type.getType("L" + ETUPLE_NAME + i + ";");
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitCall(erjang.beam.ExtFunc,
* erjang.beam.Arg[], boolean, boolean)
*/
@Override
public void visitCall(ExtFun fun, Arg[] args, boolean is_tail,
boolean isExternal) {
ensure_exception_handler_in_place();
BuiltInFunction bif = null;
bif = BIFUtil.getMethod(fun.mod.getName(),
fun.fun.getName(), args, false, false);
if (bif != null || isExternal) {
if (bif == null) {
String field = CompilerVisitor.this
.getExternalFunction(fun);
String funTypeName = EFUN_NAME + args.length;
EFun.ensure(args.length);
mv.visitFieldInsn(GETSTATIC, self_type
.getInternalName(), field, "L" + funTypeName
+ ";");
mv.visitVarInsn(ALOAD, 0);
for (int i = 0; i < args.length; i++) {
push(args[i], EOBJECT_TYPE);
}
mv.visitMethodInsn(INVOKEVIRTUAL, funTypeName,
(is_tail && !isExitFunc(fun)) ? "invoke_tail" : "invoke", EUtil
.getSignature(args.length, true));
} else if (bif.isVirtual()) {
// System.err.println("DIRECT "+bif);
push(args[0], bif.owner);
int off = 0;
if (bif.getArgumentTypes().length > 0
&& bif.getArgumentTypes()[0].equals(EPROC_TYPE)) {
mv.visitVarInsn(ALOAD, 0);
off = 1;
}
for (int i = 1; i < args.length; i++) {
push(args[i], bif.getArgumentTypes()[off-1]);
}
mv.visitMethodInsn(INVOKEVIRTUAL, bif.owner
.getInternalName(), bif.getName(), bif
.getDescriptor());
} else {
// System.err.println("DIRECT "+bif);
int off = 0;
if (bif.getArgumentTypes().length > 0
&& bif.getArgumentTypes()[0].equals(EPROC_TYPE)) {
mv.visitVarInsn(ALOAD, 0);
off = 1;
}
for (int i = 0; i < args.length; i++) {
push(args[i], bif.getArgumentTypes()[off + i]);
}
mv.visitMethodInsn(INVOKESTATIC, bif.owner
.getInternalName(), bif.getName(), bif
.getDescriptor());
}
if (is_tail || isExitFunc(fun)) {
mv.visitInsn(ARETURN);
} else {
mv.visitVarInsn(ASTORE, xregs[0]);
}
} else {
// are we self-recursive?
if (is_tail && fun.arity == ASMFunctionAdapter.this.arity
&& fun.fun == ASMFunctionAdapter.this.fun_name) {
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKEVIRTUAL, EPROC_NAME,
"check_exit", "()V");
// System.out.println("self-recursive in " + fun);
mv.visitJumpInsn(GOTO,
getLabel(ASMFunctionAdapter.this.startLabel));
return;
}
mv.visitVarInsn(ALOAD, 0);
for (int i = 0; i < args.length; i++) {
push(args[i], EOBJECT_TYPE);
}
FunInfo target = funInfos.get(new FunID(fun.mod, fun.name(), fun.arity));
mv.visitMethodInsn(INVOKESTATIC, self_type
.getInternalName(), EUtil.getJavaName(fun.fun,
fun.arity)
+ (is_tail ? "$tail" : (target.may_return_tail_marker ? "$call" : "")), EUtil
.getSignature(args.length, true));
if (is_tail) {
mv.visitInsn(ARETURN);
} else {
mv.visitVarInsn(ASTORE, xregs[0]);
}
}
}
/**
* @param fun
* @return
*/
private boolean isExitFunc(ExtFun fun) {
if (fun.mod == ERLANG_ATOM) {
if (fun.fun == CodeAtoms.EXIT_ATOM && fun.arity==1)
return true;
if (fun.fun == CodeAtoms.ERROR_ATOM && (fun.arity==1 || fun.arity==2))
return true;
if (fun.fun == CodeAtoms.NIF_ERROR_ATOM && (fun.arity==1))
return true;
if (fun.fun == CodeAtoms.THROW_ATOM && fun.arity==1)
return true;
}
return false;
}
}
}
final static Method IS_NONEMPTY_LIST_TEST = Method
.getMethod("erjang.ECons testNonEmptyList()");
final static Method IS_LIST_TEST = Method.getMethod("erjang.ECons testCons()");
final static Method IS_TUPLE_TEST = Method.getMethod("erjang.ETuple testTuple()");
final static Method IS_INTEGER_TEST = Method
.getMethod("erjang.EInteger testInteger()");
final static Method IS_ATOM_TEST = Method.getMethod("erjang.EAtom testAtom()");
final static Method IS_FLOAT_TEST = Method
.getMethod("erjang.EDouble testFloat()");
final static Method IS_NIL_TEST = Method.getMethod("erjang.ENil testNil()");
final static Method IS_BOOLEAN_TEST = Method
.getMethod("erjang.EAtom testBoolean()");
final static Method IS_NUMBER_TEST = Method
.getMethod("erjang.ENumber testNumber()");
final static Method IS_BINARY_TEST = Method
.getMethod("erjang.EBinary testBinary()");
final static Method IS_BITSTRING_TEST = Method
.getMethod("erjang.EBitString testBitString()");
final static Method IS_PID_TEST = Method.getMethod("erjang.EPID testPID()");
final static Method IS_PORT_TEST = Method.getMethod("erjang.EPort testPort()");
final static Method IS_REFERENCE_TEST = Method.getMethod(ERef.class.getName()
+ " testReference()");
final static Method IS_FUNCTION_TEST = Method
.getMethod("erjang.EFun testFunction()");
final static Method IS_FUNCTION2_TEST = Method
.getMethod("erjang.EFun testFunction(int nargs)");
Map<String, ExtFun> imported = new HashMap<String, ExtFun>();
private Map<FunID, FunInfo> funInfos;
/**
* @param fun
* @return
*/
public String getExternalFunction(ExtFun fun) {
String name = EUtil.getJavaName(fun);
if (!imported.containsKey(name)) {
imported.put(name, fun);
}
return name;
}
static class Lambda {
private final EAtom fun;
private final int arity;
private final int freevars;
private final int index;
private final int old_index;
private final int old_uniq;
private final EBinary uniq;
public Lambda(EAtom fun, int arity, int freevars, int index, int old_index, EBinary uniq, int old_uniq) {
this.fun = fun;
this.arity = arity;
this.freevars = freevars;
this.index = index;
this.old_index = old_index;
this.uniq = uniq;
this.old_uniq = old_uniq;
}
}
/**
* @param fun
* @param arity_plus
* @param length
* @param index TODO
* @param old_index TODO
* @param uniq TODO
* @param old_uniq
*/
public void register_lambda(EAtom fun, int arity_plus, int freevars, int index, int old_index, EBinary uniq, int old_uniq) {
lambdas_xx.put(new FunID(module_name, fun, arity_plus),
new Lambda(fun, arity_plus, freevars, index, old_index, uniq, old_uniq));
}
public Lambda get_lambda_freevars(EAtom fun, int arity_plus) {
return lambdas_xx.get(new FunID(module_name, fun, arity_plus));
}
static public byte[] make_invoker(String module, String function,
Type self_type, String mname,
String fname, int arity, boolean proc, boolean exported, Lambda lambda,
Type return_type, boolean is_tail_call, final boolean is_pausable) {
int freevars = lambda==null ? 0 : lambda.freevars;
String outer_name = self_type.getInternalName();
String inner_name = "FN_" + mname;
String full_inner_name = outer_name + "$" + inner_name;
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES|ClassWriter.COMPUTE_MAXS);
int residual_arity = arity - freevars;
String super_class_name = EFUN_NAME + residual_arity +
(exported ? "Exported" : "");
if (exported) EFun.ensure_exported(residual_arity);
else EFun.ensure(residual_arity);
cw.visit(V1_6, ACC_FINAL | ACC_PUBLIC, full_inner_name, null,
super_class_name, null);
if (lambda != null) {
cw.visitField(ACC_STATIC|ACC_PUBLIC|ACC_FINAL, "index", "I", null, new Integer(lambda.index));
cw.visitField(ACC_STATIC|ACC_PUBLIC|ACC_FINAL, "old_index", "I", null, new Integer(lambda.old_index));
cw.visitField(ACC_STATIC|ACC_PUBLIC|ACC_FINAL, "old_uniq", "I", null, new Integer(lambda.old_uniq));
/** */
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "encode", "("+ Type.getDescriptor(EOutputStream.class) +")V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 1);
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, full_inner_name, "pid", EPID_TYPE.getDescriptor());
mv.visitLdcInsn(module);
mv.visitFieldInsn(GETSTATIC, full_inner_name, "old_index", "I");
mv.visitInsn(I2L);
mv.visitLdcInsn(new Integer(arity));
mv.visitFieldInsn(GETSTATIC, outer_name, "module_md5", EBINARY_TYPE.getDescriptor());
mv.visitFieldInsn(GETSTATIC, full_inner_name, "index", "I");
mv.visitInsn(I2L);
mv.visitFieldInsn(GETSTATIC, full_inner_name, "old_uniq", "I");
mv.visitInsn(I2L);
mv.visitLdcInsn(new Integer(freevars));
mv.visitTypeInsn(ANEWARRAY, EOBJECT_NAME);
for (int i = 0; i < freevars; i++) {
mv.visitInsn(DUP);
if (i <= 5) {
mv.visitInsn(ICONST_0+i);
} else {
mv.visitLdcInsn(new Integer(i));
}
mv.visitVarInsn(ALOAD, 0); // load self
mv.visitFieldInsn(GETFIELD, full_inner_name, "fv"+i, EOBJECT_DESC);
mv.visitInsn(AASTORE);
}
mv.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(EOutputStream.class), "write_fun",
"("+EPID_TYPE.getDescriptor()+"Ljava/lang/String;"
+"JI"+EBINARY_TYPE.getDescriptor()
+"JJ"+Type.getDescriptor(EObject[].class)+")V");
mv.visitInsn(RETURN);
mv.visitMaxs(10, 3);
mv.visitEnd();
}
make_constructor(cw, module, function,
full_inner_name, super_class_name, lambda, exported);
make_go_method(cw, outer_name, fname, full_inner_name, arity, proc,
freevars, return_type, is_tail_call, is_pausable);
make_go2_method(cw, outer_name, fname, full_inner_name, arity, proc,
freevars, return_type, is_tail_call, is_pausable);
return cw.toByteArray();
}
private static void make_constructor(ClassWriter cw,
String module_name, String function_name,
String full_inner_name, String super_class_name, Lambda lambda, boolean exported) {
StringBuilder sb = new StringBuilder("(");
int freevars = lambda==null?0:lambda.freevars;
if (lambda != null) {
sb.append(EPID_TYPE.getDescriptor());
cw.visitField(ACC_PUBLIC|ACC_FINAL, "pid", EPID_TYPE.getDescriptor(), null, null);
}
// create the free vars
for (int i = 0; i < freevars; i++) {
cw.visitField(ACC_PUBLIC | ACC_FINAL, "fv" + i, EOBJECT_DESC,
null, null);
sb.append(EOBJECT_DESC);
}
sb.append(")V");
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", sb.toString(),
null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
if (exported) {
mv.visitLdcInsn(module_name);
mv.visitLdcInsn(function_name);
mv.visitMethodInsn(INVOKESPECIAL, super_class_name, "<init>", "(Ljava/lang/String;Ljava/lang/String;)V");
} else {
mv.visitMethodInsn(INVOKESPECIAL, super_class_name, "<init>", "()V");
}
if (lambda != null) {
mv.visitVarInsn(ALOAD, 0);
mv.visitVarInsn(ALOAD, 1);
mv.visitFieldInsn(PUTFIELD, full_inner_name, "pid",
EPID_TYPE.getDescriptor());
}
for (int i = 0; i < freevars; i++) {
mv.visitVarInsn(ALOAD, 0);
mv.visitVarInsn(ALOAD, i + 2);
mv
.visitFieldInsn(PUTFIELD, full_inner_name, "fv" + i,
EOBJECT_DESC);
}
mv.visitInsn(RETURN);
mv.visitMaxs(3, 3);
mv.visitEnd();
if (lambda != null) {
mv = cw.visitMethod(ACC_PROTECTED, "get_env", "()"+ESEQ_DESC, null, null);
mv.visitCode();
mv.visitFieldInsn(GETSTATIC, ERT_NAME, "NIL", ENIL_TYPE.getDescriptor());
for (int i = freevars-1; i >= 0; i--) {
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, full_inner_name, "fv"+i, EOBJECT_DESC);
mv.visitMethodInsn(INVOKEVIRTUAL, ESEQ_NAME, "cons", "("+EOBJECT_DESC+")"+ESEQ_DESC);
}
mv.visitInsn(ARETURN);
mv.visitMaxs(3, 3);
mv.visitEnd();
mv = cw.visitMethod(ACC_PROTECTED, "get_pid", "()"+EOBJECT_DESC, null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, full_inner_name, "pid", EPID_TYPE.getDescriptor());
mv.visitInsn(ARETURN);
mv.visitMaxs(3, 3);
mv.visitEnd();
mv = cw.visitMethod(ACC_PROTECTED, "get_id", "()"+Type.getDescriptor(FunID.class), null, null);
mv.visitCode();
mv.visitFieldInsn(GETSTATIC, full_inner_name.substring(0, full_inner_name.indexOf('$')),
anon_fun_name(lambda), Type.getDescriptor(LocalFunID.class));
mv.visitInsn(ARETURN);
mv.visitMaxs(3, 3);
mv.visitEnd();
}
}
private static void make_invoke_method(ClassWriter cw, String outer_name,
String mname, int arity, boolean proc, int freevars, Type returnType, boolean isTailCall) {
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "invoke", EUtil
.getSignature(arity - freevars, true), null, PAUSABLE_EX);
mv.visitCode();
if (proc) {
mv.visitVarInsn(ALOAD, 1);
}
for (int i = 0; i < arity - freevars; i++) {
mv.visitVarInsn(ALOAD, i + 2);
}
for (int i = 0; i < freevars; i++) {
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, outer_name + "$FN_" + mname, "fv" + i,
EOBJECT_DESC);
}
mv.visitMethodInsn(INVOKESTATIC, outer_name, mname, EUtil.getSignature(
arity, proc, returnType));
if (isTailCall) {
mv.visitVarInsn(ASTORE, arity + 2);
Label done = new Label();
Label loop = new Label();
mv.visitLabel(loop);
mv.visitVarInsn(ALOAD, arity + 2);
if (EProc.TAIL_MARKER == null) {
mv.visitJumpInsn(IFNONNULL, done);
} else {
mv.visitFieldInsn(GETSTATIC, EPROC_NAME, "TAIL_MARKER", EOBJECT_DESC);
mv.visitJumpInsn(IF_ACMPNE, done);
}
// load proc
mv.visitVarInsn(ALOAD, 1);
mv.visitFieldInsn(GETFIELD, EPROC_NAME, "tail", EFUN_DESCRIPTOR);
mv.visitVarInsn(ALOAD, 1);
mv.visitMethodInsn(INVOKEVIRTUAL, EFUN_NAME, "go", GO_DESC);
mv.visitVarInsn(ASTORE, arity + 2);
mv.visitJumpInsn(GOTO, loop);
mv.visitLabel(done);
mv.visitVarInsn(ALOAD, arity + 2);
}
mv.visitInsn(ARETURN);
mv.visitMaxs(arity + 2, arity + 2);
mv.visitEnd();
}
public static void make_invoketail_method(ClassWriter cw,
String full_inner, int arity, int freevars) {
MethodVisitor mv;
mv = cw.visitMethod(ACC_PUBLIC|ACC_FINAL, "invoke_tail", EUtil.getSignature(arity
- freevars, true), null, null);
mv.visitCode();
for (int i = 0; i < arity - freevars; i++) {
mv.visitVarInsn(ALOAD, 1);
mv.visitVarInsn(ALOAD, i + 2);
mv.visitFieldInsn(PUTFIELD, EPROC_NAME, "arg" + i, EOBJECT_DESC);
}
mv.visitVarInsn(ALOAD, 1);
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(PUTFIELD, EPROC_NAME, "tail", EFUN_DESCRIPTOR);
if (EProc.TAIL_MARKER == null) {
mv.visitInsn(ACONST_NULL);
} else {
mv.visitFieldInsn(GETSTATIC, EPROC_NAME, "TAIL_MARKER", EOBJECT_DESC);
}
mv.visitInsn(ARETURN);
mv.visitMaxs(arity + 2, arity + 2);
mv.visitEnd();
}
private static void make_go_method(ClassWriter cw, String outer_name,
String mname, String full_inner, int arity, boolean proc,
int freevars, Type returnType, boolean isTailCall, boolean isPausable) {
if (!isPausable) return;
MethodVisitor mv;
mv = cw.visitMethod(ACC_PUBLIC, "go", GO_DESC, null, PAUSABLE_EX);
mv.visitCode();
for (int i = 0; i < arity - freevars; i++) {
mv.visitVarInsn(ALOAD, 1);
mv.visitFieldInsn(GETFIELD, EPROC_NAME, "arg" + i, EOBJECT_DESC);
mv.visitVarInsn(ASTORE, i + 2);
}
for (int i = 0; i < arity - freevars; i++) {
mv.visitVarInsn(ALOAD, 1);
mv.visitInsn(ACONST_NULL);
mv.visitFieldInsn(PUTFIELD, EPROC_NAME, "arg" + i, EOBJECT_DESC);
}
if (proc)
mv.visitVarInsn(ALOAD, 1);
for (int i = 0; i < arity - freevars; i++) {
mv.visitVarInsn(ALOAD, i + 2);
}
for (int i = 0; i < freevars; i++) {
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, full_inner, "fv" + i, EOBJECT_DESC);
}
mv.visitMethodInsn(INVOKESTATIC, outer_name, mname, EUtil.getSignature(
arity, proc, returnType));
mv.visitInsn(ARETURN);
mv.visitMaxs(arity + 2, arity + 2);
mv.visitEnd();
cw.visitEnd();
}
private static void make_go2_method(ClassWriter cw, String outer_name,
String mname, String full_inner, int arity, boolean proc,
int freevars, Type returnType, boolean isTailCall, boolean isPausable) {
if (isPausable) {
if (ModuleAnalyzer.log.isLoggable(Level.FINE)) {
ModuleAnalyzer.log.fine
("not generating go2 (pausable) for "+full_inner);
}
return;
}
MethodVisitor mv;
mv = cw.visitMethod(ACC_PUBLIC, "go2", GO_DESC, null, null);
mv.visitCode();
for (int i = 0; i < arity - freevars; i++) {
mv.visitVarInsn(ALOAD, 1);
mv.visitFieldInsn(GETFIELD, EPROC_NAME, "arg" + i, EOBJECT_DESC);
mv.visitVarInsn(ASTORE, i + 2);
}
for (int i = 0; i < arity - freevars; i++) {
mv.visitVarInsn(ALOAD, 1);
mv.visitInsn(ACONST_NULL);
mv.visitFieldInsn(PUTFIELD, EPROC_NAME, "arg" + i, EOBJECT_DESC);
}
if (proc)
mv.visitVarInsn(ALOAD, 1);
for (int i = 0; i < arity - freevars; i++) {
mv.visitVarInsn(ALOAD, i + 2);
}
for (int i = 0; i < freevars; i++) {
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, full_inner, "fv" + i, EOBJECT_DESC);
}
mv.visitMethodInsn(INVOKESTATIC, outer_name, mname, EUtil.getSignature(
arity, proc, returnType));
mv.visitInsn(ARETURN);
mv.visitMaxs(arity + 2, arity + 2);
mv.visitEnd();
cw.visitEnd();
}
public void setFunInfos(Map<FunID, FunInfo> funInfos) {
this.funInfos = funInfos;
}
}
/** Active exception handler */
class EXHandler {
int handler_beam_label;
Label begin, end, target;
BeamExceptionHandler beam_exh;
}
| src/main/java/erjang/beam/CompilerVisitor.java | /**
* This file is part of Erjang - A JVM-based Erlang VM
*
* Copyright (c) 2009 by Trifork
*
* 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 erjang.beam;
import static erjang.beam.CodeAtoms.ERLANG_ATOM;
import static erjang.beam.CodeAtoms.FALSE_ATOM;
import static erjang.beam.CodeAtoms.TRUE_ATOM;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import kilim.Pausable;
import kilim.analysis.ClassInfo;
import kilim.analysis.ClassWeaver;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.Method;
import com.trifork.clj_ds.IPersistentCollection;
import erjang.EAtom;
import erjang.EBinMatchState;
import erjang.EBinary;
import erjang.EBitString;
import erjang.EBitStringBuilder;
import erjang.ECons;
import erjang.EDouble;
import erjang.EFun;
import erjang.EInteger;
import erjang.EBig;
import erjang.EInternalPID;
import erjang.EList;
import erjang.EModuleManager;
import erjang.ENil;
import erjang.ENumber;
import erjang.EObject;
import erjang.EOutputStream;
import erjang.EPID;
import erjang.EPort;
import erjang.EProc;
import erjang.ERT;
import erjang.ERef;
import erjang.ESeq;
import erjang.ESmall;
import erjang.EString;
import erjang.ETuple;
import erjang.ETuple2;
import erjang.ErlangException;
import erjang.Export;
import erjang.FunID;
import erjang.Import;
import erjang.LocalFunID;
import erjang.Module;
import erjang.beam.Arg.Kind;
import erjang.beam.ModuleAnalyzer.FunInfo;
import erjang.beam.repr.ExtFun;
import erjang.beam.repr.Insn;
import erjang.m.erlang.ErlBif;
/**
*
*/
public class CompilerVisitor implements ModuleVisitor, Opcodes {
public static boolean PARANOIA_MODE = false;
// a select ins with up to this many cases that are all
// atom values is just encoded as an if-then-else-etc.
public static final int ATOM_SELECT_IF_ELSE_LIMIT = 4;
EAtom am_source = EAtom.intern("source");
ECons atts = ERT.NIL;
ECons compile_info = ERT.NIL;
String source = null;
private Set<String> exported = new HashSet<String>();
private final ClassVisitor cv;
private EAtom module_name;
private Type self_type;
private static final EObject ATOM_field_flags = EAtom.intern("field_flags");
private static final EObject ATOM_start = EAtom.intern("start");
static final String[] PAUSABLE_EX = new String[] { Type.getType(
Pausable.class).getInternalName() };
static final Type EBINMATCHSTATE_TYPE = Type.getType(EBinMatchState.class);
static final Type EBINSTRINGBUILDER_TYPE = Type
.getType(EBitStringBuilder.class);
static final Type ERLANG_EXCEPTION_TYPE = Type
.getType(ErlangException.class);
static final Type ERT_TYPE = Type.getType(ERT.class);
static final Type EINTEGER_TYPE = Type.getType(EInteger.class);
static final Type ESTRING_TYPE = Type.getType(EString.class);
static final Type ECOMPILEDMODULE_TYPE = Type.getType(ECompiledModule.class);
/**
*
*/
static final String ECOMPILEDMODULE_NAME = ECOMPILEDMODULE_TYPE.getInternalName();
static final Type ENUMBER_TYPE = Type.getType(ENumber.class);
static final Type EOBJECT_TYPE = Type.getType(EObject.class);
static final String EOBJECT_DESC = EOBJECT_TYPE.getDescriptor();
static final Type EPROC_TYPE = Type.getType(EProc.class);
static final String EPROC_NAME = EPROC_TYPE.getInternalName();
static final String EPROC_DESC = EPROC_TYPE.getDescriptor();
static final Type ESMALL_TYPE = Type.getType(ESmall.class);
static final String ESMALL_NAME = ESMALL_TYPE.getInternalName();
static final Type EEXCEPTION_TYPE = Type.getType(ErlangException.class);
static final String EEXCEPTION_DESC = EEXCEPTION_TYPE.getDescriptor();
/**/
static final String GO_DESC = "(" + EPROC_TYPE.getDescriptor() + ")"
+ EOBJECT_DESC;
static final Type EDOUBLE_TYPE = Type.getType(EDouble.class);
static final Type EBIG_TYPE = Type.getType(EBig.class);
static final Type ENIL_TYPE = Type.getType(ENil.class);
static final Type EATOM_TYPE = Type.getType(EAtom.class);
static final Type ETUPLE_TYPE = Type.getType(ETuple.class);
static final Type EBINARY_TYPE = Type.getType(EBinary.class);
static final Type EBITSTRING_TYPE = Type.getType(EBitString.class);
static final Type EBITSTRINGBUILDER_TYPE = Type
.getType(EBitStringBuilder.class);
static final Type ECONS_TYPE = Type.getType(ECons.class);
static final Type ESEQ_TYPE = Type.getType(ESeq.class);
static final Type ELIST_TYPE = Type.getType(EList.class);
static final Type EFUN_TYPE = Type.getType(EFun.class);
/**
*
*/
static final String EFUN_NAME = EFUN_TYPE.getInternalName();
static final String EOBJECT_NAME = EOBJECT_TYPE.getInternalName();
static final String ETUPLE_NAME = ETUPLE_TYPE.getInternalName();
static final String ERT_NAME = ERT_TYPE.getInternalName();
static final String EDOUBLE_NAME = EDOUBLE_TYPE.getInternalName();
static final String EBIG_NAME = EBIG_TYPE.getInternalName();
static final String EINTEGER_NAME = EINTEGER_TYPE.getInternalName();
static final String ENIL_NAME = ENIL_TYPE.getInternalName();
static final String ESEQ_NAME = ESEQ_TYPE.getInternalName();
static final String ETUPLE_DESC = ETUPLE_TYPE.getDescriptor();
static final String EATOM_DESC = EATOM_TYPE.getDescriptor();
static final String ECONS_DESC = ECONS_TYPE.getDescriptor();
static final String ESEQ_DESC = ESEQ_TYPE.getDescriptor();
/**
*
*/
static final String EFUN_DESCRIPTOR = EFUN_TYPE.getDescriptor();
static final Type EPID_TYPE = Type.getType(EPID.class);
static final Type EPORT_TYPE = Type.getType(EPort.class);
static final Type EMATCHSTATE_TYPE = Type.getType(EBinMatchState.class);
static final Type MODULE_ANN_TYPE = Type.getType(Module.class);
static final Type IMPORT_ANN_TYPE = Type.getType(Import.class);
static final Type EXPORT_ANN_TYPE = Type.getType(Export.class);
private final ClassRepo classRepo;
/**
* @param classRepo
*
*/
public CompilerVisitor(ClassVisitor cv, ClassRepo classRepo) {
this.cv = cv;
this.classRepo = classRepo;
}
/*
* (non-Javadoc)
*
* @see erjang.beam.ModuleVisitor#visitModule(erjang.EAtom)
*/
@Override
public void visitModule(EAtom name) {
this.module_name = name;
this.self_type = Type.getType("L" + getInternalClassName() + ";");
cv.visit(V1_6, ACC_PUBLIC, self_type.getInternalName(), null,
ECOMPILEDMODULE_NAME, null);
add_module_annotation(cv);
}
private void add_module_annotation(ClassVisitor cv) {
AnnotationVisitor av = cv.visitAnnotation(MODULE_ANN_TYPE
.getDescriptor(), true);
av.visit("value", getModuleName());
av.visitEnd();
}
public String getInternalClassName() {
String moduleName = getModuleName();
return Compiler.moduleClassName(moduleName);
}
/**
* @return
*/
private String getModuleName() {
return module_name.getName();
}
Map<EObject, String> constants = new HashMap<EObject, String>();
/*
* (non-Javadoc)
*
* @see erjang.beam.ModuleVisitor#visitAttribute(erjang.EAtom,
* erjang.EObject)
*/
@Override
public void visitAttribute(EAtom att, EObject value) {
atts = atts.cons(ETuple2.make(att, value));
}
@Override
public void visitCompile(EAtom att, EObject value) {
EString string;
if (att == am_source && (string = value.testString()) != null) {
source = string.stringValue();
}
compile_info = compile_info.cons(ETuple2.make(att, value));
}
String source() {
if (source == null) {
return module_name.getName() + ".erl";
} else {
int idx = source.lastIndexOf('/');
if (idx == -1) {
return source;
} else {
return source.substring(idx+1);
}
}
}
/*
* (non-Javadoc)
*
* @see erjang.beam.ModuleVisitor#visitEnd()
*/
@Override
public void visitEnd() {
cv.visitSource(source(), null);
// wow, this is where we generate <clinit>
for (Map.Entry<String, ExtFun> ent : imported.entrySet()) {
String field_name = ent.getKey();
ExtFun f = ent.getValue();
FieldVisitor fv = cv.visitField(ACC_STATIC, ent.getKey(), "L"
+ EFUN_NAME + f.arity + ";", null, null);
EFun.ensure(f.arity);
AnnotationVisitor av = fv.visitAnnotation(IMPORT_ANN_TYPE
.getDescriptor(), true);
av.visit("module", f.mod.getName());
av.visit("fun", f.fun.getName());
av.visit("arity", f.arity);
av.visitEnd();
fv.visitEnd();
}
generate_classinit();
cv.visitEnd();
}
/**
*
*/
private void generate_classinit() {
MethodVisitor mv = cv.visitMethod(ACC_STATIC | ACC_PRIVATE, "<clinit>",
"()V", null, null);
mv.visitCode();
for (Map.Entry<String, String> ent : funs.entrySet()) {
String field = ent.getKey();
String clazz = ent.getValue();
mv.visitTypeInsn(NEW, clazz);
mv.visitInsn(DUP);
mv.visitMethodInsn(INVOKESPECIAL, clazz, "<init>", "()V");
mv.visitFieldInsn(PUTSTATIC, self_type.getInternalName(), field,
"L" + funt.get(field) + ";");
}
for (Map.Entry<EObject, String> ent : constants.entrySet()) {
EObject term = ent.getKey();
term.emit_const(mv);
mv.visitFieldInsn(Opcodes.PUTSTATIC, self_type.getInternalName(),
ent.getValue(), Type.getType(term.getClass())
.getDescriptor());
}
cv.visitField(ACC_STATIC|ACC_PRIVATE,
"attributes", ESEQ_TYPE.getDescriptor(), null, null);
atts.emit_const(mv);
mv.visitFieldInsn(Opcodes.PUTSTATIC, self_type.getInternalName(),
"attributes", ESEQ_TYPE.getDescriptor());
cv.visitField(ACC_STATIC|ACC_PRIVATE,
"compile", ESEQ_TYPE.getDescriptor(), null, null);
compile_info.emit_const(mv);
mv.visitFieldInsn(Opcodes.PUTSTATIC, self_type.getInternalName(),
"compile", ESEQ_TYPE.getDescriptor());
if (this.module_md5 != null) {
cv.visitField(ACC_STATIC, "module_md5", EBINARY_TYPE.getDescriptor(), null, null);
module_md5.emit_const(mv);
mv.visitFieldInsn(PUTSTATIC, self_type.getInternalName(), "module_md5", EBINARY_TYPE.getDescriptor());
}
mv.visitInsn(RETURN);
mv.visitMaxs(200, 10);
mv.visitEnd();
// make the method module_name
mv = cv.visitMethod(ACC_PROTECTED, "module_name",
"()Ljava/lang/String;", null, null);
mv.visitCode();
mv.visitLdcInsn(this.module_name.getName());
mv.visitInsn(ARETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
// make the method attributes
mv = cv.visitMethod(ACC_PROTECTED, "attributes",
"()" + ESEQ_TYPE.getDescriptor(), null, null);
mv.visitCode();
mv.visitFieldInsn(Opcodes.GETSTATIC, self_type.getInternalName(), "attributes",
ESEQ_TYPE.getDescriptor());
mv.visitInsn(ARETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
// make the method attributes
mv = cv.visitMethod(ACC_PROTECTED, "compile",
"()" + ESEQ_TYPE.getDescriptor(), null, null);
mv.visitCode();
mv.visitFieldInsn(Opcodes.GETSTATIC, self_type.getInternalName(), "compile",
ESEQ_TYPE.getDescriptor());
mv.visitInsn(ARETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
// make default constructor
mv = cv.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, ECOMPILEDMODULE_NAME, "<init>", "()V");
mv.visitInsn(RETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
mv = cv.visitMethod(ACC_PUBLIC, "registerImportsAndExports", "()V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, ECOMPILEDMODULE_NAME, "registerImportsAndExports", "()V");
for (Lambda l : lambdas_xx.values() ) {
mv.visitTypeInsn(NEW, Type.getInternalName(LocalFunID.class));
mv.visitInsn(DUP);
module_name.emit_const(mv);
l.fun.emit_const(mv);
push_int(mv, l.arity);
push_int(mv, l.old_index);
push_int(mv, l.index);
push_int(mv, l.old_uniq);
mv.visitFieldInsn(GETSTATIC, self_type.getInternalName(), "module_md5", EBINARY_TYPE.getDescriptor());
mv.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(LocalFunID.class), "<init>",
"("+EATOM_DESC+EATOM_DESC+"IIII"+EBINARY_TYPE.getDescriptor()+")V"
);
mv.visitInsn(DUP);
cv.visitField(ACC_STATIC, anon_fun_name(l), Type.getDescriptor(LocalFunID.class), null, null).visitEnd();
mv.visitFieldInsn(PUTSTATIC, self_type.getInternalName(), anon_fun_name(l), Type.getDescriptor(LocalFunID.class));
String mname = EUtil.getJavaName(l.fun, l.arity-l.freevars);
String outer_name = self_type.getInternalName();
String inner_name = "FN_" + mname;
String full_inner_name = outer_name + "$" + inner_name;
mv.visitLdcInsn(full_inner_name.replace('/', '.'));
mv.visitMethodInsn(INVOKESTATIC, Type.getInternalName(Class.class), "forName",
"(Ljava/lang/String;)Ljava/lang/Class;");
mv.visitMethodInsn(INVOKESTATIC, Type.getInternalName(EModuleManager.class), "register_lambda",
"(" + Type.getDescriptor(LocalFunID.class)
+ Type.getDescriptor(Class.class) + ")V");
}
mv.visitInsn(RETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
}
public static String anon_fun_name(Lambda l) {
return "lambda_"+l.index+"_"+l.old_index+"_"+l.old_uniq;
}
private void push_int(MethodVisitor mv, int val) {
if (val == -1) {
mv.visitInsn(ICONST_M1);
} else if (val >= 0 && val <= 5) {
mv.visitInsn(ICONST_0+val);
} else {
mv.visitLdcInsn(new Integer(val));
}
}
/*
* (non-Javadoc)
*
* @see erjang.beam.ModuleVisitor#visitExport(erjang.EAtom, int, int)
*/
@Override
public void visitExport(EAtom name, int arity, int entry) {
exported.add(EUtil.getJavaName(name, arity));
}
boolean isExported(EAtom name, int arity) {
return exported.contains(EUtil.getJavaName(name, arity));
}
@Override
public void declareFunction(EAtom fun, int arity, int label) {
/* ignore */
}
@Override
public FunctionVisitor visitFunction(EAtom name, int arity, int startLabel) {
return new ASMFunctionAdapter(name, arity, startLabel);
}
Map<FunID, Lambda> lambdas_xx = new TreeMap<FunID, Lambda>();
Map<String, String> funs = new HashMap<String, String>();
Map<String, String> funt = new HashMap<String, String>();
Set<String> non_pausable_methods = new HashSet<String>();
public EBinary module_md5;
private static final String SEQ_CONS_SIG = "(" + EOBJECT_DESC + ")"
+ ESEQ_DESC;
private static final String FUNC_INFO_SIG = "(" + EATOM_DESC + EATOM_DESC + ESEQ_DESC +")"
+ EOBJECT_DESC;
private static final String ERT_CONS_SIG = "(" + EOBJECT_DESC + EOBJECT_DESC + ")"
+ ECONS_TYPE.getDescriptor();
private static final String TEST_FUN_SIG ="(" + EOBJECT_DESC + EFUN_DESCRIPTOR + ")V";
class ASMFunctionAdapter implements FunctionVisitor2 {
private final EAtom fun_name;
private final int arity;
private final int startLabel;
Map<Integer, Label> labels = new TreeMap<Integer, Label>();
Map<Integer, Label> ex_handler_labels = new TreeMap<Integer, Label>();
Set<Integer> label_inserted = new TreeSet<Integer>();
List<EXHandler> ex_handlers = new ArrayList<EXHandler>();
EXHandler activeExceptionHandler;
BeamExceptionHandler active_beam_exh;
private boolean isTailRecursive;
private MethodVisitor mv;
private int[] xregs;
private int[] yregs;
private int[] fpregs;
private Label start;
private Label end;
private int scratch_reg;
private int bit_string_builder;
private int bit_string_matcher;
private int bit_string_save;
private FunInfo funInfo;
private Collection<Integer> deadBlocks;
Label getLabel(int i) {
if (i <= 0)
throw new Error();
Label l = labels.get(i);
if (l == null) {
labels.put(i, l = new Label());
}
return l;
}
Label getExceptionHandlerLabel(BeamExceptionHandler exh) {
int i = exh.getHandlerLabel();
Label l = ex_handler_labels.get(i);
if (l == null) {
ex_handler_labels.put(i, l = new Label());
}
return l;
}
/**
* @param name
* @param arity
* @param startLabel
* @param isTailRecursive
*/
public ASMFunctionAdapter(EAtom name, int arity, int startLabel) {
this.fun_name = name;
this.arity = arity;
this.startLabel = startLabel;
}
@Override
public void visitMaxs(Collection<Integer> x_regs, int y_count, int fp_count,
boolean isTailRecursive, Collection<Integer> dead_blocks) {
FunID me = new FunID(module_name, fun_name, arity);
this.funInfo = funInfos.get(me);
this.isTailRecursive = isTailRecursive;
this.deadBlocks = dead_blocks;
Lambda lambda = get_lambda_freevars(fun_name, arity);
final int freevars =
lambda == null
? 0
: lambda.freevars;
int real_arity = arity-freevars;
String javaName = EUtil.getJavaName(fun_name, real_arity);
String signature = EUtil.getSignature(arity, true);
mv = cv.visitMethod(ACC_STATIC | ACC_PUBLIC, javaName, signature,
null, funInfo.is_pausable ? PAUSABLE_EX : null);
if (!funInfo.is_pausable) {
non_pausable_methods.add(javaName);
}
this.start = new Label();
this.end = new Label();
mv.visitCode();
allocate_regs_to_locals(x_regs, y_count, fp_count);
mv.visitLabel(start);
mv.visitJumpInsn(GOTO, getLabel(startLabel));
}
/*
* (non-Javadoc)
*
* @see erjang.beam.FunctionVisitor#visitEnd()
*/
@Override
public void visitEnd() {
adjust_exception_handlers(null, false);
mv.visitLabel(end);
for (EXHandler h : ex_handlers) {
if (! label_inserted.contains(h.handler_beam_label))
throw new InternalError("Exception handler not inserted: "+h.handler_beam_label);
if (deadBlocks.contains(h.handler_beam_label)) {
System.out.println("skipping dead ex handler "+ fun_name + ", label #"+h.handler_beam_label);
continue;
}
mv.visitTryCatchBlock(h.begin, h.end, h.target,
Type.getType(ErlangException.class).getInternalName());
}
mv.visitMaxs(20, scratch_reg + 3);
mv.visitEnd();
int arity_plus = arity;
Lambda lambda = get_lambda_freevars(fun_name, arity_plus);
final int freevars =
lambda == null
? 0
: lambda.freevars;
int real_arity = arity_plus-freevars;
String mname = EUtil.getJavaName(fun_name, real_arity);
String outer_name = self_type.getInternalName();
String inner_name = "FN_" + mname;
String full_inner_name = outer_name + "$" + inner_name;
boolean make_fun = false;
boolean is_exported = isExported(fun_name, arity);
if (lambda != null) {
CompilerVisitor.this.module_md5 = lambda.uniq;
make_fun = true;
} else {
if (funInfo.is_called_locally_in_nontail_position)
generate_invoke_call_self();
if (funInfo.is_called_locally_in_tail_position)
generate_tail_call_self(full_inner_name);
if (funInfo.mustHaveFun()) {
FieldVisitor fv = cv.visitField(ACC_STATIC | ACC_FINAL, mname,
"L" + full_inner_name + ";", null, null);
EFun.ensure(arity);
if (is_exported) {
if (ModuleAnalyzer.log.isLoggable(Level.FINE))
ModuleAnalyzer.log.fine("export " + module_name + ":"
+ fun_name + "/" + arity);
AnnotationVisitor an = fv.visitAnnotation(EXPORT_ANN_TYPE
.getDescriptor(), true);
an.visit("module", module_name.getName());
an.visit("fun", fun_name.getName());
an.visit("arity", new Integer(arity));
an.visitEnd();
}
fv.visitEnd();
funs.put(mname, full_inner_name);
funt.put(mname, full_inner_name);
EFun.ensure(arity);
make_fun = true;
}
}
if (make_fun) {
cv.visitInnerClass(full_inner_name, outer_name, inner_name,
ACC_STATIC);
byte[] data = CompilerVisitor.make_invoker(module_name.getName(), fun_name.getName(), self_type, mname, mname,
arity, true, is_exported, lambda, EOBJECT_TYPE, funInfo.may_return_tail_marker, funInfo.is_pausable|funInfo.call_is_pausable);
ClassWeaver w = new ClassWeaver(data, new Compiler.ErjangDetector(
self_type.getInternalName(), non_pausable_methods));
w.weave();
if (w.getClassInfos().size() == 0) { // Class did not need weaving
try {
classRepo.store(full_inner_name, data);
} catch (IOException e) {
e.printStackTrace();
}
} else {
for (ClassInfo ci : w.getClassInfos()) {
try {
// System.out.println("> storing "+ci.className);
String iname = ci.className.replace('.', '/');
classRepo.store(iname, ci.bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
private void ensure_exception_handler_in_place() {
adjust_exception_handlers(active_beam_exh, false);
}
private void adjust_exception_handlers(BeamExceptionHandler exh, boolean expectChange) {
int desiredLabel = exh==null ? -1
: exh.getHandlerLabel();
int actualLabel = activeExceptionHandler==null ? -1
: activeExceptionHandler.handler_beam_label;
if (expectChange) assert(actualLabel != desiredLabel);
if (actualLabel != desiredLabel) {
// Terminate the old handler block:
if (activeExceptionHandler != null) {
mv.visitLabel(activeExceptionHandler.end);
activeExceptionHandler = null;
}
//...and begin a new if necessary:
if (exh != null) {
EXHandler h = new EXHandler();
h.begin = new Label();
h.end = new Label();
h.target = getExceptionHandlerLabel(exh);
h.handler_beam_label = exh.getHandlerLabel();
h.beam_exh = exh;
ex_handlers.add(h);
mv.visitLabel(h.begin);
// mv.visitInsn(NOP); // To avoid potentially-empty exception block; Kilim can't handle those.
activeExceptionHandler = h;
}
}
}
/**
*
*/
private void generate_invoke_call_self() {
boolean pausable = funInfo.is_pausable || funInfo.call_is_pausable;
String javaName = EUtil.getJavaName(fun_name, arity);
String signature = EUtil.getSignature(arity, true);
mv = cv.visitMethod(ACC_STATIC, javaName + "$call", signature,
null, pausable ? PAUSABLE_EX : null);
mv.visitCode();
if (!pausable) {
non_pausable_methods.add(javaName + "$call");
}
// if (isTailRecursive) {
mv.visitVarInsn(ALOAD, 0);
for (int i = 0; i < arity; i++) {
mv.visitVarInsn(ALOAD, i + 1);
}
mv.visitMethodInsn(INVOKESTATIC, self_type.getInternalName(),
javaName, EUtil.getSignature(arity, true));
if (funInfo.may_return_tail_marker) {
mv.visitVarInsn(ASTORE, arity + 1);
Label done = new Label();
Label loop = new Label();
mv.visitLabel(loop);
mv.visitVarInsn(ALOAD, arity + 1);
if (EProc.TAIL_MARKER == null) {
mv.visitJumpInsn(IFNONNULL, done);
} else {
mv.visitFieldInsn(GETSTATIC, EPROC_NAME, "TAIL_MARKER",
EOBJECT_DESC);
mv.visitJumpInsn(IF_ACMPNE, done);
}
// load proc
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, EPROC_NAME, "tail", EFUN_DESCRIPTOR);
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKEVIRTUAL, EFUN_NAME, (pausable ? "go" : "go2"), GO_DESC);
mv.visitVarInsn(ASTORE, arity + 1);
mv.visitJumpInsn(GOTO, loop);
mv.visitLabel(done);
mv.visitVarInsn(ALOAD, arity + 1);
}
mv.visitInsn(ARETURN);
mv.visitMaxs(arity + 2, arity + 2);
mv.visitEnd();
}
/**
* @param full_inner_name TODO
*
*/
private void generate_tail_call_self(String full_inner_name) {
String javaName = EUtil.getJavaName(fun_name, arity);
String signature = EUtil.getSignature(arity, true);
mv = cv.visitMethod(ACC_STATIC, javaName + "$tail", signature,
null, null);
mv.visitCode();
// if (isTailRecursive) {
for (int i = 0; i < arity; i++) {
mv.visitVarInsn(ALOAD, 0);
mv.visitVarInsn(ALOAD, i + 1);
mv
.visitFieldInsn(PUTFIELD, EPROC_NAME, "arg" + i,
EOBJECT_DESC);
}
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETSTATIC, self_type.getInternalName(), javaName,
"L" + full_inner_name + ";");
mv.visitFieldInsn(PUTFIELD, EPROC_NAME, "tail", EFUN_DESCRIPTOR);
if (EProc.TAIL_MARKER == null) {
mv.visitInsn(ACONST_NULL);
} else {
mv.visitFieldInsn(GETSTATIC, EPROC_NAME, "TAIL_MARKER",
EOBJECT_DESC);
}
/*
* } else { for (int i = 0; i < arity + 1; i++) {
* mv.visitVarInsn(ALOAD, i); }
*
* mv.visitMethodInsn(INVOKESTATIC, self_type.getInternalName(),
* javaName, signature); }
*/
mv.visitInsn(ARETURN);
mv.visitMaxs(arity + 2, arity + 2);
mv.visitEnd();
}
/**
* @param xCount
* @param yCount
* @param fpCount
*/
private void allocate_regs_to_locals(Collection<Integer> xRegs, int yCount, int fpCount) {
int max_y = yCount;
int max_f = fpCount;
int local = 1;
Integer[] xxregs = xRegs.toArray(new Integer[xRegs.size()]);
if (xxregs.length > 0) {
Arrays.sort(xxregs);
Integer biggest_used = xxregs[ xxregs.length - 1 ];
xregs = new int[biggest_used+1];
for (int i = 0; i < xxregs.length; i++) {
xregs[xxregs[i]] = i+local;
}
local += xxregs.length;
}
yregs = new int[max_y];
for (int i = 0; i < max_y; i++) {
// mv.visitLocalVariable("Y" + i, EOBJECT_DESCRIPTOR,
// null, start, end, local);
yregs[i] = local;
local += 1;
}
fpregs = new int[max_f];
for (int i = 0; i < max_f; i++) {
// mv.visitLocalVariable("F" + i,
// Type.DOUBLE_TYPE.getDescriptor(), null, start, end,
// local);
fpregs[i] = local;
local += 2;
}
this.bit_string_builder = local++;
this.bit_string_matcher = local++;
this.bit_string_save = local++;
this.scratch_reg = local;
}
/*
* (non-Javadoc)
*
* @see erjang.beam.FunctionVisitor#visitLabeledBlock(int)
*/
@Override
public BlockVisitor visitLabeledBlock(int label) {
Label blockLabel = getLabel(label);
mv.visitLabel(blockLabel);
label_inserted.add(label);
// mv.visitLineNumber(label & 0x7fff, blockLabel);
return new ASMBlockVisitor(label);
}
class ASMBlockVisitor implements BlockVisitor2 {
final int beam_label;
public ASMBlockVisitor(int beam_label) {this.beam_label=beam_label;}
@Override
public void visitBegin(BeamExceptionHandler exh) {
active_beam_exh = exh;
if (exh==null || (exh.getHandlerLabel() != beam_label)) {
adjust_exception_handlers(exh, false);
mv.visitInsn(NOP);
}
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitBSAdd(erjang.beam.Arg[],
* erjang.beam.Arg)
*/
@Override
public void visitBSAdd(Arg in1, Arg in2, int scale, Arg out) {
push(in1, Type.INT_TYPE);
push_scaled(in2, scale);
mv.visitInsn(IADD);
pop(out, Type.INT_TYPE);
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitBS(erjang.beam.BeamOpcode,
* erjang.beam.Arg)
*/
@Override
public void visitBS(BeamOpcode opcode, Arg arg, Arg imm) {
switch (opcode) {
case bs_save2:
case bs_restore2:
push(arg, EOBJECT_TYPE);
if (imm.value == ATOM_start) {
String methName =
(opcode == BeamOpcode.bs_restore2)
? "bs_restore2_start" : "bs_save2_start";
mv.visitMethodInsn(INVOKESTATIC, EBINMATCHSTATE_TYPE.getInternalName(), methName, "("+EOBJECT_DESC+")V");
} else {
push(imm, Type.INT_TYPE);
mv.visitMethodInsn(INVOKESTATIC, EBINMATCHSTATE_TYPE.getInternalName(), opcode.name(), "("+EOBJECT_DESC+"I)V");
}
return;
case bs_context_to_binary:
push(arg, EOBJECT_TYPE);
mv.visitMethodInsn(INVOKESTATIC, EBINMATCHSTATE_TYPE
.getInternalName(), "bs_context_to_binary", "(" +EOBJECT_DESC + ")" + EOBJECT_DESC);
pop(arg, EOBJECT_TYPE);
return;
case bs_utf8_size:
push(arg, EOBJECT_TYPE);
mv.visitMethodInsn(INVOKESTATIC, EBINSTRINGBUILDER_TYPE.getInternalName(), "bs_utf8_size",
"(" + EOBJECT_DESC +")" + ESMALL_TYPE.getDescriptor());
pop(imm, ESMALL_TYPE);
return;
case bs_utf16_size:
push(arg, EOBJECT_TYPE);
mv.visitMethodInsn(INVOKESTATIC, EBINSTRINGBUILDER_TYPE.getInternalName(), "bs_utf16_size",
"(" + EOBJECT_DESC +")" + ESMALL_TYPE.getDescriptor());
pop(imm, ESMALL_TYPE);
return;
}
throw new Error("unhandled: " + opcode);
}
@Override
public void visitInitWritable(Arg size, Arg out) {
push(size, EOBJECT_TYPE);
mv.visitMethodInsn(INVOKESTATIC,
EBITSTRINGBUILDER_TYPE.getInternalName(), "bs_init_writable",
"("+EOBJECT_DESC+")"+EBITSTRINGBUILDER_TYPE.getDescriptor());
mv.visitInsn(DUP);
mv.visitVarInsn(ASTORE, bit_string_builder);
mv.visitMethodInsn(INVOKEVIRTUAL, EBITSTRINGBUILDER_TYPE
.getInternalName(), "bitstring", "()"
+ EBITSTRING_TYPE.getDescriptor());
pop(out, EBITSTRING_TYPE);
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitInitBitString(erjang.EObject,
* erjang.beam.Arg, erjang.beam.Arg)
*/
@Override
public void visitInitBitString(Arg size, int flags, Arg out, boolean unit_is_bits) {
push(size, Type.INT_TYPE);
mv.visitLdcInsn(new Integer(flags));
String methodName = unit_is_bits? "bs_initBits" : "bs_init";
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, methodName, "(II)"
+ EBITSTRINGBUILDER_TYPE.getDescriptor());
mv.visitInsn(DUP);
mv.visitVarInsn(ASTORE, bit_string_builder);
mv.visitMethodInsn(INVOKEVIRTUAL, EBITSTRINGBUILDER_TYPE
.getInternalName(), "bitstring", "()"
+ EBITSTRING_TYPE.getDescriptor());
pop(out, EBITSTRING_TYPE);
return;
}
@Override
public void visitBitStringAppend(BeamOpcode opcode, int label, Arg extra_size, Arg src, int unit, int flags, Arg dst) {
push(src, EOBJECT_TYPE);
push(extra_size, Type.INT_TYPE);
push_int(unit);
push_int(flags);
mv.visitMethodInsn(INVOKESTATIC, EBITSTRINGBUILDER_TYPE.getInternalName(),
opcode.name(), "("+ EOBJECT_DESC +"III)"+EBITSTRINGBUILDER_TYPE.getDescriptor());
mv.visitInsn(DUP);
mv.visitVarInsn(ASTORE, bit_string_builder);
mv.visitMethodInsn(INVOKEVIRTUAL, EBITSTRINGBUILDER_TYPE
.getInternalName(), "bitstring", "()"
+ EBITSTRING_TYPE.getDescriptor());
pop(dst, EBITSTRING_TYPE);
return;
}
/*
* (non-Javadoc)
*
* @see
* erjang.beam.BlockVisitor2#visitBitStringPut(erjang.beam.BeamOpcode
* , erjang.EObject)
*/
@Override
public void visitBitStringPut(BeamOpcode opcode, Arg arg, Arg size,
int unit, int flags)
{
switch (opcode) {
case bs_put_string:
mv.visitVarInsn(ALOAD, bit_string_builder);
push(arg, ESTRING_TYPE);
mv.visitMethodInsn(INVOKEVIRTUAL, EBITSTRINGBUILDER_TYPE
.getInternalName(), "put_string", "("
+ ESTRING_TYPE.getDescriptor() + ")V");
return;
case bs_put_integer:
mv.visitVarInsn(ALOAD, bit_string_builder);
push(arg, EINTEGER_TYPE);
push_scaled(size, unit);
push_int(flags);
mv.visitMethodInsn(INVOKEVIRTUAL, EBITSTRINGBUILDER_TYPE
.getInternalName(), "put_integer", "("
+ EOBJECT_DESC + "II)V");
return;
case bs_put_float:
mv.visitVarInsn(ALOAD, bit_string_builder);
push(arg, EDOUBLE_TYPE);
push_scaled(size, unit);
push_int(flags);
mv.visitMethodInsn(INVOKEVIRTUAL, EBITSTRINGBUILDER_TYPE
.getInternalName(), "put_float", "("+EOBJECT_DESC+"II)V");
return;
case bs_put_utf8:
mv.visitVarInsn(ALOAD, bit_string_builder);
push(arg, EINTEGER_TYPE);
push_int(flags);
mv.visitMethodInsn(INVOKEVIRTUAL, EBITSTRINGBUILDER_TYPE
.getInternalName(), "put_utf8", "("+EOBJECT_DESC+"I)V");
return;
case bs_put_utf16:
mv.visitVarInsn(ALOAD, bit_string_builder);
push(arg, EINTEGER_TYPE);
push_int(flags);
mv.visitMethodInsn(INVOKEVIRTUAL, EBITSTRINGBUILDER_TYPE
.getInternalName(), "put_utf16", "("+EOBJECT_DESC+"I)V");
return;
case bs_put_utf32:
mv.visitVarInsn(ALOAD, bit_string_builder);
push(arg, EINTEGER_TYPE);
push_int(flags);
mv.visitMethodInsn(INVOKEVIRTUAL, EBITSTRINGBUILDER_TYPE
.getInternalName(), "put_utf32", "("+EOBJECT_DESC+"I)V");
return;
case bs_put_binary:
mv.visitVarInsn(ALOAD, bit_string_builder);
push(arg, EBITSTRING_TYPE);
if (size.kind == Kind.IMMEDIATE &&
size.value.equals(EAtom.intern("all")))
push_int(-1);
else
push_scaled(size, unit);
push_int(flags);
mv.visitMethodInsn(INVOKEVIRTUAL, EBITSTRINGBUILDER_TYPE
.getInternalName(), "put_bitstring", "("
+ EOBJECT_TYPE.getDescriptor() + "II)V");
return;
}
throw new Error("unhandled: " + opcode);
}
@Override
public void visitBitStringTest(BeamOpcode test, int failLabel, Arg in, int intg, Arg dst) {
switch (test) {
case bs_start_match2: {
push(in, EOBJECT_TYPE);
push_int(intg); // Slots
mv.visitMethodInsn(INVOKESTATIC, EBINMATCHSTATE_TYPE
.getInternalName(), test.name(), "(" + EOBJECT_DESC
+ "I)" + EMATCHSTATE_TYPE.getDescriptor());
mv.visitInsn(DUP);
mv.visitVarInsn(ASTORE, bit_string_matcher);
mv.visitJumpInsn(IFNULL, getLabel(failLabel));
mv.visitVarInsn(ALOAD, bit_string_matcher);
pop(dst, EBINMATCHSTATE_TYPE);
return;
}
/* {test,bs_get_utf8,{f,6},[{x,0},1,
{field_flags,[...,unsigned,big]},{x,1}]}. */
case bs_get_utf8:
case bs_get_utf16:
case bs_get_utf32: {
push(in, EBINMATCHSTATE_TYPE);
push_int(intg); // Flags
mv.visitMethodInsn(INVOKEVIRTUAL, EBINMATCHSTATE_TYPE
.getInternalName(), test.name(), "(I)I");
mv.visitInsn(DUP);
mv.visitVarInsn(ISTORE, scratch_reg);
mv.visitJumpInsn(IFLT, getLabel(failLabel));
mv.visitVarInsn(ILOAD, scratch_reg);
emit_box(Type.INT_TYPE, ESMALL_TYPE);
pop(dst, ESMALL_TYPE);
return;
}
default:
throw new Error("unhandled bit string test: " + test);
}
}
@Override
public void visitBitStringTest(BeamOpcode test, int failLabel, Arg in, EBitString bin) {
switch (test) {
case bs_match_string: {
push(in, EBINMATCHSTATE_TYPE);
push_immediate(bin, EBITSTRING_TYPE);
mv.visitMethodInsn(INVOKEVIRTUAL, EBINMATCHSTATE_TYPE
.getInternalName(), test.name(), "("
+ EBITSTRING_TYPE.getDescriptor() + ")"
+ EBITSTRING_TYPE);
mv.visitJumpInsn(IFNULL, getLabel(failLabel));
return;
}
default:
throw new Error("unhandled bit string test: " + test);
}
}
@Override
public void visitBitStringTest(BeamOpcode test, int failLabel, Arg in, Arg bits, int unit, int flags) {
switch (test) {
case bs_skip_bits2: {
// {test,bs_skip_bits2, {f,39},
// [{x,1},{x,0},8,{field_flags,0}]}
push(in, EBINMATCHSTATE_TYPE);
push(bits, EINTEGER_TYPE);
push_int(unit); // TODO: Scale here instead?
push_int(flags);
mv.visitMethodInsn(INVOKEVIRTUAL, EBINMATCHSTATE_TYPE
.getInternalName(), test.name(), "(" + EOBJECT_DESC
+ "II)" + EOBJECT_DESC);
mv.visitJumpInsn(IFNULL, getLabel(failLabel));
return;
}
default:
throw new Error("unhandled bit string test: " + test);
}
}
@Override
public void visitLine(int line) {
Label here = new Label();
mv.visitLabel(here);
mv.visitLineNumber(line, here);
}
@Override
public void visitBitStringTest(BeamOpcode test, int failLabel, Arg in, Arg bits, int unit, int flags, Arg dst) {
switch (test) {
case bs_get_binary2: {
push(in, EBINMATCHSTATE_TYPE);
push(bits, EOBJECT_TYPE); //TODO: scale by unit, handling 'all'
push_int(flags);
mv.visitMethodInsn(INVOKEVIRTUAL, EBINMATCHSTATE_TYPE
.getInternalName(), test.name(), "(" + EOBJECT_DESC
+ "I)" + EBITSTRING_TYPE);
mv.visitInsn(DUP);
mv.visitVarInsn(ASTORE, scratch_reg);
mv.visitJumpInsn(IFNULL, getLabel(failLabel));
mv.visitVarInsn(ALOAD, scratch_reg);
pop(dst, EBITSTRING_TYPE);
return;
}
// {test,bs_get_integer2,{f,348},[{x,3},4,{integer,32},1,{field_flags,0},{x,4}]}
case bs_get_integer2: {
push(in, EBINMATCHSTATE_TYPE);
push(bits, Type.INT_TYPE);
push_int(unit);
push_int(flags);
mv.visitMethodInsn(INVOKEVIRTUAL, EBINMATCHSTATE_TYPE
.getInternalName(), test.name(), "(III)"
+ EINTEGER_TYPE.getDescriptor());
mv.visitInsn(DUP);
mv.visitVarInsn(ASTORE, scratch_reg);
mv.visitJumpInsn(IFNULL, getLabel(failLabel));
mv.visitVarInsn(ALOAD, scratch_reg);
pop(dst, EOBJECT_TYPE);
return;
}
case bs_get_float2: {
push(in, EBINMATCHSTATE_TYPE);
push(bits, Type.INT_TYPE);
push_int(unit);
push_int(flags);
mv.visitMethodInsn(INVOKEVIRTUAL, EBINMATCHSTATE_TYPE
.getInternalName(), test.name(), "(III)"
+ EDOUBLE_TYPE.getDescriptor());
mv.visitInsn(DUP);
mv.visitVarInsn(ASTORE, scratch_reg);
mv.visitJumpInsn(IFNULL, getLabel(failLabel));
mv.visitVarInsn(ALOAD, scratch_reg);
pop(dst, EOBJECT_TYPE);
return;
}
default:
throw new Error("unhandled bit string test: " + test);
}
}
@Override
public void visitBitStringTest(BeamOpcode test, int failLabel, Arg in, int intg) {
// case bs_test_tail2: // intg == expected bits left
// case bs_test_unit: // intg == unit
// case bs_skip_utfXX: // intg == flags
push(in, EBINMATCHSTATE_TYPE);
push_int(intg);
mv.visitMethodInsn(INVOKEVIRTUAL, EBINMATCHSTATE_TYPE
.getInternalName(), test.name(), "(I)Z");
mv.visitJumpInsn(IFEQ, getLabel(failLabel));
return;
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitInsn(erjang.beam.BeamOpcode,
* int, erjang.beam.Arg[], erjang.beam.Arg)
*/
@Override
public void visitInsn(BeamOpcode opcode, int failLabel, Arg[] in,
Arg ex) {
if (opcode == BeamOpcode.raise) {
push(in[0], EOBJECT_TYPE);
push(in[1], EOBJECT_TYPE);
// raise will actually throw (if successful)
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "raise", "("
+ EOBJECT_DESC + EOBJECT_DESC + ")"
+ EOBJECT_DESC);
mv.visitInsn(ARETURN);
return;
}
throw new Error("unhandled: " + opcode);
}
/**
*
*/
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitInsn(erjang.beam.BeamOpcode,
* int, erjang.beam.Arg[], erjang.beam.Arg,
* java.lang.reflect.Method)
*/
public void visitDecrement(Arg src, Arg out) {
push(src, src.type);
mv.visitMethodInsn(INVOKEVIRTUAL, EOBJECT_NAME, "dec", "()"+ENUMBER_TYPE.getDescriptor());
pop(out, EOBJECT_TYPE);
};
@Override
public void visitIncrement(Arg src, Arg out) {
push(src, src.type);
mv.visitMethodInsn(INVOKEVIRTUAL, EOBJECT_NAME, "inc", "()"+ENUMBER_TYPE.getDescriptor());
pop(out, EOBJECT_TYPE);
return;
}
@Override
public void visitInsn(BeamOpcode opcode, int failLabel, Arg[] in,
Arg out, BuiltInFunction bif) {
ensure_exception_handler_in_place();
switch (opcode) {
case bif0:
case bif1:
case bif2:
case gc_bif1:
case gc_bif2:
case gc_bif3:
case fadd:
case fsub:
case fmul:
case fdiv:
Type[] parameterTypes = bif.getArgumentTypes();
push(in, parameterTypes, bif.isVirtual());
mv.visitMethodInsn(bif.isVirtual() ? INVOKEVIRTUAL : INVOKESTATIC, bif.owner
.getInternalName(), bif.getName(), bif
.getDescriptor());
if (failLabel != 0) {
// guard
// dup result for test
if (out != null) {
pop(out, bif.getReturnType());
push(out, bif.getReturnType());
}
if (bif.getReturnType().getSort() == Type.BOOLEAN) {
mv.visitJumpInsn(IFEQ, getLabel(failLabel));
} else {
if (bif.getReturnType().getSort() != Type.OBJECT)
throw new Error(
"guards must return object type - "
+ bif);
mv.visitJumpInsn(IFNULL, getLabel(failLabel));
}
} else {
if (PARANOIA_MODE && bif.getReturnType().getSort() == Type.OBJECT) {
// Expect non-guards to return non-null.
mv.visitInsn(DUP);
mv.visitLdcInsn(bif.toString());
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME,
"paranoiaCheck", "(Lerjang/EObject;Ljava/lang/String;)V");
}
pop(out, bif.getReturnType());
}
return;
}
throw new Error();
}
public void visitUnreachablePoint() {
// mv.visitLdcInsn("Reached unreachable point.");
// mv.visitInsn(DUP);
// mv.visitMethodInsn(INVOKESPECIAL, "java/lang/RuntimeException", "<init>", "(Ljava/lang/String;)V");
// mv.visitInsn(ATHROW);
}
public void visitCatchBlockStart(BeamOpcode opcode, int label, Arg out, BeamExceptionHandler exh) {
switch (opcode) {
case K_try:
case K_catch: {
active_beam_exh = exh;
return;
}
}
}
public void visitCatchBlockEnd(BeamOpcode opcode, Arg out, BeamExceptionHandler exh) {
active_beam_exh = exh.getParent();
adjust_exception_handlers(active_beam_exh, false);
switch (opcode) {
case try_end: {
} break;
case catch_end: {
// Insert exception decoding sequence:
Label after = new Label();
mv.visitJumpInsn(GOTO, after);
mv.visitLabel(getExceptionHandlerLabel(exh));
// Remember the exception value:
mv.visitInsn(DUP);
mv.visitVarInsn(ALOAD, 0);
mv.visitInsn(SWAP);
mv.visitFieldInsn(PUTFIELD, EPROC_NAME,
"last_exception", EEXCEPTION_DESC);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME,
"decode_exception2", "("
+ ERLANG_EXCEPTION_TYPE.getDescriptor()
+ ")" + EOBJECT_DESC);
mv.visitVarInsn(ASTORE, xregs[0]);
mv.visitLabel(after);
} break;
case try_case: {
mv.visitLabel(getExceptionHandlerLabel(exh));
// Remember the exception value:
mv.visitInsn(DUP);
mv.visitVarInsn(ALOAD, 0);
mv.visitInsn(SWAP);
mv.visitFieldInsn(PUTFIELD, EPROC_NAME,
"last_exception", EEXCEPTION_DESC);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME,
"decode_exception3", "("
+ ERLANG_EXCEPTION_TYPE.getDescriptor()
+ ")" + getTubleType(3).getDescriptor());
mv.visitInsn(DUP);
mv.visitFieldInsn(GETFIELD, ETUPLE_NAME + 3, "elem1",
EOBJECT_DESC);
mv.visitVarInsn(ASTORE, xregs[0]);
mv.visitInsn(DUP);
mv.visitFieldInsn(GETFIELD, ETUPLE_NAME + 3, "elem2",
EOBJECT_DESC);
mv.visitVarInsn(ASTORE, xregs[1]);
mv.visitFieldInsn(GETFIELD, ETUPLE_NAME + 3, "elem3",
EOBJECT_DESC);
mv.visitVarInsn(ASTORE, xregs[2]);
} break;
}
}
/**
* @param out
* @return
*/
private int var_index(Arg out) {
switch (out.kind) {
case X:
return xregs[out.no];
case Y:
return yregs[out.no];
case F:
return fpregs[out.no];
}
throw new Error();
}
/**
* @param out
* @param stack_type
*/
private void pop(Arg out, Type stack_type) {
if (out == null) {
if (stack_type != null
&& Type.DOUBLE_TYPE.equals(stack_type)) {
mv.visitInsn(POP2);
} else {
mv.visitInsn(POP);
}
return;
}
if (stack_type == Type.DOUBLE_TYPE
&& (out.kind == Kind.X || out.kind == Kind.Y)) {
emit_convert(
stack_type,
stack_type == Type.DOUBLE_TYPE ? EDOUBLE_TYPE
: (stack_type == Type.INT_TYPE ? EINTEGER_TYPE
: EOBJECT_TYPE));
}
if (out.kind == Kind.X || out.kind == Kind.Y) {
if (out.type == Type.INT_TYPE
|| out.type == Type.BOOLEAN_TYPE
|| (out.type == null && stack_type == Type.INT_TYPE)
|| (out.type == null && stack_type == Type.BOOLEAN_TYPE)) {
mv.visitVarInsn(ISTORE, var_index(out));
} else {
mv.visitVarInsn(ASTORE, var_index(out));
}
} else if (out.kind == Kind.F) {
if (!stack_type.equals(Type.DOUBLE_TYPE)) {
emit_convert(stack_type, Type.DOUBLE_TYPE);
}
mv.visitVarInsn(DSTORE, var_index(out));
} else {
throw new Error();
}
}
/**
* @param type
* @param stackType
*/
private void emit_convert(Type from_type, Type to_type) {
if (from_type.equals(to_type))
return;
if (from_type.getSort() == Type.OBJECT
&& to_type.getSort() == Type.OBJECT) {
return;
}
if (to_type.getSort() == Type.OBJECT) {
emit_box(from_type, to_type);
} else {
emit_unbox(from_type, to_type);
}
}
/**
* @param fromType
* @param toType
*/
private void emit_unbox(Type fromType, Type toType) {
if (toType.equals(Type.INT_TYPE)) {
if (fromType.equals(ESMALL_TYPE)) {
mv.visitFieldInsn(GETFIELD, ESMALL_NAME, "value", "I");
return;
}
}
if (toType.equals(Type.DOUBLE_TYPE)) {
if (fromType.equals(EDOUBLE_TYPE)) {
mv.visitFieldInsn(GETFIELD, EDOUBLE_NAME, "value", "D");
return;
}
}
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "unboxTo"
+ primTypeName(toType), "(" + fromType.getDescriptor()
+ ")" + toType.getDescriptor());
}
/**
* @param toType
* @return
*/
private String primTypeName(Type typ) {
switch (typ.getSort()) {
case Type.DOUBLE:
return "Double";
case Type.INT:
return "Int";
case Type.BOOLEAN:
return "Atom";
default:
throw new Error();
}
}
/**
* @param fromType
* @param toType
*/
private void emit_box(Type fromType, Type toType) {
if (fromType.equals(Type.INT_TYPE)
&& toType.getSort() == Type.OBJECT) {
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "box", "(I)"
+ ESMALL_TYPE.getDescriptor());
} else if (fromType.equals(Type.DOUBLE_TYPE)
&& toType.getSort() == Type.OBJECT) {
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "box", "(D)"
+ EDOUBLE_TYPE.getDescriptor());
} else if (fromType.equals(Type.BOOLEAN_TYPE)
&& toType.getSort() == Type.OBJECT) {
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "box", "(Z)"
+ EATOM_TYPE.getDescriptor());
} else {
throw new Error("cannot box " + fromType + " -> " + toType);
}
}
/**
* @param in
* @param parameterTypes
*/
private void push(Arg[] in, Type[] parameterTypes, boolean isVirtual) {
int off = 0;
if (isVirtual) {
push(in[0], EOBJECT_TYPE);
off = 1;
}
if (in.length == parameterTypes.length - 1
&& EPROC_TYPE.equals(parameterTypes[0])) {
mv.visitVarInsn(ALOAD, 0);
}
for (int i = 0; i < in.length-off; i++) {
Arg arg = in[i+off];
Type pt = parameterTypes[i];
push(arg, pt);
}
}
private void push_scaled(Arg value, int factor) {
if (value.kind == Kind.IMMEDIATE &&
value.value instanceof ESmall)
{
ESmall sm = (ESmall)value.value;
mv.visitLdcInsn(new Integer(factor * sm.intValue()));
} else {
push(value, Type.INT_TYPE);
push_int(factor);
mv.visitInsn(IMUL);
}
}
/**
* @param arg
* @param class1
*/
private void push(Arg value, Type stack_type) {
Type t = value.type;
if (value.kind == Kind.X || value.kind == Kind.Y) {
if (value.type == Type.INT_TYPE
|| value.type == Type.BOOLEAN_TYPE) {
// throw new Error("should not happen");
mv.visitVarInsn(ILOAD, var_index(value));
} else {
mv.visitVarInsn(ALOAD, var_index(value));
}
} else if (value.kind == Kind.F) {
mv.visitVarInsn(DLOAD, var_index(value));
} else if (value.kind == Kind.IMMEDIATE) {
t = push_immediate(value.value, stack_type);
} else {
throw new Error();
}
if (t != null && !t.equals(stack_type)) {
emit_convert(t, stack_type);
}
}
/**
* @param value
* @param stack_type
*/
private Type push_immediate(EObject value, Type stack_type) {
if (value == ERT.NIL) {
mv.visitFieldInsn(GETSTATIC, ERT_NAME, "NIL", ENIL_TYPE
.getDescriptor());
return ENIL_TYPE;
}
if (value == ERT.TRUE) {
mv.visitFieldInsn(GETSTATIC, ERT_NAME, "TRUE", EATOM_DESC);
return EATOM_TYPE;
}
if (value == ERT.FALSE) {
mv.visitFieldInsn(GETSTATIC, ERT_NAME, "FALSE", EATOM_DESC);
return EATOM_TYPE;
}
// Handle conversions to primitive Java types:
if (stack_type.getSort() != Type.OBJECT) {
if (value instanceof ESmall) {
mv.visitLdcInsn(new Integer(value.asInt()));
return Type.INT_TYPE;
} else if (value instanceof EBig && stack_type.getSort() == Type.DOUBLE) {
push_immediate(value, EBIG_TYPE);
mv.visitMethodInsn(INVOKEVIRTUAL, EBIG_NAME, "doubleValue", "()D");
return Type.DOUBLE_TYPE;
} else if (value instanceof EDouble) {
mv.visitLdcInsn(new Double(((EDouble) value).value));
return Type.DOUBLE_TYPE;
} else if (value == TRUE_ATOM) {
mv.visitInsn(ICONST_1);
return Type.BOOLEAN_TYPE;
} else if (value == FALSE_ATOM) {
mv.visitInsn(ICONST_0);
return Type.BOOLEAN_TYPE;
}
if (value instanceof ETuple2) {
ETuple2 t2 = (ETuple2) value;
if (t2.elm(1) == ATOM_field_flags) {
push_int(t2.elem2.asInt());
return Type.INT_TYPE;
}
}
throw new Error("cannot convert " + value + " as "
+ stack_type);
}
String known = constants.get(value);
if (known == null) {
Type type = Type.getType(value.getClass());
String cn = getConstantName(value, constants.size());
constants.put(value, known = cn);
cv.visitField(ACC_STATIC, known, type.getDescriptor(),
null, null);
// System.err.println(constants);
}
if (known != null) {
Type type = Type.getType(value.getClass());
mv.visitFieldInsn(GETSTATIC, self_type.getInternalName(),
known, type.getDescriptor());
return type;
}
throw new Error("cannot push " + value + " as " + stack_type);
// return Type.getType(value.getClass());
}
/**
* @param value
* @param size
* @return
*/
private String getConstantName(EObject value, int size) {
if (value instanceof EAtom)
return "atom_" + EUtil.toJavaIdentifier((EAtom) value);
if (value instanceof ENumber)
return EUtil.toJavaIdentifier("num_"
+ value.toString().replace('.', '_').replace('-',
'_'));
if (value instanceof EString)
return "str_" + size;
else
return "cst_" + size;
}
/*
* (non-Javadoc)
*
* @see
* erjang.beam.BlockVisitor2#visitReceive(erjang.beam.BeamOpcode,
* int, erjang.beam.Arg)
*/
@Override
public void visitReceive(BeamOpcode opcode, int blockLabel, Arg out) {
switch (opcode) {
case loop_rec:
ensure_exception_handler_in_place();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "loop_rec",
"(" + EPROC_TYPE.getDescriptor() + ")"
+ EOBJECT_DESC);
mv.visitInsn(DUP);
pop(out, EOBJECT_TYPE);
mv.visitJumpInsn(IFNULL, getLabel(blockLabel));
return;
}
throw new Error();
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitInsn(erjang.beam.BeamOpcode,
* erjang.beam.Arg[], erjang.beam.Arg)
*/
@Override
public void visitInsn(BeamOpcode opcode, Arg[] in, Arg out) {
switch (opcode) {
case put_list:
push(in[0], EOBJECT_TYPE);
push(in[1], EOBJECT_TYPE);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "cons", ERT_CONS_SIG);
pop(out, ECONS_TYPE);
return;
case call_fun:
case i_call_fun_last: {
ensure_exception_handler_in_place();
boolean is_tail = opcode == BeamOpcode.i_call_fun_last;
int nargs = in.length - 1;
push(in[nargs], EOBJECT_TYPE);
mv.visitInsn(DUP);
String funtype = EFUN_NAME + nargs;
mv.visitMethodInsn(INVOKESTATIC, funtype, "cast", "("
+ EOBJECT_DESC + ")L" + funtype + ";");
mv.visitInsn(DUP_X1);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "test_fun", TEST_FUN_SIG);
mv.visitVarInsn(ALOAD, 0); // load proc
for (int i = 0; i < nargs; i++) {
push(in[i], EOBJECT_TYPE);
}
mv.visitMethodInsn(INVOKEVIRTUAL, funtype,
is_tail ? "invoke_tail" : "invoke",
EUtil.getSignature(nargs, true));
if (is_tail) {
mv.visitInsn(ARETURN);
} else {
pop(out, EOBJECT_TYPE);
}
return;
}
}//switch
throw new Error();
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitInsn(erjang.beam.BeamOpcode)
*/
@Override
public void visitInsn(BeamOpcode insn) {
switch (insn) {
case if_end:
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "if_end", EUtil
.getSignature(0, false));
mv.visitInsn(ARETURN);
return;
case timeout:
mv.visitVarInsn(ALOAD, 0);
mv
.visitMethodInsn(INVOKESTATIC, ERT_NAME, "timeout",
"("+EPROC_DESC+")V");
return;
case remove_message:
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME,
"remove_message", "(" + EPROC_TYPE.getDescriptor()
+ ")V");
return;
}
throw new Error();
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitInsn(erjang.beam.BeamOpcode,
* int, erjang.beam.Arg)
*/
@Override
public void visitInsn(BeamOpcode opcode, int val, Arg out) {
switch (opcode) {
case put_tuple:
mv.visitTypeInsn(NEW, out.type.getInternalName());
mv.visitInsn(DUP);
mv.visitMethodInsn(INVOKESPECIAL, out.type
.getInternalName(), "<init>", "()V");
pop(out, out.type);
return;
case wait_timeout: {
mv.visitVarInsn(ALOAD, 0);
push(out, EOBJECT_TYPE);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "wait_timeout",
"(" + EPROC_TYPE.getDescriptor()
+ EOBJECT_TYPE.getDescriptor() + ")Z");
mv.visitJumpInsn(IFNE, getLabel(val));
return;
}
case loop_rec_end:
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "loop_rec_end",
"(" + EPROC_TYPE.getDescriptor() + ")V");
mv.visitJumpInsn(GOTO, getLabel(val));
return;
case wait: {
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "wait",
"(" + EPROC_TYPE.getDescriptor() + ")V");
mv.visitJumpInsn(GOTO, getLabel(val));
return;
}
}
throw new Error("unhandled: " + opcode);
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitInsn(erjang.beam.BeamOpcode,
* erjang.beam.Arg, erjang.beam.Arg, int)
*/
@Override
public void visitInsn(BeamOpcode opcode, Arg val, Arg out, int pos) {
if (opcode == BeamOpcode.put) {
push(out, out.type);
push(val, EOBJECT_TYPE);
mv.visitFieldInsn(PUTFIELD, out.type.getInternalName(),
"elem" + pos, EOBJECT_DESC);
return;
} else if (opcode == BeamOpcode.get_tuple_element) {
int known_arity = get_known_arity(val.type);
if (known_arity >= pos+1) {
push(val, val.type);
mv.visitFieldInsn(GETFIELD, val.type.getInternalName(),
"elem" + (pos + 1), EOBJECT_DESC);
} else {
push(val, val.type);
mv.visitTypeInsn(CHECKCAST, ETUPLE_NAME);
push_int(pos + 1);
mv.visitMethodInsn(INVOKEVIRTUAL, ETUPLE_NAME, "elm",
"(I)" + EOBJECT_DESC);
}
pop(out, EOBJECT_TYPE);
return;
} else if (opcode == BeamOpcode.set_tuple_element) {
push(out, out.type);
if (get_known_arity(out.type) < 0)
mv.visitTypeInsn(CHECKCAST, ETUPLE_NAME);
push_int(pos + 1);
push(val, val.type);
mv.visitMethodInsn(INVOKEVIRTUAL, ETUPLE_NAME, "set", "(I"
+ EOBJECT_DESC + ")V");
return;
}
throw new Error();
}
/**
* @param type
* @return -1 if non-ETuple; arity [#elements] otherwise
*/
private int get_known_arity(Type type) {
String in = type.getInternalName();
if (in.startsWith(ETUPLE_NAME)) {
int pfx_len = ETUPLE_NAME.length();
if (in.length() == pfx_len) {
return 0;
}
try {
String arity = in.substring(pfx_len);
return Integer.parseInt(arity);
} catch (NumberFormatException e) {
return 0;
}
}
// not a tuple
return -1;
}
/**
* @param pos
*/
private void push_int(int pos) {
if (pos >= -1 && pos <= 5) {
mv.visitInsn(ICONST_0 + pos);
} else {
mv.visitLdcInsn(new Integer(pos));
}
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitTest(erjang.beam.BeamOpcode,
* int, erjang.beam.Arg, java.lang.reflect.Method)
*/
@Override
public void visitInsn(BeamOpcode test, int failLabel, Arg arg1,
org.objectweb.asm.commons.Method bif) {
throw new Error();
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor#visitEnd()
*/
@Override
public void visitEnd() {
// skip //
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor#visitInsn(erjang.beam.BeamOpcode,
* erjang.ETuple)
*/
@Override
public void visitInsn(Insn insn) {
throw new Error();
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitInsn(erjang.beam.BeamOpcode,
* erjang.beam.Arg)
*/
@Override
public void visitInsn(BeamOpcode opcode, Arg arg) {
switch (opcode) {
case K_return:
push(arg, EOBJECT_TYPE);
mv.visitInsn(ARETURN);
return;
case init:
push_immediate(ERT.NIL, ENIL_TYPE);
pop(arg, ENIL_TYPE);
return;
case try_case_end:
push(arg, EOBJECT_TYPE);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "try_case_end",
EUtil.getSignature(1, false));
mv.visitInsn(ARETURN);
return;
case case_end:
push(arg, EOBJECT_TYPE);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "case_end",
EUtil.getSignature(1, false));
mv.visitInsn(ARETURN);
return;
case badmatch:
push(arg, EOBJECT_TYPE);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "badmatch",
EUtil.getSignature(1, false));
mv.visitInsn(ARETURN);
return;
}
throw new Error("unhandled " + opcode);
}
public void visitInsn(BeamOpcode opcode, ExtFun f) {
switch (opcode) {
case func_info:
push_immediate(f.mod, EATOM_TYPE);
push_immediate(f.fun, EATOM_TYPE);
push_immediate(ERT.NIL, ENIL_TYPE);
for (int i=f.arity-1; i>=0; i--) {
push(new Arg(Kind.X, i), EOBJECT_TYPE);
mv.visitMethodInsn(INVOKEVIRTUAL, ESEQ_NAME, "cons", SEQ_CONS_SIG);
}
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "func_info", FUNC_INFO_SIG);
mv.visitInsn(ARETURN);
return;
}//switch
throw new Error("unhandled " + opcode);
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitTest(erjang.beam.BeamOpcode,
* int, erjang.beam.Arg)
*/
@Override
public void visitTest(BeamOpcode test, int failLabel, Arg arg1,
Type out) {
Method test_bif = get_test_bif(test, arg1.type);
// System.err.println(test_bif);
push(arg1, arg1.type);
mv.visitMethodInsn(INVOKEVIRTUAL, EOBJECT_NAME, test_bif
.getName(), test_bif.getDescriptor());
Type returnType = test_bif.getReturnType();
if (failLabel != 0) {
// guard
if (returnType.getSort() != Type.OBJECT)
throw new Error("guards must return object type: "
+ test_bif);
// dup result for test
if (arg1 != null) {
mv.visitInsn(DUP);
mv.visitVarInsn(ASTORE, scratch_reg);
}
mv.visitJumpInsn(IFNULL, getLabel(failLabel));
if (arg1 != null) {
mv.visitVarInsn(ALOAD, scratch_reg);
pop(arg1, returnType);
}
} else {
pop(arg1, returnType);
}
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitTest(erjang.beam.BeamOpcode,
* int, erjang.beam.Arg, int, org.objectweb.asm.Type)
*/
@Override
public void visitTest(BeamOpcode test, int failLabel, Arg arg,
int arity, Type tupleType) {
switch (test) {
case test_arity: {
Type tt = getTubleType(arity);
if (tt.equals(arg.type)) {
// do nothing //
} else {
push(arg, EOBJECT_TYPE);
mv.visitMethodInsn(INVOKESTATIC, tt.getInternalName(),
"cast", "(" + arg.type.getDescriptor() + ")"
+ tt.getDescriptor());
mv.visitInsn(DUP);
mv.visitVarInsn(ASTORE, scratch_reg);
mv.visitJumpInsn(IFNULL, getLabel(failLabel));
mv.visitVarInsn(ALOAD, scratch_reg);
pop(arg, getTubleType(arity));
}
return;
}
}//switch
throw new Error("unhandled " + test);
}
@Override
public void visitTest(BeamOpcode test, int failLabel, Arg arg,
Arg arity, Type funType) {
switch (test) {
case is_function2:
// push object to test
push(arg, EOBJECT_TYPE);
// push arity
push(arity, Type.INT_TYPE);
// call object.testFunction2(nargs)
mv.visitMethodInsn(INVOKEVIRTUAL, EOBJECT_NAME,
"testFunction2", "(I)" + EFUN_DESCRIPTOR);
mv.visitInsn(DUP);
mv.visitVarInsn(ASTORE, scratch_reg);
mv.visitJumpInsn(IFNULL, getLabel(failLabel));
mv.visitVarInsn(ALOAD, scratch_reg);
pop(arg, funType);
return;
}
throw new Error("unhandled " + test);
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitTest(erjang.beam.BeamOpcode,
* int, erjang.beam.Arg[], erjang.beam.Arg, org.objectweb.asm.Type)
*/
@Override
public void visitTest(BeamOpcode test, int failLabel, Arg[] args,
Type outType) {
switch (test) {
case is_eq_exact:
{
if (args[0].kind==Kind.IMMEDIATE && args[0].value.equalsExactly(ESmall.ZERO)) {
push(args[1], EOBJECT_TYPE);
mv.visitMethodInsn(INVOKEVIRTUAL, EOBJECT_NAME, "is_zero",
"()Z");
mv.visitJumpInsn(IFEQ, getLabel(failLabel));
return;
}
if (args[1].kind==Kind.IMMEDIATE && args[1].value.equalsExactly(ESmall.ZERO)) {
push(args[0], EOBJECT_TYPE);
mv.visitMethodInsn(INVOKEVIRTUAL, EOBJECT_NAME, "is_zero",
"()Z");
mv.visitJumpInsn(IFEQ, getLabel(failLabel));
return;
}
}
case is_ne_exact:
case is_ne:
case is_eq:
{
// if arg[0] is object type, and arg[1] is not, then swap args.
if (args[0].type.equals(EOBJECT_TYPE) && !args[1].type.equals(EOBJECT_TYPE)) {
Arg t = args[0];
args[0] = args[1];
args[1] = t;
}
}
case is_lt:
case is_ge:
{
// this particular case can be coded as a java instruction instruction
if ((test == BeamOpcode.is_eq_exact || test == BeamOpcode.is_eq)
&& (args[0].type.equals(EATOM_TYPE) || args[1].type
.equals(EATOM_TYPE))) {
push(args[0], EOBJECT_TYPE);
push(args[1], EOBJECT_TYPE);
mv.visitJumpInsn(IF_ACMPNE, getLabel(failLabel));
return;
}
for (int i = 0; i < args.length; i++) {
push(args[i], EOBJECT_TYPE);
}
mv.visitMethodInsn(INVOKEVIRTUAL, EOBJECT_NAME,
test.name(), "(" + EOBJECT_DESC + ")Z");
if (failLabel != 0) {
mv.visitJumpInsn(IFEQ, getLabel(failLabel));
} else {
throw new Error("test with no fail label?");
}
//
if (test == BeamOpcode.is_eq_exact && !Type.VOID_TYPE.equals(outType)) {
if (args[0].type.equals(EOBJECT_TYPE) && args[0].kind.isReg()) {
push(args[1], outType);
args[0].type = outType;
pop(args[0], outType);
} else if (args[1].type.equals(EOBJECT_TYPE) && args[1].kind.isReg()) {
push(args[0], outType);
args[1].type = outType;
pop(args[1], outType);
}
}
return;
}
}
throw new Error("unhandled " + test);
}
/**
* @param test
* @return
*/
private String test2name(BeamOpcode test) {
return test.name();
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitInsn(erjang.beam.BeamOpcode,
* erjang.beam.Arg, erjang.beam.Arg)
*/
@Override
public void visitInsn(BeamOpcode opcode, Arg arg1, Arg arg2) {
switch (opcode) {
case fconv:
case move:
case fmove:
if (arg1.kind == Kind.F) {
push(arg1, Type.DOUBLE_TYPE);
if (arg2.kind == Kind.F) {
pop(arg2, Type.DOUBLE_TYPE);
} else {
emit_convert(Type.DOUBLE_TYPE, EDOUBLE_TYPE);
pop(arg2, EDOUBLE_TYPE);
}
} else {
if (arg2.kind == Kind.F) {
push(arg1, Type.DOUBLE_TYPE);
pop(arg2, Type.DOUBLE_TYPE);
} else {
push(arg1, arg1.type);
pop(arg2, arg1.type);
}
}
break;
default:
throw new Error("unhandled: " + opcode);
}
}
/**
* @param test
* @param args
* @return
*/
private Method get_test_bif(BeamOpcode test, Type type) {
if (!type.getInternalName().startsWith("erjang/E")) {
throw new Error("expecting EObject");
}
switch (test) {
case is_nonempty_list:
return IS_NONEMPTY_LIST_TEST;
case is_nil:
return IS_NIL_TEST;
case is_boolean:
return IS_BOOLEAN_TEST;
case is_number:
return IS_NUMBER_TEST;
case is_float:
return IS_FLOAT_TEST;
case is_atom:
return IS_ATOM_TEST;
case is_list:
return IS_LIST_TEST;
case is_tuple:
return IS_TUPLE_TEST;
case is_integer:
return IS_INTEGER_TEST;
case is_binary:
return IS_BINARY_TEST;
case is_bitstr:
return IS_BITSTRING_TEST;
case is_pid:
return IS_PID_TEST;
case is_port:
return IS_PORT_TEST;
case is_reference:
return IS_REFERENCE_TEST;
case is_function:
return IS_FUNCTION_TEST;
case is_function2:
return IS_FUNCTION2_TEST;
}
throw new Error("unhandled " + test);
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitInsn(erjang.beam.BeamOpcode,
* erjang.beam.Arg[])
*/
@Override
public void visitInsn(BeamOpcode opcode, Arg[] ys) {
if (opcode == BeamOpcode.allocate_zero
|| opcode == BeamOpcode.allocate_heap_zero) {
mv.visitFieldInsn(GETSTATIC, ERT_NAME, "NIL", ENIL_TYPE
.getDescriptor());
for (int i = 0; i < ys.length; i++) {
if (i != (ys.length - 1))
mv.visitInsn(DUP);
mv.visitInsn(NOP);
pop(ys[i], ENIL_TYPE);
}
return;
} else if (opcode == BeamOpcode.get_list) {
push(ys[0], ECONS_TYPE);
mv.visitInsn(DUP);
mv.visitMethodInsn(INVOKEVIRTUAL, ECONS_TYPE
.getInternalName(), "head", "()" + EOBJECT_DESC);
pop(ys[1], EOBJECT_TYPE);
mv.visitMethodInsn(INVOKEVIRTUAL, ECONS_TYPE
.getInternalName(), "tail", "()" + EOBJECT_DESC);
pop(ys[2], EOBJECT_TYPE);
return;
}
ensure_exception_handler_in_place();
if (opcode == BeamOpcode.apply || opcode == BeamOpcode.apply_last) {
int arity = ys.length-2;
push(ys[ys.length-2], EOBJECT_TYPE); // push mod
push(ys[ys.length-1], EOBJECT_TYPE); // push fun
push_int(arity); // push arity
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "resolve_fun", "("+EOBJECT_DESC+EOBJECT_DESC+"I)"+EFUN_DESCRIPTOR);
String funtype = EFUN_NAME + arity;
mv.visitMethodInsn(INVOKESTATIC, funtype, "cast", "("
+ EOBJECT_DESC + ")L" + funtype + ";");
mv.visitVarInsn(ALOAD, 0); // push eproc
int loops = 0;
for (int i = 0; i <= ys.length-3; i++) {
push(ys[i], EOBJECT_TYPE);
loops += 1;
}
if (loops != arity) {
// invariant for above complicated loop logic.
throw new InternalError("bad args here");
}
boolean is_tail = opcode == BeamOpcode.apply_last;
if (is_tail) {
mv.visitMethodInsn(INVOKEVIRTUAL, funtype, "invoke_tail", EUtil
.getSignature(arity, true));
mv.visitInsn(ARETURN);
} else {
mv.visitMethodInsn(INVOKEVIRTUAL, funtype,
"invoke", EUtil
.getSignature(arity, true));
mv.visitVarInsn(ASTORE, xregs[0]);
}
return;
} else if (opcode == BeamOpcode.send) {
mv.visitVarInsn(ALOAD, 0);
for (int i = 0; i < ys.length; i++) {
push(ys[i], EOBJECT_TYPE);
}
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME, "send", EUtil
.getSignature(ys.length, true));
mv.visitVarInsn(ASTORE, xregs[0]);
return;
}
throw new Error("unhandled:" + opcode);
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitInsn(erjang.beam.BeamOpcode,
* erjang.beam.ExtFunc, int)
*/
@Override
public void visitInsn(BeamOpcode opcode, ExtFun efun,
Arg[] freevars, int index, int old_index, EBinary uniq, int old_uniq) {
ensure_exception_handler_in_place();
if (opcode == BeamOpcode.make_fun2) {
CompilerVisitor.this.register_lambda(efun.fun, efun.arity,
freevars.length, index, old_index, uniq, old_uniq);
String inner = EUtil.getFunClassName(self_type, efun, freevars.length);
mv.visitTypeInsn(NEW, inner);
mv.visitInsn(DUP);
// load proc
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKEVIRTUAL, EPROC_NAME, "self_handle", "()" + Type.getDescriptor(EInternalPID.class));
// String funtype = EFUN_NAME + efun.no;
for (int i = 0; i < freevars.length; i++) {
push(freevars[i], EOBJECT_TYPE);
}
StringBuilder sb = new StringBuilder("(");
sb.append(EPID_TYPE.getDescriptor());
for (int i = 0; i < freevars.length; i++) {
sb.append(EOBJECT_DESC);
}
sb.append(")V");
// sb.append("L").append(funtype).append(";");
String gen_fun_desc = sb.toString();
mv.visitMethodInsn(INVOKESPECIAL, inner, "<init>",
gen_fun_desc);
mv.visitVarInsn(ASTORE, xregs[0]);
return;
}
throw new Error();
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitSelectValue(erjang.beam.Arg,
* int, erjang.beam.Arg[], int[])
*/
@Override
public void visitSelectValue(Arg in, int failLabel, Arg[] values,
int[] targets) {
boolean all_small_ints = true;
for (int i = 0; i < values.length; i++) {
if (!(values[i].value instanceof ESmall)) {
all_small_ints = false;
break;
}
}
if (all_small_ints) {
int[] ivals = new int[values.length];
Label[] label = new Label[values.length];
for (int i = 0; i < values.length; i++) {
ivals[i] = values[i].value.asInt();
label[i] = getLabel(targets[i]);
}
push(in, Type.INT_TYPE);
sort(ivals, label);
mv.visitLookupSwitchInsn(getLabel(failLabel), ivals, label);
return;
}
if (values.length < ATOM_SELECT_IF_ELSE_LIMIT) {
boolean all_atoms = true;
for (int i = 0; i < values.length; i++) {
if (!(values[i].value instanceof EAtom)) {
all_atoms = false;
break;
}
}
if (all_atoms) {
for (int i = 0; i < values.length; i++) {
push(in, in.type);
push(values[i], values[i].type);
mv.visitJumpInsn(IF_ACMPEQ, getLabel(targets[i]));
}
mv.visitJumpInsn(GOTO, getLabel(failLabel));
return;
}
}
class Case implements Comparable<Case> {
final Arg arg;
final Label label;
/**
* @param arg
* @param label2
*/
public Case(Arg arg, Label label) {
this.arg = arg;
this.label = label;
}
EObject value() {
return arg.value;
}
/*
* (non-Javadoc)
*
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(Case o) {
int h = hashCode();
int ho = o.hashCode();
if (h < ho)
return -1;
if (h > ho)
return 1;
return value().erlangCompareTo(o.value());
}
}
Map<Integer, List<Case>> cases = new TreeMap<Integer, List<Case>>();
for (int i = 0; i < values.length; i++) {
int hash = values[i].value.hashCode();
List<Case> c = cases.get(hash);
if (c == null) {
cases.put(hash, c = new ArrayList<Case>());
}
c.add(new Case(values[i], getLabel(targets[i])));
}
int[] hashes = new int[cases.size()];
Label[] tests = new Label[cases.size()];
List<Case>[] idx_cases = new List[cases.size()];
int idx = 0;
for (Map.Entry<Integer, List<Case>> c : cases.entrySet()) {
hashes[idx] = c.getKey();
idx_cases[idx] = c.getValue();
tests[idx++] = new Label();
}
push(in, EOBJECT_TYPE);
mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object",
"hashCode", "()I");
mv.visitLookupSwitchInsn(getLabel(failLabel), hashes, tests);
for (int i = 0; i < idx_cases.length; i++) {
mv.visitLabel(tests[i]);
for (Case c : idx_cases[i]) {
Arg val_j = c.arg;
Label target_j = c.label;
if (val_j.type.equals(EATOM_TYPE)) {
push(in, in.type);
push(val_j, val_j.type);
mv.visitJumpInsn(IF_ACMPEQ, target_j);
} else {
if (in.type == val_j.type) {
push(in, in.type);
push(val_j, val_j.type);
mv.visitMethodInsn(INVOKESTATIC, ERT_NAME,
"eq", "(" + in.type.getDescriptor()
+ in.type.getDescriptor()
+ ")Z");
} else {
push(in, EOBJECT_TYPE);
push(val_j, EOBJECT_TYPE);
mv.visitMethodInsn(INVOKEVIRTUAL,
"java/lang/Object", "equals",
"(Ljava/lang/Object;)Z");
}
mv.visitJumpInsn(IFNE, target_j);
}
}
mv.visitJumpInsn(GOTO, getLabel(failLabel));
}
}
/**
* @param ivals
* @param label
*/
private int[] sort(int[] ivals, Label[] label) {
Label[] orig_labels = label.clone();
int[] orig_ivals = ivals.clone();
int[] res = new int[ivals.length];
Arrays.sort(ivals);
next_val: for (int i = 0; i < ivals.length; i++) {
int find = ivals[i];
for (int p = 0; p < orig_ivals.length; p++) {
int was = orig_ivals[p];
if (find == was) {
res[p] = i;
label[i] = orig_labels[p];
continue next_val;
}
}
}
return res;
}
/** class that we use to sort the labels for select_arity switch */
class TupleArityLabel implements Comparable<TupleArityLabel> {
Label cast_label = new Label();
Label target;
int arity;
public TupleArityLabel(int arity, Label target) {
this.arity = arity;
this.target = target;
}
@Override
public int compareTo(TupleArityLabel o) {
if (this.arity < o.arity)
return -1;
if (this.arity == o.arity)
return 0;
return 1;
}
}
/** Switch based on arity of incoming <code>in</code> tuple value. */
@Override
public void visitSelectTuple(Arg in, int failLabel, int[] arities,
int[] targets) {
push(in, ETUPLE_TYPE);
//if (in.type == null) {
mv.visitTypeInsn(CHECKCAST, ETUPLE_NAME);
//}
mv.visitMethodInsn(INVOKEVIRTUAL, ETUPLE_NAME, "arity", "()I");
TupleArityLabel[] cases = new TupleArityLabel[targets.length];
for (int i = 0; i < targets.length; i++) {
cases[i] = new TupleArityLabel(arities[i], getLabel(targets[i]));
}
Arrays.sort(cases);
Label[] casts = new Label[cases.length];
int[] values = new int[cases.length];
for (int i = 0; i < cases.length; i++) {
values[i] = cases[i].arity;
casts[i] = cases[i].cast_label;
}
mv.visitLookupSwitchInsn(getLabel(failLabel), values, casts);
for (int i = 0; i < cases.length; i++) {
mv.visitLabel(cases[i].cast_label);
// NOTE: unfortunately, we have to use a cast here. There
// is no real way around it, except maybe make some
// special ETuple methods for small tuple sizes?
// that is an option for future optimization of pattern match.
push(in, ETUPLE_TYPE);
mv.visitTypeInsn(CHECKCAST, getTubleType(cases[i].arity).getInternalName());
pop(in, getTubleType(cases[i].arity));
mv.visitJumpInsn(GOTO, cases[i].target);
}
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitJump(int)
*/
@Override
public void visitJump(int label) {
mv.visitJumpInsn(GOTO, getLabel(label));
}
/**
* @param i
* @return
*/
private Type getTubleType(int i) {
return Type.getType("L" + ETUPLE_NAME + i + ";");
}
/*
* (non-Javadoc)
*
* @see erjang.beam.BlockVisitor2#visitCall(erjang.beam.ExtFunc,
* erjang.beam.Arg[], boolean, boolean)
*/
@Override
public void visitCall(ExtFun fun, Arg[] args, boolean is_tail,
boolean isExternal) {
ensure_exception_handler_in_place();
BuiltInFunction bif = null;
bif = BIFUtil.getMethod(fun.mod.getName(),
fun.fun.getName(), args, false, false);
if (bif != null || isExternal) {
if (bif == null) {
String field = CompilerVisitor.this
.getExternalFunction(fun);
String funTypeName = EFUN_NAME + args.length;
EFun.ensure(args.length);
mv.visitFieldInsn(GETSTATIC, self_type
.getInternalName(), field, "L" + funTypeName
+ ";");
mv.visitVarInsn(ALOAD, 0);
for (int i = 0; i < args.length; i++) {
push(args[i], EOBJECT_TYPE);
}
mv.visitMethodInsn(INVOKEVIRTUAL, funTypeName,
(is_tail && !isExitFunc(fun)) ? "invoke_tail" : "invoke", EUtil
.getSignature(args.length, true));
} else if (bif.isVirtual()) {
// System.err.println("DIRECT "+bif);
push(args[0], bif.owner);
int off = 0;
if (bif.getArgumentTypes().length > 0
&& bif.getArgumentTypes()[0].equals(EPROC_TYPE)) {
mv.visitVarInsn(ALOAD, 0);
off = 1;
}
for (int i = 1; i < args.length; i++) {
push(args[i], bif.getArgumentTypes()[off-1]);
}
mv.visitMethodInsn(INVOKEVIRTUAL, bif.owner
.getInternalName(), bif.getName(), bif
.getDescriptor());
} else {
// System.err.println("DIRECT "+bif);
int off = 0;
if (bif.getArgumentTypes().length > 0
&& bif.getArgumentTypes()[0].equals(EPROC_TYPE)) {
mv.visitVarInsn(ALOAD, 0);
off = 1;
}
for (int i = 0; i < args.length; i++) {
push(args[i], bif.getArgumentTypes()[off + i]);
}
mv.visitMethodInsn(INVOKESTATIC, bif.owner
.getInternalName(), bif.getName(), bif
.getDescriptor());
}
if (is_tail || isExitFunc(fun)) {
mv.visitInsn(ARETURN);
} else {
mv.visitVarInsn(ASTORE, xregs[0]);
}
} else {
// are we self-recursive?
if (is_tail && fun.arity == ASMFunctionAdapter.this.arity
&& fun.fun == ASMFunctionAdapter.this.fun_name) {
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKEVIRTUAL, EPROC_NAME,
"check_exit", "()V");
// System.out.println("self-recursive in " + fun);
mv.visitJumpInsn(GOTO,
getLabel(ASMFunctionAdapter.this.startLabel));
return;
}
mv.visitVarInsn(ALOAD, 0);
for (int i = 0; i < args.length; i++) {
push(args[i], EOBJECT_TYPE);
}
FunInfo target = funInfos.get(new FunID(fun.mod, fun.name(), fun.arity));
mv.visitMethodInsn(INVOKESTATIC, self_type
.getInternalName(), EUtil.getJavaName(fun.fun,
fun.arity)
+ (is_tail ? "$tail" : (target.may_return_tail_marker ? "$call" : "")), EUtil
.getSignature(args.length, true));
if (is_tail) {
mv.visitInsn(ARETURN);
} else {
mv.visitVarInsn(ASTORE, xregs[0]);
}
}
}
/**
* @param fun
* @return
*/
private boolean isExitFunc(ExtFun fun) {
if (fun.mod == ERLANG_ATOM) {
if (fun.fun == CodeAtoms.EXIT_ATOM && fun.arity==1)
return true;
if (fun.fun == CodeAtoms.ERROR_ATOM && (fun.arity==1 || fun.arity==2))
return true;
if (fun.fun == CodeAtoms.NIF_ERROR_ATOM && (fun.arity==1))
return true;
if (fun.fun == CodeAtoms.THROW_ATOM && fun.arity==1)
return true;
}
return false;
}
}
}
final static Method IS_NONEMPTY_LIST_TEST = Method
.getMethod("erjang.ECons testNonEmptyList()");
final static Method IS_LIST_TEST = Method.getMethod("erjang.ECons testCons()");
final static Method IS_TUPLE_TEST = Method.getMethod("erjang.ETuple testTuple()");
final static Method IS_INTEGER_TEST = Method
.getMethod("erjang.EInteger testInteger()");
final static Method IS_ATOM_TEST = Method.getMethod("erjang.EAtom testAtom()");
final static Method IS_FLOAT_TEST = Method
.getMethod("erjang.EDouble testFloat()");
final static Method IS_NIL_TEST = Method.getMethod("erjang.ENil testNil()");
final static Method IS_BOOLEAN_TEST = Method
.getMethod("erjang.EAtom testBoolean()");
final static Method IS_NUMBER_TEST = Method
.getMethod("erjang.ENumber testNumber()");
final static Method IS_BINARY_TEST = Method
.getMethod("erjang.EBinary testBinary()");
final static Method IS_BITSTRING_TEST = Method
.getMethod("erjang.EBitString testBitString()");
final static Method IS_PID_TEST = Method.getMethod("erjang.EPID testPID()");
final static Method IS_PORT_TEST = Method.getMethod("erjang.EPort testPort()");
final static Method IS_REFERENCE_TEST = Method.getMethod(ERef.class.getName()
+ " testReference()");
final static Method IS_FUNCTION_TEST = Method
.getMethod("erjang.EFun testFunction()");
final static Method IS_FUNCTION2_TEST = Method
.getMethod("erjang.EFun testFunction(int nargs)");
Map<String, ExtFun> imported = new HashMap<String, ExtFun>();
private Map<FunID, FunInfo> funInfos;
/**
* @param fun
* @return
*/
public String getExternalFunction(ExtFun fun) {
String name = EUtil.getJavaName(fun);
if (!imported.containsKey(name)) {
imported.put(name, fun);
}
return name;
}
static class Lambda {
private final EAtom fun;
private final int arity;
private final int freevars;
private final int index;
private final int old_index;
private final int old_uniq;
private final EBinary uniq;
public Lambda(EAtom fun, int arity, int freevars, int index, int old_index, EBinary uniq, int old_uniq) {
this.fun = fun;
this.arity = arity;
this.freevars = freevars;
this.index = index;
this.old_index = old_index;
this.uniq = uniq;
this.old_uniq = old_uniq;
}
}
/**
* @param fun
* @param arity_plus
* @param length
* @param index TODO
* @param old_index TODO
* @param uniq TODO
* @param old_uniq
*/
public void register_lambda(EAtom fun, int arity_plus, int freevars, int index, int old_index, EBinary uniq, int old_uniq) {
lambdas_xx.put(new FunID(module_name, fun, arity_plus),
new Lambda(fun, arity_plus, freevars, index, old_index, uniq, old_uniq));
}
public Lambda get_lambda_freevars(EAtom fun, int arity_plus) {
return lambdas_xx.get(new FunID(module_name, fun, arity_plus));
}
static public byte[] make_invoker(String module, String function,
Type self_type, String mname,
String fname, int arity, boolean proc, boolean exported, Lambda lambda,
Type return_type, boolean is_tail_call, final boolean is_pausable) {
int freevars = lambda==null ? 0 : lambda.freevars;
String outer_name = self_type.getInternalName();
String inner_name = "FN_" + mname;
String full_inner_name = outer_name + "$" + inner_name;
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES|ClassWriter.COMPUTE_MAXS);
int residual_arity = arity - freevars;
String super_class_name = EFUN_NAME + residual_arity +
(exported ? "Exported" : "");
if (exported) EFun.ensure_exported(residual_arity);
else EFun.ensure(residual_arity);
cw.visit(V1_6, ACC_FINAL | ACC_PUBLIC, full_inner_name, null,
super_class_name, null);
if (lambda != null) {
cw.visitField(ACC_STATIC|ACC_PUBLIC|ACC_FINAL, "index", "I", null, new Integer(lambda.index));
cw.visitField(ACC_STATIC|ACC_PUBLIC|ACC_FINAL, "old_index", "I", null, new Integer(lambda.old_index));
cw.visitField(ACC_STATIC|ACC_PUBLIC|ACC_FINAL, "old_uniq", "I", null, new Integer(lambda.old_uniq));
/** */
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "encode", "("+ Type.getDescriptor(EOutputStream.class) +")V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 1);
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, full_inner_name, "pid", EPID_TYPE.getDescriptor());
mv.visitLdcInsn(module);
mv.visitFieldInsn(GETSTATIC, full_inner_name, "old_index", "I");
mv.visitInsn(I2L);
mv.visitLdcInsn(new Integer(arity));
mv.visitFieldInsn(GETSTATIC, outer_name, "module_md5", EBINARY_TYPE.getDescriptor());
mv.visitFieldInsn(GETSTATIC, full_inner_name, "index", "I");
mv.visitInsn(I2L);
mv.visitFieldInsn(GETSTATIC, full_inner_name, "old_uniq", "I");
mv.visitInsn(I2L);
mv.visitLdcInsn(new Integer(freevars));
mv.visitTypeInsn(ANEWARRAY, EOBJECT_NAME);
for (int i = 0; i < freevars; i++) {
mv.visitInsn(DUP);
if (i <= 5) {
mv.visitInsn(ICONST_0+i);
} else {
mv.visitLdcInsn(new Integer(i));
}
mv.visitVarInsn(ALOAD, 0); // load self
mv.visitFieldInsn(GETFIELD, full_inner_name, "fv"+i, EOBJECT_DESC);
mv.visitInsn(AASTORE);
}
mv.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(EOutputStream.class), "write_fun",
"("+EPID_TYPE.getDescriptor()+"Ljava/lang/String;"
+"JI"+EBINARY_TYPE.getDescriptor()
+"JJ"+Type.getDescriptor(EObject[].class)+")V");
mv.visitInsn(RETURN);
mv.visitMaxs(10, 3);
mv.visitEnd();
}
make_constructor(cw, module, function,
full_inner_name, super_class_name, lambda, exported);
make_go_method(cw, outer_name, fname, full_inner_name, arity, proc,
freevars, return_type, is_tail_call, is_pausable);
make_go2_method(cw, outer_name, fname, full_inner_name, arity, proc,
freevars, return_type, is_tail_call, is_pausable);
return cw.toByteArray();
}
private static void make_constructor(ClassWriter cw,
String module_name, String function_name,
String full_inner_name, String super_class_name, Lambda lambda, boolean exported) {
StringBuilder sb = new StringBuilder("(");
int freevars = lambda==null?0:lambda.freevars;
if (lambda != null) {
sb.append(EPID_TYPE.getDescriptor());
cw.visitField(ACC_PUBLIC|ACC_FINAL, "pid", EPID_TYPE.getDescriptor(), null, null);
}
// create the free vars
for (int i = 0; i < freevars; i++) {
cw.visitField(ACC_PUBLIC | ACC_FINAL, "fv" + i, EOBJECT_DESC,
null, null);
sb.append(EOBJECT_DESC);
}
sb.append(")V");
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", sb.toString(),
null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
if (exported) {
mv.visitLdcInsn(module_name);
mv.visitLdcInsn(function_name);
mv.visitMethodInsn(INVOKESPECIAL, super_class_name, "<init>", "(Ljava/lang/String;Ljava/lang/String;)V");
} else {
mv.visitMethodInsn(INVOKESPECIAL, super_class_name, "<init>", "()V");
}
if (lambda != null) {
mv.visitVarInsn(ALOAD, 0);
mv.visitVarInsn(ALOAD, 1);
mv.visitFieldInsn(PUTFIELD, full_inner_name, "pid",
EPID_TYPE.getDescriptor());
}
for (int i = 0; i < freevars; i++) {
mv.visitVarInsn(ALOAD, 0);
mv.visitVarInsn(ALOAD, i + 2);
mv
.visitFieldInsn(PUTFIELD, full_inner_name, "fv" + i,
EOBJECT_DESC);
}
mv.visitInsn(RETURN);
mv.visitMaxs(3, 3);
mv.visitEnd();
if (lambda != null) {
mv = cw.visitMethod(ACC_PROTECTED, "get_env", "()"+ESEQ_DESC, null, null);
mv.visitCode();
mv.visitFieldInsn(GETSTATIC, ERT_NAME, "NIL", ENIL_TYPE.getDescriptor());
for (int i = freevars-1; i >= 0; i--) {
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, full_inner_name, "fv"+i, EOBJECT_DESC);
mv.visitMethodInsn(INVOKEVIRTUAL, ESEQ_NAME, "cons", "("+EOBJECT_DESC+")"+ESEQ_DESC);
}
mv.visitInsn(ARETURN);
mv.visitMaxs(3, 3);
mv.visitEnd();
mv = cw.visitMethod(ACC_PROTECTED, "get_pid", "()"+EOBJECT_DESC, null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, full_inner_name, "pid", EPID_TYPE.getDescriptor());
mv.visitInsn(ARETURN);
mv.visitMaxs(3, 3);
mv.visitEnd();
mv = cw.visitMethod(ACC_PROTECTED, "get_id", "()"+Type.getDescriptor(FunID.class), null, null);
mv.visitCode();
mv.visitFieldInsn(GETSTATIC, full_inner_name.substring(0, full_inner_name.indexOf('$')),
anon_fun_name(lambda), Type.getDescriptor(LocalFunID.class));
mv.visitInsn(ARETURN);
mv.visitMaxs(3, 3);
mv.visitEnd();
}
}
private static void make_invoke_method(ClassWriter cw, String outer_name,
String mname, int arity, boolean proc, int freevars, Type returnType, boolean isTailCall) {
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "invoke", EUtil
.getSignature(arity - freevars, true), null, PAUSABLE_EX);
mv.visitCode();
if (proc) {
mv.visitVarInsn(ALOAD, 1);
}
for (int i = 0; i < arity - freevars; i++) {
mv.visitVarInsn(ALOAD, i + 2);
}
for (int i = 0; i < freevars; i++) {
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, outer_name + "$FN_" + mname, "fv" + i,
EOBJECT_DESC);
}
mv.visitMethodInsn(INVOKESTATIC, outer_name, mname, EUtil.getSignature(
arity, proc, returnType));
if (isTailCall) {
mv.visitVarInsn(ASTORE, arity + 2);
Label done = new Label();
Label loop = new Label();
mv.visitLabel(loop);
mv.visitVarInsn(ALOAD, arity + 2);
if (EProc.TAIL_MARKER == null) {
mv.visitJumpInsn(IFNONNULL, done);
} else {
mv.visitFieldInsn(GETSTATIC, EPROC_NAME, "TAIL_MARKER", EOBJECT_DESC);
mv.visitJumpInsn(IF_ACMPNE, done);
}
// load proc
mv.visitVarInsn(ALOAD, 1);
mv.visitFieldInsn(GETFIELD, EPROC_NAME, "tail", EFUN_DESCRIPTOR);
mv.visitVarInsn(ALOAD, 1);
mv.visitMethodInsn(INVOKEVIRTUAL, EFUN_NAME, "go", GO_DESC);
mv.visitVarInsn(ASTORE, arity + 2);
mv.visitJumpInsn(GOTO, loop);
mv.visitLabel(done);
mv.visitVarInsn(ALOAD, arity + 2);
}
mv.visitInsn(ARETURN);
mv.visitMaxs(arity + 2, arity + 2);
mv.visitEnd();
}
public static void make_invoketail_method(ClassWriter cw,
String full_inner, int arity, int freevars) {
MethodVisitor mv;
mv = cw.visitMethod(ACC_PUBLIC|ACC_FINAL, "invoke_tail", EUtil.getSignature(arity
- freevars, true), null, null);
mv.visitCode();
for (int i = 0; i < arity - freevars; i++) {
mv.visitVarInsn(ALOAD, 1);
mv.visitVarInsn(ALOAD, i + 2);
mv.visitFieldInsn(PUTFIELD, EPROC_NAME, "arg" + i, EOBJECT_DESC);
}
mv.visitVarInsn(ALOAD, 1);
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(PUTFIELD, EPROC_NAME, "tail", EFUN_DESCRIPTOR);
if (EProc.TAIL_MARKER == null) {
mv.visitInsn(ACONST_NULL);
} else {
mv.visitFieldInsn(GETSTATIC, EPROC_NAME, "TAIL_MARKER", EOBJECT_DESC);
}
mv.visitInsn(ARETURN);
mv.visitMaxs(arity + 2, arity + 2);
mv.visitEnd();
}
private static void make_go_method(ClassWriter cw, String outer_name,
String mname, String full_inner, int arity, boolean proc,
int freevars, Type returnType, boolean isTailCall, boolean isPausable) {
if (!isPausable) return;
MethodVisitor mv;
mv = cw.visitMethod(ACC_PUBLIC, "go", GO_DESC, null, PAUSABLE_EX);
mv.visitCode();
for (int i = 0; i < arity - freevars; i++) {
mv.visitVarInsn(ALOAD, 1);
mv.visitFieldInsn(GETFIELD, EPROC_NAME, "arg" + i, EOBJECT_DESC);
mv.visitVarInsn(ASTORE, i + 2);
}
for (int i = 0; i < arity - freevars; i++) {
mv.visitVarInsn(ALOAD, 1);
mv.visitInsn(ACONST_NULL);
mv.visitFieldInsn(PUTFIELD, EPROC_NAME, "arg" + i, EOBJECT_DESC);
}
if (proc)
mv.visitVarInsn(ALOAD, 1);
for (int i = 0; i < arity - freevars; i++) {
mv.visitVarInsn(ALOAD, i + 2);
}
for (int i = 0; i < freevars; i++) {
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, full_inner, "fv" + i, EOBJECT_DESC);
}
mv.visitMethodInsn(INVOKESTATIC, outer_name, mname, EUtil.getSignature(
arity, proc, returnType));
mv.visitInsn(ARETURN);
mv.visitMaxs(arity + 2, arity + 2);
mv.visitEnd();
cw.visitEnd();
}
private static void make_go2_method(ClassWriter cw, String outer_name,
String mname, String full_inner, int arity, boolean proc,
int freevars, Type returnType, boolean isTailCall, boolean isPausable) {
if (isPausable) {
if (ModuleAnalyzer.log.isLoggable(Level.FINE)) {
ModuleAnalyzer.log.fine
("not generating go2 (pausable) for "+full_inner);
}
return;
}
MethodVisitor mv;
mv = cw.visitMethod(ACC_PUBLIC, "go2", GO_DESC, null, null);
mv.visitCode();
for (int i = 0; i < arity - freevars; i++) {
mv.visitVarInsn(ALOAD, 1);
mv.visitFieldInsn(GETFIELD, EPROC_NAME, "arg" + i, EOBJECT_DESC);
mv.visitVarInsn(ASTORE, i + 2);
}
for (int i = 0; i < arity - freevars; i++) {
mv.visitVarInsn(ALOAD, 1);
mv.visitInsn(ACONST_NULL);
mv.visitFieldInsn(PUTFIELD, EPROC_NAME, "arg" + i, EOBJECT_DESC);
}
if (proc)
mv.visitVarInsn(ALOAD, 1);
for (int i = 0; i < arity - freevars; i++) {
mv.visitVarInsn(ALOAD, i + 2);
}
for (int i = 0; i < freevars; i++) {
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, full_inner, "fv" + i, EOBJECT_DESC);
}
mv.visitMethodInsn(INVOKESTATIC, outer_name, mname, EUtil.getSignature(
arity, proc, returnType));
mv.visitInsn(ARETURN);
mv.visitMaxs(arity + 2, arity + 2);
mv.visitEnd();
cw.visitEnd();
}
public void setFunInfos(Map<FunID, FunInfo> funInfos) {
this.funInfos = funInfos;
}
}
/** Active exception handler */
class EXHandler {
int handler_beam_label;
Label begin, end, target;
BeamExceptionHandler beam_exh;
}
| Remove debug message | src/main/java/erjang/beam/CompilerVisitor.java | Remove debug message | <ide><path>rc/main/java/erjang/beam/CompilerVisitor.java
<ide> throw new InternalError("Exception handler not inserted: "+h.handler_beam_label);
<ide>
<ide> if (deadBlocks.contains(h.handler_beam_label)) {
<del> System.out.println("skipping dead ex handler "+ fun_name + ", label #"+h.handler_beam_label);
<ide> continue;
<ide> }
<ide> |
|
JavaScript | bsd-2-clause | 3ceae40aa666354a237926527792e864c36a5778 | 0 | tidepool-org/blip,tidepool-org/blip,tidepool-org/blip | import React, { useState } from 'react';
import moment from 'moment';
import WindowSizeListener from 'react-window-size-listener';
import { withDesign } from 'storybook-addon-designs';
import { withKnobs, boolean, date, optionsKnob as options } from '@storybook/addon-knobs';
import 'react-dates/lib/css/_datepicker.css';
import 'react-dates/initialize';
import DatePicker from '../app/components/elements/DatePicker';
import DateRangePicker from '../app/components/elements/DateRangePicker';
// This silly decorator allows the components to properly re-render when knob values are changed
const withWrapper = Story => <Story />;
export default {
title: 'Date Pickers',
decorators: [withDesign, withKnobs, withWrapper],
};
export const DatePickerStory = () => {
const initialDate = new Date();
const dateKnob = (name, defaultValue) => {
const stringTimestamp = date(name, defaultValue);
return moment.utc(stringTimestamp);
};
const getFocused = () => boolean('Initially Focused', true);
return <DatePicker
id="singleDatePicker"
focused={getFocused()}
date={dateKnob('Initial Date', initialDate)}
/>;
};
DatePickerStory.story = {
name: 'Single Date',
parameters: {
design: {
type: 'figma',
url: 'https://www.figma.com/file/iuXkrpuLTXExSnuPJE3Jtn/Tidepool-Design-System---Sprint-1?node-id=198%3A6',
},
},
};
export const DateRangePickerStory = () => {
const initialStartDate = new Date();
const initialEndDate = new Date();
initialEndDate.setDate(initialEndDate.getDate() + 7);
const dateKnob = (name, defaultValue) => {
const stringTimestamp = date(name, defaultValue);
return moment.utc(stringTimestamp);
};
const focusedInputKnob = () => {
const label = 'Initially Focused Input';
const valuesObj = {
'Start Date': 'startDate',
'End Date': 'endDate',
None: null,
};
const defaultValue = 'startDate';
const optionsObj = {
display: 'select',
};
return options(label, valuesObj, defaultValue, optionsObj);
};
const [orientation, setOrientation] = useState('horizontal');
const handleWindowResize = size => {
setOrientation(size.windowWidth > 550 ? 'horizontal' : 'vertical');
};
return (
<React.Fragment>
<DateRangePicker
startDateId="dateRangeStart"
endDateId="dateRangeEnd"
orientation={orientation}
focusedInput={focusedInputKnob()}
startDate={dateKnob('Initial Start Date', initialStartDate)}
endDate={dateKnob('Initial End Date', initialEndDate)}
/>
<WindowSizeListener onResize={handleWindowResize} />
</React.Fragment>
);
};
DateRangePickerStory.story = {
name: 'Date Range',
parameters: {
design: {
type: 'figma',
url: 'https://www.figma.com/file/iuXkrpuLTXExSnuPJE3Jtn/Tidepool-Design-System---Sprint-1?node-id=198%3A6',
},
},
};
| stories/Datepicker.stories.js | import React from 'react';
import moment from 'moment';
import { withDesign } from 'storybook-addon-designs';
import { withKnobs, boolean, date, optionsKnob as options } from '@storybook/addon-knobs';
import 'react-dates/lib/css/_datepicker.css';
import 'react-dates/initialize';
import DatePicker from '../app/components/elements/DatePicker';
import DateRangePicker from '../app/components/elements/DateRangePicker';
// This silly decorator allows the components to properly re-render when knob values are changed
const withWrapper = Story => <Story />;
export default {
title: 'Date Pickers',
decorators: [withDesign, withKnobs, withWrapper],
};
export const DatePickerStory = () => {
const initialDate = new Date();
const initialDateKnob = (name, defaultValue) => {
const stringTimestamp = date(name, defaultValue);
return moment.utc(stringTimestamp);
};
const getFocused = () => boolean('Initially Focused', true);
return <DatePicker
id="singleDatePicker"
initialFocused={getFocused()}
initialDate={initialDateKnob('Initial Date', initialDate)}
/>;
};
DatePickerStory.story = {
name: 'Single Date',
parameters: {
design: {
type: 'figma',
url: 'https://www.figma.com/file/iuXkrpuLTXExSnuPJE3Jtn/Tidepool-Design-System---Sprint-1?node-id=198%3A6',
},
},
};
export const DateRangePickerStory = () => {
const initialStartDate = new Date();
const initialEndDate = new Date();
initialEndDate.setDate(initialEndDate.getDate() + 7);
const initialDateKnob = (name, defaultValue) => {
const stringTimestamp = date(name, defaultValue);
return moment.utc(stringTimestamp);
};
const focusedInputKnob = () => {
const label = 'Initially Focused Input';
const valuesObj = {
'Start Date': 'startDate',
'End Date': 'endDate',
None: null,
};
const defaultValue = 'startDate';
const optionsObj = {
display: 'select',
};
return options(label, valuesObj, defaultValue, optionsObj);
};
return <DateRangePicker
startDateId="dateRangeStart"
endDateId="dateRangeEnd"
initialFocusedInput={focusedInputKnob()}
initialStartDate={initialDateKnob('Initial Start Date', initialStartDate)}
initialEndDate={initialDateKnob('Initial End Date', initialEndDate)}
/>;
};
DateRangePickerStory.story = {
name: 'Date Range',
parameters: {
design: {
type: 'figma',
url: 'https://www.figma.com/file/iuXkrpuLTXExSnuPJE3Jtn/Tidepool-Design-System---Sprint-1?node-id=198%3A6',
},
},
};
| [WEB-591] Update datepicker stories to match simplified API and add responsive example for the range picker
| stories/Datepicker.stories.js | [WEB-591] Update datepicker stories to match simplified API and add responsive example for the range picker | <ide><path>tories/Datepicker.stories.js
<del>import React from 'react';
<add>import React, { useState } from 'react';
<ide> import moment from 'moment';
<add>import WindowSizeListener from 'react-window-size-listener';
<ide>
<ide> import { withDesign } from 'storybook-addon-designs';
<ide> import { withKnobs, boolean, date, optionsKnob as options } from '@storybook/addon-knobs';
<ide> export const DatePickerStory = () => {
<ide> const initialDate = new Date();
<ide>
<del> const initialDateKnob = (name, defaultValue) => {
<add> const dateKnob = (name, defaultValue) => {
<ide> const stringTimestamp = date(name, defaultValue);
<ide> return moment.utc(stringTimestamp);
<ide> };
<ide>
<ide> return <DatePicker
<ide> id="singleDatePicker"
<del> initialFocused={getFocused()}
<del> initialDate={initialDateKnob('Initial Date', initialDate)}
<add> focused={getFocused()}
<add> date={dateKnob('Initial Date', initialDate)}
<ide> />;
<ide> };
<ide>
<ide> const initialEndDate = new Date();
<ide> initialEndDate.setDate(initialEndDate.getDate() + 7);
<ide>
<del> const initialDateKnob = (name, defaultValue) => {
<add> const dateKnob = (name, defaultValue) => {
<ide> const stringTimestamp = date(name, defaultValue);
<ide> return moment.utc(stringTimestamp);
<ide> };
<ide> return options(label, valuesObj, defaultValue, optionsObj);
<ide> };
<ide>
<del> return <DateRangePicker
<del> startDateId="dateRangeStart"
<del> endDateId="dateRangeEnd"
<del> initialFocusedInput={focusedInputKnob()}
<del> initialStartDate={initialDateKnob('Initial Start Date', initialStartDate)}
<del> initialEndDate={initialDateKnob('Initial End Date', initialEndDate)}
<del> />;
<add> const [orientation, setOrientation] = useState('horizontal');
<add>
<add> const handleWindowResize = size => {
<add> setOrientation(size.windowWidth > 550 ? 'horizontal' : 'vertical');
<add> };
<add>
<add> return (
<add> <React.Fragment>
<add> <DateRangePicker
<add> startDateId="dateRangeStart"
<add> endDateId="dateRangeEnd"
<add> orientation={orientation}
<add> focusedInput={focusedInputKnob()}
<add> startDate={dateKnob('Initial Start Date', initialStartDate)}
<add> endDate={dateKnob('Initial End Date', initialEndDate)}
<add> />
<add> <WindowSizeListener onResize={handleWindowResize} />
<add> </React.Fragment>
<add> );
<ide> };
<ide>
<ide> DateRangePickerStory.story = { |
|
Java | bsd-3-clause | 114b769a6a0a2bfc33ad16e420c5b68a39120d69 | 0 | edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon | /*
* $Id: LockssServlet.java,v 1.36 2004-03-04 19:24:11 tlipkis Exp $
*/
/*
Copyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.servlet;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import java.util.*;
import java.net.*;
import java.text.*;
// import com.mortbay.servlet.*;
// import org.mortbay.util.*;
import org.mortbay.html.*;
import org.mortbay.tools.*;
import org.lockss.app.*;
import org.lockss.util.*;
import org.lockss.daemon.*;
/** Abstract base class for LOCKSS servlets
*/
// SingleThreadModel causes servlet instances to be assigned to only a
// single thread (request) at a time.
public abstract class LockssServlet extends HttpServlet
implements SingleThreadModel {
// Constants
static final String PARAM_LOCAL_IP = Configuration.PREFIX + "localIPAddress";
// static final String PARAM_IS_CLUSTER_ADMIN =
// Configuration.PREFIX + "clusterAdmin";
static final String PARAM_CONTACT_ADDR =
Configuration.PREFIX + "admin.contactEmail";
static final String DEFAULT_CONTACT_ADDR = "contactnotset@notset";
static final String PARAM_PLATFORM_VERSION =
Configuration.PREFIX + "platform.version";
static final String PARAM_ADMIN_ADDRESS =
Configuration.PREFIX + "admin.IPAddress";
public static final String JAVASCRIPT_RESOURCE =
"org/lockss/htdocs/admin.js";
/** Format to display date/time in headers */
public static final DateFormat headerDf =
new SimpleDateFormat("HH:mm:ss MM/dd/yy");
static final String BACKGROUND_COLOR = "#FFFFFF";
static final Image IMAGE_LOGO_LARGE = image("lockss-logo-large.gif",
160, 160, 0);
static final Image IMAGE_LOGO_SMALL = image("lockss-logo-small.gif",
80, 81, 0);
static final Image IMAGE_TM = image("tm.gif", 16, 16, 0);
static final Image IMAGE_LOCKSS_RED = image("lockss-type-red.gif",
595, 31, 0);
protected static final String footAccessDenied =
"Clicking on this link will result in an access denied error, unless your browser is configured to proxy through a LOCKSS cache, or your workstation is allowed access by the publisher.";
protected static Logger log = Logger.getLogger("LockssServlet");
protected ServletContext context;
private LockssDaemon theDaemon = null;
// Request-local storage. Convenient, but requires servlet instances
// to be single threaded, and must ensure reset them to avoid carrying
// over state between requests.
protected HttpServletRequest req;
protected HttpServletResponse resp;
protected URL reqURL;
private String adminDir = null;
protected String client; // client param
protected String clientAddr; // client addr, even if no param
protected String adminAddr;
protected String adminHost;
protected String localAddr;
private Vector footnotes;
private int footNumber;
ServletDescr _myServletDescr = null;
private String myName = null;
/** Marker for servlets whose class can't be found */
static class UnavailableServletMarker {
}
static Class UNAVAILABLE_SERVLET_MARKER = UnavailableServletMarker.class;
// Servlet descriptor.
static class ServletDescr {
public Class cls;
public String heading; // display name
public String name; // url path component to invoke servlet
public int flags = 0;
// flags
public static int ON_CLIENT = 1; // runs on client (else on admin)
public static int PER_CLIENT = 2; // per client (takes client arg)
public static int NOT_IN_NAV = 4; // no link in nav table
public static int LARGE_LOGO = 8; // use large LOCKSS logo
public static int DEBUG_ONLY = 0x10; // debug user only
public static int STATUS = ON_CLIENT | PER_CLIENT; // shorthand
public ServletDescr(Class cls, String heading, String name, int flags) {
this.cls = cls;
this.heading = heading;
this.name = name;
this.flags = flags;
}
public ServletDescr(Class cls, String heading, int flags) {
this(cls, heading,
cls.getName().substring(cls.getName().lastIndexOf('.') + 1),
flags);
}
public ServletDescr(Class cls, String heading) {
this(cls, heading, 0);
}
public ServletDescr(String className, String heading, String name) {
this(classForName(className), heading, name, 0);
}
public ServletDescr(String className, String heading, int flags) {
this(classForName(className), heading, flags);
}
static Class classForName(String className) {
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
return UNAVAILABLE_SERVLET_MARKER;
}
}
boolean isPerClient() {
return (flags & PER_CLIENT) != 0;
}
boolean runsOnClient() {
return (flags & ON_CLIENT) != 0;
}
boolean isInNavTable() {
return (flags & NOT_IN_NAV) == 0;
}
boolean isDebugOnly() {
return (flags & DEBUG_ONLY) != 0;
}
boolean isLargeLogo() {
return (flags & LARGE_LOGO) != 0;
}
}
// Descriptors for all servlets.
protected static ServletDescr SERVLET_AU_CONFIG =
new ServletDescr(AuConfig.class, "Journal Configuration");
protected static ServletDescr SERVLET_DAEMON_STATUS =
new ServletDescr(DaemonStatus.class, "Daemon Status");
protected static ServletDescr SERVLET_PROXY_INFO =
new ServletDescr(ProxyConfig.class, "Proxy Info", "info/ProxyInfo", 0);
protected static ServletDescr SERVLET_THREAD_DUMP =
new ServletDescr("org.lockss.servlet.ThreadDump", "Thread Dump",
ServletDescr.DEBUG_ONLY);
protected static ServletDescr LINK_LOGS =
new ServletDescr(null, "Logs", "log", ServletDescr.DEBUG_ONLY);
protected static ServletDescr SERVLET_ADMIN_ACCESS_CONTROL =
new ServletDescr(AdminIpAccess.class, "Admin Access Control");
protected static ServletDescr SERVLET_PROXY_ACCESS_CONTROL =
new ServletDescr(ProxyIpAccess.class, "Proxy Access Control");
// protected static ServletDescr SERVLET_ADMIN_HOME =
// new ServletDescr(Admin.class, "Admin Home", ServletDescr.LARGE_LOGO);
// protected static ServletDescr SERVLET_JOURNAL_STATUS =
// new ServletDescr(JournalStatus.class, "Journal Status",
// ServletDescr.STATUS);
// protected static ServletDescr SERVLET_JOURNAL_SETUP =
// new ServletDescr(JournalSettings.class, "Journal Setup",
// ServletDescr.PER_CLIENT);
// protected static ServletDescr SERVLET_DAEMON_STATUS =
// new ServletDescr(DaemonStatus.class, "Daemon Status",
// ServletDescr.STATUS + ServletDescr.NOT_IN_NAV);
// All servlets must be listed here (even if not in van table).
// Order of descrs determines order in nav table.
static ServletDescr servletDescrs[] = {
SERVLET_AU_CONFIG,
SERVLET_ADMIN_ACCESS_CONTROL,
SERVLET_PROXY_ACCESS_CONTROL,
SERVLET_PROXY_INFO,
SERVLET_DAEMON_STATUS,
LINK_LOGS,
SERVLET_THREAD_DUMP,
// SERVLET_ADMIN_HOME,
// SERVLET_JOURNAL_STATUS,
// SERVLET_JOURNAL_SETUP,
// SERVLET_DAEMON_STATUS,
// SERVLET_ACCESS_CONTROL,
};
// Create mapping from servlet class to ServletDescr
private static final Hashtable servletToDescr = new Hashtable();
static {
for (int i = 0; i < servletDescrs.length; i++) {
ServletDescr d = servletDescrs[i];
if (d.cls != null && d.cls != UNAVAILABLE_SERVLET_MARKER) {
servletToDescr.put(d.cls, d);
}
}
};
private ServletDescr findServletDescr(Object o) {
ServletDescr d = (ServletDescr)servletToDescr.get(o.getClass());
if (d != null) return d;
// if not in map, o might be an instance of a subclass of a servlet class
// that's in the map.
for (int i = 0; i < servletDescrs.length; i++) {
d = servletDescrs[i];
if (d.cls != null && d.cls.isInstance(o)) {
// found a descr that describes a superclass. Add actual class to map
servletToDescr.put(o.getClass(), d);
return d;
}
}
return null; // shouldn't happen
// XXX do something better here
}
/** Run once when servlet loaded. */
public void init(ServletConfig config) throws ServletException {
super.init(config);
context = config.getServletContext();
theDaemon = (LockssDaemon)context.getAttribute("LockssDaemon");
}
/** Servlets must implement this method. */
protected abstract void lockssHandleRequest() throws ServletException, IOException;
/** Common request handling. */
public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
this.req = req;
this.resp = resp;
if (log.isDebug()) {
logParams();
}
resp.setContentType("text/html");
footNumber = 0;
reqURL = new URL(UrlUtil.getRequestURL(req));
adminAddr = req.getParameter("admin");
if (adminAddr == null) {
adminAddr = Configuration.getParam(PARAM_ADMIN_ADDRESS);
}
adminHost = reqURL.getHost();
client = req.getParameter("client");
clientAddr = client;
if (clientAddr == null) {
clientAddr = getLocalIPAddr();
}
lockssHandleRequest();
}
finally {
// Don't hold on to stuff forever
req = null;
resp = null;
reqURL = null;
adminDir = null;
localAddr = null;
footnotes = null;
_myServletDescr = null;
myName = null;
}
}
// Return descriptor of running servlet
protected ServletDescr myServletDescr() {
if (_myServletDescr == null) {
_myServletDescr = findServletDescr(this);
}
return _myServletDescr;
}
// By default, servlet heading is in descr. Override method to
// compute other heading
protected String getHeading(ServletDescr d) {
if (d == null) return "Unknown Servlet";
return d.heading;
}
protected String getHeading() {
return getHeading(myServletDescr());
}
String getLocalIPAddr() {
if (localAddr == null) {
try {
IPAddr localHost = IPAddr.getLocalHost();
localAddr = localHost.getHostAddress();
} catch (UnknownHostException e) {
// shouldn't happen
log.error("LockssServlet: getLocalHost: " + e.toString());
return "???";
}
}
return localAddr;
}
// Return IP addr used by LCAP. If specified by (misleadingly named)
// localIPAddress prop, might not really be our address (if we are
// behind NAT).
String getLcapIPAddr() {
String ip = Configuration.getParam(PARAM_LOCAL_IP);
if (ip.length() <= 0) {
return getLocalIPAddr();
}
return ip;
}
String getMachineName() {
if (myName == null) {
// Return the canonical name of the interface the request was aimed
// at. (localIPAddress prop isn't necessarily right here, as it
// might be the address of a NAT that we're behind.)
String host = reqURL.getHost();
try {
IPAddr localHost = IPAddr.getByName(host);
String ip = localHost.getHostAddress();
myName = getMachineName(ip);
} catch (UnknownHostException e) {
// shouldn't happen
log.error("getMachineName", e);
return host;
}
}
return myName;
}
String getMachineName(String ip) {
try {
IPAddr inet = IPAddr.getByName(ip);
return inet.getHostName();
} catch (UnknownHostException e) {
log.warning("getMachineName", e);
}
return ip;
}
// return IP given name or IP
String getMachineIP(String name) {
try {
IPAddr inet = IPAddr.getByName(name);
return inet.getHostAddress();
} catch (UnknownHostException e) {
return null;
}
}
// Servlet predicates
boolean isPerClient() {
return myServletDescr().isPerClient();
}
boolean runsOnClient() {
return myServletDescr().runsOnClient();
}
boolean isServletLinkInNav(ServletDescr d) {
return !isThisServlet(d) || linkMeInNav();
}
boolean isThisServlet(ServletDescr d) {
return d == myServletDescr();
}
/** servlets may override this to determine whether they should be
* a link in nav table */
protected boolean linkMeInNav() {
return false;
}
boolean isLargeLogo() {
return myServletDescr().isLargeLogo();
}
// machine predicates
boolean isClusterAdmin() {
return false;
// return Configuration.getBooleanParam(PARAM_IS_CLUSTER_ADMIN, false);
}
// user predicates
protected boolean isDebugUser() {
return req.isUserInRole("debugRole");
}
// Called when a servlet doesn't get the parameters it expects/needs
protected void paramError() throws IOException {
PrintWriter wrtr = resp.getWriter();
Page page = new Page();
// add referer, params, msg to contact lockss unless from old bookmark
// or manually entered url
page.add("Parameter error");
page.write(wrtr);
}
// return true iff error
protected boolean checkParam(boolean ok, String msg) throws IOException {
if (ok) return false;
log.error(myServletDescr().name + ": " + msg);
paramError();
return true;
}
/** Construct servlet URL, with params as necessary. Avoid generating a
* hostname different from that used in the original request, or
* browsers will prompt again for login
*/
String srvURL(ServletDescr d, String params) {
return srvURL(null, d, params);
}
/** Construct servlet absolute URL, with params as necessary.
*/
String srvAbsURL(ServletDescr d, String params) {
return srvURL(getMachineName(), d, params);
}
/** Construct servlet URL, with params as necessary. Avoid generating a
* hostname different from that used in the original request, or
* browsers will prompt again for login
*/
String srvURL(String host, ServletDescr d, String params) {
StringBuffer sb = new StringBuffer();
StringBuffer paramsb = new StringBuffer();
if (!clientAddr.equals(adminAddr)) {
if (!d.runsOnClient()) {
if (runsOnClient()) { // invoking admin servlet from client
host = adminAddr;
}
} else if (!runsOnClient()) { // invoking client servlet from admin
host = clientAddr;
paramsb.append("&admin=");
paramsb.append(adminHost);
}
}
if (params != null) {
paramsb.append('&');
paramsb.append(params);
}
if (d.isPerClient()) {
paramsb.append("&client=");
paramsb.append(clientAddr);
}
if (host != null) {
sb.append(reqURL.getProtocol());
sb.append("://");
sb.append(host);
sb.append(':');
sb.append(reqURL.getPort());
}
sb.append('/');
sb.append(d.name);
if (paramsb.length() != 0) {
paramsb.setCharAt(0, '?');
sb.append(paramsb.toString());
}
return sb.toString();
}
/** Return a link to a servlet */
String srvLink(ServletDescr d, String text) {
return srvLink(d, text, null);
}
/** Return a link to a servlet with params */
String srvLink(ServletDescr d, String text, String params) {
return new Link(srvURL(d, params),
(text != null ? text : d.heading)).toString();
}
/** Return an absolute link to a servlet with params */
String srvAbsLink(ServletDescr d, String text, String params) {
return new Link(srvAbsURL(d, params),
(text != null ? text : d.heading)).toString();
}
/** Return text as a link iff isLink */
String conditionalSrvLink(ServletDescr d, String text, String params,
boolean isLink) {
if (isLink) {
return srvLink(d, text, params);
} else {
return text;
}
}
/** Return text as a link iff isLink */
String conditionalSrvLink(ServletDescr d, String text, boolean isLink) {
return conditionalSrvLink(d, text, null, isLink);
}
/** Concatenate params for URL string */
String concatParams(String p1, String p2) {
if (p1 == null || p1.equals("")) {
return p2;
}
if (p2 == null || p2.equals("")) {
return p1;
}
return p1 + "&" + p2;
}
protected String urlEncode(String param) {
return URLEncoder.encode(param);
}
protected boolean isServletInNav(ServletDescr d) {
if (!isDebugUser() && d.isDebugOnly()) return false;
if (d.cls == UNAVAILABLE_SERVLET_MARKER) return false;
return d.isInNavTable() && (!d.isPerClient() || isPerClient());
}
// Build servlet navigation table
private Table getNavTable() {
Table navTable = new Table(0, " CELLSPACING=2 CELLPADDING=0 ");
boolean clientTitle = false;
for (int i = 0; i < servletDescrs.length; i++) {
ServletDescr d = servletDescrs[i];
if (isServletInNav(d)) {
navTable.newRow();
navTable.newCell();
if (d.isPerClient()) {
if (!clientTitle) {
// Insert client name before first per-client servlet
navTable.cell().attribute("WIDTH=\"15\"");
navTable.newCell();
navTable.cell().attribute("COLSPAN=\"2\"");
navTable.add("<b>" + getMachineName(clientAddr) + "</b>");
navTable.newRow();
navTable.newCell();
clientTitle = true;
}
navTable.cell().attribute("WIDTH=\"15\"");
navTable.newCell();
navTable.cell().attribute("WIDTH=\"15\"");
navTable.newCell();
} else {
navTable.cell().attribute("COLSPAN=\"3\"");
}
if (false /*isThisServlet(d)*/) {
navTable.add("<font size=-1 color=green>");
} else {
navTable.add("<font size=-1>");
}
navTable.add(conditionalSrvLink(d, d.heading, isServletLinkInNav(d)));
navTable.add("</font>");
}
}
navTable.newRow();
navTable.newCell();
navTable.cell().attribute("COLSPAN=\"3\"");
String contactAddr =
Configuration.getParam(PARAM_CONTACT_ADDR, DEFAULT_CONTACT_ADDR);
navTable.add("<font size=-1>");
navTable.add(new Link("mailto:" + contactAddr, "Contact Us"));
navTable.add("</font>");
return navTable;
}
protected Table getExplanationBlock(String text) {
Table exp = new Table(0, "width=\"85%\"");
exp.center();
exp.newCell("align=center");
exp.add(text);
return exp;
}
protected String getRequestKey() {
String key = req.getPathInfo();
if (key != null && key.startsWith("/")) {
return key.substring(1);
}
return key;
}
/** Common page setup. */
protected Page newPage() {
Page page = new Page();
String heading = getHeading();
page.add("<!doctype html public \"-//w3c//dtd html 4.0 transitional//en\">");
page.addHeader("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">");
page.addHeader("<meta http-equiv=\"content-type\" content=\"text/html;charset=ISO-8859-1\">");
page.addHeader("<style type=\"text/css\"><!-- sup {font-weight: normal} --> </STYLE>");
if (heading != null)
page.title("LOCKSS: " + heading);
else
page.title("LOCKSS");
page.attribute("BGCOLOR", BACKGROUND_COLOR);
page.add(getHeader());
return page;
}
// Common page header
private Composite getHeader() {
String heading = getHeading();
if (heading == null) {
heading = "Cache Administration";
}
Composite comp = new Composite();
Table table = new Table(0, " cellspacing=2 cellpadding=0 width=\"100%\"");
comp.add(table);
String machineName = getMachineName();
table.newRow();
Image logo = isLargeLogo() ? IMAGE_LOGO_LARGE : IMAGE_LOGO_SMALL;
table.newCell("valign=top align=center width=\"20%\"");
// table.newCell("valign=top width=\"25%\"");
// table.newCell("valign=top align=center width=" +
// (logo.width() + IMAGE_TM.width() + 20));
table.add(new Link("/index.html", logo));
table.add(IMAGE_TM);
// table.newCell("valign=center align=center width=\"60%\"");
table.newCell("valign=top align=center width=\"60%\"");
table.add("<br>");
table.add("<font size=+2><b>");
table.add(heading);
table.add("</b></font>");
table.add("<br>");
Date startDate = getLockssDaemon().getStartDate();
String since =
StringUtil.timeIntervalToString(TimeBase.msSince(startDate.getTime()));
table.add(getMachineName() + " at " +
headerDf.format(new Date()) + ", up " + since);
// table.newCell("valign=center align=right width=\"25%\"");
table.newCell("valign=center align=center width=\"20%\"");
table.add(getNavTable());
// comp.add("<br><center><font size=+2><b>Cache Administration</b></font></center>");
// comp.add("<center><b>" + machineName + "</b></center>");
// comp.add("<br><center><font size=+1><b>"+heading+"</b></font></center>");
// Date startDate = getLockssDaemon().getStartDate();
// String since =
// StringUtil.timeIntervalToString(TimeBase.msSince(startDate.getTime()));
// comp.add("<center>" + getMachineName() + " at " +
// headerDf.format(new Date()) + ", up " + since + "</center>");
// // comp.add("<center>Running since " + headerDf.format(startDate) + "</center>");
comp.add("<br>");
return comp;
}
// Common page footer
public Element getFooter() {
Composite comp = new Composite();
String vDaemon = theDaemon.getVersionInfo();
addNotes(comp);
comp.add("<p>");
Table table = new Table(0, " CELLSPACING=0 CELLPADDING=0 ALIGN=CENTER");
table.newRow("VALIGN=TOP");
table.newCell();
table.add(IMAGE_LOCKSS_RED);
table.newCell();
table.add(IMAGE_TM);
table.newRow();
table.newCell("COLSPAN=2");
table.add("<center><font size=-1>" + vDaemon + "</font></center>");
comp.add(table);
// comp.add("<center><font size=-1>" + vDaemon + "</font></center>");
return comp;
}
// eventually this should calculate w & h
static Image image(String file, int w, int h, int border) {
return new Image("/images/" + file, w, h, border);
}
/** Add html tags to grey the text if isGrey is true */
protected String greyText(String txt, boolean isGrey) {
if (!isGrey) {
return txt;
}
return "<font color=gray>" + txt + "</font>";
}
/** Store a footnote, assign it a number, return html for footnote
* reference. If footnote in null or empty, no footnote is added and am
* empty string is returned. */
protected String addFootnote(String s) {
if (s == null || s.length() == 0) {
return "";
}
if (footNumber == 0) {
if (footnotes == null) {
footnotes = new Vector(10, 10);
} else {
footnotes.removeAllElements();
}
}
int n = footnotes.indexOf(s);
if (n < 0) {
n = footNumber++;
footnotes.addElement(s);
}
return "<sup><font size=-1>" + (n+1) + "</font></sup>";
}
/** Add accumulated footnotes to Composite. */
protected void addNotes(Composite elem) {
if (footnotes == null || footNumber == 0) {
return;
}
elem.add("<p><b>Notes:</b>");
elem.add("<ol><font size=-1>");
for (int n = 0; n < footNumber; n++) {
elem.add("<li value=" + (n+1) + ">" + footnotes.elementAt(n));
}
footnotes.removeAllElements();
elem.add("</font></ol>");
}
protected void addJavaScript(Composite comp) {
Script script = new Script(getJavascript());
comp.add(script);
}
private static String jstext = null;
private static synchronized String getJavascript() {
if (jstext == null) {
try {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream istr = loader.getResourceAsStream(JAVASCRIPT_RESOURCE);
jstext = StringUtil.fromInputStream(istr);
istr.close();
} catch (Exception e) {
log.error("Can't load javascript", e);
}
}
return jstext;
}
/** Return the daemon instance. */
protected LockssDaemon getLockssDaemon() {
return theDaemon;
}
protected void logParams() {
Enumeration en = req.getParameterNames();
while (en.hasMoreElements()) {
String name = (String)en.nextElement();
log.debug(name + " = " + req.getParameter(name));
}
}
/** Convenience method */
protected String encodeText(String s) {
return HtmlUtil.encode(s, HtmlUtil.ENCODE_TEXT);
}
/** Convenience method */
protected String encodeTextArea(String s) {
return HtmlUtil.encode(s, HtmlUtil.ENCODE_TEXTAREA);
}
/** Convenience method */
protected String encodeAttr(String s) {
return HtmlUtil.encode(s, HtmlUtil.ENCODE_ATTR);
}
}
| src/org/lockss/servlet/LockssServlet.java | /*
* $Id: LockssServlet.java,v 1.35 2004-03-04 19:20:53 tlipkis Exp $
*/
/*
Copyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.servlet;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import java.util.*;
import java.net.*;
import java.text.*;
// import com.mortbay.servlet.*;
// import org.mortbay.util.*;
import org.mortbay.html.*;
import org.mortbay.tools.*;
import org.lockss.app.*;
import org.lockss.util.*;
import org.lockss.daemon.*;
/** Abstract base class for LOCKSS servlets
*/
// SingleThreadModel causes servlet instances to be assigned to only a
// single thread (request) at a time.
public abstract class LockssServlet extends HttpServlet
implements SingleThreadModel {
// Constants
static final String PARAM_LOCAL_IP = Configuration.PREFIX + "localIPAddress";
// static final String PARAM_IS_CLUSTER_ADMIN =
// Configuration.PREFIX + "clusterAdmin";
static final String PARAM_CONTACT_ADDR =
Configuration.PREFIX + "admin.contactEmail";
static final String DEFAULT_CONTACT_ADDR = "contactnotset@notset";
static final String PARAM_PLATFORM_VERSION =
Configuration.PREFIX + "platform.version";
static final String PARAM_ADMIN_ADDRESS =
Configuration.PREFIX + "admin.IPAddress";
public static final String JAVASCRIPT_RESOURCE =
"org/lockss/htdocs/admin.js";
/** Format to display date/time in headers */
public static final DateFormat headerDf =
new SimpleDateFormat("HH:mm:ss MM/dd/yy");
static final String BACKGROUND_COLOR = "#FFFFFF";
static final Image IMAGE_LOGO_LARGE = image("lockss-logo-large.gif",
160, 160, 0);
static final Image IMAGE_LOGO_SMALL = image("lockss-logo-small.gif",
80, 81, 0);
static final Image IMAGE_TM = image("tm.gif", 16, 16, 0);
static final Image IMAGE_LOCKSS_RED = image("lockss-type-red.gif",
595, 31, 0);
protected static final String footAccessDenied =
"Clicking on this link will result in an access denied error, unless your browser is configured to proxy through a LOCKSS cache, or your workstation is allowed access by the publisher.";
protected static Logger log = Logger.getLogger("LockssServlet");
protected ServletContext context;
private LockssDaemon theDaemon = null;
// Request-local storage. Convenient, but requires servlet instances
// to be single threaded, and must ensure reset them to avoid carrying
// over state between requests.
protected HttpServletRequest req;
protected HttpServletResponse resp;
protected URL reqURL;
private String adminDir = null;
protected String client; // client param
protected String clientAddr; // client addr, even if no param
protected String adminAddr;
protected String adminHost;
protected String localAddr;
private Vector footnotes;
private int footNumber;
ServletDescr _myServletDescr = null;
private String myName = null;
/** Marker for servlets whose class can't be found */
static class UnavailableServletMarker {
}
static Class UNAVAILABLE_SERVLET_MARKER = UnavailableServletMarker.class;
// Servlet descriptor.
static class ServletDescr {
public Class cls;
public String heading; // display name
public String name; // url path component to invoke servlet
public int flags = 0;
// flags
public static int ON_CLIENT = 1; // runs on client (else on admin)
public static int PER_CLIENT = 2; // per client (takes client arg)
public static int NOT_IN_NAV = 4; // no link in nav table
public static int LARGE_LOGO = 8; // use large LOCKSS logo
public static int DEBUG_ONLY = 0x10; // debug user only
public static int STATUS = ON_CLIENT | PER_CLIENT; // shorthand
public ServletDescr(Class cls, String heading, String name, int flags) {
this.cls = cls;
this.heading = heading;
this.name = name;
this.flags = flags;
}
public ServletDescr(Class cls, String heading, int flags) {
this(cls, heading,
cls.getName().substring(cls.getName().lastIndexOf('.') + 1),
flags);
}
public ServletDescr(Class cls, String heading) {
this(cls, heading, 0);
}
public ServletDescr(String className, String heading, String name) {
this(classForName(className), heading, name, 0);
}
public ServletDescr(String className, String heading, int flags) {
this(classForName(className), heading, flags);
}
static Class classForName(String className) {
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
return UnavailableServletMarker.class;
}
}
boolean isPerClient() {
return (flags & PER_CLIENT) != 0;
}
boolean runsOnClient() {
return (flags & ON_CLIENT) != 0;
}
boolean isInNavTable() {
return (flags & NOT_IN_NAV) == 0;
}
boolean isDebugOnly() {
return (flags & DEBUG_ONLY) != 0;
}
boolean isLargeLogo() {
return (flags & LARGE_LOGO) != 0;
}
}
// Descriptors for all servlets.
protected static ServletDescr SERVLET_AU_CONFIG =
new ServletDescr(AuConfig.class, "Journal Configuration");
protected static ServletDescr SERVLET_DAEMON_STATUS =
new ServletDescr(DaemonStatus.class, "Daemon Status");
protected static ServletDescr SERVLET_PROXY_INFO =
new ServletDescr(ProxyConfig.class, "Proxy Info", "info/ProxyInfo", 0);
protected static ServletDescr SERVLET_THREAD_DUMP =
new ServletDescr("org.lockss.servlet.ThreadDump", "Thread Dump",
ServletDescr.DEBUG_ONLY);
protected static ServletDescr LINK_LOGS =
new ServletDescr(null, "Logs", "log", ServletDescr.DEBUG_ONLY);
protected static ServletDescr SERVLET_ADMIN_ACCESS_CONTROL =
new ServletDescr(AdminIpAccess.class, "Admin Access Control");
protected static ServletDescr SERVLET_PROXY_ACCESS_CONTROL =
new ServletDescr(ProxyIpAccess.class, "Proxy Access Control");
// protected static ServletDescr SERVLET_ADMIN_HOME =
// new ServletDescr(Admin.class, "Admin Home", ServletDescr.LARGE_LOGO);
// protected static ServletDescr SERVLET_JOURNAL_STATUS =
// new ServletDescr(JournalStatus.class, "Journal Status",
// ServletDescr.STATUS);
// protected static ServletDescr SERVLET_JOURNAL_SETUP =
// new ServletDescr(JournalSettings.class, "Journal Setup",
// ServletDescr.PER_CLIENT);
// protected static ServletDescr SERVLET_DAEMON_STATUS =
// new ServletDescr(DaemonStatus.class, "Daemon Status",
// ServletDescr.STATUS + ServletDescr.NOT_IN_NAV);
// All servlets must be listed here (even if not in van table).
// Order of descrs determines order in nav table.
static ServletDescr servletDescrs[] = {
SERVLET_AU_CONFIG,
SERVLET_ADMIN_ACCESS_CONTROL,
SERVLET_PROXY_ACCESS_CONTROL,
SERVLET_PROXY_INFO,
SERVLET_DAEMON_STATUS,
LINK_LOGS,
SERVLET_THREAD_DUMP,
// SERVLET_ADMIN_HOME,
// SERVLET_JOURNAL_STATUS,
// SERVLET_JOURNAL_SETUP,
// SERVLET_DAEMON_STATUS,
// SERVLET_ACCESS_CONTROL,
};
// Create mapping from servlet class to ServletDescr
private static final Hashtable servletToDescr = new Hashtable();
static {
for (int i = 0; i < servletDescrs.length; i++) {
ServletDescr d = servletDescrs[i];
if (d.cls != null && d.cls != UNAVAILABLE_SERVLET_MARKER) {
servletToDescr.put(d.cls, d);
}
}
};
private ServletDescr findServletDescr(Object o) {
ServletDescr d = (ServletDescr)servletToDescr.get(o.getClass());
if (d != null) return d;
// if not in map, o might be an instance of a subclass of a servlet class
// that's in the map.
for (int i = 0; i < servletDescrs.length; i++) {
d = servletDescrs[i];
if (d.cls != null && d.cls.isInstance(o)) {
// found a descr that describes a superclass. Add actual class to map
servletToDescr.put(o.getClass(), d);
return d;
}
}
return null; // shouldn't happen
// XXX do something better here
}
/** Run once when servlet loaded. */
public void init(ServletConfig config) throws ServletException {
super.init(config);
context = config.getServletContext();
theDaemon = (LockssDaemon)context.getAttribute("LockssDaemon");
}
/** Servlets must implement this method. */
protected abstract void lockssHandleRequest() throws ServletException, IOException;
/** Common request handling. */
public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
this.req = req;
this.resp = resp;
if (log.isDebug()) {
logParams();
}
resp.setContentType("text/html");
footNumber = 0;
reqURL = new URL(UrlUtil.getRequestURL(req));
adminAddr = req.getParameter("admin");
if (adminAddr == null) {
adminAddr = Configuration.getParam(PARAM_ADMIN_ADDRESS);
}
adminHost = reqURL.getHost();
client = req.getParameter("client");
clientAddr = client;
if (clientAddr == null) {
clientAddr = getLocalIPAddr();
}
lockssHandleRequest();
}
finally {
// Don't hold on to stuff forever
req = null;
resp = null;
reqURL = null;
adminDir = null;
localAddr = null;
footnotes = null;
_myServletDescr = null;
myName = null;
}
}
// Return descriptor of running servlet
protected ServletDescr myServletDescr() {
if (_myServletDescr == null) {
_myServletDescr = findServletDescr(this);
}
return _myServletDescr;
}
// By default, servlet heading is in descr. Override method to
// compute other heading
protected String getHeading(ServletDescr d) {
if (d == null) return "Unknown Servlet";
return d.heading;
}
protected String getHeading() {
return getHeading(myServletDescr());
}
String getLocalIPAddr() {
if (localAddr == null) {
try {
IPAddr localHost = IPAddr.getLocalHost();
localAddr = localHost.getHostAddress();
} catch (UnknownHostException e) {
// shouldn't happen
log.error("LockssServlet: getLocalHost: " + e.toString());
return "???";
}
}
return localAddr;
}
// Return IP addr used by LCAP. If specified by (misleadingly named)
// localIPAddress prop, might not really be our address (if we are
// behind NAT).
String getLcapIPAddr() {
String ip = Configuration.getParam(PARAM_LOCAL_IP);
if (ip.length() <= 0) {
return getLocalIPAddr();
}
return ip;
}
String getMachineName() {
if (myName == null) {
// Return the canonical name of the interface the request was aimed
// at. (localIPAddress prop isn't necessarily right here, as it
// might be the address of a NAT that we're behind.)
String host = reqURL.getHost();
try {
IPAddr localHost = IPAddr.getByName(host);
String ip = localHost.getHostAddress();
myName = getMachineName(ip);
} catch (UnknownHostException e) {
// shouldn't happen
log.error("getMachineName", e);
return host;
}
}
return myName;
}
String getMachineName(String ip) {
try {
IPAddr inet = IPAddr.getByName(ip);
return inet.getHostName();
} catch (UnknownHostException e) {
log.warning("getMachineName", e);
}
return ip;
}
// return IP given name or IP
String getMachineIP(String name) {
try {
IPAddr inet = IPAddr.getByName(name);
return inet.getHostAddress();
} catch (UnknownHostException e) {
return null;
}
}
// Servlet predicates
boolean isPerClient() {
return myServletDescr().isPerClient();
}
boolean runsOnClient() {
return myServletDescr().runsOnClient();
}
boolean isServletLinkInNav(ServletDescr d) {
return !isThisServlet(d) || linkMeInNav();
}
boolean isThisServlet(ServletDescr d) {
return d == myServletDescr();
}
/** servlets may override this to determine whether they should be
* a link in nav table */
protected boolean linkMeInNav() {
return false;
}
boolean isLargeLogo() {
return myServletDescr().isLargeLogo();
}
// machine predicates
boolean isClusterAdmin() {
return false;
// return Configuration.getBooleanParam(PARAM_IS_CLUSTER_ADMIN, false);
}
// user predicates
protected boolean isDebugUser() {
return req.isUserInRole("debugRole");
}
// Called when a servlet doesn't get the parameters it expects/needs
protected void paramError() throws IOException {
PrintWriter wrtr = resp.getWriter();
Page page = new Page();
// add referer, params, msg to contact lockss unless from old bookmark
// or manually entered url
page.add("Parameter error");
page.write(wrtr);
}
// return true iff error
protected boolean checkParam(boolean ok, String msg) throws IOException {
if (ok) return false;
log.error(myServletDescr().name + ": " + msg);
paramError();
return true;
}
/** Construct servlet URL, with params as necessary. Avoid generating a
* hostname different from that used in the original request, or
* browsers will prompt again for login
*/
String srvURL(ServletDescr d, String params) {
return srvURL(null, d, params);
}
/** Construct servlet absolute URL, with params as necessary.
*/
String srvAbsURL(ServletDescr d, String params) {
return srvURL(getMachineName(), d, params);
}
/** Construct servlet URL, with params as necessary. Avoid generating a
* hostname different from that used in the original request, or
* browsers will prompt again for login
*/
String srvURL(String host, ServletDescr d, String params) {
StringBuffer sb = new StringBuffer();
StringBuffer paramsb = new StringBuffer();
if (!clientAddr.equals(adminAddr)) {
if (!d.runsOnClient()) {
if (runsOnClient()) { // invoking admin servlet from client
host = adminAddr;
}
} else if (!runsOnClient()) { // invoking client servlet from admin
host = clientAddr;
paramsb.append("&admin=");
paramsb.append(adminHost);
}
}
if (params != null) {
paramsb.append('&');
paramsb.append(params);
}
if (d.isPerClient()) {
paramsb.append("&client=");
paramsb.append(clientAddr);
}
if (host != null) {
sb.append(reqURL.getProtocol());
sb.append("://");
sb.append(host);
sb.append(':');
sb.append(reqURL.getPort());
}
sb.append('/');
sb.append(d.name);
if (paramsb.length() != 0) {
paramsb.setCharAt(0, '?');
sb.append(paramsb.toString());
}
return sb.toString();
}
/** Return a link to a servlet */
String srvLink(ServletDescr d, String text) {
return srvLink(d, text, null);
}
/** Return a link to a servlet with params */
String srvLink(ServletDescr d, String text, String params) {
return new Link(srvURL(d, params),
(text != null ? text : d.heading)).toString();
}
/** Return an absolute link to a servlet with params */
String srvAbsLink(ServletDescr d, String text, String params) {
return new Link(srvAbsURL(d, params),
(text != null ? text : d.heading)).toString();
}
/** Return text as a link iff isLink */
String conditionalSrvLink(ServletDescr d, String text, String params,
boolean isLink) {
if (isLink) {
return srvLink(d, text, params);
} else {
return text;
}
}
/** Return text as a link iff isLink */
String conditionalSrvLink(ServletDescr d, String text, boolean isLink) {
return conditionalSrvLink(d, text, null, isLink);
}
/** Concatenate params for URL string */
String concatParams(String p1, String p2) {
if (p1 == null || p1.equals("")) {
return p2;
}
if (p2 == null || p2.equals("")) {
return p1;
}
return p1 + "&" + p2;
}
protected String urlEncode(String param) {
return URLEncoder.encode(param);
}
protected boolean isServletInNav(ServletDescr d) {
if (!isDebugUser() && d.isDebugOnly()) return false;
if (d.cls == UNAVAILABLE_SERVLET_MARKER) return false;
return d.isInNavTable() && (!d.isPerClient() || isPerClient());
}
// Build servlet navigation table
private Table getNavTable() {
Table navTable = new Table(0, " CELLSPACING=2 CELLPADDING=0 ");
boolean clientTitle = false;
for (int i = 0; i < servletDescrs.length; i++) {
ServletDescr d = servletDescrs[i];
if (isServletInNav(d)) {
navTable.newRow();
navTable.newCell();
if (d.isPerClient()) {
if (!clientTitle) {
// Insert client name before first per-client servlet
navTable.cell().attribute("WIDTH=\"15\"");
navTable.newCell();
navTable.cell().attribute("COLSPAN=\"2\"");
navTable.add("<b>" + getMachineName(clientAddr) + "</b>");
navTable.newRow();
navTable.newCell();
clientTitle = true;
}
navTable.cell().attribute("WIDTH=\"15\"");
navTable.newCell();
navTable.cell().attribute("WIDTH=\"15\"");
navTable.newCell();
} else {
navTable.cell().attribute("COLSPAN=\"3\"");
}
if (false /*isThisServlet(d)*/) {
navTable.add("<font size=-1 color=green>");
} else {
navTable.add("<font size=-1>");
}
navTable.add(conditionalSrvLink(d, d.heading, isServletLinkInNav(d)));
navTable.add("</font>");
}
}
navTable.newRow();
navTable.newCell();
navTable.cell().attribute("COLSPAN=\"3\"");
String contactAddr =
Configuration.getParam(PARAM_CONTACT_ADDR, DEFAULT_CONTACT_ADDR);
navTable.add("<font size=-1>");
navTable.add(new Link("mailto:" + contactAddr, "Contact Us"));
navTable.add("</font>");
return navTable;
}
protected Table getExplanationBlock(String text) {
Table exp = new Table(0, "width=\"85%\"");
exp.center();
exp.newCell("align=center");
exp.add(text);
return exp;
}
protected String getRequestKey() {
String key = req.getPathInfo();
if (key != null && key.startsWith("/")) {
return key.substring(1);
}
return key;
}
/** Common page setup. */
protected Page newPage() {
Page page = new Page();
String heading = getHeading();
page.add("<!doctype html public \"-//w3c//dtd html 4.0 transitional//en\">");
page.addHeader("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">");
page.addHeader("<meta http-equiv=\"content-type\" content=\"text/html;charset=ISO-8859-1\">");
page.addHeader("<style type=\"text/css\"><!-- sup {font-weight: normal} --> </STYLE>");
if (heading != null)
page.title("LOCKSS: " + heading);
else
page.title("LOCKSS");
page.attribute("BGCOLOR", BACKGROUND_COLOR);
page.add(getHeader());
return page;
}
// Common page header
private Composite getHeader() {
String heading = getHeading();
if (heading == null) {
heading = "Cache Administration";
}
Composite comp = new Composite();
Table table = new Table(0, " cellspacing=2 cellpadding=0 width=\"100%\"");
comp.add(table);
String machineName = getMachineName();
table.newRow();
Image logo = isLargeLogo() ? IMAGE_LOGO_LARGE : IMAGE_LOGO_SMALL;
table.newCell("valign=top align=center width=\"20%\"");
// table.newCell("valign=top width=\"25%\"");
// table.newCell("valign=top align=center width=" +
// (logo.width() + IMAGE_TM.width() + 20));
table.add(new Link("/index.html", logo));
table.add(IMAGE_TM);
// table.newCell("valign=center align=center width=\"60%\"");
table.newCell("valign=top align=center width=\"60%\"");
table.add("<br>");
table.add("<font size=+2><b>");
table.add(heading);
table.add("</b></font>");
table.add("<br>");
Date startDate = getLockssDaemon().getStartDate();
String since =
StringUtil.timeIntervalToString(TimeBase.msSince(startDate.getTime()));
table.add(getMachineName() + " at " +
headerDf.format(new Date()) + ", up " + since);
// table.newCell("valign=center align=right width=\"25%\"");
table.newCell("valign=center align=center width=\"20%\"");
table.add(getNavTable());
// comp.add("<br><center><font size=+2><b>Cache Administration</b></font></center>");
// comp.add("<center><b>" + machineName + "</b></center>");
// comp.add("<br><center><font size=+1><b>"+heading+"</b></font></center>");
// Date startDate = getLockssDaemon().getStartDate();
// String since =
// StringUtil.timeIntervalToString(TimeBase.msSince(startDate.getTime()));
// comp.add("<center>" + getMachineName() + " at " +
// headerDf.format(new Date()) + ", up " + since + "</center>");
// // comp.add("<center>Running since " + headerDf.format(startDate) + "</center>");
comp.add("<br>");
return comp;
}
// Common page footer
public Element getFooter() {
Composite comp = new Composite();
String vDaemon = theDaemon.getVersionInfo();
addNotes(comp);
comp.add("<p>");
Table table = new Table(0, " CELLSPACING=0 CELLPADDING=0 ALIGN=CENTER");
table.newRow("VALIGN=TOP");
table.newCell();
table.add(IMAGE_LOCKSS_RED);
table.newCell();
table.add(IMAGE_TM);
table.newRow();
table.newCell("COLSPAN=2");
table.add("<center><font size=-1>" + vDaemon + "</font></center>");
comp.add(table);
// comp.add("<center><font size=-1>" + vDaemon + "</font></center>");
return comp;
}
// eventually this should calculate w & h
static Image image(String file, int w, int h, int border) {
return new Image("/images/" + file, w, h, border);
}
/** Add html tags to grey the text if isGrey is true */
protected String greyText(String txt, boolean isGrey) {
if (!isGrey) {
return txt;
}
return "<font color=gray>" + txt + "</font>";
}
/** Store a footnote, assign it a number, return html for footnote
* reference. If footnote in null or empty, no footnote is added and am
* empty string is returned. */
protected String addFootnote(String s) {
if (s == null || s.length() == 0) {
return "";
}
if (footNumber == 0) {
if (footnotes == null) {
footnotes = new Vector(10, 10);
} else {
footnotes.removeAllElements();
}
}
int n = footnotes.indexOf(s);
if (n < 0) {
n = footNumber++;
footnotes.addElement(s);
}
return "<sup><font size=-1>" + (n+1) + "</font></sup>";
}
/** Add accumulated footnotes to Composite. */
protected void addNotes(Composite elem) {
if (footnotes == null || footNumber == 0) {
return;
}
elem.add("<p><b>Notes:</b>");
elem.add("<ol><font size=-1>");
for (int n = 0; n < footNumber; n++) {
elem.add("<li value=" + (n+1) + ">" + footnotes.elementAt(n));
}
footnotes.removeAllElements();
elem.add("</font></ol>");
}
protected void addJavaScript(Composite comp) {
Script script = new Script(getJavascript());
comp.add(script);
}
private static String jstext = null;
private static synchronized String getJavascript() {
if (jstext == null) {
try {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream istr = loader.getResourceAsStream(JAVASCRIPT_RESOURCE);
jstext = StringUtil.fromInputStream(istr);
istr.close();
} catch (Exception e) {
log.error("Can't load javascript", e);
}
}
return jstext;
}
/** Return the daemon instance. */
protected LockssDaemon getLockssDaemon() {
return theDaemon;
}
protected void logParams() {
Enumeration en = req.getParameterNames();
while (en.hasMoreElements()) {
String name = (String)en.nextElement();
log.debug(name + " = " + req.getParameter(name));
}
}
/** Convenience method */
protected String encodeText(String s) {
return HtmlUtil.encode(s, HtmlUtil.ENCODE_TEXT);
}
/** Convenience method */
protected String encodeTextArea(String s) {
return HtmlUtil.encode(s, HtmlUtil.ENCODE_TEXTAREA);
}
/** Convenience method */
protected String encodeAttr(String s) {
return HtmlUtil.encode(s, HtmlUtil.ENCODE_ATTR);
}
}
| Use proper symbol.
git-svn-id: 293778eaa97c8c94097d610b1bd5133a8f478f36@2626 4f837ed2-42f5-46e7-a7a5-fa17313484d4
| src/org/lockss/servlet/LockssServlet.java | Use proper symbol. | <ide><path>rc/org/lockss/servlet/LockssServlet.java
<ide> /*
<del> * $Id: LockssServlet.java,v 1.35 2004-03-04 19:20:53 tlipkis Exp $
<add> * $Id: LockssServlet.java,v 1.36 2004-03-04 19:24:11 tlipkis Exp $
<ide> */
<ide>
<ide> /*
<ide> try {
<ide> return Class.forName(className);
<ide> } catch (ClassNotFoundException e) {
<del> return UnavailableServletMarker.class;
<add> return UNAVAILABLE_SERVLET_MARKER;
<ide> }
<ide> }
<ide> boolean isPerClient() { |
|
JavaScript | mit | 3699cafc761c2625badedba78f3ec48cb4753cd8 | 0 | andela-jomadoye/JedDoc-Manager,andela-jomadoye/JedDoc-Manager | import { expect } from 'chai';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import nock from 'nock';
import * as userActions from '../../actions/loginActions';
import {
SET_CURRENT_USER,
} from '../../actions/actionTypes';
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
const user = {
email: '[email protected]',
firstName: 'jedidiah',
lastName: 'Omadoye',
password: 'password',
};
describe('Authentication actions', () => {
after(() => {
nock.cleanAll();
});
describe('login', () => {
const response = {
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
};
after(() => {
nock.cleanAll();
});
it('should login a user', () => {
nock('/api')
.post('/users/login', user)
.reply(201, response);
const expectedActions = [
{ type: SET_CURRENT_USER },
];
const store = mockStore({
user: {},
});
store.dispatch(userActions.setCurrentUser(user));
expect(store.getActions()[0].type)
.to.eql(expectedActions[0].type);
});
});
describe('signup', () => {
const response = {
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
password: user.password,
};
after(() => {
nock.cleanAll();
});
it('should signup a user', () => {
nock('/api')
.post('/users', user)
.reply(201, response);
const expectedActions = [
{ type: SET_CURRENT_USER },
];
const store = mockStore({
user: {},
});
store.dispatch(userActions.setCurrentUser(user));
expect(store.getActions()[0].type)
.to.eql(expectedActions[0].type);
});
});
});
| client/test/actions/authActions.spec.js | import { expect } from 'chai';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import nock from 'nock';
import * as userActions from '../../actions/loginActions';
import {
SET_CURRENT_USER,
LOAD_AUTHORIZE_TO_VIEW_DOCUMENT_SUCCESS,
} from '../../actions/actionTypes';
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
const user = {
email: '[email protected]',
firstName: 'jedidiah',
lastName: 'Omadoye',
password: 'password',
};
describe('Authentication actions', () => {
after(() => {
nock.cleanAll();
});
describe('login', () => {
const response = {
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
};
after(() => {
nock.cleanAll();
});
it('should login a user', () => {
nock('/api')
.post('/users/login', user)
.reply(201, response);
const expectedActions = [
{ type: SET_CURRENT_USER },
];
const store = mockStore({
user: {},
});
store.dispatch(userActions.setCurrentUser(user));
expect(store.getActions()[0].type)
.to.eql(expectedActions[0].type);
});
});
describe('signup', () => {
const response = {
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
password: user.password,
};
after(() => {
nock.cleanAll();
});
it('should signup a user', () => {
nock('/api')
.post('/users', user)
.reply(201, response);
const expectedActions = [
{ type: SET_CURRENT_USER },
];
const store = mockStore({
user: {},
});
store.dispatch(userActions.setCurrentUser(user));
expect(store.getActions()[0].type)
.to.eql(expectedActions[0].type);
});
});
});
| feature(client) add auth spec
[143585203]
| client/test/actions/authActions.spec.js | feature(client) add auth spec | <ide><path>lient/test/actions/authActions.spec.js
<ide> import * as userActions from '../../actions/loginActions';
<ide> import {
<ide> SET_CURRENT_USER,
<del> LOAD_AUTHORIZE_TO_VIEW_DOCUMENT_SUCCESS,
<ide> } from '../../actions/actionTypes';
<ide>
<ide> const middlewares = [thunk]; |
|
Java | epl-1.0 | e5e9b11b99cba939ec3751615e15305d1cb35ca3 | 0 | ChangeOrientedProgrammingEnvironment/eclipseRecorder,ChangeOrientedProgrammingEnvironment/eclipseRecorder | package edu.oregonstate.cope.eclipse;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.ui.progress.UIJob;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Version;
import edu.oregonstate.cope.clientRecorder.ClientRecorder;
import edu.oregonstate.cope.clientRecorder.Properties;
import edu.oregonstate.cope.clientRecorder.RecorderFacade;
import edu.oregonstate.cope.clientRecorder.Uninstaller;
import edu.oregonstate.cope.clientRecorder.util.LoggerInterface;
/**
* The activator class controls the plug-in life cycle
*/
public class COPEPlugin extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "org.oregonstate.edu.eclipse"; //$NON-NLS-1$
private static final String PREFERENCES_IGNORED_PROJECTS = "ignoredProjects";
// The shared instance
static COPEPlugin plugin;
// The ID of the current workspace
String workspaceID;
private RecorderFacade recorderFacade;
private SnapshotManager snapshotManager;
private List<String> ignoredProjects;
/**
* The constructor
*/
public COPEPlugin() {
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
* )
*/
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
UIJob uiJob = new StartPluginUIJob(this, "Registering listeners");
uiJob.schedule();
}
public void initializeSnapshotManager() {
snapshotManager = new SnapshotManager(getVersionedLocalStorage().getAbsolutePath());
}
public void takeSnapshotOfKnownProjects() {
snapshotManager.takeSnapshotOfKnownProjects();
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
* )
*/
public void stop(BundleContext context) throws Exception {
snapshotManager.takeSnapshotOfSessionTouchedProjects();
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static COPEPlugin getDefault() {
return plugin;
}
public ClientRecorder getClientRecorder() {
return recorderFacade.getClientRecorder();
}
public Properties getWorkspaceProperties() {
return recorderFacade.getWorkspaceProperties();
}
public Properties getInstallationProperties() {
return recorderFacade.getInstallationProperties();
}
public Uninstaller getUninstaller() {
return recorderFacade.getUninstaller();
}
public void initializeRecorder(String workspaceDirectory, String permanentDirectory, String workspaceID, String IDE) {
this.workspaceID = workspaceID;
recorderFacade = RecorderFacade.instance().initialize(workspaceDirectory, permanentDirectory, IDE);
}
protected File getWorkspaceIdFile() {
File pluginStoragePath = getVersionedLocalStorage();
return new File(pluginStoragePath.getAbsolutePath() + File.separator + "workspace_id");
}
public String getWorkspaceID() {
File workspaceIdFile = getWorkspaceIdFile();
String workspaceID = "";
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(workspaceIdFile));
workspaceID = reader.readLine();
reader.close();
} catch (IOException e) {
}
return workspaceID;
}
public File getLocalStorage() {
return COPEPlugin.plugin.getStateLocation().toFile();
}
public File getBundleStorage() {
return COPEPlugin.getDefault().getBundle().getDataFile("");
}
public File getVersionedLocalStorage() {
return getVersionedPath(getLocalStorage().toPath()).toFile();
}
public File getVersionedBundleStorage() {
return getVersionedPath(getBundleStorage().toPath()).toFile();
}
private Path getVersionedPath(Path path) {
String version = getPluginVersion().toString();
return path.resolve(version);
}
public Version getPluginVersion() {
return COPEPlugin.plugin.getBundle().getVersion();
}
public LoggerInterface getLogger() {
return recorderFacade.getLogger();
}
public SnapshotManager getSnapshotManager() {
return snapshotManager;
}
/**
* Used only by the Installer.
* TODO something is fishy here, this string should not leak outside
*/
public String _getInstallationConfigFileName() {
return RecorderFacade.instance().getInstallationConfigFilename();
}
public List<String> getIgnoreProjectsList() {
return ignoredProjects;
}
public void setIgnoredProjectsList(List<String> ignoredProjects) {
StringBuffer value = new StringBuffer();
for (String project : ignoredProjects) {
value.append(project);
value.append(";");
}
COPEPlugin.getDefault().getWorkspaceProperties().addProperty(PREFERENCES_IGNORED_PROJECTS, value.toString());
this.ignoredProjects = ignoredProjects;
}
public void readIgnoredProjects() {
String ignoredProjectsString = getWorkspaceProperties().getProperty(PREFERENCES_IGNORED_PROJECTS);
String[] projectNames = ignoredProjectsString.split(";");
ignoredProjects = new ArrayList<>();
for (String project : projectNames) {
ignoredProjects.add(project);
}
}
public IProject getProjectForEditor(IEditorInput editorInput) {
IProject project;
IFile file = ((FileEditorInput) editorInput).getFile();
project = file.getProject();
return project;
}
public List<String> getListOfWorkspaceProjects() {
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
List<String> projectNames = new ArrayList<String>();
for (IProject project : projects) {
projectNames.add(project.getName());
}
return projectNames;
}
}
| edu.oregonstate.cope.eclipse/src/edu/oregonstate/cope/eclipse/COPEPlugin.java | package edu.oregonstate.cope.eclipse;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.ui.progress.UIJob;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Version;
import edu.oregonstate.cope.clientRecorder.ClientRecorder;
import edu.oregonstate.cope.clientRecorder.Properties;
import edu.oregonstate.cope.clientRecorder.RecorderFacade;
import edu.oregonstate.cope.clientRecorder.Uninstaller;
import edu.oregonstate.cope.clientRecorder.util.LoggerInterface;
/**
* The activator class controls the plug-in life cycle
*/
public class COPEPlugin extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "org.oregonstate.edu.eclipse"; //$NON-NLS-1$
private static final String PREFERENCES_IGNORED_PROJECTS = "ignoredProjects";
// The shared instance
static COPEPlugin plugin;
// The ID of the current workspace
String workspaceID;
private RecorderFacade recorderFacade;
private SnapshotManager snapshotManager;
private List<String> ignoredProjects;
/**
* The constructor
*/
public COPEPlugin() {
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
* )
*/
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
UIJob uiJob = new StartPluginUIJob(this, "Registering listeners");
uiJob.schedule();
}
public void initializeSnapshotManager() {
snapshotManager = new SnapshotManager(getVersionedLocalStorage().getAbsolutePath());
}
public void takeSnapshotOfKnownProjects() {
snapshotManager.takeSnapshotOfKnownProjects();
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
* )
*/
public void stop(BundleContext context) throws Exception {
snapshotManager.takeSnapshotOfSessionTouchedProjects();
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static COPEPlugin getDefault() {
return plugin;
}
public ClientRecorder getClientRecorder() {
return recorderFacade.getClientRecorder();
}
public Properties getWorkspaceProperties() {
return recorderFacade.getWorkspaceProperties();
}
public Properties getInstallationProperties() {
return recorderFacade.getInstallationProperties();
}
public Uninstaller getUninstaller() {
return recorderFacade.getUninstaller();
}
public void initializeRecorder(String workspaceDirectory, String permanentDirectory, String workspaceID, String IDE) {
this.workspaceID = workspaceID;
recorderFacade = RecorderFacade.instance().initialize(workspaceDirectory, permanentDirectory, IDE);
}
protected File getWorkspaceIdFile() {
File pluginStoragePath = getVersionedLocalStorage();
return new File(pluginStoragePath.getAbsolutePath() + File.separator + "workspace_id");
}
public String getWorkspaceID() {
File workspaceIdFile = getWorkspaceIdFile();
String workspaceID = "";
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(workspaceIdFile));
workspaceID = reader.readLine();
reader.close();
} catch (IOException e) {
}
return workspaceID;
}
public File getLocalStorage() {
return COPEPlugin.plugin.getStateLocation().toFile();
}
public File getBundleStorage() {
return COPEPlugin.getDefault().getBundle().getDataFile("");
}
public File getVersionedLocalStorage() {
return getVersionedPath(getLocalStorage().toPath()).toFile();
}
public File getVersionedBundleStorage() {
return getVersionedPath(getBundleStorage().toPath()).toFile();
}
private Path getVersionedPath(Path path) {
String version = getPluginVersion().toString();
return path.resolve(version);
}
public Version getPluginVersion() {
return COPEPlugin.plugin.getBundle().getVersion();
}
public LoggerInterface getLogger() {
return recorderFacade.getLogger();
}
public SnapshotManager getSnapshotManager() {
return snapshotManager;
}
/**
* Used only by the Installer.
* TODO something is fishy here, this string should not leak outside
*/
public String _getInstallationConfigFileName() {
return RecorderFacade.instance().getInstallationConfigFilename();
}
public List<String> getIgnoreProjectsList() {
return ignoredProjects;
}
protected void setIgnoredProjectsList(List<String> ignoredProjects) {
StringBuffer value = new StringBuffer();
for (String project : ignoredProjects) {
value.append(project);
value.append(";");
}
COPEPlugin.getDefault().getWorkspaceProperties().addProperty(PREFERENCES_IGNORED_PROJECTS, value.toString());
this.ignoredProjects = ignoredProjects;
}
public void readIgnoredProjects() {
String ignoredProjectsString = getWorkspaceProperties().getProperty(PREFERENCES_IGNORED_PROJECTS);
String[] projectNames = ignoredProjectsString.split(";");
ignoredProjects = new ArrayList<>();
for (String project : projectNames) {
ignoredProjects.add(project);
}
}
public IProject getProjectForEditor(IEditorInput editorInput) {
IProject project;
IFile file = ((FileEditorInput) editorInput).getFile();
project = file.getProject();
return project;
}
public List<String> getListOfWorkspaceProjects() {
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
List<String> projectNames = new ArrayList<String>();
for (IProject project : projects) {
projectNames.add(project.getName());
}
return projectNames;
}
}
| Made the method public
| edu.oregonstate.cope.eclipse/src/edu/oregonstate/cope/eclipse/COPEPlugin.java | Made the method public | <ide><path>du.oregonstate.cope.eclipse/src/edu/oregonstate/cope/eclipse/COPEPlugin.java
<ide> return ignoredProjects;
<ide> }
<ide>
<del> protected void setIgnoredProjectsList(List<String> ignoredProjects) {
<add> public void setIgnoredProjectsList(List<String> ignoredProjects) {
<ide> StringBuffer value = new StringBuffer();
<ide> for (String project : ignoredProjects) {
<ide> value.append(project); |
|
Java | apache-2.0 | dd5e0f3f41d412d1202ba1664b846e05922ee1a8 | 0 | deeplearning4j/DataVec,huitseeker/DataVec,deeplearning4j/DataVec,huitseeker/DataVec | /*
* * Copyright 2016 Skymind, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*/
package org.datavec.image.loader;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacv.OpenCVFrameConverter;
import org.datavec.api.berkeley.Pair;
import org.datavec.image.data.ImageWritable;
import org.datavec.image.transform.ColorConversionTransform;
import org.datavec.image.transform.EqualizeHistTransform;
import org.datavec.image.transform.ImageTransform;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.impl.accum.Sum;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.util.FeatureUtil;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.*;
import static org.bytedeco.javacpp.opencv_core.CV_8UC;
import static org.bytedeco.javacpp.opencv_core.Mat;
import static org.bytedeco.javacpp.opencv_imgproc.COLOR_BGR2YCrCb;
/**
* CifarLoader is loader specific for the Cifar10 dataset
*
* Reference: Learning Multiple Layers of Features from Tiny Images, Alex Krizhevsky, 2009.
*
* There is a special preProcessor used to normalize the dataset based on Sergey Zagoruyko example
* https://github.com/szagoruyko/cifar.torch
*/
public class CifarLoader extends NativeImageLoader implements Serializable {
public final static int NUM_TRAIN_IMAGES = 50000;
public final static int NUM_TEST_IMAGES = 10000;
public final static int NUM_LABELS = 10; // Note 6000 imgs per class
public final static int HEIGHT = 32;
public final static int WIDTH = 32;
public final static int CHANNELS = 3;
public final static int BYTEFILELEN = 3073;
public static String dataBinUrl = "https://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz";
public static String localDir = "cifar";
public static String dataBinFile = "cifar-10-batches-bin";
public static File fullDir = new File(BASE_DIR, FilenameUtils.concat(localDir, dataBinFile));
public static File meanVarPath = new File(fullDir, "meanVarPath.txt");
protected static String labelFileName = "batches.meta.txt";
protected static InputStream inputStream;
protected static InputStream trainInputStream;
protected static InputStream testInputStream;
protected static List<DataSet> inputBatched;
protected static List<String> labels = new ArrayList<>();
public static String[] TRAINFILENAMES = {"data_batch_1.bin", "data_batch_2.bin", "data_batch_3.bin", "data_batch_4.bin", "data_batch5.bin"};
public static String TESTFILENAME = "test_batch.bin";
protected static String trainFilesSerialized = FilenameUtils.concat(fullDir.toString(), "cifar_train_serialized");
protected static String testFilesSerialized = FilenameUtils.concat(fullDir.toString(), "cifar_test_serialized.ser");
protected static boolean train = true;
public static boolean useSpecialPreProcessCifar = false;
public static Map<String, String> cifarDataMap = new HashMap<>();
protected static int height = HEIGHT;
protected static int width = WIDTH;
protected static int channels = CHANNELS;
protected static long seed = System.currentTimeMillis();
protected static boolean shuffle = true;
protected int numExamples = 0;
protected static int numToConvertDS = 10000; // Each file is 10000 images, limiting for file preprocess load
protected double uMean = 0;
protected double uStd = 0;
protected double vMean = 0;
protected double vStd = 0;
protected boolean meanStdStored = false;
protected int loadDSIndex = 0;
protected DataSet loadDS = new DataSet();
protected int fileNum = 0;
public CifarLoader() {
this(height,width, channels, null, train, useSpecialPreProcessCifar, fullDir, seed, shuffle);
}
public CifarLoader(boolean train) {
this(height, width, channels, null, train, useSpecialPreProcessCifar, fullDir, seed, shuffle);
}
public CifarLoader(boolean train, File fullPath) {
this(height, width, channels, null, train, useSpecialPreProcessCifar, fullPath, seed, shuffle);
}
public CifarLoader(int height, int width, int channels, boolean train, boolean useSpecialPreProcessCifar) {
this(height, width, channels, null, train, useSpecialPreProcessCifar, fullDir, seed, shuffle);
}
public CifarLoader(int height, int width, int channels, ImageTransform imgTransform, boolean train, boolean useSpecialPreProcessCifar) {
this(height, width, channels, imgTransform, train, useSpecialPreProcessCifar, fullDir, seed, shuffle);
}
public CifarLoader(int height, int width, int channels, ImageTransform imgTransform, boolean train, boolean useSpecialPreProcessCifar, boolean shuffle) {
this(height, width, channels, imgTransform, train, useSpecialPreProcessCifar, fullDir, seed, shuffle);
}
public CifarLoader(int height, int width, int channels, ImageTransform imgTransform, boolean train, boolean useSpecialPreProcessCifar, File fullPath, long seed, boolean shuffle) {
super(height, width, channels, imgTransform);
this.height = height;
this.width = width;
this.channels = channels;
this.train = train;
this.useSpecialPreProcessCifar = useSpecialPreProcessCifar;
this.fullDir = fullPath;
this.seed = seed;
this.shuffle = shuffle;
load();
}
@Override
public INDArray asRowVector(File f) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public INDArray asRowVector(InputStream inputStream) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public INDArray asMatrix(File f) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public INDArray asMatrix(InputStream inputStream) throws IOException {
throw new UnsupportedOperationException();
}
public void generateMaps() {
cifarDataMap.put("filesFilename", new File(dataBinUrl).getName());
cifarDataMap.put("filesURL", dataBinUrl);
cifarDataMap.put("filesFilenameUnzipped", dataBinFile);
}
private void defineLabels() {
try {
File path = new File(fullDir, labelFileName);
BufferedReader br = new BufferedReader(new FileReader(path));
String line;
while ((line = br.readLine()) != null) {
labels.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void load() {
if (!cifarRawFilesExist() && !fullDir.exists()) {
generateMaps();
fullDir.mkdir();
log.info("Downloading {}...", localDir);
downloadAndUntar(cifarDataMap, new File(BASE_DIR, localDir));
}
try {
Collection<File> subFiles = FileUtils.listFiles(fullDir, new String[]{"bin"}, true);
Iterator trainIter = subFiles.iterator();
trainInputStream = new SequenceInputStream(new FileInputStream((File) trainIter.next()), new FileInputStream((File) trainIter.next()));
while (trainIter.hasNext()) {
File nextFile = (File) trainIter.next();
if (!TESTFILENAME.equals(nextFile.getName()))
trainInputStream = new SequenceInputStream(trainInputStream, new FileInputStream(nextFile));
}
testInputStream = new FileInputStream(new File(fullDir, TESTFILENAME));
} catch (Exception e) {
e.printStackTrace();
}
if(labels.isEmpty()) defineLabels();
if (useSpecialPreProcessCifar && train && !cifarProcessedFilesExists()) {
for (int i = fileNum+1; i <= (TRAINFILENAMES.length); i++) {
inputStream = trainInputStream;
DataSet result = convertDataSet(numToConvertDS);
result.save(new File(trainFilesSerialized + i + ".ser"));
}
for (int i = 1; i <= (TRAINFILENAMES.length); i++){
normalizeCifar(new File(trainFilesSerialized + i + ".ser"));
}
inputStream = testInputStream;
DataSet result = convertDataSet(numToConvertDS);
result.save(new File(testFilesSerialized));
normalizeCifar(new File(testFilesSerialized));
}
setInputStream();
}
public boolean cifarRawFilesExist() {
File f = new File(fullDir, TESTFILENAME);
if (!f.exists()) return false;
for (String name : TRAINFILENAMES) {
f = new File(fullDir, name);
if (!f.exists()) return false;
}
return true;
}
private boolean cifarProcessedFilesExists() {
File f;
if (train) {
f = new File(trainFilesSerialized + 1 + ".ser");
if (!f.exists()) return false;
} else {
f = new File(testFilesSerialized);
if (!f.exists()) return false;
}
return true;
}
/**
* Preprocess and store cifar based on successful Torch approach by Sergey Zagoruyko
* Reference: https://github.com/szagoruyko/cifar.torch
*/
public opencv_core.Mat convertCifar(Mat orgImage) {
numExamples++;
Mat resImage = new Mat();
OpenCVFrameConverter.ToMat converter = new OpenCVFrameConverter.ToMat();
// ImageTransform yuvTransform = new ColorConversionTransform(new Random(seed), COLOR_BGR2Luv);
// ImageTransform histEqualization = new EqualizeHistTransform(new Random(seed), COLOR_BGR2Luv);
ImageTransform yuvTransform = new ColorConversionTransform(new Random(seed), COLOR_BGR2YCrCb);
ImageTransform histEqualization = new EqualizeHistTransform(new Random(seed), COLOR_BGR2YCrCb);
if (converter != null) {
ImageWritable writable = new ImageWritable(converter.convert(orgImage));
// TODO determine if need to normalize y before transform - opencv docs rec but currently doing after
writable = yuvTransform.transform(writable); // Converts to chrome color to help emphasize image objects
writable = histEqualization.transform(writable); // Normalizes values to further clarify object of interest
resImage = converter.convert(writable.getFrame());
}
return resImage;
}
/**
* Normalize and store cifar based on successful Torch approach by Sergey Zagoruyko
* Reference: https://github.com/szagoruyko/cifar.torch
*/
public void normalizeCifar(File fileName) {
DataSet result = new DataSet();
result.load(fileName);
if(!meanStdStored && train) {
uMean = Math.abs(uMean/numExamples);
uStd = Math.sqrt(uStd);
vMean = Math.abs(vMean/numExamples);
vStd = Math.sqrt(vStd);
// TODO find cleaner way to store and load (e.g. json or yaml)
try {
FileUtils.write(meanVarPath, uMean + "," + uStd + "," + vMean + "," + vStd);
} catch (IOException e) {
e.printStackTrace();
}
meanStdStored = true;
} else if (uMean == 0 && meanStdStored) {
try {
String[] values = FileUtils.readFileToString(meanVarPath).split(",");
uMean = Double.parseDouble(values[0]);
uStd = Double.parseDouble(values[1]);
vMean = Double.parseDouble(values[2]);
vStd = Double.parseDouble(values[3]);
} catch (IOException e) {
e.printStackTrace();
}
}
for (int i = 0; i < result.numExamples(); i++) {
INDArray newFeatures = result.get(i).getFeatureMatrix();
newFeatures.tensorAlongDimension(0, new int[] {0,2,3}).divi(255);
newFeatures.tensorAlongDimension(1, new int[] {0,2,3}).subi(uMean).divi(uStd);
newFeatures.tensorAlongDimension(2, new int[] {0,2,3}).subi(vMean).divi(vStd);
result.get(i).setFeatures(newFeatures);
}
result.save(fileName);
}
public Pair<INDArray, opencv_core.Mat> convertMat(byte[] byteFeature) {
INDArray label= FeatureUtil.toOutcomeVector(byteFeature[0], NUM_LABELS); ; // first value in the 3073 byte array
opencv_core.Mat image = new opencv_core.Mat(HEIGHT, WIDTH, CV_8UC(CHANNELS)); // feature are 3072
ByteBuffer imageData = image.createBuffer();
for (int i = 0; i < HEIGHT * WIDTH; i++) {
imageData.put(3 * i, byteFeature[i + 1 + 2 * height * width]); // blue
imageData.put(3 * i + 1, byteFeature[i + 1 + height * width]); // green
imageData.put(3 * i + 2, byteFeature[i + 1]); // red
}
if (useSpecialPreProcessCifar) {
image = convertCifar(image);
}
return new Pair<>(label, image);
}
public DataSet convertDataSet(int num) {
int batchNumCount = 0;
List<DataSet> dataSets = new ArrayList<>();
Pair<INDArray, opencv_core.Mat> matConversion;
byte[] byteFeature = new byte[BYTEFILELEN];
try {
while (inputStream.read(byteFeature) != -1 && batchNumCount != num) {
matConversion = convertMat(byteFeature);
try {
dataSets.add(new DataSet(asMatrix(matConversion.getSecond()), matConversion.getFirst()));
batchNumCount++;
} catch (Exception e) {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
DataSet result = new DataSet();
try {
result = result.merge(dataSets);
} catch (IllegalArgumentException e) {
return result;
}
double uTempMean, vTempMean;
for (DataSet data :result) {
try {
if (useSpecialPreProcessCifar) {
INDArray uChannel = data.getFeatures().tensorAlongDimension(1, new int[] {0,2,3});
INDArray vChannel = data.getFeatures().tensorAlongDimension(2, new int[] {0,2,3});
uTempMean = uChannel.mean(new int[] {0,2,3}).getDouble(0);
// TODO INDArray.var result is incorrect based on dimensions passed in thus using manual
uStd += varManual(uChannel, uTempMean);
uMean += uTempMean;
vTempMean = vChannel.mean(new int[] {0,2,3}).getDouble(0);
vStd += varManual(vChannel, vTempMean);
vMean += vTempMean;
} else {
// normalize if just input stream and not special preprocess
data.setFeatures(data.getFeatureMatrix().div(255));
}
} catch (IllegalArgumentException e) {
throw new IllegalStateException("The number of channels must be 3 to special preProcess Cifar with.");
}
}
if(shuffle && num > 1) result.shuffle(seed);
return result;
}
public double varManual(INDArray x, double mean) {
INDArray xSubMean = x.sub(mean);
INDArray squared = xSubMean.muli(xSubMean);
double accum = Nd4j.getExecutioner().execAndReturn(new Sum(squared)).getFinalResult().doubleValue();
return accum/x.ravel().length();
}
public DataSet next(int batchSize) {
return next(batchSize, 0);
}
public DataSet next(int batchSize, int exampleNum) {
List<DataSet> temp = new ArrayList<>();
DataSet result;
if (cifarProcessedFilesExists() && useSpecialPreProcessCifar) {
if (exampleNum == 0 || ((exampleNum/fileNum) == numToConvertDS && train)) {
fileNum++;
if (train) loadDS.load(new File(trainFilesSerialized + fileNum + ".ser"));
loadDS.load(new File(testFilesSerialized));
// Shuffle all examples in file before batching happens also for each reset
if(shuffle && batchSize > 1) loadDS.shuffle(seed);
loadDSIndex = 0;
// inputBatched = loadDS.batchBy(batchSize);
}
// TODO loading full train dataset when using cuda causes memory error - find way to load into list off gpu
// result = inputBatched.get(batchNum);
for (int i = 0; i < batchSize; i++) {
if (loadDS.get(loadDSIndex) != null) temp.add(loadDS.get(loadDSIndex));
else break;
loadDSIndex ++;
}
if (temp.size() > 1 ) result = DataSet.merge(temp);
else result = temp.get(0);
} else {
result = convertDataSet(batchSize);
}
return result;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream() {
if (train) inputStream = trainInputStream;
else inputStream = testInputStream;
}
public List<String> getLabels(){
return labels;
}
public void reset(){
numExamples = 0;
fileNum = 0;
load();
}
public void train() {
train = true;
setInputStream();
}
public void test() {
train = false;
setInputStream();
shuffle = false;
numExamples = 0;
fileNum = 0;
}
}
| datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/CifarLoader.java | /*
* * Copyright 2016 Skymind, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*/
package org.datavec.image.loader;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacv.OpenCVFrameConverter;
import org.datavec.api.berkeley.Pair;
import org.datavec.image.data.ImageWritable;
import org.datavec.image.transform.ColorConversionTransform;
import org.datavec.image.transform.EqualizeHistTransform;
import org.datavec.image.transform.ImageTransform;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.impl.accum.Sum;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.util.FeatureUtil;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.*;
import static org.bytedeco.javacpp.opencv_core.CV_8UC;
import static org.bytedeco.javacpp.opencv_core.Mat;
import static org.bytedeco.javacpp.opencv_imgproc.COLOR_BGR2YCrCb;
/**
* CifarLoader is loader specific for the Cifar10 dataset
*
* Reference: Learning Multiple Layers of Features from Tiny Images, Alex Krizhevsky, 2009.
*
* There is a special preProcessor used to normalize the dataset based on Sergey Zagoruyko example
* https://github.com/szagoruyko/cifar.torch
*/
public class CifarLoader extends NativeImageLoader implements Serializable {
public final static int NUM_TRAIN_IMAGES = 50000;
public final static int NUM_TEST_IMAGES = 10000;
public final static int NUM_LABELS = 10; // Note 6000 imgs per class
public final static int HEIGHT = 32;
public final static int WIDTH = 32;
public final static int CHANNELS = 3;
public final static int BYTEFILELEN = 3073;
public static String dataBinUrl = "https://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz";
public static String localDir = "cifar";
public static String dataBinFile = "cifar-10-batches-bin";
public static File fullDir = new File(BASE_DIR, FilenameUtils.concat(localDir, dataBinFile));
public static File meanVarPath = new File(fullDir, "meanVarPath.txt");
protected static String labelFileName = "batches.meta.txt";
protected static InputStream inputStream;
protected static InputStream trainInputStream;
protected static InputStream testInputStream;
protected static List<DataSet> inputBatched;
protected static List<String> labels = new ArrayList<>();
public static String[] TRAINFILENAMES = {"data_batch_1.bin", "data_batch_2.bin", "data_batch_3.bin", "data_batch_4.bin", "data_batch5.bin"};
public static String TESTFILENAME = "test_batch.bin";
protected static String trainFilesSerialized = FilenameUtils.concat(fullDir.toString(), "cifar_train_serialized");
protected static String testFilesSerialized = FilenameUtils.concat(fullDir.toString(), "cifar_test_serialized.ser");
protected static boolean train = true;
public static boolean useSpecialPreProcessCifar = false;
public static Map<String, String> cifarDataMap = new HashMap<>();
protected static int height = HEIGHT;
protected static int width = WIDTH;
protected static int channels = CHANNELS;
protected static long seed = System.currentTimeMillis();
protected static boolean shuffle = true;
protected int numExamples = 0;
protected static int numToConvertDS = 10000; // Each file is 10000 images, limiting for file preprocess load
protected double uMean = 0;
protected double uStd = 0;
protected double vMean = 0;
protected double vStd = 0;
protected boolean meanStdStored = false;
protected int loadDSIndex = 0;
protected DataSet loadDS = new DataSet();
protected int fileNum = 0;
public CifarLoader() {
this(height,width, channels, null, train, useSpecialPreProcessCifar, fullDir, seed, shuffle);
}
public CifarLoader(boolean train) {
this(height, width, channels, null, train, useSpecialPreProcessCifar, fullDir, seed, shuffle);
}
public CifarLoader(boolean train, File fullPath) {
this(height, width, channels, null, train, useSpecialPreProcessCifar, fullPath, seed, shuffle);
}
public CifarLoader(int height, int width, int channels, boolean train, boolean useSpecialPreProcessCifar) {
this(height, width, channels, null, train, useSpecialPreProcessCifar, fullDir, seed, shuffle);
}
public CifarLoader(int height, int width, int channels, ImageTransform imgTransform, boolean train, boolean useSpecialPreProcessCifar) {
this(height, width, channels, imgTransform, train, useSpecialPreProcessCifar, fullDir, seed, shuffle);
}
public CifarLoader(int height, int width, int channels, ImageTransform imgTransform, boolean train, boolean useSpecialPreProcessCifar, boolean shuffle) {
this(height, width, channels, imgTransform, train, useSpecialPreProcessCifar, fullDir, seed, shuffle);
}
public CifarLoader(int height, int width, int channels, ImageTransform imgTransform, boolean train, boolean useSpecialPreProcessCifar, File fullPath, long seed, boolean shuffle) {
super(height, width, channels, imgTransform);
this.height = height;
this.width = width;
this.channels = channels;
this.train = train;
this.useSpecialPreProcessCifar = useSpecialPreProcessCifar;
this.fullDir = fullPath;
this.seed = seed;
this.shuffle = shuffle;
load();
}
@Override
public INDArray asRowVector(File f) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public INDArray asRowVector(InputStream inputStream) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public INDArray asMatrix(File f) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public INDArray asMatrix(InputStream inputStream) throws IOException {
throw new UnsupportedOperationException();
}
public void generateMaps() {
cifarDataMap.put("filesFilename", new File(dataBinUrl).getName());
cifarDataMap.put("filesURL", dataBinUrl);
cifarDataMap.put("filesFilenameUnzipped", dataBinFile);
}
private void defineLabels() {
try {
File path = new File(fullDir, labelFileName);
BufferedReader br = new BufferedReader(new FileReader(path));
String line;
while ((line = br.readLine()) != null) {
labels.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void load() {
if (!cifarRawFilesExist() && !fullDir.exists()) {
generateMaps();
fullDir.mkdir();
log.info("Downloading {}...", localDir);
downloadAndUntar(cifarDataMap, new File(BASE_DIR, localDir));
}
try {
Collection<File> subFiles = FileUtils.listFiles(fullDir, new String[]{"bin"}, true);
Iterator trainIter = subFiles.iterator();
trainInputStream = new SequenceInputStream(new FileInputStream((File) trainIter.next()), new FileInputStream((File) trainIter.next()));
while (trainIter.hasNext()) {
File nextFile = (File) trainIter.next();
if (!TESTFILENAME.equals(nextFile.getName()))
trainInputStream = new SequenceInputStream(trainInputStream, new FileInputStream(nextFile));
}
testInputStream = new FileInputStream(new File(fullDir, TESTFILENAME));
} catch (Exception e) {
e.printStackTrace();
}
defineLabels();
if (useSpecialPreProcessCifar && train && !cifarProcessedFilesExists()) {
for (int i = fileNum+1; i <= (TRAINFILENAMES.length); i++) {
inputStream = trainInputStream;
DataSet result = convertDataSet(numToConvertDS);
result.save(new File(trainFilesSerialized + i + ".ser"));
}
for (int i = 1; i <= (TRAINFILENAMES.length); i++){
normalizeCifar(new File(trainFilesSerialized + i + ".ser"));
}
inputStream = testInputStream;
DataSet result = convertDataSet(numToConvertDS);
result.save(new File(testFilesSerialized));
normalizeCifar(new File(testFilesSerialized));
}
setInputStream();
}
public boolean cifarRawFilesExist() {
File f = new File(fullDir, TESTFILENAME);
if (!f.exists()) return false;
for (String name : TRAINFILENAMES) {
f = new File(fullDir, name);
if (!f.exists()) return false;
}
return true;
}
private boolean cifarProcessedFilesExists() {
File f;
if (train) {
f = new File(trainFilesSerialized + 1 + ".ser");
if (!f.exists()) return false;
} else {
f = new File(testFilesSerialized);
if (!f.exists()) return false;
}
return true;
}
/**
* Preprocess and store cifar based on successful Torch approach by Sergey Zagoruyko
* Reference: https://github.com/szagoruyko/cifar.torch
*/
public opencv_core.Mat convertCifar(Mat orgImage) {
numExamples++;
Mat resImage = new Mat();
OpenCVFrameConverter.ToMat converter = new OpenCVFrameConverter.ToMat();
// ImageTransform yuvTransform = new ColorConversionTransform(new Random(seed), COLOR_BGR2Luv);
// ImageTransform histEqualization = new EqualizeHistTransform(new Random(seed), COLOR_BGR2Luv);
ImageTransform yuvTransform = new ColorConversionTransform(new Random(seed), COLOR_BGR2YCrCb);
ImageTransform histEqualization = new EqualizeHistTransform(new Random(seed), COLOR_BGR2YCrCb);
if (converter != null) {
ImageWritable writable = new ImageWritable(converter.convert(orgImage));
// TODO determine if need to normalize y before transform - opencv docs rec but currently doing after
writable = yuvTransform.transform(writable); // Converts to chrome color to help emphasize image objects
writable = histEqualization.transform(writable); // Normalizes values to further clarify object of interest
resImage = converter.convert(writable.getFrame());
}
return resImage;
}
/**
* Normalize and store cifar based on successful Torch approach by Sergey Zagoruyko
* Reference: https://github.com/szagoruyko/cifar.torch
*/
public void normalizeCifar(File fileName) {
DataSet result = new DataSet();
result.load(fileName);
if(!meanStdStored && train) {
uMean = Math.abs(uMean/numExamples);
uStd = Math.sqrt(uStd);
vMean = Math.abs(vMean/numExamples);
vStd = Math.sqrt(vStd);
// TODO find cleaner way to store and load (e.g. json or yaml)
try {
FileUtils.write(meanVarPath, uMean + "," + uStd + "," + vMean + "," + vStd);
} catch (IOException e) {
e.printStackTrace();
}
meanStdStored = true;
} else if (uMean == 0 && meanStdStored) {
try {
String[] values = FileUtils.readFileToString(meanVarPath).split(",");
uMean = Double.parseDouble(values[0]);
uStd = Double.parseDouble(values[1]);
vMean = Double.parseDouble(values[2]);
vStd = Double.parseDouble(values[3]);
} catch (IOException e) {
e.printStackTrace();
}
}
for (int i = 0; i < result.numExamples(); i++) {
INDArray newFeatures = result.get(i).getFeatureMatrix();
newFeatures.tensorAlongDimension(0, new int[] {0,2,3}).divi(255);
newFeatures.tensorAlongDimension(1, new int[] {0,2,3}).subi(uMean).divi(uStd);
newFeatures.tensorAlongDimension(2, new int[] {0,2,3}).subi(vMean).divi(vStd);
result.get(i).setFeatures(newFeatures);
}
result.save(fileName);
}
public Pair<INDArray, opencv_core.Mat> convertMat(byte[] byteFeature) {
INDArray label= FeatureUtil.toOutcomeVector(byteFeature[0], NUM_LABELS); ; // first value in the 3073 byte array
opencv_core.Mat image = new opencv_core.Mat(HEIGHT, WIDTH, CV_8UC(CHANNELS)); // feature are 3072
ByteBuffer imageData = image.createBuffer();
for (int i = 0; i < HEIGHT * WIDTH; i++) {
imageData.put(3 * i, byteFeature[i + 1 + 2 * height * width]); // blue
imageData.put(3 * i + 1, byteFeature[i + 1 + height * width]); // green
imageData.put(3 * i + 2, byteFeature[i + 1]); // red
}
if (useSpecialPreProcessCifar) {
image = convertCifar(image);
}
return new Pair<>(label, image);
}
public DataSet convertDataSet(int num) {
int batchNumCount = 0;
List<DataSet> dataSets = new ArrayList<>();
Pair<INDArray, opencv_core.Mat> matConversion;
byte[] byteFeature = new byte[BYTEFILELEN];
try {
while (inputStream.read(byteFeature) != -1 && batchNumCount != num) {
matConversion = convertMat(byteFeature);
try {
dataSets.add(new DataSet(asMatrix(matConversion.getSecond()), matConversion.getFirst()));
batchNumCount++;
} catch (Exception e) {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
DataSet result = new DataSet();
try {
result = result.merge(dataSets);
} catch (IllegalArgumentException e) {
return result;
}
double uTempMean, vTempMean;
for (DataSet data :result) {
try {
if (useSpecialPreProcessCifar) {
INDArray uChannel = data.getFeatures().tensorAlongDimension(1, new int[] {0,2,3});
INDArray vChannel = data.getFeatures().tensorAlongDimension(2, new int[] {0,2,3});
uTempMean = uChannel.mean(new int[] {0,2,3}).getDouble(0);
// TODO INDArray.var result is incorrect based on dimensions passed in thus using manual
uStd += varManual(uChannel, uTempMean);
uMean += uTempMean;
vTempMean = vChannel.mean(new int[] {0,2,3}).getDouble(0);
vStd += varManual(vChannel, vTempMean);
vMean += vTempMean;
} else {
// normalize if just input stream and not special preprocess
data.setFeatures(data.getFeatureMatrix().div(255));
}
} catch (IllegalArgumentException e) {
throw new IllegalStateException("The number of channels must be 3 to special preProcess Cifar with.");
}
}
if(shuffle && num > 1) result.shuffle(seed);
return result;
}
public double varManual(INDArray x, double mean) {
INDArray xSubMean = x.sub(mean);
INDArray squared = xSubMean.muli(xSubMean);
double accum = Nd4j.getExecutioner().execAndReturn(new Sum(squared)).getFinalResult().doubleValue();
return accum/x.ravel().length();
}
public DataSet next(int batchSize) {
return next(batchSize, 0);
}
public DataSet next(int batchSize, int exampleNum) {
List<DataSet> temp = new ArrayList<>();
DataSet result;
if (cifarProcessedFilesExists() && useSpecialPreProcessCifar) {
if (exampleNum == 0 || ((exampleNum/fileNum) == numToConvertDS && train)) {
fileNum++;
if (train) loadDS.load(new File(trainFilesSerialized + fileNum + ".ser"));
loadDS.load(new File(testFilesSerialized));
// Shuffle all examples in file before batching happens also for each reset
if(shuffle && batchSize > 1) loadDS.shuffle(seed);
loadDSIndex = 0;
// inputBatched = loadDS.batchBy(batchSize);
}
// TODO loading full train dataset when using cuda causes memory error - find way to load into list off gpu
// result = inputBatched.get(batchNum);
for (int i = 0; i < batchSize; i++) {
if (loadDS.get(loadDSIndex) != null) temp.add(loadDS.get(loadDSIndex));
else break;
loadDSIndex ++;
}
if (temp.size() > 1 ) result = DataSet.merge(temp);
else result = temp.get(0);
} else {
result = convertDataSet(batchSize);
}
return result;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream() {
if (train) inputStream = trainInputStream;
else inputStream = testInputStream;
}
public List<String> getLabels(){
return labels;
}
public void reset(){
numExamples = 0;
fileNum = 0;
load();
}
public void train() {
train = true;
setInputStream();
}
public void test() {
train = false;
setInputStream();
shuffle = false;
}
}
| Removed the loader and just reset variables when calling test.
| datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/CifarLoader.java | Removed the loader and just reset variables when calling test. | <ide><path>atavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/CifarLoader.java
<ide> e.printStackTrace();
<ide> }
<ide>
<del> defineLabels();
<add> if(labels.isEmpty()) defineLabels();
<ide>
<ide> if (useSpecialPreProcessCifar && train && !cifarProcessedFilesExists()) {
<ide> for (int i = fileNum+1; i <= (TRAINFILENAMES.length); i++) {
<ide> train = false;
<ide> setInputStream();
<ide> shuffle = false;
<add> numExamples = 0;
<add> fileNum = 0;
<ide> }
<ide>
<ide> } |
|
Java | mit | 75f9faba9890d5e26db5a13bd87913b57c69fbf7 | 0 | oleg-nenashev/remoting,jenkinsci/remoting,oleg-nenashev/remoting,jenkinsci/remoting | /*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* 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 hudson.remoting;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.remoting.Channel.Mode;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchProviderException;
import java.security.PrivilegedActionException;
import java.security.cert.CertificateFactory;
import javax.annotation.CheckForNull;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import org.jenkinsci.remoting.util.IOUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.CmdLineException;
import javax.crypto.spec.IvParameterSpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.TrustManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.File;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileWriter;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLConnection;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLClassLoader;
import java.net.InetSocketAddress;
import java.net.HttpURLConnection;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateException;
import java.security.NoSuchAlgorithmException;
import java.security.KeyManagementException;
import java.security.SecureRandom;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
/**
* Entry point for running a {@link Channel}. This is the main method of the slave JVM.
*
* <p>
* This class also defines several methods for
* starting a channel on a fresh JVM.
*
* @author Kohsuke Kawaguchi
*/
@SuppressFBWarnings(value = "DM_EXIT", justification = "This class is runnable. It is eligible to exit in the case of wrong params")
public class Launcher {
public Mode mode = Mode.BINARY;
// no-op, but left for backward compatibility
@Option(name="-ping")
public boolean ping = true;
@Option(name="-slaveLog", usage="create local slave error log")
public File slaveLog = null;
@Option(name="-text",usage="encode communication with the master with base64. " +
"Useful for running slave over 8-bit unsafe protocol like telnet")
public void setTextMode(boolean b) {
mode = b?Mode.TEXT:Mode.BINARY;
System.out.println("Running in "+mode.name().toLowerCase(Locale.ENGLISH)+" mode");
}
@Option(name="-jnlpUrl",usage="instead of talking to the master via stdin/stdout, " +
"emulate a JNLP client by making a TCP connection to the master. " +
"Connection parameters are obtained by parsing the JNLP file.")
public URL slaveJnlpURL = null;
@Option(name="-jnlpCredentials",metaVar="USER:PASSWORD",usage="HTTP BASIC AUTH header to pass in for making HTTP requests.")
public String slaveJnlpCredentials = null;
@Option(name="-secret", metaVar="HEX_SECRET", usage="Slave connection secret to use instead of -jnlpCredentials.")
public String secret;
@Option(name="-proxyCredentials",metaVar="USER:PASSWORD",usage="HTTP BASIC AUTH header to pass in for making HTTP authenticated proxy requests.")
public String proxyCredentials = null;
@Option(name="-cp",aliases="-classpath",metaVar="PATH",
usage="add the given classpath elements to the system classloader.")
public void addClasspath(String pathList) throws Exception {
Method $addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
$addURL.setAccessible(true);
for(String token : pathList.split(File.pathSeparator))
$addURL.invoke(ClassLoader.getSystemClassLoader(),new File(token).toURI().toURL());
// fix up the system.class.path to pretend that those jar files
// are given through CLASSPATH or something.
// some tools like JAX-WS RI and Hadoop relies on this.
System.setProperty("java.class.path",System.getProperty("java.class.path")+File.pathSeparatorChar+pathList);
}
@Option(name="-tcp",usage="instead of talking to the master via stdin/stdout, " +
"listens to a random local port, write that port number to the given file, " +
"then wait for the master to connect to that port.")
public File tcpPortFile=null;
@Option(name="-auth",metaVar="user:pass",usage="If your Jenkins is security-enabled, specify a valid user name and password.")
public String auth = null;
/**
* @since 2.24
*/
@Option(name="-jar-cache",metaVar="DIR",usage="Cache directory that stores jar files sent from the master")
public File jarCache = new File(System.getProperty("user.home"),".jenkins/cache/jars");
@Option(name = "-cert",
usage = "Specify additional X.509 encoded PEM certificates to trust when connecting to Jenkins " +
"root URLs. If starting with @ then the remainder is assumed to be the name of the " +
"certificate file to read.", forbids = "-noCertificateCheck")
public List<String> candidateCertificates;
public InetSocketAddress connectionTarget = null;
@Option(name="-connectTo",usage="make a TCP connection to the given host and port, then start communication.",metaVar="HOST:PORT")
public void setConnectTo(String target) {
String[] tokens = target.split(":");
if(tokens.length!=2) {
System.err.println("Illegal parameter: "+target);
System.exit(1);
}
connectionTarget = new InetSocketAddress(tokens[0],Integer.parseInt(tokens[1]));
}
/**
* Bypass HTTPS security check by using free-for-all trust manager.
*
* @param ignored
* This is ignored.
*/
@Option(name="-noCertificateCheck", forbids = "-cert")
public void setNoCertificateCheck(boolean ignored) throws NoSuchAlgorithmException, KeyManagementException {
System.out.println("Skipping HTTPS certificate checks altogether. Note that this is not secure at all.");
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[]{new NoCheckTrustManager()}, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
// bypass host name check, too.
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
}
@Option(name="-noReconnect",usage="Doesn't try to reconnect when a communication fail, and exit instead")
public boolean noReconnect = false;
@Option(name = "-noKeepAlive",
usage = "Disable TCP socket keep alive on connection to the master.")
public boolean noKeepAlive = false;
public static void main(String... args) throws Exception {
Launcher launcher = new Launcher();
CmdLineParser parser = new CmdLineParser(launcher);
try {
parser.parseArgument(args);
launcher.run();
} catch (CmdLineException e) {
System.err.println(e.getMessage());
System.err.println("java -jar slave.jar [options...]");
parser.printUsage(System.err);
System.err.println();
}
}
@edu.umd.cs.findbugs.annotations.SuppressWarnings("DM_DEFAULT_ENCODING") // log file, just like console output, should be in platform default encoding
public void run() throws Exception {
if (slaveLog!=null) {
System.setErr(new PrintStream(new TeeOutputStream(System.err,new FileOutputStream(slaveLog))));
}
if(auth!=null) {
final int idx = auth.indexOf(':');
if(idx<0) throw new CmdLineException(null, "No ':' in the -auth option");
Authenticator.setDefault(new Authenticator() {
@Override public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(auth.substring(0,idx), auth.substring(idx+1).toCharArray());
}
});
}
if (candidateCertificates != null && !candidateCertificates.isEmpty()) {
HttpsURLConnection.setDefaultSSLSocketFactory(getSSLSocketFactory());
}
if(connectionTarget!=null) {
runAsTcpClient();
} else
if(slaveJnlpURL!=null) {
List<String> jnlpArgs = parseJnlpArguments();
if (jarCache != null) {
jnlpArgs.add("-jar-cache");
jnlpArgs.add(jarCache.getPath());
}
if (this.noReconnect) {
jnlpArgs.add("-noreconnect");
}
if (this.noKeepAlive) {
jnlpArgs.add("-noKeepAlive");
}
if (candidateCertificates != null && !candidateCertificates.isEmpty()) {
for (String c: candidateCertificates) {
jnlpArgs.add("-cert");
jnlpArgs.add(c);
}
}
try {
hudson.remoting.jnlp.Main._main(jnlpArgs.toArray(new String[jnlpArgs.size()]));
} catch (CmdLineException e) {
System.err.println("JNLP file "+slaveJnlpURL+" has invalid arguments: "+jnlpArgs);
System.err.println("Most likely a configuration error in the master");
System.err.println(e.getMessage());
System.exit(1);
}
} else
if(tcpPortFile!=null) {
runAsTcpServer();
} else {
runWithStdinStdout();
}
System.exit(0);
}
@CheckForNull
private SSLSocketFactory getSSLSocketFactory()
throws PrivilegedActionException, KeyStoreException, NoSuchProviderException, CertificateException,
NoSuchAlgorithmException, IOException, KeyManagementException {
SSLSocketFactory sslSocketFactory = null;
if (candidateCertificates != null && !candidateCertificates.isEmpty()) {
CertificateFactory factory;
try {
factory = CertificateFactory.getInstance("X.509");
} catch (CertificateException e) {
throw new IllegalStateException("Java platform specification mandates support for X.509", e);
}
KeyStore keyStore = Engine.getCacertsKeyStore();
// load the keystore
keyStore.load(null, null);
int i = 0;
for (String certOrAtFilename : candidateCertificates) {
certOrAtFilename = certOrAtFilename.trim();
byte[] cert;
if (certOrAtFilename.startsWith("@")) {
File file = new File(certOrAtFilename.substring(1));
long length;
if (file.isFile()
&& (length = file.length()) < 65536
&& length > "-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----".length()) {
FileInputStream fis = null;
try {
// we do basic size validation, if there are x509 certificates that have a PEM encoding
// larger
// than 64kb we can revisit the upper bound.
cert = new byte[(int) length];
fis = new FileInputStream(file);
int read = fis.read(cert);
if (cert.length != read) {
LOGGER.log(Level.WARNING, "Only read {0} bytes from {1}, expected to read {2}",
new Object[]{read, file, cert.length});
// skip it
continue;
}
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Could not read certificate from " + file, e);
continue;
} finally {
IOUtils.closeQuietly(fis);
}
} else {
if (file.isFile()) {
LOGGER.log(Level.WARNING,
"Could not read certificate from {0}. File size is not within " +
"the expected range for a PEM encoded X.509 certificate",
file.getAbsolutePath());
} else {
LOGGER.log(Level.WARNING, "Could not read certificate from {0}. File not found",
file.getAbsolutePath());
}
continue;
}
} else {
try {
cert = certOrAtFilename.getBytes("US-ASCII");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("US-ASCII support is mandated by the JLS", e);
}
}
try {
keyStore.setCertificateEntry(String.format("alias-%d", i++),
factory.generateCertificate(new ByteArrayInputStream(cert)));
} catch (ClassCastException e) {
LOGGER.log(Level.WARNING, "Expected X.509 certificate from " + certOrAtFilename, e);
} catch (CertificateException e) {
LOGGER.log(Level.WARNING, "Could not parse X.509 certificate from " + certOrAtFilename, e);
}
}
// prepare the trust manager
TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
// prepare the SSL context
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, trustManagerFactory.getTrustManagers(), null);
// now we have our custom socket factory
sslSocketFactory = ctx.getSocketFactory();
}
return sslSocketFactory;
}
/**
* Parses the connection arguments from JNLP file given in the URL.
*/
public List<String> parseJnlpArguments() throws ParserConfigurationException, SAXException, IOException, InterruptedException {
if (secret != null) {
slaveJnlpURL = new URL(slaveJnlpURL + "?encrypt=true");
if (slaveJnlpCredentials != null) {
throw new IOException("-jnlpCredentials and -secret are mutually exclusive");
}
}
while (true) {
URLConnection con = null;
try {
con = Util.openURLConnection(slaveJnlpURL);
if (con instanceof HttpURLConnection) {
HttpURLConnection http = (HttpURLConnection) con;
if (slaveJnlpCredentials != null) {
String userPassword = slaveJnlpCredentials;
String encoding = Base64.encode(userPassword.getBytes("UTF-8"));
http.setRequestProperty("Authorization", "Basic " + encoding);
}
if (System.getProperty("proxyCredentials", proxyCredentials) != null) {
String encoding = Base64.encode(System.getProperty("proxyCredentials", proxyCredentials).getBytes("UTF-8"));
http.setRequestProperty("Proxy-Authorization", "Basic " + encoding);
}
}
con.connect();
if (con instanceof HttpURLConnection) {
HttpURLConnection http = (HttpURLConnection) con;
if(http.getResponseCode()>=400)
// got the error code. report that (such as 401)
throw new IOException("Failed to load "+slaveJnlpURL+": "+http.getResponseCode()+" "+http.getResponseMessage());
}
Document dom;
// check if this URL points to a .jnlp file
String contentType = con.getHeaderField("Content-Type");
String expectedContentType = secret == null ? "application/x-java-jnlp-file" : "application/octet-stream";
InputStream input = con.getInputStream();
if (secret != null) {
byte[] payload = toByteArray(input);
// the first 16 bytes (128bit) are initialization vector
try {
Cipher cipher = Cipher.getInstance("AES/CFB8/NoPadding");
cipher.init(Cipher.DECRYPT_MODE,
new SecretKeySpec(fromHexString(secret.substring(0, Math.min(secret.length(), 32))), "AES"),
new IvParameterSpec(payload,0,16));
byte[] decrypted = cipher.doFinal(payload,16,payload.length-16);
input = new ByteArrayInputStream(decrypted);
} catch (GeneralSecurityException x) {
throw (IOException)new IOException("Failed to decrypt the JNLP file. Invalid secret key?").initCause(x);
}
}
if(contentType==null || !contentType.startsWith(expectedContentType)) {
// load DOM anyway, but if it fails to parse, that's probably because this is not an XML file to begin with.
try {
dom = loadDom(slaveJnlpURL, input);
} catch (SAXException e) {
throw new IOException(slaveJnlpURL+" doesn't look like a JNLP file; content type was "+contentType);
} catch (IOException e) {
throw new IOException(slaveJnlpURL+" doesn't look like a JNLP file; content type was "+contentType);
}
} else {
dom = loadDom(slaveJnlpURL, input);
}
// exec into the JNLP launcher, to fetch the connection parameter through JNLP.
NodeList argElements = dom.getElementsByTagName("argument");
List<String> jnlpArgs = new ArrayList<String>();
for( int i=0; i<argElements.getLength(); i++ )
jnlpArgs.add(argElements.item(i).getTextContent());
if (slaveJnlpCredentials != null) {
jnlpArgs.add("-credentials");
jnlpArgs.add(slaveJnlpCredentials);
}
// force a headless mode
jnlpArgs.add("-headless");
return jnlpArgs;
} catch (SSLHandshakeException e) {
if(e.getMessage().contains("PKIX path building failed")) {
// invalid SSL certificate. One reason this happens is when the certificate is self-signed
IOException x = new IOException("Failed to validate a server certificate. If you are using a self-signed certificate, you can use the -noCertificateCheck option to bypass this check.");
x.initCause(e);
throw x;
} else
throw e;
} catch (IOException e) {
if (this.noReconnect)
throw (IOException)new IOException("Failing to obtain "+slaveJnlpURL).initCause(e);
System.err.println("Failing to obtain "+slaveJnlpURL);
e.printStackTrace(System.err);
System.err.println("Waiting 10 seconds before retry");
Thread.sleep(10*1000);
// retry
} finally {
if (con instanceof HttpURLConnection) {
HttpURLConnection http = (HttpURLConnection) con;
http.disconnect();
}
}
}
}
private byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c;
while ((c = input.read()) != -1) {
baos.write(c);
}
return baos.toByteArray();
}
// from hudson.Util
private static byte[] fromHexString(String data) {
byte[] r = new byte[data.length() / 2];
for (int i = 0; i < data.length(); i += 2)
r[i / 2] = (byte) Integer.parseInt(data.substring(i, i + 2), 16);
return r;
}
private static Document loadDom(URL slaveJnlpURL, InputStream is) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
return db.parse(is, slaveJnlpURL.toExternalForm());
}
/**
* Listens on an ephemeral port, record that port number in a port file,
* then accepts one TCP connection.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("DM_DEFAULT_ENCODING") // port number file should be in platform default encoding
private void runAsTcpServer() throws IOException, InterruptedException {
// if no one connects for too long, assume something went wrong
// and avoid hanging forever
ServerSocket ss = new ServerSocket(0,1);
ss.setSoTimeout(30*1000);
// write a port file to report the port number
FileWriter w = new FileWriter(tcpPortFile);
try {
w.write(String.valueOf(ss.getLocalPort()));
} finally {
w.close();
}
// accept just one connection and that's it.
// when we are done, remove the port file to avoid stale port file
Socket s;
try {
s = ss.accept();
ss.close();
} finally {
boolean deleted = tcpPortFile.delete();
if (!deleted) {
LOGGER.log(Level.WARNING, "Cannot delete the temporary TCP port file {0}", tcpPortFile);
}
}
runOnSocket(s);
}
private void runOnSocket(Socket s) throws IOException, InterruptedException {
// this prevents a connection from silently terminated by the router in between or the other peer
// and that goes without unnoticed. However, the time out is often very long (for example 2 hours
// by default in Linux) that this alone is enough to prevent that.
s.setKeepAlive(true);
// we take care of buffering on our own
s.setTcpNoDelay(true);
main(new BufferedInputStream(SocketChannelStream.in(s)),
new BufferedOutputStream(SocketChannelStream.out(s)), mode,ping,
new FileSystemJarCache(jarCache,true));
}
/**
* Connects to the given TCP port and then start running
*/
private void runAsTcpClient() throws IOException, InterruptedException {
// if no one connects for too long, assume something went wrong
// and avoid hanging forever
Socket s = new Socket(connectionTarget.getAddress(),connectionTarget.getPort());
runOnSocket(s);
}
private void runWithStdinStdout() throws IOException, InterruptedException {
// use stdin/stdout for channel communication
ttyCheck();
if (isWindows()) {
/*
To prevent the dead lock between GetFileType from _ioinit in C runtime and blocking read that ChannelReaderThread
would do on stdin, load the crypto DLL first.
This is a band-aid solution to the problem. Still searching for more fundamental fix.
02f1e750 7c90d99a ntdll!KiFastSystemCallRet
02f1e754 7c810f63 ntdll!NtQueryVolumeInformationFile+0xc
02f1e784 77c2c9f9 kernel32!GetFileType+0x7e
02f1e7e8 77c1f01d msvcrt!_ioinit+0x19f
02f1e88c 7c90118a msvcrt!__CRTDLL_INIT+0xac
02f1e8ac 7c91c4fa ntdll!LdrpCallInitRoutine+0x14
02f1e9b4 7c916371 ntdll!LdrpRunInitializeRoutines+0x344
02f1ec60 7c9164d3 ntdll!LdrpLoadDll+0x3e5
02f1ef08 7c801bbd ntdll!LdrLoadDll+0x230
02f1ef70 7c801d72 kernel32!LoadLibraryExW+0x18e
02f1ef84 7c801da8 kernel32!LoadLibraryExA+0x1f
02f1efa0 77de8830 kernel32!LoadLibraryA+0x94
02f1f05c 6d3eb1be ADVAPI32!CryptAcquireContextA+0x512
WARNING: Stack unwind information not available. Following frames may be wrong.
02f1f13c 6d99c844 java_6d3e0000!Java_sun_security_provider_NativeSeedGenerator_nativeGenerateSeed+0x6e
see http://weblogs.java.net/blog/kohsuke/archive/2009/09/28/reading-stdin-may-cause-your-jvm-hang
for more details
*/
new SecureRandom().nextBoolean();
}
// this will prevent programs from accidentally writing to System.out
// and messing up the stream.
OutputStream os = new StandardOutputStream();
System.setOut(System.err);
// System.in/out appear to be already buffered (at least that was the case in Linux and Windows as of Java6)
// so we are not going to double-buffer these.
main(System.in, os, mode, ping, new FileSystemJarCache(jarCache,true));
}
private static void ttyCheck() {
try {
Method m = System.class.getMethod("console");
Object console = m.invoke(null);
if(console!=null) {
// we seem to be running from interactive console. issue a warning.
// but since this diagnosis could be wrong, go on and do what we normally do anyway. Don't exit.
System.out.println(
"WARNING: Are you running slave agent from an interactive console?\n" +
"If so, you are probably using it incorrectly.\n" +
"See http://wiki.jenkins-ci.org/display/JENKINS/Launching+slave.jar+from+from+console");
}
} catch (LinkageError e) {
// we are probably running on JDK5 that doesn't have System.console()
// we can't check
} catch (InvocationTargetException e) {
// this is impossible
throw new AssertionError(e);
} catch (NoSuchMethodException e) {
// must be running on JDK5
} catch (IllegalAccessException e) {
// this is impossible
throw new AssertionError(e);
}
}
public static void main(InputStream is, OutputStream os) throws IOException, InterruptedException {
main(is,os,Mode.BINARY);
}
public static void main(InputStream is, OutputStream os, Mode mode) throws IOException, InterruptedException {
main(is,os,mode,false);
}
/**
* @deprecated
* Use {@link #main(InputStream, OutputStream, Mode, boolean, JarCache)}
*/
@Deprecated
public static void main(InputStream is, OutputStream os, Mode mode, boolean performPing) throws IOException, InterruptedException {
main(is, os, mode, performPing,
new FileSystemJarCache(new File(System.getProperty("user.home"),".jenkins/cache/jars"),true));
}
/**
* @since 2.24
*/
public static void main(InputStream is, OutputStream os, Mode mode, boolean performPing, JarCache cache) throws IOException, InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
ChannelBuilder cb = new ChannelBuilder("channel", executor)
.withMode(mode)
.withJarCache(cache);
// expose StandardOutputStream as a channel property, which is a better way to make this available
// to the user of Channel than Channel#getUnderlyingOutput()
if (os instanceof StandardOutputStream)
cb.withProperty(StandardOutputStream.class,os);
Channel channel = cb.build(is, os);
System.err.println("channel started");
// Both settings are available since remoting-2.0
long timeout = 1000 * Long.parseLong(
System.getProperty("hudson.remoting.Launcher.pingTimeoutSec", "240")),
interval = 1000 * Long.parseLong(
System.getProperty("hudson.remoting.Launcher.pingIntervalSec", /* was "600" but this duplicates ChannelPinger */ "0"));
Logger.getLogger(PingThread.class.getName()).log(Level.FINE, "performPing={0} timeout={1} interval={2}", new Object[] {performPing, timeout, interval});
if (performPing && timeout > 0 && interval > 0) {
new PingThread(channel, timeout, interval) {
@Deprecated
@Override
protected void onDead() {
System.err.println("Ping failed. Terminating");
System.exit(-1);
}
@Override
protected void onDead(Throwable cause) {
System.err.println("Ping failed. Terminating");
cause.printStackTrace();
System.exit(-1);
}
}.start();
}
channel.join();
System.err.println("channel stopped");
}
/**
* {@link X509TrustManager} that performs no check at all.
*/
private static class NoCheckTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
public static boolean isWindows() {
return File.pathSeparatorChar==';';
}
private static String computeVersion() {
Properties props = new Properties();
InputStream is = Launcher.class.getResourceAsStream(JENKINS_VERSION_PROP_FILE);
if (is == null) {
LOGGER.log(Level.FINE, "Cannot locate the {0} resource file. Hudson/Jenkins version is unknown",
JENKINS_VERSION_PROP_FILE);
return UNKNOWN_JENKINS_VERSION_STR;
}
try {
props.load(is);
} catch (IOException e) {
e.printStackTrace();
} finally {
closeWithLogOnly(is, JENKINS_VERSION_PROP_FILE);
}
return props.getProperty("version", UNKNOWN_JENKINS_VERSION_STR);
}
private static void closeWithLogOnly(Closeable stream, String name) {
try {
stream.close();
} catch (IOException ex) {
LOGGER.log(Level.WARNING, "Cannot close the resource file " + name, ex);
}
}
/**
* Version number of Hudson this slave.jar is from.
*/
public static final String VERSION = computeVersion();
private static final String JENKINS_VERSION_PROP_FILE = "hudson-version.properties";
private static final String UNKNOWN_JENKINS_VERSION_STR = "?";
private static final Logger LOGGER = Logger.getLogger(Launcher.class.getName());
}
| src/main/java/hudson/remoting/Launcher.java | /*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* 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 hudson.remoting;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.remoting.Channel.Mode;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchProviderException;
import java.security.PrivilegedActionException;
import java.security.cert.CertificateFactory;
import javax.annotation.CheckForNull;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import org.jenkinsci.remoting.util.IOUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.CmdLineException;
import javax.crypto.spec.IvParameterSpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.TrustManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.File;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileWriter;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLConnection;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLClassLoader;
import java.net.InetSocketAddress;
import java.net.HttpURLConnection;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateException;
import java.security.NoSuchAlgorithmException;
import java.security.KeyManagementException;
import java.security.SecureRandom;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
/**
* Entry point for running a {@link Channel}. This is the main method of the slave JVM.
*
* <p>
* This class also defines several methods for
* starting a channel on a fresh JVM.
*
* @author Kohsuke Kawaguchi
*/
@SuppressFBWarnings(value = "DM_EXIT", justification = "This class is runnable. It is eligible to exit in the case of wrong params")
public class Launcher {
public Mode mode = Mode.BINARY;
// no-op, but left for backward compatibility
@Option(name="-ping")
public boolean ping = true;
@Option(name="-slaveLog", usage="create local slave error log")
public File slaveLog = null;
@Option(name="-text",usage="encode communication with the master with base64. " +
"Useful for running slave over 8-bit unsafe protocol like telnet")
public void setTextMode(boolean b) {
mode = b?Mode.TEXT:Mode.BINARY;
System.out.println("Running in "+mode.name().toLowerCase(Locale.ENGLISH)+" mode");
}
@Option(name="-jnlpUrl",usage="instead of talking to the master via stdin/stdout, " +
"emulate a JNLP client by making a TCP connection to the master. " +
"Connection parameters are obtained by parsing the JNLP file.")
public URL slaveJnlpURL = null;
@Option(name="-jnlpCredentials",metaVar="USER:PASSWORD",usage="HTTP BASIC AUTH header to pass in for making HTTP requests.")
public String slaveJnlpCredentials = null;
@Option(name="-secret", metaVar="HEX_SECRET", usage="Slave connection secret to use instead of -jnlpCredentials.")
public String secret;
@Option(name="-proxyCredentials",metaVar="USER:PASSWORD",usage="HTTP BASIC AUTH header to pass in for making HTTP authenticated proxy requests.")
public String proxyCredentials = null;
@Option(name="-cp",aliases="-classpath",metaVar="PATH",
usage="add the given classpath elements to the system classloader.")
public void addClasspath(String pathList) throws Exception {
Method $addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
$addURL.setAccessible(true);
for(String token : pathList.split(File.pathSeparator))
$addURL.invoke(ClassLoader.getSystemClassLoader(),new File(token).toURI().toURL());
// fix up the system.class.path to pretend that those jar files
// are given through CLASSPATH or something.
// some tools like JAX-WS RI and Hadoop relies on this.
System.setProperty("java.class.path",System.getProperty("java.class.path")+File.pathSeparatorChar+pathList);
}
@Option(name="-tcp",usage="instead of talking to the master via stdin/stdout, " +
"listens to a random local port, write that port number to the given file, " +
"then wait for the master to connect to that port.")
public File tcpPortFile=null;
@Option(name="-auth",metaVar="user:pass",usage="If your Jenkins is security-enabled, specify a valid user name and password.")
public String auth = null;
/**
* @since 2.24
*/
@Option(name="-jar-cache",metaVar="DIR",usage="Cache directory that stores jar files sent from the master")
public File jarCache = new File(System.getProperty("user.home"),".jenkins/cache/jars");
@Option(name = "-cert",
usage = "Specify additional X.509 encoded PEM certificates to trust when connecting to Jenkins " +
"root URLs. If starting with @ then the remainder is assumed to be the name of the " +
"certificate file to read.", forbids = "-noCertificateCheck")
public List<String> candidateCertificates;
public InetSocketAddress connectionTarget = null;
@Option(name="-connectTo",usage="make a TCP connection to the given host and port, then start communication.",metaVar="HOST:PORT")
public void setConnectTo(String target) {
String[] tokens = target.split(":");
if(tokens.length!=2) {
System.err.println("Illegal parameter: "+target);
System.exit(1);
}
connectionTarget = new InetSocketAddress(tokens[0],Integer.parseInt(tokens[1]));
}
/**
* Bypass HTTPS security check by using free-for-all trust manager.
*
* @param ignored
* This is ignored.
*/
@Option(name="-noCertificateCheck", forbids = "-cert")
public void setNoCertificateCheck(boolean ignored) throws NoSuchAlgorithmException, KeyManagementException {
System.out.println("Skipping HTTPS certificate checks altogether. Note that this is not secure at all.");
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[]{new NoCheckTrustManager()}, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
// bypass host name check, too.
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
}
@Option(name="-noReconnect",usage="Doesn't try to reconnect when a communication fail, and exit instead")
public boolean noReconnect = false;
@Option(name = "-noKeepAlive",
usage = "Disable TCP socket keep alive on connection to the master.")
public boolean noKeepAlive = false;
public static void main(String... args) throws Exception {
Launcher launcher = new Launcher();
CmdLineParser parser = new CmdLineParser(launcher);
try {
parser.parseArgument(args);
launcher.run();
} catch (CmdLineException e) {
System.err.println(e.getMessage());
System.err.println("java -jar slave.jar [options...]");
parser.printUsage(System.err);
System.err.println();
}
}
@edu.umd.cs.findbugs.annotations.SuppressWarnings("DM_DEFAULT_ENCODING") // log file, just like console output, should be in platform default encoding
public void run() throws Exception {
if (slaveLog!=null) {
System.setErr(new PrintStream(new TeeOutputStream(System.err,new FileOutputStream(slaveLog))));
}
if(auth!=null) {
final int idx = auth.indexOf(':');
if(idx<0) throw new CmdLineException(null, "No ':' in the -auth option");
Authenticator.setDefault(new Authenticator() {
@Override public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(auth.substring(0,idx), auth.substring(idx+1).toCharArray());
}
});
}
if (candidateCertificates != null && !candidateCertificates.isEmpty()) {
HttpsURLConnection.setDefaultSSLSocketFactory(getSSLSocketFactory());
}
if(connectionTarget!=null) {
runAsTcpClient();
} else
if(slaveJnlpURL!=null) {
List<String> jnlpArgs = parseJnlpArguments();
if (jarCache != null) {
jnlpArgs.add("-jar-cache");
jnlpArgs.add(jarCache.getPath());
}
if (this.noReconnect) {
jnlpArgs.add("-noreconnect");
}
if (this.noKeepAlive) {
jnlpArgs.add("-noKeepAlive");
}
if (candidateCertificates != null && !candidateCertificates.isEmpty()) {
for (String c: candidateCertificates) {
jnlpArgs.add("-cert");
jnlpArgs.add(c);
}
}
try {
hudson.remoting.jnlp.Main._main(jnlpArgs.toArray(new String[jnlpArgs.size()]));
} catch (CmdLineException e) {
System.err.println("JNLP file "+slaveJnlpURL+" has invalid arguments: "+jnlpArgs);
System.err.println("Most likely a configuration error in the master");
System.err.println(e.getMessage());
System.exit(1);
}
} else
if(tcpPortFile!=null) {
runAsTcpServer();
} else {
runWithStdinStdout();
}
System.exit(0);
}
@CheckForNull
private SSLSocketFactory getSSLSocketFactory()
throws PrivilegedActionException, KeyStoreException, NoSuchProviderException, CertificateException,
NoSuchAlgorithmException, IOException, KeyManagementException {
SSLSocketFactory sslSocketFactory = null;
if (candidateCertificates != null && !candidateCertificates.isEmpty()) {
CertificateFactory factory;
try {
factory = CertificateFactory.getInstance("X.509");
} catch (CertificateException e) {
throw new IllegalStateException("Java platform specification mandates support for X.509", e);
}
KeyStore keyStore = Engine.getCacertsKeyStore();
// load the keystore
keyStore.load(null, null);
int i = 0;
for (String certOrAtFilename : candidateCertificates) {
certOrAtFilename = certOrAtFilename.trim();
byte[] cert;
if (certOrAtFilename.startsWith("@")) {
File file = new File(certOrAtFilename.substring(1));
long length;
if (file.isFile()
&& (length = file.length()) < 65536
&& length > "-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----".length()) {
FileInputStream fis = null;
try {
// we do basic size validation, if there are x509 certificates that have a PEM encoding
// larger
// than 64kb we can revisit the upper bound.
cert = new byte[(int) length];
fis = new FileInputStream(file);
int read = fis.read(cert);
if (cert.length != read) {
LOGGER.log(Level.WARNING, "Only read {0} bytes from {1}, expected to read {2}",
new Object[]{read, file, cert.length});
// skip it
continue;
}
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Could not read certificate from " + file, e);
continue;
} finally {
IOUtils.closeQuietly(fis);
}
} else {
if (file.isFile()) {
LOGGER.log(Level.WARNING,
"Could not read certificate from {0}. File size is not within " +
"the expected range for a PEM encoded X.509 certificate",
file.getAbsolutePath());
} else {
LOGGER.log(Level.WARNING, "Could not read certificate from {0}. File not found",
file.getAbsolutePath());
}
continue;
}
} else {
try {
cert = certOrAtFilename.getBytes("US-ASCII");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("US-ASCII support is mandated by the JLS", e);
}
}
try {
keyStore.setCertificateEntry(String.format("alias-%d", i++),
factory.generateCertificate(new ByteArrayInputStream(cert)));
} catch (ClassCastException e) {
LOGGER.log(Level.WARNING, "Expected X.509 certificate from " + certOrAtFilename, e);
} catch (CertificateException e) {
LOGGER.log(Level.WARNING, "Could not parse X.509 certificate from " + certOrAtFilename, e);
}
}
// prepare the trust manager
TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
// prepare the SSL context
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, trustManagerFactory.getTrustManagers(), null);
// now we have our custom socket factory
sslSocketFactory = ctx.getSocketFactory();
}
return sslSocketFactory;
}
/**
* Parses the connection arguments from JNLP file given in the URL.
*/
public List<String> parseJnlpArguments() throws ParserConfigurationException, SAXException, IOException, InterruptedException {
if (secret != null) {
slaveJnlpURL = new URL(slaveJnlpURL + "?encrypt=true");
if (slaveJnlpCredentials != null) {
throw new IOException("-jnlpCredentials and -secret are mutually exclusive");
}
}
while (true) {
try {
URLConnection con = Util.openURLConnection(slaveJnlpURL);
if (con instanceof HttpURLConnection) {
HttpURLConnection http = (HttpURLConnection) con;
if (slaveJnlpCredentials != null) {
String userPassword = slaveJnlpCredentials;
String encoding = Base64.encode(userPassword.getBytes("UTF-8"));
http.setRequestProperty("Authorization", "Basic " + encoding);
}
if (System.getProperty("proxyCredentials", proxyCredentials) != null) {
String encoding = Base64.encode(System.getProperty("proxyCredentials", proxyCredentials).getBytes("UTF-8"));
http.setRequestProperty("Proxy-Authorization", "Basic " + encoding);
}
}
con.connect();
if (con instanceof HttpURLConnection) {
HttpURLConnection http = (HttpURLConnection) con;
if(http.getResponseCode()>=400)
// got the error code. report that (such as 401)
throw new IOException("Failed to load "+slaveJnlpURL+": "+http.getResponseCode()+" "+http.getResponseMessage());
}
Document dom;
// check if this URL points to a .jnlp file
String contentType = con.getHeaderField("Content-Type");
String expectedContentType = secret == null ? "application/x-java-jnlp-file" : "application/octet-stream";
InputStream input = con.getInputStream();
if (secret != null) {
byte[] payload = toByteArray(input);
// the first 16 bytes (128bit) are initialization vector
try {
Cipher cipher = Cipher.getInstance("AES/CFB8/NoPadding");
cipher.init(Cipher.DECRYPT_MODE,
new SecretKeySpec(fromHexString(secret.substring(0, Math.min(secret.length(), 32))), "AES"),
new IvParameterSpec(payload,0,16));
byte[] decrypted = cipher.doFinal(payload,16,payload.length-16);
input = new ByteArrayInputStream(decrypted);
} catch (GeneralSecurityException x) {
throw (IOException)new IOException("Failed to decrypt the JNLP file. Invalid secret key?").initCause(x);
}
}
if(contentType==null || !contentType.startsWith(expectedContentType)) {
// load DOM anyway, but if it fails to parse, that's probably because this is not an XML file to begin with.
try {
dom = loadDom(slaveJnlpURL, input);
} catch (SAXException e) {
throw new IOException(slaveJnlpURL+" doesn't look like a JNLP file; content type was "+contentType);
} catch (IOException e) {
throw new IOException(slaveJnlpURL+" doesn't look like a JNLP file; content type was "+contentType);
}
} else {
dom = loadDom(slaveJnlpURL, input);
}
// exec into the JNLP launcher, to fetch the connection parameter through JNLP.
NodeList argElements = dom.getElementsByTagName("argument");
List<String> jnlpArgs = new ArrayList<String>();
for( int i=0; i<argElements.getLength(); i++ )
jnlpArgs.add(argElements.item(i).getTextContent());
if (slaveJnlpCredentials != null) {
jnlpArgs.add("-credentials");
jnlpArgs.add(slaveJnlpCredentials);
}
// force a headless mode
jnlpArgs.add("-headless");
return jnlpArgs;
} catch (SSLHandshakeException e) {
if(e.getMessage().contains("PKIX path building failed")) {
// invalid SSL certificate. One reason this happens is when the certificate is self-signed
IOException x = new IOException("Failed to validate a server certificate. If you are using a self-signed certificate, you can use the -noCertificateCheck option to bypass this check.");
x.initCause(e);
throw x;
} else
throw e;
} catch (IOException e) {
if (this.noReconnect)
throw (IOException)new IOException("Failing to obtain "+slaveJnlpURL).initCause(e);
System.err.println("Failing to obtain "+slaveJnlpURL);
e.printStackTrace(System.err);
System.err.println("Waiting 10 seconds before retry");
Thread.sleep(10*1000);
// retry
}
}
}
private byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c;
while ((c = input.read()) != -1) {
baos.write(c);
}
return baos.toByteArray();
}
// from hudson.Util
private static byte[] fromHexString(String data) {
byte[] r = new byte[data.length() / 2];
for (int i = 0; i < data.length(); i += 2)
r[i / 2] = (byte) Integer.parseInt(data.substring(i, i + 2), 16);
return r;
}
private static Document loadDom(URL slaveJnlpURL, InputStream is) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
return db.parse(is, slaveJnlpURL.toExternalForm());
}
/**
* Listens on an ephemeral port, record that port number in a port file,
* then accepts one TCP connection.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("DM_DEFAULT_ENCODING") // port number file should be in platform default encoding
private void runAsTcpServer() throws IOException, InterruptedException {
// if no one connects for too long, assume something went wrong
// and avoid hanging forever
ServerSocket ss = new ServerSocket(0,1);
ss.setSoTimeout(30*1000);
// write a port file to report the port number
FileWriter w = new FileWriter(tcpPortFile);
try {
w.write(String.valueOf(ss.getLocalPort()));
} finally {
w.close();
}
// accept just one connection and that's it.
// when we are done, remove the port file to avoid stale port file
Socket s;
try {
s = ss.accept();
ss.close();
} finally {
boolean deleted = tcpPortFile.delete();
if (!deleted) {
LOGGER.log(Level.WARNING, "Cannot delete the temporary TCP port file {0}", tcpPortFile);
}
}
runOnSocket(s);
}
private void runOnSocket(Socket s) throws IOException, InterruptedException {
// this prevents a connection from silently terminated by the router in between or the other peer
// and that goes without unnoticed. However, the time out is often very long (for example 2 hours
// by default in Linux) that this alone is enough to prevent that.
s.setKeepAlive(true);
// we take care of buffering on our own
s.setTcpNoDelay(true);
main(new BufferedInputStream(SocketChannelStream.in(s)),
new BufferedOutputStream(SocketChannelStream.out(s)), mode,ping,
new FileSystemJarCache(jarCache,true));
}
/**
* Connects to the given TCP port and then start running
*/
private void runAsTcpClient() throws IOException, InterruptedException {
// if no one connects for too long, assume something went wrong
// and avoid hanging forever
Socket s = new Socket(connectionTarget.getAddress(),connectionTarget.getPort());
runOnSocket(s);
}
private void runWithStdinStdout() throws IOException, InterruptedException {
// use stdin/stdout for channel communication
ttyCheck();
if (isWindows()) {
/*
To prevent the dead lock between GetFileType from _ioinit in C runtime and blocking read that ChannelReaderThread
would do on stdin, load the crypto DLL first.
This is a band-aid solution to the problem. Still searching for more fundamental fix.
02f1e750 7c90d99a ntdll!KiFastSystemCallRet
02f1e754 7c810f63 ntdll!NtQueryVolumeInformationFile+0xc
02f1e784 77c2c9f9 kernel32!GetFileType+0x7e
02f1e7e8 77c1f01d msvcrt!_ioinit+0x19f
02f1e88c 7c90118a msvcrt!__CRTDLL_INIT+0xac
02f1e8ac 7c91c4fa ntdll!LdrpCallInitRoutine+0x14
02f1e9b4 7c916371 ntdll!LdrpRunInitializeRoutines+0x344
02f1ec60 7c9164d3 ntdll!LdrpLoadDll+0x3e5
02f1ef08 7c801bbd ntdll!LdrLoadDll+0x230
02f1ef70 7c801d72 kernel32!LoadLibraryExW+0x18e
02f1ef84 7c801da8 kernel32!LoadLibraryExA+0x1f
02f1efa0 77de8830 kernel32!LoadLibraryA+0x94
02f1f05c 6d3eb1be ADVAPI32!CryptAcquireContextA+0x512
WARNING: Stack unwind information not available. Following frames may be wrong.
02f1f13c 6d99c844 java_6d3e0000!Java_sun_security_provider_NativeSeedGenerator_nativeGenerateSeed+0x6e
see http://weblogs.java.net/blog/kohsuke/archive/2009/09/28/reading-stdin-may-cause-your-jvm-hang
for more details
*/
new SecureRandom().nextBoolean();
}
// this will prevent programs from accidentally writing to System.out
// and messing up the stream.
OutputStream os = new StandardOutputStream();
System.setOut(System.err);
// System.in/out appear to be already buffered (at least that was the case in Linux and Windows as of Java6)
// so we are not going to double-buffer these.
main(System.in, os, mode, ping, new FileSystemJarCache(jarCache,true));
}
private static void ttyCheck() {
try {
Method m = System.class.getMethod("console");
Object console = m.invoke(null);
if(console!=null) {
// we seem to be running from interactive console. issue a warning.
// but since this diagnosis could be wrong, go on and do what we normally do anyway. Don't exit.
System.out.println(
"WARNING: Are you running slave agent from an interactive console?\n" +
"If so, you are probably using it incorrectly.\n" +
"See http://wiki.jenkins-ci.org/display/JENKINS/Launching+slave.jar+from+from+console");
}
} catch (LinkageError e) {
// we are probably running on JDK5 that doesn't have System.console()
// we can't check
} catch (InvocationTargetException e) {
// this is impossible
throw new AssertionError(e);
} catch (NoSuchMethodException e) {
// must be running on JDK5
} catch (IllegalAccessException e) {
// this is impossible
throw new AssertionError(e);
}
}
public static void main(InputStream is, OutputStream os) throws IOException, InterruptedException {
main(is,os,Mode.BINARY);
}
public static void main(InputStream is, OutputStream os, Mode mode) throws IOException, InterruptedException {
main(is,os,mode,false);
}
/**
* @deprecated
* Use {@link #main(InputStream, OutputStream, Mode, boolean, JarCache)}
*/
@Deprecated
public static void main(InputStream is, OutputStream os, Mode mode, boolean performPing) throws IOException, InterruptedException {
main(is, os, mode, performPing,
new FileSystemJarCache(new File(System.getProperty("user.home"),".jenkins/cache/jars"),true));
}
/**
* @since 2.24
*/
public static void main(InputStream is, OutputStream os, Mode mode, boolean performPing, JarCache cache) throws IOException, InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
ChannelBuilder cb = new ChannelBuilder("channel", executor)
.withMode(mode)
.withJarCache(cache);
// expose StandardOutputStream as a channel property, which is a better way to make this available
// to the user of Channel than Channel#getUnderlyingOutput()
if (os instanceof StandardOutputStream)
cb.withProperty(StandardOutputStream.class,os);
Channel channel = cb.build(is, os);
System.err.println("channel started");
// Both settings are available since remoting-2.0
long timeout = 1000 * Long.parseLong(
System.getProperty("hudson.remoting.Launcher.pingTimeoutSec", "240")),
interval = 1000 * Long.parseLong(
System.getProperty("hudson.remoting.Launcher.pingIntervalSec", /* was "600" but this duplicates ChannelPinger */ "0"));
Logger.getLogger(PingThread.class.getName()).log(Level.FINE, "performPing={0} timeout={1} interval={2}", new Object[] {performPing, timeout, interval});
if (performPing && timeout > 0 && interval > 0) {
new PingThread(channel, timeout, interval) {
@Deprecated
@Override
protected void onDead() {
System.err.println("Ping failed. Terminating");
System.exit(-1);
}
@Override
protected void onDead(Throwable cause) {
System.err.println("Ping failed. Terminating");
cause.printStackTrace();
System.exit(-1);
}
}.start();
}
channel.join();
System.err.println("channel stopped");
}
/**
* {@link X509TrustManager} that performs no check at all.
*/
private static class NoCheckTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
public static boolean isWindows() {
return File.pathSeparatorChar==';';
}
private static String computeVersion() {
Properties props = new Properties();
InputStream is = Launcher.class.getResourceAsStream(JENKINS_VERSION_PROP_FILE);
if (is == null) {
LOGGER.log(Level.FINE, "Cannot locate the {0} resource file. Hudson/Jenkins version is unknown",
JENKINS_VERSION_PROP_FILE);
return UNKNOWN_JENKINS_VERSION_STR;
}
try {
props.load(is);
} catch (IOException e) {
e.printStackTrace();
} finally {
closeWithLogOnly(is, JENKINS_VERSION_PROP_FILE);
}
return props.getProperty("version", UNKNOWN_JENKINS_VERSION_STR);
}
private static void closeWithLogOnly(Closeable stream, String name) {
try {
stream.close();
} catch (IOException ex) {
LOGGER.log(Level.WARNING, "Cannot close the resource file " + name, ex);
}
}
/**
* Version number of Hudson this slave.jar is from.
*/
public static final String VERSION = computeVersion();
private static final String JENKINS_VERSION_PROP_FILE = "hudson-version.properties";
private static final String UNKNOWN_JENKINS_VERSION_STR = "?";
private static final Logger LOGGER = Logger.getLogger(Launcher.class.getName());
}
| [FIXED JENKINS-42371] - Call disconnect() on HttpURLConnection object (#152)
[FIXED JENKINS-42371] - Call disconnect() on HttpURLConnection object | src/main/java/hudson/remoting/Launcher.java | [FIXED JENKINS-42371] - Call disconnect() on HttpURLConnection object (#152) | <ide><path>rc/main/java/hudson/remoting/Launcher.java
<ide> }
<ide> }
<ide> while (true) {
<add> URLConnection con = null;
<ide> try {
<del> URLConnection con = Util.openURLConnection(slaveJnlpURL);
<add> con = Util.openURLConnection(slaveJnlpURL);
<ide> if (con instanceof HttpURLConnection) {
<ide> HttpURLConnection http = (HttpURLConnection) con;
<ide> if (slaveJnlpCredentials != null) {
<ide> System.err.println("Waiting 10 seconds before retry");
<ide> Thread.sleep(10*1000);
<ide> // retry
<add> } finally {
<add> if (con instanceof HttpURLConnection) {
<add> HttpURLConnection http = (HttpURLConnection) con;
<add> http.disconnect();
<add> }
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | 57407ac438b557d7f33aba30188d98248dac1797 | 0 | Chuckv01/cordova-plugin-media,Chuckv01/cordova-plugin-media | /*
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.cordova.media;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaRecorder;
import android.os.Environment;
import org.apache.cordova.LOG;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.LinkedList;
/**
* This class implements the audio playback and recording capabilities used by Cordova.
* It is called by the AudioHandler Cordova class.
* Only one file can be played or recorded per class instance.
*
* Local audio files must reside in one of two places:
* android_asset: file name must start with /android_asset/sound.mp3
* sdcard: file name is just sound.mp3
*/
public class AudioPlayer implements OnCompletionListener, OnPreparedListener, OnErrorListener {
// AudioPlayer modes
public enum MODE { NONE, PLAY, RECORD };
// AudioPlayer states
public enum STATE { MEDIA_NONE,
MEDIA_STARTING,
MEDIA_RUNNING,
MEDIA_PAUSED,
MEDIA_STOPPED,
MEDIA_LOADING
};
private static final String LOG_TAG = "AudioPlayer";
// AudioPlayer message ids
private static int MEDIA_STATE = 1;
private static int MEDIA_DURATION = 2;
private static int MEDIA_POSITION = 3;
private static int MEDIA_ERROR = 9;
// Media error codes
private static int MEDIA_ERR_NONE_ACTIVE = 0;
private static int MEDIA_ERR_ABORTED = 1;
// private static int MEDIA_ERR_NETWORK = 2;
// private static int MEDIA_ERR_DECODE = 3;
// private static int MEDIA_ERR_NONE_SUPPORTED = 4;
private AudioHandler handler; // The AudioHandler object
private String id; // The id of this player (used to identify Media object in JavaScript)
private MODE mode = MODE.NONE; // Playback or Recording mode
private STATE state = STATE.MEDIA_NONE; // State of recording or playback
private String audioFile = null; // File name to play or record to
private float duration = -1; // Duration of audio
private MediaRecorder recorder = null; // Audio recording object
private LinkedList<String> tempFiles = null; // Temporary recording file name
private String tempFile = null;
private MediaPlayer player = null; // Audio player object
private boolean prepareOnly = true; // playback after file prepare flag
private int seekOnPrepared = 0; // seek to this location once media is prepared
/**
* Constructor.
*
* @param handler The audio handler object
* @param id The id of this audio player
*/
public AudioPlayer(AudioHandler handler, String id, String file) {
this.handler = handler;
this.id = id;
this.audioFile = file;
this.tempFiles = new LinkedList<String>();
}
private String generateTempFile() {
String tempFileName = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
tempFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/tmprecording-" + System.currentTimeMillis() + ".3gp";
} else {
tempFileName = "/data/data/" + handler.cordova.getActivity().getPackageName() + "/cache/tmprecording-" + System.currentTimeMillis() + ".3gp";
}
return tempFileName;
}
/**
* Destroy player and stop audio playing or recording.
*/
public void destroy() {
// Stop any play or record
if (this.player != null) {
if ((this.state == STATE.MEDIA_RUNNING) || (this.state == STATE.MEDIA_PAUSED)) {
this.player.stop();
this.setState(STATE.MEDIA_STOPPED);
}
this.player.release();
this.player = null;
}
if (this.recorder != null) {
this.stopRecording(true);
this.recorder.release();
this.recorder = null;
}
}
/**
* Start recording the specified file.
*
* @param file The name of the file
*/
public void startRecording(String file) {
switch (this.mode) {
case PLAY:
LOG.d(LOG_TAG, "AudioPlayer Error: Can't record in play mode.");
sendErrorStatus(MEDIA_ERR_ABORTED);
break;
case NONE:
this.audioFile = file;
this.recorder = new MediaRecorder();
this.recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
this.recorder.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS); // RAW_AMR);
this.recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); //AMR_NB);
this.tempFile = generateTempFile();
this.recorder.setOutputFile(this.tempFile);
try {
this.recorder.prepare();
this.recorder.start();
this.setState(STATE.MEDIA_RUNNING);
return;
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
sendErrorStatus(MEDIA_ERR_ABORTED);
break;
case RECORD:
LOG.d(LOG_TAG, "AudioPlayer Error: Already recording.");
sendErrorStatus(MEDIA_ERR_ABORTED);
}
}
/**
* Save temporary recorded file to specified name
*
* @param file
*/
public void moveFile(String file) {
/* this is a hack to save the file as the specified name */
if (!file.startsWith("/")) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
file = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + file;
} else {
file = "/data/data/" + handler.cordova.getActivity().getPackageName() + "/cache/" + file;
}
}
int size = this.tempFiles.size();
LOG.d(LOG_TAG, "size = " + size);
// only one file so just copy it
if (size == 1) {
String logMsg = "renaming " + this.tempFile + " to " + file;
LOG.d(LOG_TAG, logMsg);
File f = new File(this.tempFile);
if (!f.renameTo(new File(file))) LOG.e(LOG_TAG, "FAILED " + logMsg);
}
// more than one file so the user must have pause recording. We'll need to concat files.
else {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(new File(file));
FileInputStream inputStream = null;
File inputFile = null;
for (int i = 0; i < size; i++) {
try {
inputFile = new File(this.tempFiles.get(i));
inputStream = new FileInputStream(inputFile);
copy(inputStream, outputStream, (i>0));
} catch(Exception e) {
LOG.e(LOG_TAG, e.getLocalizedMessage(), e);
} finally {
if (inputStream != null) try {
inputStream.close();
inputFile.delete();
inputFile = null;
} catch (Exception e) {
LOG.e(LOG_TAG, e.getLocalizedMessage(), e);
}
}
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if (outputStream != null) try {
outputStream.close();
} catch (Exception e) {
LOG.e(LOG_TAG, e.getLocalizedMessage(), e);
}
}
}
}
private static long copy(InputStream from, OutputStream to, boolean skipHeader)
throws IOException {
byte[] buf = new byte[8096];
long total = 0;
if (skipHeader) {
from.skip(6);
}
while (true) {
int r = from.read(buf);
if (r == -1) {
break;
}
to.write(buf, 0, r);
total += r;
}
return total;
}
/**
* Stop/Pause recording and save to the file specified when recording started.
*/
public void stopRecording(boolean stop) {
if (this.recorder != null) {
try{
if (this.state == STATE.MEDIA_RUNNING) {
this.recorder.stop();
}
this.recorder.reset();
if (!this.tempFiles.contains(this.tempFile)) {
this.tempFiles.add(this.tempFile);
}
if (stop) {
LOG.d(LOG_TAG, "stopping recording");
this.setState(STATE.MEDIA_STOPPED);
this.moveFile(this.audioFile);
} else {
LOG.d(LOG_TAG, "pause recording");
this.setState(STATE.MEDIA_PAUSED);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Resume recording and save to the file specified when recording started.
*/
public void resumeRecording() {
startRecording(this.audioFile);
}
//==========================================================================
// Playback
//==========================================================================
/**
* Start or resume playing audio file.
*
* @param file The name of the audio file.
*/
public void startPlaying(String file) {
if (this.readyPlayer(file) && this.player != null) {
this.player.start();
this.setState(STATE.MEDIA_RUNNING);
this.seekOnPrepared = 0; //insures this is always reset
} else {
this.prepareOnly = false;
}
}
/**
* Seek or jump to a new time in the track.
*/
public void seekToPlaying(int milliseconds) {
if (this.readyPlayer(this.audioFile)) {
if (milliseconds > 0) {
this.player.seekTo(milliseconds);
}
LOG.d(LOG_TAG, "Send a onStatus update for the new seek");
sendStatusChange(MEDIA_POSITION, null, (milliseconds / 1000.0f));
}
else {
this.seekOnPrepared = milliseconds;
}
}
/**
* Pause playing.
*/
public void pausePlaying() {
// If playing, then pause
if (this.state == STATE.MEDIA_RUNNING && this.player != null) {
this.player.pause();
this.setState(STATE.MEDIA_PAUSED);
}
else {
LOG.d(LOG_TAG, "AudioPlayer Error: pausePlaying() called during invalid state: " + this.state.ordinal());
sendErrorStatus(MEDIA_ERR_NONE_ACTIVE);
}
}
/**
* Stop playing the audio file.
*/
public void stopPlaying() {
if ((this.state == STATE.MEDIA_RUNNING) || (this.state == STATE.MEDIA_PAUSED)) {
this.player.pause();
this.player.seekTo(0);
LOG.d(LOG_TAG, "stopPlaying is calling stopped");
this.setState(STATE.MEDIA_STOPPED);
}
else {
LOG.d(LOG_TAG, "AudioPlayer Error: stopPlaying() called during invalid state: " + this.state.ordinal());
sendErrorStatus(MEDIA_ERR_NONE_ACTIVE);
}
}
/**
* Resume playing.
*/
public void resumePlaying() {
this.startPlaying(this.audioFile);
}
/**
* Callback to be invoked when playback of a media source has completed.
*
* @param player The MediaPlayer that reached the end of the file
*/
public void onCompletion(MediaPlayer player) {
LOG.d(LOG_TAG, "on completion is calling stopped");
this.setState(STATE.MEDIA_STOPPED);
}
/**
* Get current position of playback.
*
* @return position in msec or -1 if not playing
*/
public long getCurrentPosition() {
if ((this.state == STATE.MEDIA_RUNNING) || (this.state == STATE.MEDIA_PAUSED)) {
int curPos = this.player.getCurrentPosition();
sendStatusChange(MEDIA_POSITION, null, (curPos / 1000.0f));
return curPos;
}
else {
return -1;
}
}
/**
* Determine if playback file is streaming or local.
* It is streaming if file name starts with "http://"
*
* @param file The file name
* @return T=streaming, F=local
*/
public boolean isStreaming(String file) {
if (file.contains("http://") || file.contains("https://") || file.contains("rtsp://")) {
return true;
}
else {
return false;
}
}
/**
* Get the duration of the audio file.
*
* @param file The name of the audio file.
* @return The duration in msec.
* -1=can't be determined
* -2=not allowed
*/
public float getDuration(String file) {
// Can't get duration of recording
if (this.recorder != null) {
return (-2); // not allowed
}
// If audio file already loaded and started, then return duration
if (this.player != null) {
return this.duration;
}
// If no player yet, then create one
else {
this.prepareOnly = true;
this.startPlaying(file);
// This will only return value for local, since streaming
// file hasn't been read yet.
return this.duration;
}
}
/**
* Callback to be invoked when the media source is ready for playback.
*
* @param player The MediaPlayer that is ready for playback
*/
public void onPrepared(MediaPlayer player) {
// Listen for playback completion
this.player.setOnCompletionListener(this);
// seek to any location received while not prepared
this.seekToPlaying(this.seekOnPrepared);
// If start playing after prepared
if (!this.prepareOnly) {
this.player.start();
this.setState(STATE.MEDIA_RUNNING);
this.seekOnPrepared = 0; //reset only when played
} else {
this.setState(STATE.MEDIA_STARTING);
}
// Save off duration
this.duration = getDurationInSeconds();
// reset prepare only flag
this.prepareOnly = true;
// Send status notification to JavaScript
sendStatusChange(MEDIA_DURATION, null, this.duration);
}
/**
* By default Android returns the length of audio in mills but we want seconds
*
* @return length of clip in seconds
*/
private float getDurationInSeconds() {
return (this.player.getDuration() / 1000.0f);
}
/**
* Callback to be invoked when there has been an error during an asynchronous operation
* (other errors will throw exceptions at method call time).
*
* @param player the MediaPlayer the error pertains to
* @param arg1 the type of error that has occurred: (MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_SERVER_DIED)
* @param arg2 an extra code, specific to the error.
*/
public boolean onError(MediaPlayer player, int arg1, int arg2) {
LOG.d(LOG_TAG, "AudioPlayer.onError(" + arg1 + ", " + arg2 + ")");
// we don't want to send success callback
// so we don't call setState() here
this.state = STATE.MEDIA_STOPPED;
this.destroy();
// Send error notification to JavaScript
sendErrorStatus(arg1);
return false;
}
/**
* Set the state and send it to JavaScript.
*
* @param state
*/
private void setState(STATE state) {
if (this.state != state) {
sendStatusChange(MEDIA_STATE, null, (float)state.ordinal());
}
this.state = state;
}
/**
* Set the mode and send it to JavaScript.
*
* @param mode
*/
private void setMode(MODE mode) {
if (this.mode != mode) {
//mode is not part of the expected behavior, so no notification
//this.handler.webView.sendJavascript("cordova.require('cordova-plugin-media.Media').onStatus('" + this.id + "', " + MEDIA_STATE + ", " + mode + ");");
}
this.mode = mode;
}
/**
* Get the audio state.
*
* @return int
*/
public int getState() {
return this.state.ordinal();
}
/**
* Set the volume for audio player
*
* @param volume
*/
public void setVolume(float volume) {
if (this.player != null) {
this.player.setVolume(volume, volume);
} else {
LOG.d(LOG_TAG, "AudioPlayer Error: Cannot set volume until the audio file is initialized.");
sendErrorStatus(MEDIA_ERR_NONE_ACTIVE);
}
}
/**
* attempts to put the player in play mode
* @return true if in playmode, false otherwise
*/
private boolean playMode() {
switch(this.mode) {
case NONE:
this.setMode(MODE.PLAY);
break;
case PLAY:
break;
case RECORD:
LOG.d(LOG_TAG, "AudioPlayer Error: Can't play in record mode.");
sendErrorStatus(MEDIA_ERR_ABORTED);
return false; //player is not ready
}
return true;
}
/**
* attempts to initialize the media player for playback
* @param file the file to play
* @return false if player not ready, reports if in wrong mode or state
*/
private boolean readyPlayer(String file) {
if (playMode()) {
switch (this.state) {
case MEDIA_NONE:
if (this.player == null) {
this.player = new MediaPlayer();
this.player.setOnErrorListener(this);
}
try {
this.loadAudioFile(file);
} catch (Exception e) {
sendErrorStatus(MEDIA_ERR_ABORTED);
}
return false;
case MEDIA_LOADING:
//cordova js is not aware of MEDIA_LOADING, so we send MEDIA_STARTING instead
LOG.d(LOG_TAG, "AudioPlayer Loading: startPlaying() called during media preparation: " + STATE.MEDIA_STARTING.ordinal());
this.prepareOnly = false;
return false;
case MEDIA_STARTING:
case MEDIA_RUNNING:
case MEDIA_PAUSED:
return true;
case MEDIA_STOPPED:
//if we are readying the same file
if (file!=null && this.audioFile.compareTo(file) == 0) {
//maybe it was recording?
if (player == null) {
this.player = new MediaPlayer();
this.player.setOnErrorListener(this);
this.prepareOnly = false;
try {
this.loadAudioFile(file);
} catch (Exception e) {
sendErrorStatus(MEDIA_ERR_ABORTED);
}
return false;//we´re not ready yet
}
else {
//reset the audio file
player.seekTo(0);
player.pause();
return true;
}
} else {
//reset the player
this.player.reset();
try {
this.loadAudioFile(file);
} catch (Exception e) {
sendErrorStatus(MEDIA_ERR_ABORTED);
}
//if we had to prepare the file, we won't be in the correct state for playback
return false;
}
default:
LOG.d(LOG_TAG, "AudioPlayer Error: startPlaying() called during invalid state: " + this.state);
sendErrorStatus(MEDIA_ERR_ABORTED);
}
}
return false;
}
/**
* load audio file
* @throws IOException
* @throws IllegalStateException
* @throws SecurityException
* @throws IllegalArgumentException
*/
private void loadAudioFile(String file) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {
if (this.isStreaming(file)) {
this.player.setDataSource(file);
this.player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
//if it's a streaming file, play mode is implied
this.setMode(MODE.PLAY);
this.setState(STATE.MEDIA_STARTING);
this.player.setOnPreparedListener(this);
this.player.prepareAsync();
}
else {
if (file.startsWith("/android_asset/")) {
String f = file.substring(15);
android.content.res.AssetFileDescriptor fd = this.handler.cordova.getActivity().getAssets().openFd(f);
this.player.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
}
else {
File fp = new File(file);
if (fp.exists()) {
FileInputStream fileInputStream = new FileInputStream(file);
this.player.setDataSource(fileInputStream.getFD());
fileInputStream.close();
}
else {
this.player.setDataSource(Environment.getExternalStorageDirectory().getPath() + "/" + file);
}
}
this.setState(STATE.MEDIA_STARTING);
this.player.setOnPreparedListener(this);
this.player.prepare();
// Get duration
this.duration = getDurationInSeconds();
}
}
private void sendErrorStatus(int errorCode) {
sendStatusChange(MEDIA_ERROR, errorCode, null);
}
private void sendStatusChange(int messageType, Integer additionalCode, Float value) {
if (additionalCode != null && value != null) {
throw new IllegalArgumentException("Only one of additionalCode or value can be specified, not both");
}
JSONObject statusDetails = new JSONObject();
try {
statusDetails.put("id", this.id);
statusDetails.put("msgType", messageType);
if (additionalCode != null) {
JSONObject code = new JSONObject();
code.put("code", additionalCode.intValue());
statusDetails.put("value", code);
}
else if (value != null) {
statusDetails.put("value", value.floatValue());
}
} catch (JSONException e) {
LOG.e(LOG_TAG, "Failed to create status details", e);
}
this.handler.sendEventMessage("status", statusDetails);
}
/**
* Get current amplitude of recording.
*
* @return amplitude or 0 if not recording
*/
public float getCurrentAmplitude() {
if (this.recorder != null) {
try{
if (this.state == STATE.MEDIA_RUNNING) {
return (float) this.recorder.getMaxAmplitude() / 32762;
}
}
catch (Exception e) {
e.printStackTrace();
}
}
return 0;
}
}
| src/android/AudioPlayer.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.cordova.media;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaRecorder;
import android.os.Environment;
import org.apache.cordova.LOG;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.LinkedList;
/**
* This class implements the audio playback and recording capabilities used by Cordova.
* It is called by the AudioHandler Cordova class.
* Only one file can be played or recorded per class instance.
*
* Local audio files must reside in one of two places:
* android_asset: file name must start with /android_asset/sound.mp3
* sdcard: file name is just sound.mp3
*/
public class AudioPlayer implements OnCompletionListener, OnPreparedListener, OnErrorListener {
// AudioPlayer modes
public enum MODE { NONE, PLAY, RECORD };
// AudioPlayer states
public enum STATE { MEDIA_NONE,
MEDIA_STARTING,
MEDIA_RUNNING,
MEDIA_PAUSED,
MEDIA_STOPPED,
MEDIA_LOADING
};
private static final String LOG_TAG = "AudioPlayer";
// AudioPlayer message ids
private static int MEDIA_STATE = 1;
private static int MEDIA_DURATION = 2;
private static int MEDIA_POSITION = 3;
private static int MEDIA_ERROR = 9;
// Media error codes
private static int MEDIA_ERR_NONE_ACTIVE = 0;
private static int MEDIA_ERR_ABORTED = 1;
// private static int MEDIA_ERR_NETWORK = 2;
// private static int MEDIA_ERR_DECODE = 3;
// private static int MEDIA_ERR_NONE_SUPPORTED = 4;
private AudioHandler handler; // The AudioHandler object
private String id; // The id of this player (used to identify Media object in JavaScript)
private MODE mode = MODE.NONE; // Playback or Recording mode
private STATE state = STATE.MEDIA_NONE; // State of recording or playback
private String audioFile = null; // File name to play or record to
private float duration = -1; // Duration of audio
private MediaRecorder recorder = null; // Audio recording object
private LinkedList<String> tempFiles = null; // Temporary recording file name
private String tempFile = null;
private MediaPlayer player = null; // Audio player object
private boolean prepareOnly = true; // playback after file prepare flag
private int seekOnPrepared = 0; // seek to this location once media is prepared
/**
* Constructor.
*
* @param handler The audio handler object
* @param id The id of this audio player
*/
public AudioPlayer(AudioHandler handler, String id, String file) {
this.handler = handler;
this.id = id;
this.audioFile = file;
this.tempFiles = new LinkedList<String>();
}
private String generateTempFile() {
String tempFileName = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
tempFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/tmprecording-" + System.currentTimeMillis() + ".3gp";
} else {
tempFileName = "/data/data/" + handler.cordova.getActivity().getPackageName() + "/cache/tmprecording-" + System.currentTimeMillis() + ".3gp";
}
return tempFileName;
}
/**
* Destroy player and stop audio playing or recording.
*/
public void destroy() {
// Stop any play or record
if (this.player != null) {
if ((this.state == STATE.MEDIA_RUNNING) || (this.state == STATE.MEDIA_PAUSED)) {
this.player.stop();
this.setState(STATE.MEDIA_STOPPED);
}
this.player.release();
this.player = null;
}
if (this.recorder != null) {
this.stopRecording(true);
this.recorder.release();
this.recorder = null;
}
}
/**
* Start recording the specified file.
*
* @param file The name of the file
*/
public void startRecording(String file) {
switch (this.mode) {
case PLAY:
LOG.d(LOG_TAG, "AudioPlayer Error: Can't record in play mode.");
sendErrorStatus(MEDIA_ERR_ABORTED);
break;
case NONE:
this.audioFile = file;
this.recorder = new MediaRecorder();
this.recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
this.recorder.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS); // RAW_AMR);
this.recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); //AMR_NB);
this.tempFile = generateTempFile();
this.recorder.setOutputFile(this.tempFile);
try {
this.recorder.prepare();
this.recorder.start();
this.setState(STATE.MEDIA_RUNNING);
return;
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
sendErrorStatus(MEDIA_ERR_ABORTED);
break;
case RECORD:
LOG.d(LOG_TAG, "AudioPlayer Error: Already recording.");
sendErrorStatus(MEDIA_ERR_ABORTED);
}
}
/**
* Save temporary recorded file to specified name
*
* @param file
*/
public void moveFile(String file) {
/* this is a hack to save the file as the specified name */
if (!file.startsWith("/")) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
file = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + file;
} else {
file = "/data/data/" + handler.cordova.getActivity().getPackageName() + "/cache/" + file;
}
}
int size = this.tempFiles.size();
LOG.d(LOG_TAG, "size = " + size);
// only one file so just copy it
if (size == 1) {
String logMsg = "renaming " + this.tempFile + " to " + file;
LOG.d(LOG_TAG, logMsg);
File f = new File(this.tempFile);
if (!f.renameTo(new File(file))) LOG.e(LOG_TAG, "FAILED " + logMsg);
}
// more than one file so the user must have pause recording. We'll need to concat files.
else {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(new File(file));
FileInputStream inputStream = null;
File inputFile = null;
for (int i = 0; i < size; i++) {
try {
inputFile = new File(this.tempFiles.get(i));
inputStream = new FileInputStream(inputFile);
copy(inputStream, outputStream, (i>0));
} catch(Exception e) {
LOG.e(LOG_TAG, e.getLocalizedMessage(), e);
} finally {
if (inputStream != null) try {
inputStream.close();
inputFile.delete();
inputFile = null;
} catch (Exception e) {
LOG.e(LOG_TAG, e.getLocalizedMessage(), e);
}
}
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if (outputStream != null) try {
outputStream.close();
} catch (Exception e) {
LOG.e(LOG_TAG, e.getLocalizedMessage(), e);
}
}
}
}
private static long copy(InputStream from, OutputStream to, boolean skipHeader)
throws IOException {
byte[] buf = new byte[8096];
long total = 0;
if (skipHeader) {
from.skip(6);
}
while (true) {
int r = from.read(buf);
if (r == -1) {
break;
}
to.write(buf, 0, r);
total += r;
}
return total;
}
/**
* Stop/Pause recording and save to the file specified when recording started.
*/
public void stopRecording(boolean stop) {
if (this.recorder != null) {
try{
if (this.state == STATE.MEDIA_RUNNING) {
this.recorder.stop();
}
this.recorder.reset();
if (!this.tempFiles.contains(this.tempFile)) {
this.tempFiles.add(this.tempFile);
}
if (stop) {
LOG.d(LOG_TAG, "stopping recording");
this.setState(STATE.MEDIA_STOPPED);
this.moveFile(this.audioFile);
} else {
LOG.d(LOG_TAG, "pause recording");
this.setState(STATE.MEDIA_PAUSED);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Resume recording and save to the file specified when recording started.
*/
public void resumeRecording() {
startRecording(this.audioFile);
}
//==========================================================================
// Playback
//==========================================================================
/**
* Start or resume playing audio file.
*
* @param file The name of the audio file.
*/
public void startPlaying(String file) {
if (this.readyPlayer(file) && this.player != null) {
this.player.start();
this.setState(STATE.MEDIA_RUNNING);
this.seekOnPrepared = 0; //insures this is always reset
} else {
this.prepareOnly = false;
}
}
/**
* Seek or jump to a new time in the track.
*/
public void seekToPlaying(int milliseconds) {
if (this.readyPlayer(this.audioFile)) {
if (milliseconds > 0) {
this.player.seekTo(milliseconds);
}
LOG.d(LOG_TAG, "Send a onStatus update for the new seek");
sendStatusChange(MEDIA_POSITION, null, (milliseconds / 1000.0f));
}
else {
this.seekOnPrepared = milliseconds;
}
}
/**
* Pause playing.
*/
public void pausePlaying() {
// If playing, then pause
if (this.state == STATE.MEDIA_RUNNING && this.player != null) {
this.player.pause();
this.setState(STATE.MEDIA_PAUSED);
}
else {
LOG.d(LOG_TAG, "AudioPlayer Error: pausePlaying() called during invalid state: " + this.state.ordinal());
sendErrorStatus(MEDIA_ERR_NONE_ACTIVE);
}
}
/**
* Stop playing the audio file.
*/
public void stopPlaying() {
if ((this.state == STATE.MEDIA_RUNNING) || (this.state == STATE.MEDIA_PAUSED)) {
this.player.pause();
this.player.seekTo(0);
LOG.d(LOG_TAG, "stopPlaying is calling stopped");
this.setState(STATE.MEDIA_STOPPED);
}
else {
LOG.d(LOG_TAG, "AudioPlayer Error: stopPlaying() called during invalid state: " + this.state.ordinal());
sendErrorStatus(MEDIA_ERR_NONE_ACTIVE);
}
}
/**
* Resume playing.
*/
public void resumePlaying() {
this.startPlaying(this.audioFile);
}
/**
* Callback to be invoked when playback of a media source has completed.
*
* @param player The MediaPlayer that reached the end of the file
*/
public void onCompletion(MediaPlayer player) {
LOG.d(LOG_TAG, "on completion is calling stopped");
this.setState(STATE.MEDIA_STOPPED);
}
/**
* Get current position of playback.
*
* @return position in msec or -1 if not playing
*/
public long getCurrentPosition() {
if ((this.state == STATE.MEDIA_RUNNING) || (this.state == STATE.MEDIA_PAUSED)) {
int curPos = this.player.getCurrentPosition();
sendStatusChange(MEDIA_POSITION, null, (curPos / 1000.0f));
return curPos;
}
else {
return -1;
}
}
/**
* Determine if playback file is streaming or local.
* It is streaming if file name starts with "http://"
*
* @param file The file name
* @return T=streaming, F=local
*/
public boolean isStreaming(String file) {
if (file.contains("http://") || file.contains("https://") || file.contains("rtsp://")) {
return true;
}
else {
return false;
}
}
/**
* Get the duration of the audio file.
*
* @param file The name of the audio file.
* @return The duration in msec.
* -1=can't be determined
* -2=not allowed
*/
public float getDuration(String file) {
// Can't get duration of recording
if (this.recorder != null) {
return (-2); // not allowed
}
// If audio file already loaded and started, then return duration
if (this.player != null) {
return this.duration;
}
// If no player yet, then create one
else {
this.prepareOnly = true;
this.startPlaying(file);
// This will only return value for local, since streaming
// file hasn't been read yet.
return this.duration;
}
}
/**
* Callback to be invoked when the media source is ready for playback.
*
* @param player The MediaPlayer that is ready for playback
*/
public void onPrepared(MediaPlayer player) {
// Listen for playback completion
this.player.setOnCompletionListener(this);
// seek to any location received while not prepared
this.seekToPlaying(this.seekOnPrepared);
// If start playing after prepared
if (!this.prepareOnly) {
this.player.start();
this.setState(STATE.MEDIA_RUNNING);
this.seekOnPrepared = 0; //reset only when played
} else {
this.setState(STATE.MEDIA_STARTING);
}
// Save off duration
this.duration = getDurationInSeconds();
// reset prepare only flag
this.prepareOnly = true;
// Send status notification to JavaScript
sendStatusChange(MEDIA_DURATION, null, this.duration);
}
/**
* By default Android returns the length of audio in mills but we want seconds
*
* @return length of clip in seconds
*/
private float getDurationInSeconds() {
return (this.player.getDuration() / 1000.0f);
}
/**
* Callback to be invoked when there has been an error during an asynchronous operation
* (other errors will throw exceptions at method call time).
*
* @param player the MediaPlayer the error pertains to
* @param arg1 the type of error that has occurred: (MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_SERVER_DIED)
* @param arg2 an extra code, specific to the error.
*/
public boolean onError(MediaPlayer player, int arg1, int arg2) {
LOG.d(LOG_TAG, "AudioPlayer.onError(" + arg1 + ", " + arg2 + ")");
// we don't want to send success callback
// so we don't call setState() here
this.state = STATE.MEDIA_STOPPED;
this.destroy();
// Send error notification to JavaScript
sendErrorStatus(arg1);
return false;
}
/**
* Set the state and send it to JavaScript.
*
* @param state
*/
private void setState(STATE state) {
if (this.state != state) {
sendStatusChange(MEDIA_STATE, null, (float)state.ordinal());
}
this.state = state;
}
/**
* Set the mode and send it to JavaScript.
*
* @param mode
*/
private void setMode(MODE mode) {
if (this.mode != mode) {
//mode is not part of the expected behavior, so no notification
//this.handler.webView.sendJavascript("cordova.require('cordova-plugin-media.Media').onStatus('" + this.id + "', " + MEDIA_STATE + ", " + mode + ");");
}
this.mode = mode;
}
/**
* Get the audio state.
*
* @return int
*/
public int getState() {
return this.state.ordinal();
}
/**
* Set the volume for audio player
*
* @param volume
*/
public void setVolume(float volume) {
if (this.player != null) {
this.player.setVolume(volume, volume);
} else {
LOG.d(LOG_TAG, "AudioPlayer Error: Cannot set volume until the audio file is initialized.");
sendErrorStatus(MEDIA_ERR_NONE_ACTIVE);
}
}
/**
* attempts to put the player in play mode
* @return true if in playmode, false otherwise
*/
private boolean playMode() {
switch(this.mode) {
case NONE:
this.setMode(MODE.PLAY);
break;
case PLAY:
break;
case RECORD:
LOG.d(LOG_TAG, "AudioPlayer Error: Can't play in record mode.");
sendErrorStatus(MEDIA_ERR_ABORTED);
return false; //player is not ready
}
return true;
}
/**
* attempts to initialize the media player for playback
* @param file the file to play
* @return false if player not ready, reports if in wrong mode or state
*/
private boolean readyPlayer(String file) {
if (playMode()) {
switch (this.state) {
case MEDIA_NONE:
if (this.player == null) {
this.player = new MediaPlayer();
this.player.setOnErrorListener(this);
}
try {
this.loadAudioFile(file);
} catch (Exception e) {
sendErrorStatus(MEDIA_ERR_ABORTED);
}
return false;
case MEDIA_LOADING:
//cordova js is not aware of MEDIA_LOADING, so we send MEDIA_STARTING instead
LOG.d(LOG_TAG, "AudioPlayer Loading: startPlaying() called during media preparation: " + STATE.MEDIA_STARTING.ordinal());
this.prepareOnly = false;
return false;
case MEDIA_STARTING:
case MEDIA_RUNNING:
case MEDIA_PAUSED:
return true;
case MEDIA_STOPPED:
//if we are readying the same file
if (file!=null && this.audioFile.compareTo(file) == 0) {
//maybe it was recording?
if (player == null) {
this.player = new MediaPlayer();
this.player.setOnErrorListener(this);
this.prepareOnly = false;
try {
this.loadAudioFile(file);
} catch (Exception e) {
sendErrorStatus(MEDIA_ERR_ABORTED);
}
return false;//we´re not ready yet
}
else {
//reset the audio file
player.seekTo(0);
player.pause();
return true;
}
} else {
//reset the player
this.player.reset();
try {
this.loadAudioFile(file);
} catch (Exception e) {
sendErrorStatus(MEDIA_ERR_ABORTED);
}
//if we had to prepare the file, we won't be in the correct state for playback
return false;
}
default:
LOG.d(LOG_TAG, "AudioPlayer Error: startPlaying() called during invalid state: " + this.state);
sendErrorStatus(MEDIA_ERR_ABORTED);
}
}
return false;
}
/**
* load audio file
* @throws IOException
* @throws IllegalStateException
* @throws SecurityException
* @throws IllegalArgumentException
*/
private void loadAudioFile(String file) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {
if (this.isStreaming(file)) {
this.player.setDataSource(file);
this.player.setAudioStreamType(AudioManager.STREAM_MUSIC);
//if it's a streaming file, play mode is implied
this.setMode(MODE.PLAY);
this.setState(STATE.MEDIA_STARTING);
this.player.setOnPreparedListener(this);
this.player.prepareAsync();
}
else {
if (file.startsWith("/android_asset/")) {
String f = file.substring(15);
android.content.res.AssetFileDescriptor fd = this.handler.cordova.getActivity().getAssets().openFd(f);
this.player.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
}
else {
File fp = new File(file);
if (fp.exists()) {
FileInputStream fileInputStream = new FileInputStream(file);
this.player.setDataSource(fileInputStream.getFD());
fileInputStream.close();
}
else {
this.player.setDataSource(Environment.getExternalStorageDirectory().getPath() + "/" + file);
}
}
this.setState(STATE.MEDIA_STARTING);
this.player.setOnPreparedListener(this);
this.player.prepare();
// Get duration
this.duration = getDurationInSeconds();
}
}
private void sendErrorStatus(int errorCode) {
sendStatusChange(MEDIA_ERROR, errorCode, null);
}
private void sendStatusChange(int messageType, Integer additionalCode, Float value) {
if (additionalCode != null && value != null) {
throw new IllegalArgumentException("Only one of additionalCode or value can be specified, not both");
}
JSONObject statusDetails = new JSONObject();
try {
statusDetails.put("id", this.id);
statusDetails.put("msgType", messageType);
if (additionalCode != null) {
JSONObject code = new JSONObject();
code.put("code", additionalCode.intValue());
statusDetails.put("value", code);
}
else if (value != null) {
statusDetails.put("value", value.floatValue());
}
} catch (JSONException e) {
LOG.e(LOG_TAG, "Failed to create status details", e);
}
this.handler.sendEventMessage("status", statusDetails);
}
/**
* Get current amplitude of recording.
*
* @return amplitude or 0 if not recording
*/
public float getCurrentAmplitude() {
if (this.recorder != null) {
try{
if (this.state == STATE.MEDIA_RUNNING) {
return (float) this.recorder.getMaxAmplitude() / 32762;
}
}
catch (Exception e) {
e.printStackTrace();
}
}
return 0;
}
}
| Update AudioPlayer.java | src/android/AudioPlayer.java | Update AudioPlayer.java | <ide><path>rc/android/AudioPlayer.java
<ide> private void loadAudioFile(String file) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {
<ide> if (this.isStreaming(file)) {
<ide> this.player.setDataSource(file);
<del> this.player.setAudioStreamType(AudioManager.STREAM_MUSIC);
<add> this.player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
<ide> //if it's a streaming file, play mode is implied
<ide> this.setMode(MODE.PLAY);
<ide> this.setState(STATE.MEDIA_STARTING); |
|
Java | apache-2.0 | 4fd6203afefc99a57ef5db4e6d91a8f5703f3ca2 | 0 | sosy-lab/java-smt,sosy-lab/java-smt,sosy-lab/java-smt,sosy-lab/java-smt,sosy-lab/java-smt | /*
* JavaSMT is an API wrapper for a collection of SMT solvers.
* This file is part of JavaSMT.
*
* Copyright (C) 2007-2015 Dirk Beyer
* 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 org.sosy_lab.solver.z3;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.common.primitives.Longs;
import com.microsoft.z3.Native;
import com.microsoft.z3.enumerations.Z3_lbool;
import org.sosy_lab.common.ShutdownNotifier;
import org.sosy_lab.solver.api.BooleanFormula;
import org.sosy_lab.solver.api.InterpolatingProverEnvironment;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
class Z3InterpolatingProver extends Z3AbstractProver<Long>
implements InterpolatingProverEnvironment<Long> {
private final long z3solver;
private int level = 0;
private final Deque<List<Long>> assertedFormulas = new ArrayDeque<>();
Z3InterpolatingProver(
Z3FormulaCreator creator, long z3params, ShutdownNotifier pShutdownNotifier) {
super(creator, pShutdownNotifier);
this.z3solver = Native.mkSolver(z3context);
Native.solverIncRef(z3context, z3solver);
Native.solverSetParams(z3context, z3solver, z3params);
// add basic level, needed for addConstraints(f) without previous push()
assertedFormulas.push(new ArrayList<>());
}
@Override
public void pop() {
Preconditions.checkState(!closed);
Preconditions.checkState(Native.solverGetNumScopes(z3context, z3solver) >= 1);
Preconditions.checkState(level == assertedFormulas.size() - 1);
level--;
assertedFormulas.pop();
Native.solverPop(z3context, z3solver, 1);
}
@Override
public Long addConstraint(BooleanFormula f) {
Preconditions.checkState(!closed);
long e = creator.extractInfo(f);
Native.incRef(z3context, e);
Native.solverAssert(z3context, z3solver, e);
assertedFormulas.peek().add(e);
Native.decRef(z3context, e);
return e;
}
@Override
public void push() {
Preconditions.checkState(!closed);
Preconditions.checkState(level == assertedFormulas.size() - 1);
level++;
assertedFormulas.push(new ArrayList<>());
Native.solverPush(z3context, z3solver);
}
@Override
public boolean isUnsat() throws Z3SolverException, InterruptedException {
Preconditions.checkState(!closed);
int result = Native.solverCheck(z3context, z3solver);
shutdownNotifier.shutdownIfNecessary();
Preconditions.checkState(result != Z3_lbool.Z3_L_UNDEF.toInt());
return result == Z3_lbool.Z3_L_FALSE.toInt();
}
@Override
@SuppressWarnings({"unchecked", "varargs"})
public BooleanFormula getInterpolant(final List<Long> formulasOfA) throws InterruptedException {
Preconditions.checkState(!closed);
// calc difference: formulasOfB := assertedFormulas - formulasOfA
// we have to handle equal formulas on the stack,
// so we copy the whole stack and remove the formulas of A once.
final List<Long> formulasOfB = new LinkedList<>();
assertedFormulas.forEach(formulasOfB::addAll);
for (long af : formulasOfA) {
boolean check = formulasOfB.remove(af); // remove only first occurrence
assert check : "formula from A must be part of all asserted formulas";
}
// binary interpolant is a sequence interpolant of only 2 elements
return Iterables.getOnlyElement(
getSeqInterpolants(
ImmutableList.of(Sets.newHashSet(formulasOfA), Sets.newHashSet(formulasOfB))));
}
@Override
public List<BooleanFormula> getSeqInterpolants(List<Set<Long>> partitionedFormulas)
throws InterruptedException {
Preconditions.checkState(!closed);
Preconditions.checkArgument(
partitionedFormulas.size() >= 2, "at least 2 partitions needed for interpolation");
// a 'tree' with all subtrees starting at 0 is called a 'sequence'
return getTreeInterpolants(partitionedFormulas, new int[partitionedFormulas.size()]);
}
@Override
public List<BooleanFormula> getTreeInterpolants(
List<Set<Long>> partitionedFormulas, int[] startOfSubTree) throws InterruptedException {
Preconditions.checkState(!closed);
final long[] conjunctionFormulas = new long[partitionedFormulas.size()];
// build conjunction of each partition
for (int i = 0; i < partitionedFormulas.size(); i++) {
long conjunction =
Native.mkAnd(
z3context,
partitionedFormulas.get(i).size(),
Longs.toArray(partitionedFormulas.get(i)));
Native.incRef(z3context, conjunction);
conjunctionFormulas[i] = conjunction;
}
// build tree of interpolation-points
final long[] interpolationFormulas = new long[partitionedFormulas.size()];
final Deque<Z3TreeInterpolant> stack = new ArrayDeque<>();
int lastSubtree = -1; // subtree starts with 0. With -1<0 we start a new subtree.
for (int i = 0; i < startOfSubTree.length; i++) {
final int currentSubtree = startOfSubTree[i];
final long conjunction;
if (currentSubtree > lastSubtree) {
// start of a new subtree -> first element has no children
conjunction = conjunctionFormulas[i];
} else { // if (currentSubtree <= lastSubtree) {
// merge-point in tree, several children at a node -> pop from stack and conjunct
final List<Long> children = new ArrayList<>();
while (!stack.isEmpty() && currentSubtree <= stack.peekLast().getRootOfTree()) {
// adding at front is important for tree-structure!
children.add(0, stack.pollLast().getInterpolationPoint());
}
children.add(conjunctionFormulas[i]); // add the node itself
conjunction = Native.mkAnd(z3context, 2, Longs.toArray(children));
}
final long interpolationPoint;
if (i == startOfSubTree.length - 1) {
// the last node in the tree (=root) does not need the interpolation-point-flag
interpolationPoint = conjunction;
Preconditions.checkState(currentSubtree == 0, "subtree of root should start at 0.");
Preconditions.checkState(stack.isEmpty(), "root should be the last element in the stack.");
} else {
interpolationPoint = Native.mkInterpolant(z3context, conjunction);
}
Native.incRef(z3context, interpolationPoint);
interpolationFormulas[i] = interpolationPoint;
stack.addLast(new Z3TreeInterpolant(currentSubtree, interpolationPoint));
lastSubtree = currentSubtree;
}
Preconditions.checkState(
stack.peekLast().getRootOfTree() == 0, "subtree of root should start at 0.");
long root = stack.pollLast().getInterpolationPoint();
Preconditions.checkState(
stack.isEmpty(), "root should have been the last element in the stack.");
final long proof = Native.solverGetProof(z3context, z3solver);
Native.incRef(z3context, proof);
long interpolationResult =
Native.getInterpolant(
z3context,
proof, //refutation of premises := proof
root, // last element is end of chain (root of tree), pattern := interpolation tree
Native.mkParams(z3context));
shutdownNotifier.shutdownIfNecessary();
// n partitions -> n-1 interpolants
// the given tree interpolants are sorted in post-order,
// so we only need to copy them
final List<BooleanFormula> result = new ArrayList<>();
for (int i = 0; i < partitionedFormulas.size() - 1; i++) {
result.add(
creator.encapsulateBoolean(Native.astVectorGet(z3context, interpolationResult, i)));
}
// cleanup
Native.decRef(z3context, proof);
for (long partition : conjunctionFormulas) {
Native.decRef(z3context, partition);
}
for (long partition : interpolationFormulas) {
Native.decRef(z3context, partition);
}
return result;
}
@Override
protected long getZ3Model() {
return Native.solverGetModel(z3context, z3solver);
}
@Override
public void close() {
Preconditions.checkState(!closed);
while (level > 0) {
pop();
}
Preconditions.checkState(assertedFormulas.size() == 1);
assertedFormulas.clear();
//TODO solver_reset(z3context, z3solver);
Native.solverDecRef(z3context, z3solver);
closed = true;
}
private static class Z3TreeInterpolant {
private final int rootOfSubTree;
private final long interpolationPoint;
private Z3TreeInterpolant(int pRootOfSubtree, long pInterpolationPoint) {
rootOfSubTree = pRootOfSubtree;
interpolationPoint = pInterpolationPoint;
}
private int getRootOfTree() {
return rootOfSubTree;
}
private long getInterpolationPoint() {
return interpolationPoint;
}
}
@Override
public String toString() {
Preconditions.checkState(!closed);
return Native.solverToString(z3context, z3solver);
}
}
| src/org/sosy_lab/solver/z3/Z3InterpolatingProver.java | /*
* JavaSMT is an API wrapper for a collection of SMT solvers.
* This file is part of JavaSMT.
*
* Copyright (C) 2007-2015 Dirk Beyer
* 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 org.sosy_lab.solver.z3;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.common.primitives.Longs;
import com.microsoft.z3.Native;
import com.microsoft.z3.enumerations.Z3_lbool;
import org.sosy_lab.common.ShutdownNotifier;
import org.sosy_lab.solver.api.BooleanFormula;
import org.sosy_lab.solver.api.InterpolatingProverEnvironment;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
class Z3InterpolatingProver extends Z3AbstractProver<Long>
implements InterpolatingProverEnvironment<Long> {
private final long z3solver;
private int level = 0;
private final Deque<List<Long>> assertedFormulas = new ArrayDeque<>();
Z3InterpolatingProver(
Z3FormulaCreator creator, long z3params, ShutdownNotifier pShutdownNotifier) {
super(creator, pShutdownNotifier);
this.z3solver = Native.mkSolver(z3context);
Native.solverIncRef(z3context, z3solver);
Native.solverSetParams(z3context, z3solver, z3params);
}
@Override
public void pop() {
Preconditions.checkState(!closed);
Preconditions.checkState(Native.solverGetNumScopes(z3context, z3solver) >= 1);
level--;
assertedFormulas.pop();
Native.solverPop(z3context, z3solver, 1);
}
@Override
public Long addConstraint(BooleanFormula f) {
Preconditions.checkState(!closed);
long e = creator.extractInfo(f);
Native.incRef(z3context, e);
Native.solverAssert(z3context, z3solver, e);
assertedFormulas.peek().add(e);
Native.decRef(z3context, e);
return e;
}
@Override
public void push() {
Preconditions.checkState(!closed);
level++;
assertedFormulas.push(new ArrayList<>());
Native.solverPush(z3context, z3solver);
}
@Override
public boolean isUnsat() throws Z3SolverException, InterruptedException {
Preconditions.checkState(!closed);
int result = Native.solverCheck(z3context, z3solver);
shutdownNotifier.shutdownIfNecessary();
Preconditions.checkState(result != Z3_lbool.Z3_L_UNDEF.toInt());
return result == Z3_lbool.Z3_L_FALSE.toInt();
}
@Override
@SuppressWarnings({"unchecked", "varargs"})
public BooleanFormula getInterpolant(final List<Long> formulasOfA) throws InterruptedException {
Preconditions.checkState(!closed);
// calc difference: formulasOfB := assertedFormulas - formulasOfA
// we have to handle equal formulas on the stack,
// so we copy the whole stack and remove the formulas of A once.
final List<Long> formulasOfB = new LinkedList<>();
assertedFormulas.forEach(formulasOfB::addAll);
for (long af : formulasOfA) {
boolean check = formulasOfB.remove(af); // remove only first occurrence
assert check : "formula from A must be part of all asserted formulas";
}
// binary interpolant is a sequence interpolant of only 2 elements
return Iterables.getOnlyElement(
getSeqInterpolants(
ImmutableList.of(Sets.newHashSet(formulasOfA), Sets.newHashSet(formulasOfB))));
}
@Override
public List<BooleanFormula> getSeqInterpolants(List<Set<Long>> partitionedFormulas)
throws InterruptedException {
Preconditions.checkState(!closed);
Preconditions.checkArgument(
partitionedFormulas.size() >= 2, "at least 2 partitions needed for interpolation");
// a 'tree' with all subtrees starting at 0 is called a 'sequence'
return getTreeInterpolants(partitionedFormulas, new int[partitionedFormulas.size()]);
}
@Override
public List<BooleanFormula> getTreeInterpolants(
List<Set<Long>> partitionedFormulas, int[] startOfSubTree) throws InterruptedException {
Preconditions.checkState(!closed);
final long[] conjunctionFormulas = new long[partitionedFormulas.size()];
// build conjunction of each partition
for (int i = 0; i < partitionedFormulas.size(); i++) {
long conjunction =
Native.mkAnd(
z3context,
partitionedFormulas.get(i).size(),
Longs.toArray(partitionedFormulas.get(i)));
Native.incRef(z3context, conjunction);
conjunctionFormulas[i] = conjunction;
}
// build tree of interpolation-points
final long[] interpolationFormulas = new long[partitionedFormulas.size()];
final Deque<Z3TreeInterpolant> stack = new ArrayDeque<>();
int lastSubtree = -1; // subtree starts with 0. With -1<0 we start a new subtree.
for (int i = 0; i < startOfSubTree.length; i++) {
final int currentSubtree = startOfSubTree[i];
final long conjunction;
if (currentSubtree > lastSubtree) {
// start of a new subtree -> first element has no children
conjunction = conjunctionFormulas[i];
} else { // if (currentSubtree <= lastSubtree) {
// merge-point in tree, several children at a node -> pop from stack and conjunct
final List<Long> children = new ArrayList<>();
while (!stack.isEmpty() && currentSubtree <= stack.peekLast().getRootOfTree()) {
// adding at front is important for tree-structure!
children.add(0, stack.pollLast().getInterpolationPoint());
}
children.add(conjunctionFormulas[i]); // add the node itself
conjunction = Native.mkAnd(z3context, 2, Longs.toArray(children));
}
final long interpolationPoint;
if (i == startOfSubTree.length - 1) {
// the last node in the tree (=root) does not need the interpolation-point-flag
interpolationPoint = conjunction;
Preconditions.checkState(currentSubtree == 0, "subtree of root should start at 0.");
Preconditions.checkState(stack.isEmpty(), "root should be the last element in the stack.");
} else {
interpolationPoint = Native.mkInterpolant(z3context, conjunction);
}
Native.incRef(z3context, interpolationPoint);
interpolationFormulas[i] = interpolationPoint;
stack.addLast(new Z3TreeInterpolant(currentSubtree, interpolationPoint));
lastSubtree = currentSubtree;
}
Preconditions.checkState(
stack.peekLast().getRootOfTree() == 0, "subtree of root should start at 0.");
long root = stack.pollLast().getInterpolationPoint();
Preconditions.checkState(
stack.isEmpty(), "root should have been the last element in the stack.");
final long proof = Native.solverGetProof(z3context, z3solver);
Native.incRef(z3context, proof);
long interpolationResult =
Native.getInterpolant(
z3context,
proof, //refutation of premises := proof
root, // last element is end of chain (root of tree), pattern := interpolation tree
Native.mkParams(z3context));
shutdownNotifier.shutdownIfNecessary();
// n partitions -> n-1 interpolants
// the given tree interpolants are sorted in post-order,
// so we only need to copy them
final List<BooleanFormula> result = new ArrayList<>();
for (int i = 0; i < partitionedFormulas.size() - 1; i++) {
result.add(
creator.encapsulateBoolean(Native.astVectorGet(z3context, interpolationResult, i)));
}
// cleanup
Native.decRef(z3context, proof);
for (long partition : conjunctionFormulas) {
Native.decRef(z3context, partition);
}
for (long partition : interpolationFormulas) {
Native.decRef(z3context, partition);
}
return result;
}
@Override
protected long getZ3Model() {
return Native.solverGetModel(z3context, z3solver);
}
@Override
public void close() {
Preconditions.checkState(!closed);
while (level > 0) {
pop();
}
Preconditions.checkState(assertedFormulas.isEmpty());
//TODO solver_reset(z3context, z3solver);
Native.solverDecRef(z3context, z3solver);
closed = true;
}
private static class Z3TreeInterpolant {
private final int rootOfSubTree;
private final long interpolationPoint;
private Z3TreeInterpolant(int pRootOfSubtree, long pInterpolationPoint) {
rootOfSubTree = pRootOfSubtree;
interpolationPoint = pInterpolationPoint;
}
private int getRootOfTree() {
return rootOfSubTree;
}
private long getInterpolationPoint() {
return interpolationPoint;
}
}
@Override
public String toString() {
Preconditions.checkState(!closed);
return Native.solverToString(z3context, z3solver);
}
}
| Z3: bugfix for adding constraints on empty solver-stack.
| src/org/sosy_lab/solver/z3/Z3InterpolatingProver.java | Z3: bugfix for adding constraints on empty solver-stack. | <ide><path>rc/org/sosy_lab/solver/z3/Z3InterpolatingProver.java
<ide> this.z3solver = Native.mkSolver(z3context);
<ide> Native.solverIncRef(z3context, z3solver);
<ide> Native.solverSetParams(z3context, z3solver, z3params);
<add>
<add> // add basic level, needed for addConstraints(f) without previous push()
<add> assertedFormulas.push(new ArrayList<>());
<ide> }
<ide>
<ide> @Override
<ide> public void pop() {
<ide> Preconditions.checkState(!closed);
<ide> Preconditions.checkState(Native.solverGetNumScopes(z3context, z3solver) >= 1);
<add> Preconditions.checkState(level == assertedFormulas.size() - 1);
<ide> level--;
<del>
<ide> assertedFormulas.pop();
<ide> Native.solverPop(z3context, z3solver, 1);
<ide> }
<ide> @Override
<ide> public void push() {
<ide> Preconditions.checkState(!closed);
<add> Preconditions.checkState(level == assertedFormulas.size() - 1);
<ide> level++;
<ide> assertedFormulas.push(new ArrayList<>());
<ide> Native.solverPush(z3context, z3solver);
<ide> while (level > 0) {
<ide> pop();
<ide> }
<del> Preconditions.checkState(assertedFormulas.isEmpty());
<add>
<add> Preconditions.checkState(assertedFormulas.size() == 1);
<add> assertedFormulas.clear();
<ide>
<ide> //TODO solver_reset(z3context, z3solver);
<ide> Native.solverDecRef(z3context, z3solver); |
|
JavaScript | mit | 60d867c3bd1055ffb0816b9f70ba1782e22b5de2 | 0 | kriskowal/tengwarjs,kriskowal/tengwarjs,kriskowal/tengwarjs,kriskowal/tengwarjs |
// This module adapts streams of characters sent to one parser into a
// simplified normal form piped to another. Internally, a stream is
// represented as a function that accepts the next character and returns a new
// stream.
//
// stream("a")("b")("c") -> stream
//
// The input ends with an empty character.
//
// stream("") -> stream
//
// Functions that return streams and produce a syntax node accept a
// callback that like a stream is required to return the initial stream state.
//
// parseAbc(function (result) {
// console.log(result);
// return expectEof();
// })("a")("b")("c")("")
//
var Parser = require("./parser");
var makeTrie = require("./trie");
var makeParserFromTrie = require("./trie-parser");
var array_ = Array.prototype;
// The `normalize` function accepts a stream and returns a stream. The
// character sequence sent to the returned stream will be converted to a
// normal form, where each character is lower-case and various clusters of
// characters will be converted to a "normal" phonetic form so the subsequent
// parser only has to deal with one input for each phonetic output.
//
// normalize(parseWord(callback))("Q")("u")("x")
//
// In this example, the callback would receive "cwcs", the normal form of
// "Qux".
//
module.exports = normalize;
function normalize(callback) {
return toLowerCase(simplify(callback));
};
// This is a parser adapter that always returns the same state, but internally
// tracks the state of the wrapped parser. Each time a character
function toLowerCase(callback) {
return function passthrough(character) {
callback = callback(character.toLowerCase());
return passthrough;
};
}
// the keys of this table are characters and clusters of characters that must
// be simplified to the corresponding values before pumping them into an
// adapted parser. The adapted parser therefore only needs to handle the
// normal phoneitc form of the cluster.
var table = {
"k": "c",
"x": "cs",
"q": "cw",
"qu": "cw",
"p": "p",
"ph": "f",
"b": "b",
"bh": "v",
"ë": "e",
"â": "á",
"ê": "é",
"î": "í",
"ô": "ó",
"û": "ú"
};
// This generates a data structure that can be walked by a parser, where each
// node corresponds to having parsed a certain prefix and follows to each
// common suffix. If the parser is standing at a particular node of the trie
// and receives a character that does not match any of the subsequent subtrees,
// it "produces" the corresponding value at that node.
var trie = makeTrie(table);
var simplify = makeParserFromTrie(
trie,
function makeProducer(string) {
// producing string involves advancing the state by individual
// characters.
return function (callback) {
return Array.prototype.reduce.call(string, function (callback, character) {
return callback(character);
}, callback);
};
},
function callback(callback) {
// after a match has been emitted, loop back for another
return simplify(callback);
},
function fallback(callback) {
// if we reach a character that is not accounted for in the table, pass
// it through without alternation, then start scanning for matches
// again
return function (character) {
return simplify(callback(character));
};
}
);
| normalize.js |
var Parser = require("./parser");
var makeTrie = require("./trie");
var makeParserFromTrie = require("./trie-parser");
var array_ = Array.prototype;
module.exports = normalize;
function normalize(callback) {
return toLowerCase(simplify(callback));
};
function toLowerCase(callback) {
return function passthrough(character) {
callback = callback(character.toLowerCase());
return passthrough;
};
}
var table = {
"k": "c",
"x": "cs",
"q": "cw",
"qu": "cw",
"p": "p",
"ph": "f",
"b": "b",
"bh": "v",
"ë": "e",
"â": "á",
"ê": "é",
"î": "í",
"ô": "ó",
"û": "ú"
};
var trie = makeTrie(table);
var simplify = makeParserFromTrie(
trie,
function makeProducer(string) {
return function (callback) {
return Array.prototype.reduce.call(string, function (callback, character) {
return callback(character);
}, callback);
};
},
function callback(callback) {
return simplify(callback);
},
function fallback(callback) {
return function (character) {
return simplify(callback(character));
};
}
);
| Comment normalize
| normalize.js | Comment normalize | <ide><path>ormalize.js
<add>
<add>// This module adapts streams of characters sent to one parser into a
<add>// simplified normal form piped to another. Internally, a stream is
<add>// represented as a function that accepts the next character and returns a new
<add>// stream.
<add>//
<add>// stream("a")("b")("c") -> stream
<add>//
<add>// The input ends with an empty character.
<add>//
<add>// stream("") -> stream
<add>//
<add>// Functions that return streams and produce a syntax node accept a
<add>// callback that like a stream is required to return the initial stream state.
<add>//
<add>// parseAbc(function (result) {
<add>// console.log(result);
<add>// return expectEof();
<add>// })("a")("b")("c")("")
<add>//
<ide>
<ide> var Parser = require("./parser");
<ide> var makeTrie = require("./trie");
<ide> var makeParserFromTrie = require("./trie-parser");
<ide> var array_ = Array.prototype;
<ide>
<add>// The `normalize` function accepts a stream and returns a stream. The
<add>// character sequence sent to the returned stream will be converted to a
<add>// normal form, where each character is lower-case and various clusters of
<add>// characters will be converted to a "normal" phonetic form so the subsequent
<add>// parser only has to deal with one input for each phonetic output.
<add>//
<add>// normalize(parseWord(callback))("Q")("u")("x")
<add>//
<add>// In this example, the callback would receive "cwcs", the normal form of
<add>// "Qux".
<add>//
<ide> module.exports = normalize;
<ide> function normalize(callback) {
<ide> return toLowerCase(simplify(callback));
<ide> };
<ide>
<add>// This is a parser adapter that always returns the same state, but internally
<add>// tracks the state of the wrapped parser. Each time a character
<ide> function toLowerCase(callback) {
<ide> return function passthrough(character) {
<ide> callback = callback(character.toLowerCase());
<ide> };
<ide> }
<ide>
<add>// the keys of this table are characters and clusters of characters that must
<add>// be simplified to the corresponding values before pumping them into an
<add>// adapted parser. The adapted parser therefore only needs to handle the
<add>// normal phoneitc form of the cluster.
<ide> var table = {
<ide> "k": "c",
<ide> "x": "cs",
<ide> "û": "ú"
<ide> };
<ide>
<add>// This generates a data structure that can be walked by a parser, where each
<add>// node corresponds to having parsed a certain prefix and follows to each
<add>// common suffix. If the parser is standing at a particular node of the trie
<add>// and receives a character that does not match any of the subsequent subtrees,
<add>// it "produces" the corresponding value at that node.
<ide> var trie = makeTrie(table);
<ide>
<ide> var simplify = makeParserFromTrie(
<ide> trie,
<ide> function makeProducer(string) {
<add> // producing string involves advancing the state by individual
<add> // characters.
<ide> return function (callback) {
<ide> return Array.prototype.reduce.call(string, function (callback, character) {
<ide> return callback(character);
<ide> };
<ide> },
<ide> function callback(callback) {
<add> // after a match has been emitted, loop back for another
<ide> return simplify(callback);
<ide> },
<ide> function fallback(callback) {
<add> // if we reach a character that is not accounted for in the table, pass
<add> // it through without alternation, then start scanning for matches
<add> // again
<ide> return function (character) {
<ide> return simplify(callback(character));
<ide> }; |
|
Java | mit | e57078207dbbed1ef5d6f94e9dabd375452febc0 | 0 | HeGanjie/bruce-common-utils | package bruce.common.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import bruce.common.functional.Action1;
import bruce.common.functional.EAction1;
import bruce.common.functional.Func1;
import bruce.common.functional.LambdaUtils;
import bruce.common.functional.PersistentSet;
/**
* 文件工具类,操作文件的工具都写在这里
* @author Bruce
*
*/
public final class FileUtil {
public static final String DEFAULT_CHARSET = "utf-8";
private static final int BUFFER_SIZE = 1024 * 8;
private static final Pattern FILENAME_IN_PATH_PATTERN = Pattern.compile("(.+(?:\\/|\\\\))([^?\\s]+)(\\?.+)?");
private static final Set<String> IMAGE_SUFFIX_SET = new PersistentSet<>("JPG", "GIF", "PNG", "JPEG", "BMP").getModifiableCollection();
private static final Set<String> MEDIA_SUFFIX_SET = new PersistentSet<>(
"MP3", "MP4", "FLV", "OGG", "WMV", "WMA", "AVI", "MPEG").getModifiableCollection();
public static boolean isMediaFileSuffix(String path) {
String suffix = getSuffixByFileName(getBaseNameByPath(path));
return MEDIA_SUFFIX_SET.contains(CommonUtils.emptyIfNull(suffix).toUpperCase());
}
public static boolean isImageFileSuffix(String path) {
String suffix = getSuffixByFileName(getBaseNameByPath(path));
return IMAGE_SUFFIX_SET.contains(CommonUtils.emptyIfNull(suffix).toUpperCase());
}
public static String getSuffixByFileName(String fileName) {
if (CommonUtils.isStringNullOrWhiteSpace(fileName)) {
return null;
} else {
int lastIndexOfPoint = fileName.lastIndexOf('.');
return lastIndexOfPoint == -1 ? null : fileName.substring(lastIndexOfPoint + 1);
}
}
public static void copy(File src, File dst) {
FileInputStream is = null;
try {
is = new FileInputStream(src);
writeFile(dst, is);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) { }
}
}
}
/**
* 使用默认的编码读取项目文本资源文件
* @param resPath 资源文件路径
* @return 文件内容
*/
public static String readTextFileForDefaultEncoding(final String resPath) {
return readResourceTextFile(resPath, DEFAULT_CHARSET);
}
/**
* 读取项目文本资源文件
* @param resPath 资源文件路径
* @param encodingName 编码名称
* @return 文件内容
*/
public static String readResourceTextFile(final String resPath, final String encodingName) {
InputStream xmlResourceInputStream = FileUtil.class.getClassLoader()
.getResourceAsStream(resPath);
BufferedReader xmlFileReader = new BufferedReader(
new InputStreamReader(xmlResourceInputStream, Charset.forName(encodingName)));
return readTextFromReader(xmlFileReader);
}
public static boolean writeTextFile(File filePath, String fileContent) {
return writeFile(filePath, new ByteArrayInputStream(fileContent.getBytes()));
}
public static boolean writeTextFile(File filePath, String fileContent, String enc) {
try {
return writeFile(filePath, new ByteArrayInputStream(fileContent.getBytes(enc)));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public static boolean writeFile(File filePath, InputStream is) {
return writeFile(filePath, is, null);
}
public static boolean writeFile(File filePath, InputStream is, Action1<Long> progressCallback) {
FileOutputStream os = null;
File outFile = new File(filePath.getAbsolutePath() + ".tmp");
if (!outFile.getParentFile().exists()) outFile.mkdirs();
try {
if (outFile.exists() && !outFile.delete()) {
throw new IllegalStateException("File already writing");
}
os = new FileOutputStream(outFile);
copy(is, os, progressCallback);
return true;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
filePath.delete();
if (!outFile.renameTo(filePath)) {
throw new IllegalStateException("Writing to an opening file!");
}
}
}
}
}
public static boolean writeObj(Serializable src, String absPath) {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(absPath)));
oos.writeObject(src);
oos.flush();
return true;
}
catch (IOException e) { e.printStackTrace(); }
finally {
try {
if (oos != null) oos.close();
} catch (IOException e) { e.printStackTrace(); }
}
return false;
}
@SuppressWarnings("unchecked")
public static <T> T readObj(String absPath) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(absPath)));
return (T) ois.readObject();
}
catch (IOException e) { e.printStackTrace(); }
catch (ClassNotFoundException e) { e.printStackTrace(); }
finally {
try {
if (ois != null) ois.close();
} catch (IOException e) { e.printStackTrace(); }
}
return null;
}
public static void catFile(final File destFile, final File...files) {
catFile(destFile, Arrays.asList(files));
}
/**
* 合并文件
* @param destFile
* @param files
* @throws IOException
*/
public static void catFile(final File destFile, final List<File> files) {
if (files == null || files.isEmpty()) return;
withOpen(destFile.getAbsolutePath(), "rw", new EAction1<RandomAccessFile>() {
@Override
public void call(RandomAccessFile writing) throws Throwable {
byte[] buf = new byte[1024 * 8];
int nRead = 0;
writing.seek(destFile.length());
for (File file : files) {
RandomAccessFile reading = new RandomAccessFile(file, "r");
while ((nRead = reading.read(buf)) > 0) {
writing.write(buf, 0, nRead);
}
reading.close();
}
}
});
}
/**
* 读入文本文件
* @param textFile
* @return
*/
public static String readTextFile(File textFile) {
return readTextFile(textFile, DEFAULT_CHARSET);
}
/**
* 读入文本文件
* @param file
* @param encoding 文件编码
* @return
*/
public static String readTextFile(final File file, String encoding) {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
return readTextFromReader(br);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 根据路径取得文件名
* @param path 路径
* @return 文件名
*/
public static String getBaseNameByPath(final String path) {
Matcher m = FILENAME_IN_PATH_PATTERN.matcher(path);
if (!m.find()) return null;
return m.group(2);
}
/**
* 根据路径取得文件夹
* @param path 路径
* @return 文件夹路径
*/
public static String getFileDirPath(final String path) {
Matcher m = FILENAME_IN_PATH_PATTERN.matcher(path);
if (!m.find()) return null;
return m.group(1);
}
/**
* 从BufferedReader读取文本内容
* @param reader bufferedReader
* @return 文本内容
*/
public static String readTextFromReader(final Reader reader) {
StringBuffer sb = new StringBuffer();
char[] buf = new char[1024 * 4];
int readLen;
try {
while (-1 != (readLen = reader.read(buf))) {
sb.append(buf, 0, readLen);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
public static void withOpen(String filePath, String mode, EAction1<RandomAccessFile> block) {
RandomAccessFile recordFile = null;
try {
recordFile = new RandomAccessFile(filePath, mode);
block.call(recordFile);
}
catch (Throwable e) { throw new RuntimeException(e); }
finally {
try {
if (recordFile != null)
recordFile.close();
} catch (IOException e) { e.printStackTrace(); }
}
}
public static void writeObject(String parent, String fileName, Serializable obj) {
File parentDir = new File(parent);
parentDir.mkdirs();
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(new File(parentDir, fileName))));
oos.writeObject(obj);
oos.flush();
} catch (IOException e) {
CommonUtils.throwRuntimeExceptionAndPrint(e);
} finally {
if (oos != null)
try {
oos.close();
} catch (IOException e) {
CommonUtils.throwRuntimeExceptionAndPrint(e);
}
}
}
@SuppressWarnings("unchecked")
public static <T> T readObject(String path) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(path)));
return (T) ois.readObject();
} catch (Exception e) {
CommonUtils.throwRuntimeExceptionAndPrint(e);
} finally {
try {
if (ois != null)
ois.close();
} catch (Exception e) {
CommonUtils.throwRuntimeExceptionAndPrint(e);
}
}
return null;
}
public static List<File> recurListFiles(File root, final String ...suffixs) {
File[] dirs = root.listFiles(new FileFilter() {
@Override
public boolean accept(File f) { return f.isDirectory(); }
});
if (dirs == null) return Collections.emptyList();
List<File> selectMany = LambdaUtils.selectMany(Arrays.asList(dirs), new Func1<Collection<File>, File>() {
@Override
public Collection<File> call(File dir) { return recurListFiles(dir, suffixs); }
});
File[] files = root.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
for (String suffix : suffixs) {
if (name.endsWith(suffix)) return true;
}
return false;
}
});
selectMany.addAll(Arrays.asList(files));
return selectMany;
}
public static long copy(InputStream input, OutputStream output) throws IOException {
return copy(input, output, null);
}
public static long copy(InputStream input, OutputStream output, Action1<Long> progressCallback) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
long count = 0;
int n;
while ((n = input.read(buffer)) != -1) {
output.write(buffer, 0, n);
count += n;
if (progressCallback != null) progressCallback.call(count);
}
return count;
}
public static String zip(String[] files, String zipFile) throws IOException {
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
try {
byte data[] = new byte[BUFFER_SIZE];
BufferedInputStream origin = null;
for (String file : files) {
origin = new BufferedInputStream(new FileInputStream(file), BUFFER_SIZE);
try {
out.putNextEntry(new ZipEntry(FileUtil.getBaseNameByPath(file)));
int count;
while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) {
out.write(data, 0, count);
}
} finally {
origin.close();
}
}
} finally {
out.close();
}
return zipFile;
}
public static void unzip(String zipFile, String location) throws IOException {
try {
File f = new File(location);
if (!f.isDirectory()) f.mkdirs();
ZipInputStream zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile)));
try {
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
String path = location + ze.getName();
if (ze.isDirectory()) {
File unzipFile = new File(path);
if (!unzipFile.isDirectory()) unzipFile.mkdirs();
} else {
BufferedOutputStream fout = new BufferedOutputStream(new FileOutputStream(path, false));
try {
for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}
zin.closeEntry();
} finally {
fout.close();
}
}
}
} finally {
zin.close();
}
} catch (Exception e) {
CommonUtils.throwRuntimeExceptionAndPrint(e);
}
}
public static int recurEncodingConvert(String path, String fileSuffix, String originalEnc, String finalEnc) {
List<File> txtFiles = recurListFiles(new File(path), fileSuffix);
for (File f : txtFiles) {
String content = readTextFile(f, originalEnc);
writeTextFile(f, content, finalEnc);
}
return txtFiles.size();
}
public static void deleteDir(File dir) {
if (!dir.isDirectory()) return;
for (File file : dir.listFiles()) {
if (file.isDirectory())
deleteDir(file);
else
file.delete();
}
dir.delete();
}
public static long getFileSize(File file) {
if (!file.isDirectory()) return file.length();
long length = 0;
for (File f : file.listFiles()) {
if (f.isDirectory())
length += getFileSize(f);
else
length += f.length();
}
return length;
}
public static void main(String[] args) {
}
} | src/bruce/common/utils/FileUtil.java | package bruce.common.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import bruce.common.functional.Action1;
import bruce.common.functional.EAction1;
import bruce.common.functional.Func1;
import bruce.common.functional.LambdaUtils;
import bruce.common.functional.PersistentSet;
/**
* 文件工具类,操作文件的工具都写在这里
* @author Bruce
*
*/
public final class FileUtil {
public static final String DEFAULT_CHARSET = "utf-8";
private static final int BUFFER_SIZE = 1024 * 8;
private static final Pattern FILENAME_IN_PATH_PATTERN = Pattern.compile("(.+(?:\\/|\\\\))([^?\\s]+)(\\?.+)?");
private static final Set<String> IMAGE_SUFFIX_SET = new PersistentSet<>("JPG", "GIF", "PNG", "JPEG", "BMP").getModifiableCollection();
private static final Set<String> MEDIA_SUFFIX_SET = new PersistentSet<>(
"MP3", "MP4", "FLV", "OGG", "WMV", "WMA", "AVI", "MPEG").getModifiableCollection();
public static boolean isMediaFileSuffix(String path) {
String suffix = getSuffixByFileName(getBaseNameByPath(path));
return MEDIA_SUFFIX_SET.contains(CommonUtils.emptyIfNull(suffix).toUpperCase());
}
public static boolean isImageFileSuffix(String path) {
String suffix = getSuffixByFileName(getBaseNameByPath(path));
return IMAGE_SUFFIX_SET.contains(CommonUtils.emptyIfNull(suffix).toUpperCase());
}
public static String getSuffixByFileName(String fileName) {
if (CommonUtils.isStringNullOrWhiteSpace(fileName)) {
return null;
} else {
int lastIndexOfPoint = fileName.lastIndexOf('.');
return lastIndexOfPoint == -1 ? null : fileName.substring(lastIndexOfPoint + 1);
}
}
public static void copy(File src, File dst) {
FileInputStream is = null;
try {
is = new FileInputStream(src);
writeFile(dst, is);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) { }
}
}
}
/**
* 使用默认的编码读取项目文本资源文件
* @param resPath 资源文件路径
* @return 文件内容
*/
public static String readTextFileForDefaultEncoding(final String resPath) {
return readResourceTextFile(resPath, DEFAULT_CHARSET);
}
/**
* 读取项目文本资源文件
* @param resPath 资源文件路径
* @param encodingName 编码名称
* @return 文件内容
*/
public static String readResourceTextFile(final String resPath, final String encodingName) {
InputStream xmlResourceInputStream = FileUtil.class.getClassLoader()
.getResourceAsStream(resPath);
BufferedReader xmlFileReader = new BufferedReader(
new InputStreamReader(xmlResourceInputStream, Charset.forName(encodingName)));
return readTextFromReader(xmlFileReader);
}
public static boolean writeTextFile(File filePath, String fileContent) {
return writeFile(filePath, new ByteArrayInputStream(fileContent.getBytes()));
}
public static boolean writeTextFile(File filePath, String fileContent, String enc) {
try {
return writeFile(filePath, new ByteArrayInputStream(fileContent.getBytes(enc)));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public static boolean writeFile(File filePath, InputStream is) {
return writeFile(filePath, is, null);
}
public static boolean writeFile(File filePath, InputStream is, Action1<Long> progressCallback) {
FileOutputStream os = null;
File outFile = new File(filePath.getAbsolutePath() + ".tmp");
if (!outFile.getParentFile().exists()) outFile.mkdirs();
try {
if (outFile.exists() && !outFile.delete()) {
throw new IllegalStateException("File already writing");
}
os = new FileOutputStream(outFile);
copy(is, os, progressCallback);
return true;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
filePath.delete();
if (!outFile.renameTo(filePath)) {
throw new IllegalStateException("Writing to an opening file!");
}
}
}
}
}
public static boolean writeObj(Serializable src, String absPath) {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(absPath)));
oos.writeObject(src);
oos.flush();
return true;
}
catch (IOException e) { e.printStackTrace(); }
finally {
try {
if (oos != null) oos.close();
} catch (IOException e) { e.printStackTrace(); }
}
return false;
}
@SuppressWarnings("unchecked")
public static <T> T readObj(String absPath) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(absPath)));
return (T) ois.readObject();
}
catch (IOException e) { e.printStackTrace(); }
catch (ClassNotFoundException e) { e.printStackTrace(); }
finally {
try {
if (ois != null) ois.close();
} catch (IOException e) { e.printStackTrace(); }
}
return null;
}
public static void catFile(final File destFile, final File...files) {
catFile(destFile, Arrays.asList(files));
}
/**
* 合并文件
* @param destFile
* @param files
* @throws IOException
*/
public static void catFile(final File destFile, final List<File> files) {
if (files == null || files.isEmpty()) return;
withOpen(destFile.getAbsolutePath(), "rw", new EAction1<RandomAccessFile>() {
@Override
public void call(RandomAccessFile writing) throws Throwable {
byte[] buf = new byte[1024 * 8];
int nRead = 0;
writing.seek(destFile.length());
for (File file : files) {
RandomAccessFile reading = new RandomAccessFile(file, "r");
while ((nRead = reading.read(buf)) > 0) {
writing.write(buf, 0, nRead);
}
reading.close();
}
}
});
}
/**
* 读入文本文件
* @param textFile
* @return
*/
public static String readTextFile(File textFile) {
return readTextFile(textFile, DEFAULT_CHARSET);
}
/**
* 读入文本文件
* @param file
* @param encoding 文件编码
* @return
*/
public static String readTextFile(final File file, String encoding) {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
return readTextFromReader(br);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 根据路径取得文件名
* @param path 路径
* @return 文件名
*/
public static String getBaseNameByPath(final String path) {
Matcher m = FILENAME_IN_PATH_PATTERN.matcher(path);
if (!m.find()) return null;
return m.group(2);
}
/**
* 根据路径取得文件夹
* @param path 路径
* @return 文件夹路径
*/
public static String getFileDirPath(final String path) {
Matcher m = FILENAME_IN_PATH_PATTERN.matcher(path);
if (!m.find()) return null;
return m.group(1);
}
/**
* 从BufferedReader读取文本内容
* @param reader bufferedReader
* @return 文本内容
*/
public static String readTextFromReader(final Reader reader) {
StringBuffer sb = new StringBuffer();
char[] buf = new char[1024 * 4];
int readLen;
try {
while (-1 != (readLen = reader.read(buf))) {
sb.append(buf, 0, readLen);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
public static void withOpen(String filePath, String mode, EAction1<RandomAccessFile> block) {
RandomAccessFile recordFile = null;
try {
recordFile = new RandomAccessFile(filePath, mode);
block.call(recordFile);
}
catch (Throwable e) { throw new RuntimeException(e); }
finally {
try {
if (recordFile != null)
recordFile.close();
} catch (IOException e) { e.printStackTrace(); }
}
}
public static void writeObject(String parent, String fileName, Serializable obj) {
File parentDir = new File(parent);
parentDir.mkdirs();
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(new File(parentDir, fileName))));
oos.writeObject(obj);
oos.flush();
} catch (IOException e) {
CommonUtils.throwRuntimeExceptionAndPrint(e);
} finally {
if (oos != null)
try {
oos.close();
} catch (IOException e) {
CommonUtils.throwRuntimeExceptionAndPrint(e);
}
}
}
@SuppressWarnings("unchecked")
public static <T> T readObject(String path) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(path)));
return (T) ois.readObject();
} catch (Exception e) {
CommonUtils.throwRuntimeExceptionAndPrint(e);
} finally {
try {
if (ois != null)
ois.close();
} catch (Exception e) {
CommonUtils.throwRuntimeExceptionAndPrint(e);
}
}
return null;
}
public static List<File> recurListFiles(File root, final String ...suffixs) {
File[] dirs = root.listFiles(new FileFilter() {
@Override
public boolean accept(File f) { return f.isDirectory(); }
});
List<File> selectMany = LambdaUtils.selectMany(Arrays.asList(dirs), new Func1<Collection<File>, File>() {
@Override
public Collection<File> call(File dir) { return recurListFiles(dir, suffixs); }
});
File[] files = root.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
for (String suffix : suffixs) {
if (name.endsWith(suffix)) return true;
}
return false;
}
});
selectMany.addAll(Arrays.asList(files));
return selectMany;
}
public static long copy(InputStream input, OutputStream output) throws IOException {
return copy(input, output, null);
}
public static long copy(InputStream input, OutputStream output, Action1<Long> progressCallback) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
long count = 0;
int n;
while ((n = input.read(buffer)) != -1) {
output.write(buffer, 0, n);
count += n;
if (progressCallback != null) progressCallback.call(count);
}
return count;
}
public static String zip(String[] files, String zipFile) throws IOException {
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
try {
byte data[] = new byte[BUFFER_SIZE];
BufferedInputStream origin = null;
for (String file : files) {
origin = new BufferedInputStream(new FileInputStream(file), BUFFER_SIZE);
try {
out.putNextEntry(new ZipEntry(FileUtil.getBaseNameByPath(file)));
int count;
while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) {
out.write(data, 0, count);
}
} finally {
origin.close();
}
}
} finally {
out.close();
}
return zipFile;
}
public static void unzip(String zipFile, String location) throws IOException {
try {
File f = new File(location);
if (!f.isDirectory()) f.mkdirs();
ZipInputStream zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile)));
try {
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
String path = location + ze.getName();
if (ze.isDirectory()) {
File unzipFile = new File(path);
if (!unzipFile.isDirectory()) unzipFile.mkdirs();
} else {
BufferedOutputStream fout = new BufferedOutputStream(new FileOutputStream(path, false));
try {
for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}
zin.closeEntry();
} finally {
fout.close();
}
}
}
} finally {
zin.close();
}
} catch (Exception e) {
CommonUtils.throwRuntimeExceptionAndPrint(e);
}
}
public static int recurEncodingConvert(String path, String fileSuffix, String originalEnc, String finalEnc) {
List<File> txtFiles = recurListFiles(new File(path), fileSuffix);
for (File f : txtFiles) {
String content = readTextFile(f, originalEnc);
writeTextFile(f, content, finalEnc);
}
return txtFiles.size();
}
public static void deleteDir(File dir) {
if (!dir.isDirectory()) return;
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory())
deleteDir(files[i]);
else
files[i].delete();
}
dir.delete();
}
public static void main(String[] args) {
}
} | append getFileSize method
| src/bruce/common/utils/FileUtil.java | append getFileSize method | <ide><path>rc/bruce/common/utils/FileUtil.java
<ide> import java.nio.charset.Charset;
<ide> import java.util.Arrays;
<ide> import java.util.Collection;
<add>import java.util.Collections;
<ide> import java.util.List;
<ide> import java.util.Set;
<ide> import java.util.regex.Matcher;
<ide> @Override
<ide> public boolean accept(File f) { return f.isDirectory(); }
<ide> });
<add> if (dirs == null) return Collections.emptyList();
<ide>
<ide> List<File> selectMany = LambdaUtils.selectMany(Arrays.asList(dirs), new Func1<Collection<File>, File>() {
<ide> @Override
<ide>
<ide> public static void deleteDir(File dir) {
<ide> if (!dir.isDirectory()) return;
<del> File[] files = dir.listFiles();
<del> for (int i = 0; i < files.length; i++) {
<del> if (files[i].isDirectory())
<del> deleteDir(files[i]);
<add> for (File file : dir.listFiles()) {
<add> if (file.isDirectory())
<add> deleteDir(file);
<ide> else
<del> files[i].delete();
<add> file.delete();
<ide> }
<ide> dir.delete();
<ide> }
<ide>
<add> public static long getFileSize(File file) {
<add> if (!file.isDirectory()) return file.length();
<add> long length = 0;
<add> for (File f : file.listFiles()) {
<add> if (f.isDirectory())
<add> length += getFileSize(f);
<add> else
<add> length += f.length();
<add> }
<add> return length;
<add> }
<add>
<ide> public static void main(String[] args) {
<ide> }
<ide> |
|
Java | apache-2.0 | 83dfa0a5c07b100a1ba2f73a30413483ae2a8f5b | 0 | apache/commons-math,sdinot/hipparchus,sdinot/hipparchus,apache/commons-math,Hipparchus-Math/hipparchus,sdinot/hipparchus,apache/commons-math,Hipparchus-Math/hipparchus,Hipparchus-Math/hipparchus,Hipparchus-Math/hipparchus,sdinot/hipparchus,apache/commons-math | /*
* 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.math3.random;
import java.util.Arrays;
import org.apache.commons.math3.TestUtils;
import org.apache.commons.math3.stat.Frequency;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.exception.MathIllegalArgumentException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Base class for RandomGenerator tests.
*
* Tests RandomGenerator methods directly and also executes RandomDataTest
* test cases against a RandomDataImpl created using the provided generator.
*
* RandomGenerator test classes should extend this class, implementing
* makeGenerator() to provide a concrete generator to test. The generator
* returned by makeGenerator should be seeded with a fixed seed.
*
* @version $Id$
*/
public abstract class RandomGeneratorAbstractTest extends RandomDataTest {
/** RandomGenerator under test */
protected RandomGenerator generator;
/**
* Override this method in subclasses to provide a concrete generator to test.
* Return a generator seeded with a fixed seed.
*/
protected abstract RandomGenerator makeGenerator();
/**
* Initialize generator and randomData instance in superclass.
*/
public RandomGeneratorAbstractTest() {
generator = makeGenerator();
randomData = new RandomDataImpl(generator);
}
/**
* Set a fixed seed for the tests
*/
@Before
public void setUp() {
generator = makeGenerator();
}
// Omit secureXxx tests, since they do not use the provided generator
@Override
public void testNextSecureLongIAE() {}
@Override
public void testNextSecureLongNegativeToPositiveRange() {}
@Override
public void testNextSecureLongNegativeRange() {}
@Override
public void testNextSecureLongPositiveRange() {}
@Override
public void testNextSecureIntIAE() {}
@Override
public void testNextSecureIntNegativeToPositiveRange() {}
@Override
public void testNextSecureIntNegativeRange() {}
@Override
public void testNextSecureIntPositiveRange() {}
@Override
public void testNextSecureHex() {}
@Test
/**
* Tests uniformity of nextInt(int) distribution by generating 1000
* samples for each of 10 test values and for each sample performing
* a chi-square test of homogeneity of the observed distribution with
* the expected uniform distribution. Tests are performed at the .01
* level and an average failure rate higher than 2% (i.e. more than 20
* null hypothesis rejections) causes the test case to fail.
*
* All random values are generated using the generator instance used by
* other tests and the generator is not reseeded, so this is a fixed seed
* test.
*/
public void testNextIntDirect() throws Exception {
// Set up test values - end of the array filled randomly
int[] testValues = new int[] {4, 10, 12, 32, 100, 10000, 0, 0, 0, 0};
for (int i = 6; i < 10; i++) {
final int val = generator.nextInt();
testValues[i] = val < 0 ? -val : val + 1;
}
final int numTests = 1000;
for (int i = 0; i < testValues.length; i++) {
final int n = testValues[i];
// Set up bins
int[] binUpperBounds;
if (n < 32) {
binUpperBounds = new int[n];
for (int k = 0; k < n; k++) {
binUpperBounds[k] = k;
}
} else {
binUpperBounds = new int[10];
final int step = n / 10;
for (int k = 0; k < 9; k++) {
binUpperBounds[k] = (k + 1) * step;
}
binUpperBounds[9] = n - 1;
}
// Run the tests
int numFailures = 0;
final int binCount = binUpperBounds.length;
final long[] observed = new long[binCount];
final double[] expected = new double[binCount];
expected[0] = binUpperBounds[0] == 0 ? (double) smallSampleSize / (double) n :
(double) ((binUpperBounds[0] + 1) * smallSampleSize) / (double) n;
for (int k = 1; k < binCount; k++) {
expected[k] = (double) smallSampleSize *
(double) (binUpperBounds[k] - binUpperBounds[k - 1]) / (double) n;
}
for (int j = 0; j < numTests; j++) {
Arrays.fill(observed, 0);
for (int k = 0; k < smallSampleSize; k++) {
final int value = generator.nextInt(n);
Assert.assertTrue("nextInt range",(value >= 0) && (value < n));
for (int l = 0; l < binCount; l++) {
if (binUpperBounds[l] >= value) {
observed[l]++;
break;
}
}
}
if (testStatistic.chiSquareTest(expected, observed) < 0.01) {
numFailures++;
}
}
if ((double) numFailures / (double) numTests > 0.02) {
Assert.fail("Too many failures for n = " + n +
" " + numFailures + " out of " + numTests + " tests failed.");
}
}
}
@Override // TODO is this supposed to be an override?
@Test(expected=MathIllegalArgumentException.class)
public void testNextIntIAE() {
try {
generator.nextInt(-1);
Assert.fail("MathIllegalArgumentException expected");
} catch (MathIllegalArgumentException ex) {
// ignored
}
generator.nextInt(0);
}
@Test
public void testNextLongDirect() {
long q1 = Long.MAX_VALUE/4;
long q2 = 2 * q1;
long q3 = 3 * q1;
Frequency freq = new Frequency();
long val = 0;
int value = 0;
for (int i=0; i<smallSampleSize; i++) {
val = generator.nextLong();
val = val < 0 ? -val : val;
if (val < q1) {
value = 0;
} else if (val < q2) {
value = 1;
} else if (val < q3) {
value = 2;
} else {
value = 3;
}
freq.addValue(value);
}
long[] observed = new long[4];
for (int i=0; i<4; i++) {
observed[i] = freq.getCount(i);
}
/* Use ChiSquare dist with df = 4-1 = 3, alpha = .001
* Change to 11.34 for alpha = .01
*/
Assert.assertTrue("chi-square test -- will fail about 1 in 1000 times",
testStatistic.chiSquare(expected,observed) < 16.27);
}
@Test
public void testNextBooleanDirect() {
long halfSampleSize = smallSampleSize / 2;
double[] expected = {halfSampleSize, halfSampleSize};
long[] observed = new long[2];
for (int i=0; i<smallSampleSize; i++) {
if (generator.nextBoolean()) {
observed[0]++;
} else {
observed[1]++;
}
}
/* Use ChiSquare dist with df = 2-1 = 1, alpha = .001
* Change to 6.635 for alpha = .01
*/
Assert.assertTrue("chi-square test -- will fail about 1 in 1000 times",
testStatistic.chiSquare(expected,observed) < 10.828);
}
@Test
public void testNextFloatDirect() {
Frequency freq = new Frequency();
float val = 0;
int value = 0;
for (int i=0; i<smallSampleSize; i++) {
val = generator.nextFloat();
if (val < 0.25) {
value = 0;
} else if (val < 0.5) {
value = 1;
} else if (val < 0.75) {
value = 2;
} else {
value = 3;
}
freq.addValue(value);
}
long[] observed = new long[4];
for (int i=0; i<4; i++) {
observed[i] = freq.getCount(i);
}
/* Use ChiSquare dist with df = 4-1 = 3, alpha = .001
* Change to 11.34 for alpha = .01
*/
Assert.assertTrue("chi-square test -- will fail about 1 in 1000 times",
testStatistic.chiSquare(expected,observed) < 16.27);
}
@Test
public void testDoubleDirect() {
SummaryStatistics sample = new SummaryStatistics();
final int N = 10000;
for (int i = 0; i < N; ++i) {
sample.addValue(generator.nextDouble());
}
Assert.assertEquals("Note: This test will fail randomly about 1 in 100 times.",
0.5, sample.getMean(), FastMath.sqrt(N/12.0) * 2.576);
Assert.assertEquals(1.0 / (2.0 * FastMath.sqrt(3.0)),
sample.getStandardDeviation(), 0.01);
}
@Test
public void testFloatDirect() {
SummaryStatistics sample = new SummaryStatistics();
final int N = 1000;
for (int i = 0; i < N; ++i) {
sample.addValue(generator.nextFloat());
}
Assert.assertEquals("Note: This test will fail randomly about 1 in 100 times.",
0.5, sample.getMean(), FastMath.sqrt(N/12.0) * 2.576);
Assert.assertEquals(1.0 / (2.0 * FastMath.sqrt(3.0)),
sample.getStandardDeviation(), 0.01);
}
@Test(expected=MathIllegalArgumentException.class)
public void testNextIntNeg() {
generator.nextInt(-1);
}
@Test
public void testNextInt2() {
int walk = 0;
final int N = 10000;
for (int k = 0; k < N; ++k) {
if (generator.nextInt() >= 0) {
++walk;
} else {
--walk;
}
}
Assert.assertTrue("Walked too far astray: " + walk + "\nNote: This " +
"test will fail randomly about 1 in 100 times.",
FastMath.abs(walk) < FastMath.sqrt(N) * 2.576);
}
@Test
public void testNextLong2() {
int walk = 0;
final int N = 1000;
for (int k = 0; k < N; ++k) {
if (generator.nextLong() >= 0) {
++walk;
} else {
--walk;
}
}
Assert.assertTrue("Walked too far astray: " + walk + "\nNote: This " +
"test will fail randomly about 1 in 100 times.",
FastMath.abs(walk) < FastMath.sqrt(N) * 2.576);
}
@Test
public void testNexBoolean2() {
int walk = 0;
final int N = 10000;
for (int k = 0; k < N; ++k) {
if (generator.nextBoolean()) {
++walk;
} else {
--walk;
}
}
Assert.assertTrue("Walked too far astray: " + walk + "\nNote: This " +
"test will fail randomly about 1 in 100 times.",
FastMath.abs(walk) < FastMath.sqrt(N) * 2.576);
}
@Test
public void testNexBytes() throws Exception {
long[] count = new long[256];
byte[] bytes = new byte[10];
double[] expected = new double[256];
final int sampleSize = 100000;
for (int i = 0; i < 256; i++) {
expected[i] = (double) sampleSize / 265f;
}
for (int k = 0; k < sampleSize; ++k) {
generator.nextBytes(bytes);
for (byte b : bytes) {
++count[b + 128];
}
}
TestUtils.assertChiSquareAccept(expected, count, 0.001);
}
@Test
public void testSeeding() throws Exception {
// makeGenerator initializes with fixed seed
RandomGenerator gen = makeGenerator();
RandomGenerator gen1 = makeGenerator();
checkSameSequence(gen, gen1);
// reseed, but recreate the second one
// verifies MATH-723
gen.setSeed(100);
gen1 = makeGenerator();
gen1.setSeed(100);
checkSameSequence(gen, gen1);
}
private void checkSameSequence(RandomGenerator gen1, RandomGenerator gen2) throws Exception {
final int len = 11; // Needs to be an odd number to check MATH-723
final double[][] values = new double[2][len];
for (int i = 0; i < len; i++) {
values[0][i] = gen1.nextDouble();
}
for (int i = 0; i < len; i++) {
values[1][i] = gen2.nextDouble();
}
Assert.assertTrue(Arrays.equals(values[0], values[1]));
for (int i = 0; i < len; i++) {
values[0][i] = gen1.nextFloat();
}
for (int i = 0; i < len; i++) {
values[1][i] = gen2.nextFloat();
}
Assert.assertTrue(Arrays.equals(values[0], values[1]));
for (int i = 0; i < len; i++) {
values[0][i] = gen1.nextInt();
}
for (int i = 0; i < len; i++) {
values[1][i] = gen2.nextInt();
}
Assert.assertTrue(Arrays.equals(values[0], values[1]));
for (int i = 0; i < len; i++) {
values[0][i] = gen1.nextLong();
}
for (int i = 0; i < len; i++) {
values[1][i] = gen2.nextLong();
}
Assert.assertTrue(Arrays.equals(values[0], values[1]));
for (int i = 0; i < len; i++) {
values[0][i] = gen1.nextInt(len);
}
for (int i = 0; i < len; i++) {
values[1][i] = gen2.nextInt(len);
}
Assert.assertTrue(Arrays.equals(values[0], values[1]));
for (int i = 0; i < len; i++) {
values[0][i] = gen1.nextBoolean() ? 1 : 0;
}
for (int i = 0; i < len; i++) {
values[1][i] = gen2.nextBoolean() ? 1 : 0;
}
Assert.assertTrue(Arrays.equals(values[0], values[1]));
for (int i = 0; i < len; i++) {
values[0][i] = gen1.nextGaussian();
}
for (int i = 0; i < len; i++) {
values[1][i] = gen2.nextGaussian();
}
Assert.assertTrue(Arrays.equals(values[0], values[1]));
}
}
| src/test/java/org/apache/commons/math3/random/RandomGeneratorAbstractTest.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.math3.random;
import java.util.Arrays;
import org.apache.commons.math3.TestUtils;
import org.apache.commons.math3.stat.Frequency;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.exception.MathIllegalArgumentException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Base class for RandomGenerator tests.
*
* Tests RandomGenerator methods directly and also executes RandomDataTest
* test cases against a RandomDataImpl created using the provided generator.
*
* RandomGenerator test classes should extend this class, implementing
* makeGenerator() to provide a concrete generator to test. The generator
* returned by makeGenerator should be seeded with a fixed seed.
*
* @version $Id$
*/
public abstract class RandomGeneratorAbstractTest extends RandomDataTest {
/** RandomGenerator under test */
protected RandomGenerator generator;
/**
* Override this method in subclasses to provide a concrete generator to test.
* Return a generator seeded with a fixed seed.
*/
protected abstract RandomGenerator makeGenerator();
/**
* Initialize generator and randomData instance in superclass.
*/
public RandomGeneratorAbstractTest() {
generator = makeGenerator();
randomData = new RandomDataImpl(generator);
}
/**
* Set a fixed seed for the tests
*/
@Before
public void setUp() {
generator = makeGenerator();
}
// Omit secureXxx tests, since they do not use the provided generator
@Override
public void testNextSecureLongIAE() {}
@Override
public void testNextSecureLongNegativeToPositiveRange() {}
@Override
public void testNextSecureLongNegativeRange() {}
@Override
public void testNextSecureLongPositiveRange() {}
@Override
public void testNextSecureIntIAE() {}
@Override
public void testNextSecureIntNegativeToPositiveRange() {}
@Override
public void testNextSecureIntNegativeRange() {}
@Override
public void testNextSecureIntPositiveRange() {}
@Override
public void testNextSecureHex() {}
@Test
/**
* Tests uniformity of nextInt(int) distribution by generating 1000
* samples for each of 10 test values and for each sample performing
* a chi-square test of homogeneity of the observed distribution with
* the expected uniform distribution. Tests are performed at the .01
* level and an average failure rate higher than 2% (i.e. more than 20
* null hypothesis rejections) causes the test case to fail.
*
* All random values are generated using the generator instance used by
* other tests and the generator is not reseeded, so this is a fixed seed
* test.
*/
public void testNextIntDirect() throws Exception {
// Set up test values - end of the array filled randomly
int[] testValues = new int[] {4, 10, 12, 32, 100, 10000, 0, 0, 0, 0};
for (int i = 6; i < 10; i++) {
final int val = generator.nextInt();
testValues[i] = val < 0 ? -val : val + 1;
}
final int numTests = 1000;
for (int i = 0; i < testValues.length; i++) {
final int n = testValues[i];
// Set up bins
int[] binUpperBounds;
if (n < 32) {
binUpperBounds = new int[n];
for (int k = 0; k < n; k++) {
binUpperBounds[k] = k;
}
} else {
binUpperBounds = new int[10];
final int step = n / 10;
for (int k = 0; k < 9; k++) {
binUpperBounds[k] = (k + 1) * step;
}
binUpperBounds[9] = n - 1;
}
// Run the tests
int numFailures = 0;
final int binCount = binUpperBounds.length;
final long[] observed = new long[binCount];
final double[] expected = new double[binCount];
expected[0] = binUpperBounds[0] == 0 ? (double) smallSampleSize / (double) n :
(double) ((binUpperBounds[0] + 1) * smallSampleSize) / (double) n;
for (int k = 1; k < binCount; k++) {
expected[k] = (double) smallSampleSize *
(double) (binUpperBounds[k] - binUpperBounds[k - 1]) / (double) n;
}
for (int j = 0; j < numTests; j++) {
Arrays.fill(observed, 0);
for (int k = 0; k < smallSampleSize; k++) {
final int value = generator.nextInt(n);
Assert.assertTrue("nextInt range",(value >= 0) && (value < n));
for (int l = 0; l < binCount; l++) {
if (binUpperBounds[l] >= value) {
observed[l]++;
break;
}
}
}
if (testStatistic.chiSquareTest(expected, observed) < 0.01) {
numFailures++;
}
}
if ((double) numFailures / (double) numTests > 0.02) {
Assert.fail("Too many failures for n = " + n +
" " + numFailures + " out of " + numTests + " tests failed.");
}
}
}
@Test(expected=MathIllegalArgumentException.class)
public void testNextIntIAE() {
try {
generator.nextInt(-1);
Assert.fail("MathIllegalArgumentException expected");
} catch (MathIllegalArgumentException ex) {
// ignored
}
generator.nextInt(0);
}
@Test
public void testNextLongDirect() {
long q1 = Long.MAX_VALUE/4;
long q2 = 2 * q1;
long q3 = 3 * q1;
Frequency freq = new Frequency();
long val = 0;
int value = 0;
for (int i=0; i<smallSampleSize; i++) {
val = generator.nextLong();
val = val < 0 ? -val : val;
if (val < q1) {
value = 0;
} else if (val < q2) {
value = 1;
} else if (val < q3) {
value = 2;
} else {
value = 3;
}
freq.addValue(value);
}
long[] observed = new long[4];
for (int i=0; i<4; i++) {
observed[i] = freq.getCount(i);
}
/* Use ChiSquare dist with df = 4-1 = 3, alpha = .001
* Change to 11.34 for alpha = .01
*/
Assert.assertTrue("chi-square test -- will fail about 1 in 1000 times",
testStatistic.chiSquare(expected,observed) < 16.27);
}
@Test
public void testNextBooleanDirect() {
long halfSampleSize = smallSampleSize / 2;
double[] expected = {halfSampleSize, halfSampleSize};
long[] observed = new long[2];
for (int i=0; i<smallSampleSize; i++) {
if (generator.nextBoolean()) {
observed[0]++;
} else {
observed[1]++;
}
}
/* Use ChiSquare dist with df = 2-1 = 1, alpha = .001
* Change to 6.635 for alpha = .01
*/
Assert.assertTrue("chi-square test -- will fail about 1 in 1000 times",
testStatistic.chiSquare(expected,observed) < 10.828);
}
@Test
public void testNextFloatDirect() {
Frequency freq = new Frequency();
float val = 0;
int value = 0;
for (int i=0; i<smallSampleSize; i++) {
val = generator.nextFloat();
if (val < 0.25) {
value = 0;
} else if (val < 0.5) {
value = 1;
} else if (val < 0.75) {
value = 2;
} else {
value = 3;
}
freq.addValue(value);
}
long[] observed = new long[4];
for (int i=0; i<4; i++) {
observed[i] = freq.getCount(i);
}
/* Use ChiSquare dist with df = 4-1 = 3, alpha = .001
* Change to 11.34 for alpha = .01
*/
Assert.assertTrue("chi-square test -- will fail about 1 in 1000 times",
testStatistic.chiSquare(expected,observed) < 16.27);
}
@Test
public void testDoubleDirect() {
SummaryStatistics sample = new SummaryStatistics();
final int N = 10000;
for (int i = 0; i < N; ++i) {
sample.addValue(generator.nextDouble());
}
Assert.assertEquals("Note: This test will fail randomly about 1 in 100 times.",
0.5, sample.getMean(), FastMath.sqrt(N/12.0) * 2.576);
Assert.assertEquals(1.0 / (2.0 * FastMath.sqrt(3.0)),
sample.getStandardDeviation(), 0.01);
}
@Test
public void testFloatDirect() {
SummaryStatistics sample = new SummaryStatistics();
final int N = 1000;
for (int i = 0; i < N; ++i) {
sample.addValue(generator.nextFloat());
}
Assert.assertEquals("Note: This test will fail randomly about 1 in 100 times.",
0.5, sample.getMean(), FastMath.sqrt(N/12.0) * 2.576);
Assert.assertEquals(1.0 / (2.0 * FastMath.sqrt(3.0)),
sample.getStandardDeviation(), 0.01);
}
@Test(expected=MathIllegalArgumentException.class)
public void testNextIntNeg() {
generator.nextInt(-1);
}
@Test
public void testNextInt2() {
int walk = 0;
final int N = 10000;
for (int k = 0; k < N; ++k) {
if (generator.nextInt() >= 0) {
++walk;
} else {
--walk;
}
}
Assert.assertTrue("Walked too far astray: " + walk + "\nNote: This " +
"test will fail randomly about 1 in 100 times.",
FastMath.abs(walk) < FastMath.sqrt(N) * 2.576);
}
@Test
public void testNextLong2() {
int walk = 0;
final int N = 1000;
for (int k = 0; k < N; ++k) {
if (generator.nextLong() >= 0) {
++walk;
} else {
--walk;
}
}
Assert.assertTrue("Walked too far astray: " + walk + "\nNote: This " +
"test will fail randomly about 1 in 100 times.",
FastMath.abs(walk) < FastMath.sqrt(N) * 2.576);
}
@Test
public void testNexBoolean2() {
int walk = 0;
final int N = 10000;
for (int k = 0; k < N; ++k) {
if (generator.nextBoolean()) {
++walk;
} else {
--walk;
}
}
Assert.assertTrue("Walked too far astray: " + walk + "\nNote: This " +
"test will fail randomly about 1 in 100 times.",
FastMath.abs(walk) < FastMath.sqrt(N) * 2.576);
}
@Test
public void testNexBytes() throws Exception {
long[] count = new long[256];
byte[] bytes = new byte[10];
double[] expected = new double[256];
final int sampleSize = 100000;
for (int i = 0; i < 256; i++) {
expected[i] = (double) sampleSize / 265f;
}
for (int k = 0; k < sampleSize; ++k) {
generator.nextBytes(bytes);
for (byte b : bytes) {
++count[b + 128];
}
}
TestUtils.assertChiSquareAccept(expected, count, 0.001);
}
@Test
public void testSeeding() throws Exception {
// makeGenerator initializes with fixed seed
RandomGenerator gen = makeGenerator();
RandomGenerator gen1 = makeGenerator();
checkSameSequence(gen, gen1);
// reseed, but recreate the second one
// verifies MATH-723
gen.setSeed(100);
gen1 = makeGenerator();
gen1.setSeed(100);
checkSameSequence(gen, gen1);
}
private void checkSameSequence(RandomGenerator gen1, RandomGenerator gen2) throws Exception {
final int len = 11; // Needs to be an odd number to check MATH-723
final double[][] values = new double[2][len];
for (int i = 0; i < len; i++) {
values[0][i] = gen1.nextDouble();
}
for (int i = 0; i < len; i++) {
values[1][i] = gen2.nextDouble();
}
Assert.assertTrue(Arrays.equals(values[0], values[1]));
for (int i = 0; i < len; i++) {
values[0][i] = gen1.nextFloat();
}
for (int i = 0; i < len; i++) {
values[1][i] = gen2.nextFloat();
}
Assert.assertTrue(Arrays.equals(values[0], values[1]));
for (int i = 0; i < len; i++) {
values[0][i] = gen1.nextInt();
}
for (int i = 0; i < len; i++) {
values[1][i] = gen2.nextInt();
}
Assert.assertTrue(Arrays.equals(values[0], values[1]));
for (int i = 0; i < len; i++) {
values[0][i] = gen1.nextLong();
}
for (int i = 0; i < len; i++) {
values[1][i] = gen2.nextLong();
}
Assert.assertTrue(Arrays.equals(values[0], values[1]));
for (int i = 0; i < len; i++) {
values[0][i] = gen1.nextInt(len);
}
for (int i = 0; i < len; i++) {
values[1][i] = gen2.nextInt(len);
}
Assert.assertTrue(Arrays.equals(values[0], values[1]));
for (int i = 0; i < len; i++) {
values[0][i] = gen1.nextBoolean() ? 1 : 0;
}
for (int i = 0; i < len; i++) {
values[1][i] = gen2.nextBoolean() ? 1 : 0;
}
Assert.assertTrue(Arrays.equals(values[0], values[1]));
for (int i = 0; i < len; i++) {
values[0][i] = gen1.nextGaussian();
}
for (int i = 0; i < len; i++) {
values[1][i] = gen2.nextGaussian();
}
Assert.assertTrue(Arrays.equals(values[0], values[1]));
}
}
| Add missing (?) @Override marker
git-svn-id: 80d496c472b8b763a5e941dba212da9bf48aeceb@1330623 13f79535-47bb-0310-9956-ffa450edef68
| src/test/java/org/apache/commons/math3/random/RandomGeneratorAbstractTest.java | Add missing (?) @Override marker | <ide><path>rc/test/java/org/apache/commons/math3/random/RandomGeneratorAbstractTest.java
<ide> }
<ide> }
<ide>
<add> @Override // TODO is this supposed to be an override?
<ide> @Test(expected=MathIllegalArgumentException.class)
<ide> public void testNextIntIAE() {
<ide> try { |
|
Java | agpl-3.0 | 212ca023409b790c974573f1443a148284dd7c16 | 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 | f6c04ef2-2e60-11e5-9284-b827eb9e62be | hello.java | f6badf76-2e60-11e5-9284-b827eb9e62be | f6c04ef2-2e60-11e5-9284-b827eb9e62be | hello.java | f6c04ef2-2e60-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>f6badf76-2e60-11e5-9284-b827eb9e62be
<add>f6c04ef2-2e60-11e5-9284-b827eb9e62be |
|
JavaScript | mit | 23b53a4e8638aaa86fd5a1e87d5bf5962c9132c4 | 0 | CSC383/CSC383,CSC383/CSC383 | //This page handles all resources page content
//jquery for phone fields
$(".required").keyup(function () {
if (this.value.length == this.maxLength) {
var $next = $(this).next('.required');
if ($next.length)
$(this).next('.required').focus();
else
$(this).blur();
}
});
const btnLogout = document.getElementById('btnLogout');
//Add logout event
btnLogout.addEventListener('click', e => {
auth.signOut();
});
const auth = firebase.auth();
//Add a realtime listener
auth.onAuthStateChanged(function(firebaseUser) {
if(firebaseUser) {
console.log(firebaseUser);
btnLogout.classList.remove('hide');
console.log(firebaseUser.email);
} else {
console.log('not logged in');
btnLogout.classList.add('hide');
}
});
//Loads all statistics on page load
window.onload = allStatistics();
var statRef = firebase.database();
function updateStatistics(statisticID) {
var id = statisticID;
var statValue = id + "Value";
var valueUpdate = document.getElementById(statValue);
statRef.ref("data_dashboard").update({
"" + id + "": valueUpdate
});
};
function deleteStatistic(statisticID) {
var id = statisticID;
statRef.ref("data_dashboard").child(""+id+"").remove();
allStatistics();
};
//Filters all statistics
function allStatistics() {
//Clears table of statistics
var tableRef = document.getElementById('table_body');
while ( tableRef.rows.length > 0 )
{
tableRef.deleteRow(0);
}
//Pull statistics from Firebase database
rootref.child("data_dashboard").on("child_added", function(snap) {
//store data from firebase to be used in table
var id = snap.key;
var stringID = id.toString();
var statValue = snap.val();
//Creates table with statistics pulled from firebase
$("#table_body").append("<tr><td><input id='"+id+"Statistic' type='text' value=\""+stringID+"\" ></input></td><td><input id='"+id+"Value' type='text' value=\""+statValue+"\" ></input></td><td><input type='submit' class='btn btn-success btn-send' value='Delete' onclick='deleteStatistic(\""+ stringID + "\")'></input></td><td><input type='submit' class='btn btn-success btn-send' value='Update' onclick='updateStatistic(\""+ stringID + "\")''></input></td></tr>"
);
});
};
| js/firebase-edit-data-dashboard.js | //This page handles all resources page content
//jquery for phone fields
$(".required").keyup(function () {
if (this.value.length == this.maxLength) {
var $next = $(this).next('.required');
if ($next.length)
$(this).next('.required').focus();
else
$(this).blur();
}
});
const btnLogout = document.getElementById('btnLogout');
//Add logout event
btnLogout.addEventListener('click', e => {
auth.signOut();
});
const auth = firebase.auth();
//Add a realtime listener
auth.onAuthStateChanged(function(firebaseUser) {
if(firebaseUser) {
console.log(firebaseUser);
btnLogout.classList.remove('hide');
console.log(firebaseUser.email);
} else {
console.log('not logged in');
btnLogout.classList.add('hide');
}
});
//Loads all statistics on page load
window.onload = allStatistics();
var statRef = firebase.database();
function updateStatistics(statisticID) {
var id = statisticID;
var statValue = id + "Value";
var valueUpdate = document.getElementById(statValue);
statRef.ref("data_dashboard").child(""+id+"").update({
value: ""+ valueUpdate.value +""
});
};
function deleteStatistic(statisticID) {
var id = statisticID;
statRef.ref("data_dashboard").child(""+id+"").remove();
allStatistics();
};
//Filters all statistics
function allStatistics() {
//Clears table of statistics
var tableRef = document.getElementById('table_body');
while ( tableRef.rows.length > 0 )
{
tableRef.deleteRow(0);
}
//Pull statistics from Firebase database
rootref.child("data_dashboard").on("child_added", function(snap) {
//store data from firebase to be used in table
var id = snap.key;
var stringID = id.toString();
var statValue = snap.val();
//Creates table with statistics pulled from firebase
$("#table_body").append("<tr><td><input id='"+id+"Statistic' type='text' value=\""+stringID+"\" ></input></td><td><input id='"+id+"Value' type='text' value=\""+statValue+"\" ></input></td><td><input type='submit' class='btn btn-success btn-send' value='Delete' onclick='deleteStatistic(\""+ stringID + "\")'></input></td><td><input type='submit' class='btn btn-success btn-send' value='Update' onclick='updateStatistic(\""+ stringID + "\")''></input></td></tr>"
);
});
};
| Update firebase-edit-data-dashboard.js | js/firebase-edit-data-dashboard.js | Update firebase-edit-data-dashboard.js | <ide><path>s/firebase-edit-data-dashboard.js
<ide>
<ide> var valueUpdate = document.getElementById(statValue);
<ide>
<del> statRef.ref("data_dashboard").child(""+id+"").update({
<del> value: ""+ valueUpdate.value +""
<add> statRef.ref("data_dashboard").update({
<add> "" + id + "": valueUpdate
<ide> });
<ide> };
<add>
<ide>
<ide> function deleteStatistic(statisticID) {
<ide> var id = statisticID; |
|
JavaScript | apache-2.0 | 90168dad326d1b9112a18507bf0d8a816e687a8f | 0 | DinoChiesa/apigee-edge-js | #! /usr/local/bin/node
/*jslint node:true */
// addAppCredential.js
// ------------------------------------------------------------------
// add a new credential, generated or explicitly specified, to a developer app in Apigee Edge.
//
// Copyright 2017-2019 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// last saved: <2019-September-25 17:20:49>
const edgejs = require('apigee-edge-js'),
common = edgejs.utility,
apigeeEdge = edgejs.edge,
sprintf = require('sprintf-js').sprintf,
Getopt = require('node-getopt'),
util = require('util'),
version = '20190925-1708',
getopt = new Getopt(common.commonOptions.concat([
['p' , 'product=ARG', 'required. name of the API product to enable on this app'],
['E' , 'email=ARG', 'required. email address of the developer for which to create the app'],
['A' , 'appname=ARG', 'required. name for the app'],
['I' , 'clientId=ARG', 'optional. the client id for this credential. Default: auto-generated.'],
['S' , 'secret=ARG', 'optional. the client secret for this credential. Default: auto-generated.'],
['x' , 'expiry=ARG', 'optional. expiry for the credential']
])).bindHelp();
// ========================================================
console.log(
'Apigee Edge App Credential tool, version: ' + version + '\n' +
'Node.js ' + process.version + '\n');
common.logWrite('start');
// process.argv array starts with 'node' and 'scriptname.js'
var opt = getopt.parse(process.argv.slice(2));
if ( !opt.options.appname ) {
console.log('You must specify a name of an app');
getopt.showHelp();
process.exit(1);
}
if ( !opt.options.product ) {
console.log('You must specify an API Product');
getopt.showHelp();
process.exit(1);
}
if ( !opt.options.email ) {
console.log('You must specify an email address');
getopt.showHelp();
process.exit(1);
}
common.verifyCommonRequiredParameters(opt.options, getopt);
apigeeEdge.connect(common.optToOptions(opt))
.then ( org => {
common.logWrite('connected');
let options = {
developerEmail : opt.options.email,
appName : opt.options.appname,
apiProducts : opt.options.product.split(','),
expiry : opt.options.expiry
};
if (opt.options.clientId) {
options.clientId = opt.options.clientId;
options.clientSecret = opt.options.secret;
if (opt.options.expiry) {
common.logWrite('WARNING: expiry is not supported with an explicitly-supplied client id and secret');
}
}
return org.appcredentials.add(options)
.then (result => {
if (opt.options.clientId) {
common.logWrite(sprintf('new apikey %s', result.consumerKey));
common.logWrite(sprintf('secret %s', result.consumerSecret));
}
else {
common.logWrite(sprintf('new apikey %s', result.credentials[0].consumerKey));
common.logWrite(sprintf('secret %s', result.credentials[0].consumerSecret));
}
});
})
.catch( e => console.error('error: ' + util.format(e) ) );
| examples/addAppCredential.js | #! /usr/local/bin/node
/*jslint node:true */
// addAppCredential.js
// ------------------------------------------------------------------
// add a new credential, generated or explicitly specified, to a developer app in Apigee Edge.
//
// Copyright 2017-2019 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// last saved: <2019-February-11 13:00:08>
const edgejs = require('apigee-edge-js'),
common = edgejs.utility,
apigeeEdge = edgejs.edge,
sprintf = require('sprintf-js').sprintf,
Getopt = require('node-getopt'),
version = '20181002-1052',
getopt = new Getopt(common.commonOptions.concat([
['p' , 'product=ARG', 'required. name of the API product to enable on this app'],
['E' , 'email=ARG', 'required. email address of the developer for which to create the app'],
['A' , 'appname=ARG', 'required. name for the app'],
['I' , 'clientId=ARG', 'optional. the client id for this credential. Default: auto-generated.'],
['S' , 'secret=ARG', 'optional. the client secret for this credential. Default: auto-generated.'],
['x' , 'expiry=ARG', 'optional. expiry for the credential']
])).bindHelp();
// ========================================================
console.log(
'Apigee Edge App Credential tool, version: ' + version + '\n' +
'Node.js ' + process.version + '\n');
common.logWrite('start');
// process.argv array starts with 'node' and 'scriptname.js'
var opt = getopt.parse(process.argv.slice(2));
if ( !opt.options.appname ) {
console.log('You must specify a name of an app');
getopt.showHelp();
process.exit(1);
}
if ( !opt.options.product ) {
console.log('You must specify an API Product');
getopt.showHelp();
process.exit(1);
}
if ( !opt.options.email ) {
console.log('You must specify an email address');
getopt.showHelp();
process.exit(1);
}
common.verifyCommonRequiredParameters(opt.options, getopt);
apigeeEdge.connect(common.optToOptions(opt), function(e, org) {
if (e) {
common.logWrite(JSON.stringify(e, null, 2));
common.logWrite(JSON.stringify(result, null, 2));
process.exit(1);
}
common.logWrite('connected');
if (opt.options.clientId) {
let options = {
developerEmail : opt.options.email,
appName : opt.options.appname,
clientId : opt.options.clientId,
clientSecret : opt.options.secret,
apiProduct : opt.options.product
};
org.appcredentials.add(options, function(e, result){
if (e) {
common.logWrite(JSON.stringify(e, null, 2));
common.logWrite(JSON.stringify(result, null, 2));
//console.log(e.stack);
process.exit(1);
}
//common.logWrite(sprintf('result %s', JSON.stringify(result)));
common.logWrite(sprintf('new apikey %s', result.consumerKey));
common.logWrite(sprintf('secret %s', result.consumerSecret));
});
}
else {
let options = {
developerEmail : opt.options.email,
appName : opt.options.appname,
apiProduct : opt.options.product,
expiry : opt.options.expiry
};
org.appcredentials.add(options, function(e, result){
if (e) {
common.logWrite(JSON.stringify(e, null, 2));
common.logWrite(JSON.stringify(result, null, 2));
//console.log(e.stack);
process.exit(1);
}
common.logWrite(sprintf('new apikey %s', result.credentials[0].consumerKey));
common.logWrite(sprintf('secret %s', result.credentials[0].consumerSecret));
});
}
});
| addAppCredential now specifies products correctly
| examples/addAppCredential.js | addAppCredential now specifies products correctly | <ide><path>xamples/addAppCredential.js
<ide> // See the License for the specific language governing permissions and
<ide> // limitations under the License.
<ide> //
<del>// last saved: <2019-February-11 13:00:08>
<add>// last saved: <2019-September-25 17:20:49>
<ide>
<ide> const edgejs = require('apigee-edge-js'),
<ide> common = edgejs.utility,
<ide> apigeeEdge = edgejs.edge,
<ide> sprintf = require('sprintf-js').sprintf,
<ide> Getopt = require('node-getopt'),
<del> version = '20181002-1052',
<add> util = require('util'),
<add> version = '20190925-1708',
<ide> getopt = new Getopt(common.commonOptions.concat([
<ide> ['p' , 'product=ARG', 'required. name of the API product to enable on this app'],
<ide> ['E' , 'email=ARG', 'required. email address of the developer for which to create the app'],
<ide> }
<ide>
<ide> common.verifyCommonRequiredParameters(opt.options, getopt);
<del>apigeeEdge.connect(common.optToOptions(opt), function(e, org) {
<del> if (e) {
<del> common.logWrite(JSON.stringify(e, null, 2));
<del> common.logWrite(JSON.stringify(result, null, 2));
<del> process.exit(1);
<del> }
<del> common.logWrite('connected');
<del>
<del> if (opt.options.clientId) {
<add>apigeeEdge.connect(common.optToOptions(opt))
<add> .then ( org => {
<add> common.logWrite('connected');
<ide> let options = {
<ide> developerEmail : opt.options.email,
<ide> appName : opt.options.appname,
<del> clientId : opt.options.clientId,
<del> clientSecret : opt.options.secret,
<del> apiProduct : opt.options.product
<del> };
<del>
<del> org.appcredentials.add(options, function(e, result){
<del> if (e) {
<del> common.logWrite(JSON.stringify(e, null, 2));
<del> common.logWrite(JSON.stringify(result, null, 2));
<del> //console.log(e.stack);
<del> process.exit(1);
<del> }
<del> //common.logWrite(sprintf('result %s', JSON.stringify(result)));
<del> common.logWrite(sprintf('new apikey %s', result.consumerKey));
<del> common.logWrite(sprintf('secret %s', result.consumerSecret));
<del> });
<del> }
<del> else {
<del> let options = {
<del> developerEmail : opt.options.email,
<del> appName : opt.options.appname,
<del> apiProduct : opt.options.product,
<add> apiProducts : opt.options.product.split(','),
<ide> expiry : opt.options.expiry
<ide> };
<ide>
<del> org.appcredentials.add(options, function(e, result){
<del> if (e) {
<del> common.logWrite(JSON.stringify(e, null, 2));
<del> common.logWrite(JSON.stringify(result, null, 2));
<del> //console.log(e.stack);
<del> process.exit(1);
<add> if (opt.options.clientId) {
<add> options.clientId = opt.options.clientId;
<add> options.clientSecret = opt.options.secret;
<add> if (opt.options.expiry) {
<add> common.logWrite('WARNING: expiry is not supported with an explicitly-supplied client id and secret');
<ide> }
<del> common.logWrite(sprintf('new apikey %s', result.credentials[0].consumerKey));
<del> common.logWrite(sprintf('secret %s', result.credentials[0].consumerSecret));
<del> });
<del> }
<del>});
<add> }
<add>
<add> return org.appcredentials.add(options)
<add> .then (result => {
<add> if (opt.options.clientId) {
<add> common.logWrite(sprintf('new apikey %s', result.consumerKey));
<add> common.logWrite(sprintf('secret %s', result.consumerSecret));
<add> }
<add> else {
<add> common.logWrite(sprintf('new apikey %s', result.credentials[0].consumerKey));
<add> common.logWrite(sprintf('secret %s', result.credentials[0].consumerSecret));
<add> }
<add> });
<add> })
<add> .catch( e => console.error('error: ' + util.format(e) ) ); |
|
Java | mit | 5d226952f0772cad92dca5f7695f92751875b43d | 0 | bertique/SonosNPROneServer | package me.michaeldick.sonosnpr;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.jws.WebService;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import javax.xml.soap.Detail;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPFault;
import javax.xml.ws.Holder;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.soap.SOAPFaultException;
import org.apache.cxf.headers.Header;
import org.apache.cxf.helpers.CastUtils;
import org.apache.cxf.jaxb.JAXBDataBinding;
import org.apache.cxf.jaxws.context.WrappedMessageContext;
import org.apache.cxf.message.Message;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Node;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mixpanel.mixpanelapi.ClientDelivery;
import com.mixpanel.mixpanelapi.MessageBuilder;
import com.mixpanel.mixpanelapi.MixpanelAPI;
import com.sonos.services._1.AbstractMedia;
import com.sonos.services._1.AddToContainerResult;
import com.sonos.services._1.AlbumArtUrl;
import com.sonos.services._1.AppLinkResult;
import com.sonos.services._1.ContentKey;
import com.sonos.services._1.CreateContainerResult;
import com.sonos.services._1.Credentials;
import com.sonos.services._1.DeleteContainerResult;
import com.sonos.services._1.DeviceAuthTokenResult;
import com.sonos.services._1.DeviceLinkCodeResult;
import com.sonos.services._1.DynamicData;
import com.sonos.services._1.EncryptionContext;
import com.sonos.services._1.ExtendedMetadata;
import com.sonos.services._1.GetExtendedMetadata;
import com.sonos.services._1.GetExtendedMetadataResponse;
import com.sonos.services._1.GetExtendedMetadataText;
import com.sonos.services._1.GetExtendedMetadataTextResponse;
import com.sonos.services._1.GetMediaMetadata;
import com.sonos.services._1.GetMediaMetadataResponse;
import com.sonos.services._1.GetMetadata;
import com.sonos.services._1.GetMetadataResponse;
import com.sonos.services._1.GetSessionId;
import com.sonos.services._1.GetSessionIdResponse;
import com.sonos.services._1.HttpHeaders;
import com.sonos.services._1.ItemRating;
import com.sonos.services._1.ItemType;
import com.sonos.services._1.LastUpdate;
import com.sonos.services._1.LoginToken;
import com.sonos.services._1.MediaCollection;
import com.sonos.services._1.MediaList;
import com.sonos.services._1.MediaMetadata;
import com.sonos.services._1.MediaUriAction;
import com.sonos.services._1.PositionInformation;
import com.sonos.services._1.Property;
import com.sonos.services._1.RateItem;
import com.sonos.services._1.RateItemResponse;
import com.sonos.services._1.RemoveFromContainerResult;
import com.sonos.services._1.RenameContainerResult;
import com.sonos.services._1.ReorderContainerResult;
import com.sonos.services._1.ReportPlaySecondsResult;
import com.sonos.services._1.Search;
import com.sonos.services._1.SearchResponse;
import com.sonos.services._1.SegmentMetadataList;
import com.sonos.services._1.TrackMetadata;
import com.sonos.services._1.UserInfo;
import com.sonos.services._1_1.CustomFault;
import com.sonos.services._1_1.SonosSoap;
import me.michaeldick.npr.model.Channel;
import me.michaeldick.npr.model.Media;
import me.michaeldick.npr.model.NprAuth;
import me.michaeldick.npr.model.Rating;
import me.michaeldick.npr.model.RatingsList;
@WebService
public class SonosService implements SonosSoap {
public static String NPR_CLIENT_ID = "";
public static String NPR_CLIENT_SECRET = "";
public static String MIXPANEL_PROJECT_TOKEN = "";
public static final String PROGRAM = "program";
public static final String DEFAULT = "default";
public static final String HISTORY = "history";
public static final String PODCAST = "podcasts";
public static final String AGGREGATION = "aggregation";
public static final String MUSIC = "music";
public static final String SESSIONIDTOKEN = "###";
// Error codes
public static final String SESSION_INVALID = "Client.SessionIdInvalid";
public static final String LOGIN_INVALID = "Client.LoginInvalid";
public static final String SERVICE_UNKNOWN_ERROR = "Client.ServiceUnknownError";
public static final String SERVICE_UNAVAILABLE = "Client.ServiceUnavailable";
public static final String ITEM_NOT_FOUND = "Client.ItemNotFound";
public static final String AUTH_TOKEN_EXPIRED = "Client.AuthTokenExpired";
public static final String NOT_LINKED_RETRY = "Client.NOT_LINKED_RETRY";
public static final String NOT_LINKED_FAILURE = "Client.NOT_LINKED_FAILURE";
public static final String PLAYSTATUS_SKIPPED = "skippedTrack";
private static final String RATING_ISINTERESTING = "isliked";
//private static final String IDENTITY_API_URI_DEFAULT = "https://identity.api.npr.org/v2/user";
private static final String LISTENING_API_URI_DEFAULT = "https://listening.api.npr.org/v2";
private static final String DEVICE_LINK_URI_DEFAULT = "https://authorization.api.npr.org/v2/device";
private static final String DEVICE_TOKEN_URI_DEFAULT = "https://authorization.api.npr.org/v2/token";
//private static String IDENTITY_API_URI;
private static String LISTENING_API_URI;
private static String DEVICE_LINK_URI;
private static String DEVICE_TOKEN_URI;
private static boolean isDebug = false;
private static int NUMBER_OF_STORIES_PER_CALL = 3;
private static Cache<String, Media> ListeningResponseCache;
private static Cache<String, List<Rating>> RatingCache;
private static Cache<String, List<AbstractMedia>> LastResponseToPlayer;
// Disable severe log message for SoapFault
private static java.util.logging.Logger COM_ROOT_LOGGER = java.util.logging.Logger.getLogger("com.sun.xml.internal.messaging.saaj.soap.ver1_1");
private static Logger logger = Logger.getLogger(SonosService.class.getSimpleName());
private static MessageBuilder messageBuilder;
@Resource
private WebServiceContext context;
public WebServiceContext getContext() {
return this.context;
}
public SonosService(Properties conf) {
//IDENTITY_API_URI = conf.getProperty("IDENTITY_API_URI", IDENTITY_API_URI_DEFAULT);
LISTENING_API_URI = conf.getProperty("LISTENING_API_URI", LISTENING_API_URI_DEFAULT);
DEVICE_LINK_URI = conf.getProperty("DEVICE_LINK_URI", DEVICE_LINK_URI_DEFAULT);
DEVICE_TOKEN_URI = conf.getProperty("DEVICE_TOKEN_URI", DEVICE_TOKEN_URI_DEFAULT);
isDebug = Boolean.parseBoolean(conf.getProperty("SETDEBUG", "false"));
NPR_CLIENT_ID = conf.getProperty("NPR_CLIENT_ID", System.getenv("NPR_CLIENT_ID"));
NPR_CLIENT_SECRET = conf.getProperty("NPR_CLIENT_SECRET", System.getenv("NPR_CLIENT_SECRET"));
MIXPANEL_PROJECT_TOKEN = conf.getProperty("MIXPANEL_PROJECT_TOKEN", System.getenv("MIXPANEL_PROJECT_TOKEN"));
initializeCaches();
initializeMetrics();
COM_ROOT_LOGGER.setLevel(java.util.logging.Level.OFF);
}
public SonosService () {
//IDENTITY_API_URI = IDENTITY_API_URI_DEFAULT;
LISTENING_API_URI = LISTENING_API_URI_DEFAULT;
DEVICE_LINK_URI = DEVICE_LINK_URI_DEFAULT;
DEVICE_TOKEN_URI = DEVICE_TOKEN_URI_DEFAULT;
MIXPANEL_PROJECT_TOKEN = System.getenv("MIXPANEL_PROJECT_TOKEN");
NPR_CLIENT_ID = System.getenv("NPR_CLIENT_ID");
NPR_CLIENT_SECRET = System.getenv("NPR_CLIENT_SECRET");
initializeCaches();
initializeMetrics();
COM_ROOT_LOGGER.setLevel(java.util.logging.Level.OFF);
}
private void initializeCaches() {
ListeningResponseCache = CacheBuilder.newBuilder()
.maximumSize(600)
.expireAfterWrite(20, TimeUnit.MINUTES).build();
RatingCache = CacheBuilder.newBuilder()
.maximumSize(600)
.expireAfterWrite(20, TimeUnit.MINUTES).build();
LastResponseToPlayer = CacheBuilder.newBuilder()
.maximumSize(600)
.expireAfterWrite(20, TimeUnit.MINUTES).build();
}
public void initializeMetrics() {
messageBuilder = new MessageBuilder(MIXPANEL_PROJECT_TOKEN);
}
@Override
public String getScrollIndices(String id) throws CustomFault {
logger.debug("getScrollIndices id:"+id);
// TODO Auto-generated method stub
return null;
}
@Override
public AddToContainerResult addToContainer(String id, String parentId,
int index, String updateId) throws CustomFault {
logger.debug("addToContainer");
// TODO Auto-generated method stub
return null;
}
@Override
public GetExtendedMetadataResponse getExtendedMetadata(
GetExtendedMetadata parameters) throws CustomFault {
logger.debug("getExtendedMetadata id:"+parameters.getId());
NprAuth auth = getNprAuth();
GetExtendedMetadataResponse response = new GetExtendedMetadataResponse();
Media m = ListeningResponseCache.getIfPresent(auth.getUserId()+parameters.getId());
if (m != null) {
logger.debug("ListeningResponseCache hit");
MediaMetadata mmd = buildMMD(m);
ExtendedMetadata resultWrapper = new ExtendedMetadata();
MediaMetadata result = new MediaMetadata();
result.setId(mmd.getId());
result.setItemType(mmd.getItemType());
result.setTrackMetadata(mmd.getTrackMetadata());
result.setMimeType(mmd.getMimeType());
result.setTitle(mmd.getTitle());
result.setDynamic(mmd.getDynamic());
resultWrapper.setMediaMetadata(result);
response.setGetExtendedMetadataResult(resultWrapper);
return response;
}
throwSoapFault(ITEM_NOT_FOUND);
return null;
}
@Override
public ReportPlaySecondsResult reportPlaySeconds(String id, int seconds, String contextId, String privateData,
Integer offsetMillis) throws CustomFault {
logger.debug("reportPlaySeconds id:"+id+" seconds:"+seconds);
if(seconds <= 1) {
NprAuth auth = getNprAuth();
List<Rating> ratingList = RatingCache.getIfPresent(auth.getUserId());
if(ratingList == null) {
logger.debug("ratingList is empty");
ratingList = new ArrayList<Rating>();
} else {
logger.debug("ratingList cache hit");
for(Rating r : ratingList) {
if(r.getRating().equals(RatingsList.START)) {
logger.debug("rating set to completed");
r.setRating(RatingsList.COMPLETED);
}
}
}
Media media = ListeningResponseCache.getIfPresent(auth.getUserId()+id);
if(media != null) {
Media m = media;
logger.debug("media cache hit");
m.getRating().setRating(RatingsList.START);
ratingList.add(new Rating(m.getRating()));
List<Rating> list = new ArrayList<Rating>();
list.add(new Rating(m.getRating()));
RatingCache.put(auth.getUserId(), list);
sendRecommendations(ratingList, m.getRecommendationLink(), auth);
}
}
ReportPlaySecondsResult result = new ReportPlaySecondsResult();
result.setInterval(0);
return result;
}
@Override
public void reportStatus(String id, int errorCode, String message)
throws CustomFault {
logger.debug("reportStatus");
// TODO Auto-generated method stub
}
@Override
public RateItemResponse rateItem(RateItem parameters) throws CustomFault {
logger.debug("rateItem id:"+parameters.getId()+" rating:"+parameters.getRating());
NprAuth auth = getNprAuth();
List<Rating> list = RatingCache.getIfPresent(auth.getUserId());
if(list != null) {
logger.debug("RatingCache hit");
boolean alreadyThumbed = false;
for(Rating r : list) {
if(r.getMediaId().equals(parameters.getId()) && r.getRating().equals(RatingsList.THUMBUP)) {
alreadyThumbed = true;
}
}
if (!alreadyThumbed) {
for(Rating r : list) {
if(r.getMediaId().equals(parameters.getId())) {
logger.debug("Setting rating");
Rating rnew = new Rating(r);
rnew.setRating(RatingsList.THUMBUP);
list.add(rnew);
RatingCache.put(auth.getUserId(), list);
Gson gson = new GsonBuilder().create();
logger.debug("Rating cache:"+gson.toJson(list));
break;
}
}
}
}
Media media = ListeningResponseCache.getIfPresent(auth.getUserId()+parameters.getId());
if(media != null) {
Media ratedItem = media;
ratedItem.getRating().setRating(RatingsList.THUMBUP);
ListeningResponseCache.put(auth.getUserId()+parameters.getId(), media);
}
ItemRating rating = new ItemRating();
rating.setShouldSkip(false);
RateItemResponse response = new RateItemResponse();
response.setRateItemResult(rating);
return response;
}
@Override
public void reportAccountAction(String type) throws CustomFault {
logger.debug("reportAccountAction");
// TODO Auto-generated method stub
}
@Override
public GetExtendedMetadataTextResponse getExtendedMetadataText(
GetExtendedMetadataText parameters) throws CustomFault {
logger.debug("getExtendedMetadataText id:"+parameters.getId());
// TODO Auto-generated method stub
return null;
}
@Override
public RenameContainerResult renameContainer(String id, String title)
throws CustomFault {
logger.debug("renameContainer");
// TODO Auto-generated method stub
return null;
}
@Override
public void setPlayedSeconds(String id, int seconds, String contextId, String privateData, Integer offsetMillis)
throws CustomFault {
logger.debug("setPlayedSeconds id:"+id+" sec:"+seconds);
NprAuth auth = getNprAuth();
List<Rating> list = RatingCache.getIfPresent(auth.getUserId());
if(list != null) {
logger.debug("RatingCache hit");
for(Rating r : list) {
if(r.getMediaId().equals(id)) {
logger.debug("Setting seconds");
r.setElapsed(seconds);
RatingCache.put(auth.getUserId(), list);
break;
}
}
}
ListeningResponseCache.invalidate(auth.getUserId()+id);
}
@Override
public LastUpdate getLastUpdate() throws CustomFault {
logger.debug("getLastUpdate");
NprAuth auth = getNprAuth();
LastUpdate response = new LastUpdate();
List<Rating> list = RatingCache.getIfPresent(auth.getUserId());
if(list != null)
response.setFavorites(Integer.toString(list.hashCode()));
else
response.setFavorites("1");
response.setCatalog("currentCatalog");
logger.debug("Fav: "+response.getFavorites()+" Cat: "+response.getCatalog());
return response;
}
@Override
public DeviceLinkCodeResult getDeviceLinkCode(String householdId)
throws CustomFault {
logger.debug("getDeviceLinkCode");
JSONObject sentEvent = messageBuilder.event(householdId, "getDeviceLinkCode", null);
ClientDelivery delivery = new ClientDelivery();
delivery.addMessage(sentEvent);
MixpanelAPI mixpanel = new MixpanelAPI();
try {
mixpanel.deliver(delivery);
} catch (IOException e1) {
// TODO Auto-generated catch block
logger.debug("Mixpanel error: getDeviceLinkCode");
}
Form form = new Form();
form.param("client_id", NPR_CLIENT_ID);
form.param("client_secret", NPR_CLIENT_SECRET);
form.param("scope", "identity.readonly "+
"identity.write " +
"listening.readonly " +
"listening.write " +
"localactivation");
String json = "";
try {
Client client = ClientBuilder.newClient();
json = client.target(DEVICE_LINK_URI)
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.form(form), String.class);
client.close();
} catch (NotAuthorizedException e) {
logger.info(householdId.hashCode() +": login NotAuthorized");
logger.debug(householdId.hashCode() +": "+e.getMessage());
throwSoapFault(LOGIN_INVALID);
} catch (BadRequestException e) {
logger.error("Bad request: "+e.getMessage());
logger.error(e.getResponse().readEntity(String.class));
throwSoapFault(SERVICE_UNKNOWN_ERROR);
}
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(json);
String verification_uri = "";
String user_code = "";
String device_code = "";
if (element.isJsonObject()) {
JsonObject root = element.getAsJsonObject();
verification_uri = root.get("verification_uri").getAsString();
user_code = root.get("user_code").getAsString();
device_code = root.get("device_code").getAsString();
logger.info(householdId.hashCode() +": Got verification uri");
}
DeviceLinkCodeResult response = new DeviceLinkCodeResult();
response.setLinkCode(user_code);
response.setRegUrl(verification_uri);
response.setLinkDeviceId(device_code);
response.setShowLinkCode(true);
return response;
}
@Override
public void deleteItem(String favorite) throws CustomFault {
logger.debug("deleteItem");
// TODO Auto-generated method stub
}
@Override
public DeviceAuthTokenResult getDeviceAuthToken(String householdId, String linkCode, String linkDeviceId,
String callbackPath) throws CustomFault {
logger.debug("getDeviceAuthToken");
Form form = new Form();
form.param("client_id", NPR_CLIENT_ID);
form.param("client_secret", NPR_CLIENT_SECRET);
form.param("code", linkDeviceId);
form.param("grant_type", "device_code");
String json = "";
try {
Client client = ClientBuilder.newClient();
json = client.target(DEVICE_TOKEN_URI)
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class);
client.close();
} catch (NotAuthorizedException e) {
logger.info(householdId.hashCode() +": Not linked retry");
logger.debug(householdId.hashCode() +": "+e.getMessage());
logger.debug(householdId.hashCode() +": Detailed response: "+e.getResponse().readEntity(String.class));
throwSoapFault(NOT_LINKED_RETRY, "NOT_LINKED_RETRY", "5");
} catch (BadRequestException e) {
logger.error("Bad request: "+e.getMessage());
throwSoapFault(NOT_LINKED_FAILURE, "NOT_LINKED_FAILURE", "6");
}
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(json);
String access_token = "";
if (element.isJsonObject()) {
JsonObject root = element.getAsJsonObject();
access_token = root.get("access_token").getAsString();
logger.info(householdId.hashCode() +": Got token");
}
JSONObject sentEvent = messageBuilder.event(householdId, "getDeviceAuthToken", null);
ClientDelivery delivery = new ClientDelivery();
delivery.addMessage(sentEvent);
MixpanelAPI mixpanel = new MixpanelAPI();
try {
mixpanel.deliver(delivery);
} catch (IOException e1) {
// TODO Auto-generated catch block
logger.debug("Mixpanel error: getDeviceLinkCode");
}
DeviceAuthTokenResult response = new DeviceAuthTokenResult();
response.setAuthToken(access_token);
response.setPrivateKey("KEY");
return response;
}
@Override
public CreateContainerResult createContainer(String containerType,
String title, String parentId, String seedId) throws CustomFault {
logger.debug("createContainer");
// TODO Auto-generated method stub
return null;
}
@Override
public ReorderContainerResult reorderContainer(String id, String from,
int to, String updateId) throws CustomFault {
logger.debug("reorderContainer");
// TODO Auto-generated method stub
return null;
}
@Override
public SegmentMetadataList getStreamingMetadata(String id,
XMLGregorianCalendar startTime, int duration) throws CustomFault {
logger.debug("getStreamingMetadata");
// TODO Auto-generated method stub
return null;
}
@Override
public void getMediaURI(String id, MediaUriAction action, Integer secondsSinceExplicit,
Holder<String> deviceSessionToken, Holder<String> getMediaURIResult,
Holder<EncryptionContext> deviceSessionKey, Holder<EncryptionContext> contentKey,
Holder<HttpHeaders> httpHeaders, Holder<Integer> uriTimeout,
Holder<PositionInformation> positionInformation, Holder<String> privateDataFieldName) throws CustomFault {
logger.debug("getMediaURI id:"+id);
NprAuth auth = getNprAuth();
Media m = ListeningResponseCache.getIfPresent(auth.getUserId()+id);
if(m != null) {
if(m.getAudioLink() != null) {
getMediaURIResult.value = m.getAudioLink();
} else {
logger.debug("Item not found");
throwSoapFault(ITEM_NOT_FOUND);
}
} else {
logger.debug("MediaURICache miss");
throwSoapFault(ITEM_NOT_FOUND);
}
}
@Override
public GetMediaMetadataResponse getMediaMetadata(GetMediaMetadata parameters)
throws CustomFault {
logger.debug("getMediaMetadata id:"+parameters.getId());
NprAuth auth = getNprAuth();
GetMediaMetadataResponse response = new GetMediaMetadataResponse();
Media m = ListeningResponseCache.getIfPresent(auth.getUserId()+parameters.getId());
if (m != null) {
logger.debug("ListeningResponseCache hit");
MediaMetadata mmd = buildMMD(m);
response.setGetMediaMetadataResult(mmd);
return response;
}
throwSoapFault(ITEM_NOT_FOUND);
return null;
}
@Override
public GetMetadataResponse getMetadata(GetMetadata parameters)
throws CustomFault {
logger.debug("getMetadata id:"+parameters.getId()+" count:"+parameters.getCount()+" index:"+parameters.getIndex());
NprAuth auth = getNprAuth();
// Mixpanel event
if(parameters.getId().equals(SonosService.PROGRAM+":"+SonosService.DEFAULT)
|| parameters.getId().equals(SonosService.PROGRAM+":"+SonosService.HISTORY)
|| parameters.getId().equals(SonosService.PROGRAM+":"+SonosService.MUSIC)
|| parameters.getId().equals(ItemType.SEARCH.value())) {
try {
JSONObject props = new JSONObject();
props.put("Program", parameters.getId());
JSONObject sentEvent = messageBuilder.event(auth.getUserId(), "getMetadata", props);
ClientDelivery delivery = new ClientDelivery();
delivery.addMessage(sentEvent);
MixpanelAPI mixpanel = new MixpanelAPI();
mixpanel.deliver(delivery);
} catch (IOException | JSONException e1) {
// TODO Auto-generated catch block
logger.debug("Mixpanel error: getMetadata");
}
}
GetMetadataResponse response = new GetMetadataResponse();
if(parameters.getId().equals("root")) {
response.setGetMetadataResult(getChannels(auth));
} else if(parameters.getId().startsWith(SonosService.PROGRAM+":"+SonosService.DEFAULT) && parameters.getCount() > 0) {
response.setGetMetadataResult(getProgram(auth));
} else if(parameters.getId().startsWith(SonosService.PROGRAM+":"+SonosService.HISTORY)) {
response.setGetMetadataResult(getHistory(auth));
} else if(parameters.getId().equals(SonosService.PROGRAM+":"+SonosService.MUSIC)) {
response.setGetMetadataResult(getMusicPrograms());
} else if(parameters.getId().startsWith(SonosService.PROGRAM)) {
response.setGetMetadataResult(getChannel(auth, parameters.getId().replaceAll(SonosService.PROGRAM+":", "")));
} else if(parameters.getId().startsWith(SonosService.PODCAST)) {
MediaList ml = getProgram(auth);
Media m = ListeningResponseCache.getIfPresent(auth.getUserId()+parameters.getId().replaceAll(SonosService.PODCAST+":", ""));
if (m != null) {
ml.getMediaCollectionOrMediaMetadata().add(0, buildMMD(m));
ml.setCount(ml.getCount()+1);
ml.setTotal(ml.getTotal()+1);
}
response.setGetMetadataResult(ml);
} else if(parameters.getId().startsWith(SonosService.AGGREGATION)) {
response.setGetMetadataResult(getAggregation(parameters.getId().replaceAll(SonosService.AGGREGATION+":",""), auth));
} else if(parameters.getId().equals(ItemType.SEARCH.value())) {
MediaList ml = new MediaList();
List<AbstractMedia> mcList = ml.getMediaCollectionOrMediaMetadata();
MediaCollection mc1 = new MediaCollection();
mc1.setTitle("Podcasts");
mc1.setId(SonosService.PODCAST);
mc1.setItemType(ItemType.SEARCH);
mcList.add(mc1);
ml.setCount(mcList.size());
ml.setTotal(mcList.size());
ml.setIndex(0);
response.setGetMetadataResult(ml);
} else {
return null;
}
String logLine = auth.getUserId().hashCode() + ": Got Metadata for "+parameters.getId()+", "+response.getGetMetadataResult().getCount();
logLine += " (";
for(AbstractMedia m : response.getGetMetadataResult().getMediaCollectionOrMediaMetadata()) {
logLine += m.getId().substring(m.getId().length() - 2) + " ";
}
logLine += ")";
logger.info(logLine);
return response;
}
private MediaList getChannels(NprAuth auth) {
String json = nprApiGetRequest("channels", "exploreOnly", "true", auth);
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(json);
JsonArray mainResultList = element.getAsJsonObject().getAsJsonArray("items");
MediaList ml = new MediaList();
List<AbstractMedia> mcList = ml.getMediaCollectionOrMediaMetadata();
MediaCollection mc1 = new MediaCollection();
mc1.setTitle("Play NPR One");
mc1.setId(SonosService.PROGRAM+":"+SonosService.DEFAULT);
mc1.setItemType(ItemType.PROGRAM);
mc1.setCanPlay(true);
mc1.setCanEnumerate(true);
mcList.add(mc1);
if (mainResultList != null) {
for (int i = 0; i < mainResultList.size(); i++) {
Channel c = new Channel(mainResultList.get(i).getAsJsonObject());
if(!c.getId().equals("promo") && !c.getId().equals("deepdives")) {
MediaCollection mc = new MediaCollection();
mc.setTitle(c.getFullName());
mc.setId(SonosService.PROGRAM+":"+c.getId());
mc.setItemType(ItemType.COLLECTION);
mc.setCanPlay(false);
mc.setCanEnumerate(true);
mcList.add(mc);
}
}
}
// NPR Music fake node
MediaCollection mc = new MediaCollection();
mc.setTitle("NPR Music");
mc.setId(SonosService.PROGRAM+":"+SonosService.MUSIC);
mc.setItemType(ItemType.COLLECTION);
mc.setCanPlay(false);
mc.setCanEnumerate(true);
mcList.add(mc);
ml.setCount(mcList.size());
ml.setIndex(0);
ml.setTotal(mcList.size());
logger.debug("Got program list: "+mcList.size());
return ml;
}
private MediaList getMusicPrograms() {
MediaList ml = new MediaList();
List<AbstractMedia> mcList = ml.getMediaCollectionOrMediaMetadata();
class nprMusicProgram {
String title;
String id;
String logoUrl;
nprMusicProgram(String t, String i, String l) {
title = t;
id = i;
logoUrl = l;
}
}
List<nprMusicProgram> programs = new ArrayList<nprMusicProgram>();
programs.add(new nprMusicProgram("First Listen", "98679384", null));
programs.add(new nprMusicProgram("All Songs Considered", "510019", "https://media.npr.org/images/podcasts/primary/icon_510019-045e9424ceb1fd4f5ae73df269de73b8094cd25e.jpg?s=600"));
programs.add(new nprMusicProgram("Songs We Love", "122356178", null));
programs.add(new nprMusicProgram("Tiny Desk", "510306","https://media.npr.org/images/podcasts/primary/icon_510306_sq-e07b7d616c85f470d3f723646c10bdfe42b845c2-s400-c85.jpg?s=600"));
programs.add(new nprMusicProgram("Alt.Latino", "192684845","https://media.npr.org/assets/img/2015/03/19/altlatino_sq-1d6a428fce03069afa0ff73c0f8e83aa6075e23f.jpg?s=600"));
programs.add(new nprMusicProgram("From The Top", "510026","https://media.npr.org/images/podcasts/primary/icon_510026-f866286349b685887d938edddea04dd710d21f6d-s400-c85.jpg?s=600"));
programs.add(new nprMusicProgram("Jazz Night In America", "347174538", null));
programs.add(new nprMusicProgram("Metropolis", "216842113", null));
programs.add(new nprMusicProgram("Mountain Stage", "382110109","https://media.npr.org/images/podcasts/primary/icon_382110109-a093242f6974f77af440828c4b538e41c9c1fe19.png?s=600"));
programs.add(new nprMusicProgram("Piano Jazz", "15773266","https://media.npr.org/images/podcasts/primary/icon_510056-98c2e1a249277d0d7c5343b2f2f0d7c487007ef4.jpg?s=600"));
programs.add(new nprMusicProgram("Song Travels", "150560513","https://media.npr.org/images/podcasts/primary/icon_510304-c565bd4967b2c06e2191eb0b6282ed4551dbf536.jpg?s=600"));
programs.add(new nprMusicProgram("The Thistle & Shamrock", "510069", null));
//programs.add(new nprMusicProgram("World Cafe", ""));
for(nprMusicProgram entry : programs) {
MediaCollection mc = new MediaCollection();
mc.setTitle(entry.title);
mc.setId(SonosService.AGGREGATION+":"+entry.id);
mc.setItemType(ItemType.COLLECTION);
mc.setCanPlay(false);
mc.setCanEnumerate(true);
if(entry.logoUrl != null) {
AlbumArtUrl url = new AlbumArtUrl();
url.setValue(entry.logoUrl);
mc.setAlbumArtURI(url);
}
mcList.add(mc);
}
ml.setCount(mcList.size());
ml.setIndex(0);
ml.setTotal(mcList.size());
logger.debug("Got music programs: "+mcList.size());
return ml;
}
// No longer used after switch to oauth
@Override
public GetSessionIdResponse getSessionId(GetSessionId parameters)
throws CustomFault {
logger.error("getSessionId (deprecated)");
throwSoapFault(AUTH_TOKEN_EXPIRED);
return null;
// if(parameters.getUsername().equals("") || parameters.getPassword().equals(""))
// throwSoapFault(LOGIN_INVALID);
//
// logger.debug("Attempting login");
// String authParameter = "{\"username\":\""+parameters.getUsername()+"\",\"password\":\""+parameters.getPassword()+"\"}";
// byte[] encodedAuth = Base64.encodeBase64(authParameter.getBytes());
// Form form = new Form();
// form.param("auth", new String(encodedAuth));
//
// String json = "";
// try {
// Client client = ClientBuilder.newClient();
// json = client.target(IDENTITY_API_URI)
// .request(MediaType.APPLICATION_JSON_TYPE)
// .post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class);
// client.close();
// } catch (NotAuthorizedException e) {
// logger.debug("login NotAuthorized: "+e.getMessage());
// throwSoapFault(LOGIN_INVALID);
// }
//
// JsonParser parser = new JsonParser();
// JsonElement element = parser.parse(json);
// String auth_token = "";
// String userId = "";
// if (element.isJsonObject()) {
// JsonObject root = element.getAsJsonObject();
// JsonObject data = root.getAsJsonObject("data");
// auth_token = data.get("auth_token").getAsString();
// userId = data.getAsJsonObject("user").get("id").getAsString();
// logger.debug("Login successful for: "+userId);
// }
//
// GetSessionIdResponse response = new GetSessionIdResponse();
// response.setGetSessionIdResult(userId+"###"+auth_token);
// return response;
}
@Override
public ContentKey getContentKey(String id, String uri, String deviceSessionToken) throws CustomFault {
// TODO Auto-generated method stub
return null;
}
@Override
public RemoveFromContainerResult removeFromContainer(String id,
String indices, String updateId) throws CustomFault {
logger.debug("removeFromContainer");
// TODO Auto-generated method stub
return null;
}
@Override
public DeleteContainerResult deleteContainer(String id) throws CustomFault {
logger.debug("deleteContainer");
// TODO Auto-generated method stub
return null;
}
@Override
public void reportPlayStatus(String id, String status, String contextId, Integer offsetMillis) throws CustomFault {
logger.debug("reportPlayStatus");
NprAuth auth = getNprAuth();
if(status.equals(PLAYSTATUS_SKIPPED)) {
logger.debug("PlayStatus is skipped");
List<Rating> list = RatingCache.getIfPresent(auth.getUserId());
if(list != null) {
logger.debug("Cache hit");
for(Rating r : list) {
if(r.getMediaId().equals(id)) {
r.setRating(RatingsList.SKIP);
RatingCache.put(auth.getUserId(), list);
logger.debug("Rating set");
break;
}
}
}
ListeningResponseCache.invalidate(auth.getUserId()+id);
}
}
@Override
public String createItem(String favorite) throws CustomFault {
logger.debug("createItem favorite:"+favorite);
// TODO Auto-generated method stub
return null;
}
@Override
public SearchResponse search(Search parameters) throws CustomFault {
logger.debug("search");
if(parameters.getTerm() == null || parameters.getTerm().length() < 4)
{
SearchResponse response = new SearchResponse();
response.setSearchResult(new MediaList());
return response;
}
NprAuth auth = getNprAuth();
String json = nprApiGetRequest("search/recommendations", "searchTerms", parameters.getTerm(), auth);
SearchResponse response = new SearchResponse();
response.setSearchResult(parseMediaListResponse(auth.getUserId(), json));
return response;
}
@Override
public AppLinkResult getAppLink(String householdId, String hardware, String osVersion, String sonosAppName,
String callbackPath) throws CustomFault {
// TODO Auto-generated method stub
return null;
}
@Override
public UserInfo getUserInfo() throws CustomFault {
// TODO Auto-generated method stub
return null;
}
// Private methods
private static MediaList getProgram(NprAuth auth) {
MediaList ml = new MediaList();
List<AbstractMedia> mcList = ml.getMediaCollectionOrMediaMetadata();
String json = nprApiGetRequest("recommendations", "channel", "npr", auth);
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(json);
JsonArray searchResultList = element.getAsJsonObject().getAsJsonArray("items");
List<AbstractMedia> lastProgramCall = LastResponseToPlayer.getIfPresent(auth.getUserId());
if (searchResultList == null)
return new MediaList();
LinkedList<String> newPlayQueue = new LinkedList<String>();
for (int i = 0; i < searchResultList.size(); i++) {
Media m = new Media(searchResultList.get(i).getAsJsonObject());
MediaMetadata mmd = buildMMD(m);
if(mmd != null) {
if(mcList.size() < NUMBER_OF_STORIES_PER_CALL) {
boolean wasInLastCall = false;
if(lastProgramCall != null) {
for(AbstractMedia ele : lastProgramCall) {
if(ele.getId().equals(mmd.getId())) {
wasInLastCall = true;
break;
}
}
}
if(!wasInLastCall)
mcList.add(mmd);
}
newPlayQueue.add(mmd.getId());
logger.debug("adding track id: "+mmd.getId());
ListeningResponseCache.put(auth.getUserId()+mmd.getId(), m);
}
}
ml.setCount(mcList.size());
ml.setIndex(0);
ml.setTotal(mcList.size());
logger.debug("Got program list: "+mcList.size());
LastResponseToPlayer.put(auth.getUserId(), mcList);
return ml;
}
private static String nprApiGetRequest(String path, String queryParamName, String queryParam, NprAuth auth) {
String json = "";
try {
Client client = ClientBuilder.newClient();
WebTarget target = client
.target(LISTENING_API_URI)
.path(path);
if(queryParamName != null && queryParam != null) {
target = target.queryParam(queryParamName, queryParam);
}
json = target.request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Bearer " + auth.getAuth())
.get(String.class);
client.close();
} catch (NotAuthorizedException e) {
logger.debug("request NotAuthorized: "+e.getMessage());
throwSoapFault(AUTH_TOKEN_EXPIRED);
} catch (BadRequestException e) {
logger.error("Bad request: "+e.getMessage());
logger.error(e.getResponse().readEntity(String.class));
}
return json;
}
private static MediaList getChannel(NprAuth auth, String channel) {
String json = nprApiGetRequest("recommendations", "channel", channel, auth);
return parseMediaListResponse(auth.getUserId(), json);
}
private static MediaList getHistory(NprAuth auth) {
String json = nprApiGetRequest("history", null, null, auth);
return parseMediaListResponse(auth.getUserId(), json);
}
private static MediaList parseMediaListResponse(String userId, String json) {
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(json);
JsonArray mainResultList = element.getAsJsonObject().getAsJsonArray("items");
if (mainResultList != null) {
MediaList ml = new MediaList();
List<AbstractMedia> mcList = ml.getMediaCollectionOrMediaMetadata();
for (int i = 0; i < mainResultList.size(); i++) {
Media m = new Media(mainResultList.get(i).getAsJsonObject());
if(m.getType()==Media.AggregationDocumentType.aggregation) {
mcList.add(buildMC(m));
} else {
MediaMetadata mmd = buildMMD(m);
// Trying to avoid duplicates here
if(mmd != null) {
boolean doesExist = false;
for(AbstractMedia cachedM : mcList)
{
if(cachedM.getId().equals(mmd.getId())) {
doesExist = true;
break;
}
}
if(!doesExist) {
mcList.add(buildMC(m));
logger.debug("adding track id: "+mmd.getId());
ListeningResponseCache.put(userId+mmd.getId(), m);
} else {
logger.debug("tracking existing in cache: "+mmd.getId());
}
}
}
}
ml.setCount(mcList.size());
ml.setIndex(0);
ml.setTotal(mcList.size());
logger.debug("Got program list: "+mcList.size());
return ml;
} else {
return new MediaList();
}
}
private static MediaList getAggregation(String id, NprAuth auth) {
String json = nprApiGetRequest("aggregation/"+id+"/recommendations", "startNum", "0", auth);
return parseMediaListResponse(auth.getUserId(), json);
}
public static void main(String[] args) {
Form form = new Form();
form.param("client_id", NPR_CLIENT_ID);
form.param("client_secret", NPR_CLIENT_SECRET);
form.param("scope", "identity.readonly "+
"identity.write " +
"listening.readonly " +
"listening.write " +
"localactivation");
String json = "";
try {
Client client = ClientBuilder.newClient();
json = client.target(DEVICE_LINK_URI)
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.form(form), String.class);
client.close();
} catch (NotAuthorizedException e) {
logger.debug("login NotAuthorized: "+e.getMessage());
} catch (BadRequestException e) {
logger.error("Bad request: "+e.getMessage());
logger.error(e.getResponse().readEntity(String.class));
}
System.out.println(json);
}
private static void sendRecommendations(List<Rating> ratingsToSend, String uri, NprAuth auth) {
if(ratingsToSend != null)
{
logger.debug("sendRecommendations "+ratingsToSend.size()+" to "+uri);
Gson gson = new GsonBuilder().create();
String jsonOutput = gson.toJson(ratingsToSend);
logger.debug("sending :"+jsonOutput);
Client client = ClientBuilder.newClient();
client.target(uri)
.request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Bearer "+ auth.getAuth())
.post(Entity.json(jsonOutput), String.class);
client.close();
}
}
private static MediaCollection buildMC(Media m) {
MediaCollection mc = new MediaCollection();
if(m.getType().equals(Media.AggregationDocumentType.audio)) {
Media audio = m;
mc.setId(SonosService.PODCAST+":"+audio.getUid());
mc.setItemType(ItemType.PROGRAM);
mc.setTitle(audio.getTitle());
mc.setArtist(audio.getProgram());
mc.setCanPlay(true);
mc.setCanEnumerate(true);
if(audio.getImageLinkSquare() != null) {
logger.debug("Album art found");
String albumArtUrlString = audio.getImageLinkSquare();
if(albumArtUrlString != null) {
AlbumArtUrl albumArtUrl = new AlbumArtUrl();
albumArtUrl.setValue(albumArtUrlString);
mc.setAlbumArtURI(albumArtUrl);
}
}
} else if(m.getType().equals(Media.AggregationDocumentType.aggregation)) {
Media agg = m;
mc.setId(SonosService.AGGREGATION+":"+agg.getAffiliationId());
mc.setItemType(ItemType.COLLECTION);
mc.setTitle(agg.getTitle());
mc.setCanPlay(false);
mc.setCanEnumerate(true);
if(agg.getImageLinkLogoSquare() != null) {
logger.debug("Album art found");
String albumArtUrlString = agg.getImageLinkLogoSquare();
if(albumArtUrlString != null) {
AlbumArtUrl albumArtUrl = new AlbumArtUrl();
albumArtUrl.setValue(albumArtUrlString);
mc.setAlbumArtURI(albumArtUrl);
}
}
}
return mc;
}
private static MediaMetadata buildMMD(Media m) {
MediaMetadata mmd = new MediaMetadata();
TrackMetadata tmd = new TrackMetadata();
if(m==null)
return null;
mmd.setId(m.getUid());
if(m.getAudioLink() != null) {
// Just allowing mp3's for now
mmd.setMimeType("audio/mp3");
} else {
logger.debug("No audio links found");
return null;
}
mmd.setItemType(ItemType.TRACK);
mmd.setTitle(m.getTitle());
Property property = new Property();
property.setName(RATING_ISINTERESTING);
if(m.getRating().getRating().equals(RatingsList.THUMBUP)) {
property.setValue("1");
} else {
property.setValue("0");
}
DynamicData dynData = new DynamicData();
dynData.getProperty().add(property);
mmd.setDynamic(dynData);
tmd.setCanSkip(m.isSkippable());
tmd.setArtist(m.getProgram());
if(m.getImageLinkSquare() != null) {
logger.debug("Album art found");
String albumArtUrlString = m.getImageLinkSquare();
if(albumArtUrlString != null) {
AlbumArtUrl albumArtUrl = new AlbumArtUrl();
albumArtUrl.setValue(albumArtUrlString);
tmd.setAlbumArtURI(albumArtUrl);
}
}
tmd.setDuration(m.getDuration());
mmd.setTrackMetadata(tmd);
return mmd;
}
private static void throwSoapFault(String faultMessage) {
throwSoapFault(faultMessage, "", "");
}
private static void throwSoapFault(String faultMessage, String ExceptionDetail, String SonosError) throws RuntimeException {
SOAPFault soapFault;
try {
soapFault = SOAPFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL).createFault();
soapFault.setFaultString(faultMessage);
soapFault.setFaultCode(new QName(faultMessage));
if(!ExceptionDetail.isEmpty() && !SonosError.isEmpty()) {
Detail detail = soapFault.addDetail();
SOAPElement el1 = detail.addChildElement("ExceptionDetail");
el1.setValue(ExceptionDetail);
SOAPElement el = detail.addChildElement("SonosError");
el.setValue(SonosError);
}
} catch (Exception e2) {
throw new RuntimeException("Problem processing SOAP Fault on service-side." + e2.getMessage());
}
throw new SOAPFaultException(soapFault);
}
private NprAuth getNprAuth() {
Credentials creds = getCredentialsFromHeaders();
if(creds == null)
throwSoapFault(SESSION_INVALID);
logger.debug("Got userId from header:"+creds.getLoginToken().getHouseholdId());
return new NprAuth(creds.getLoginToken().getHouseholdId(), creds.getLoginToken().getToken());
}
private Credentials getCredentialsFromHeaders() {
if(isDebug) {
Credentials c = new Credentials();
LoginToken t = new LoginToken();
t.setHouseholdId("[thehouseholdid]");
t.setToken("[thetoken]");
c.setLoginToken(t);
return c;
}
if(context == null)
return null;
MessageContext messageContext = context.getMessageContext();
if (messageContext == null
|| !(messageContext instanceof WrappedMessageContext)) {
logger.error("Message context is null or not an instance of WrappedMessageContext.");
return null;
}
Message message = ((WrappedMessageContext) messageContext)
.getWrappedMessage();
List<Header> headers = CastUtils.cast((List<?>) message
.get(Header.HEADER_LIST));
if (headers != null) {
for (Header h : headers) {
Object o = h.getObject();
// Unwrap the node using JAXB
if (o instanceof Node) {
JAXBContext jaxbContext;
try {
jaxbContext = new JAXBDataBinding(Credentials.class)
.getContext();
Unmarshaller unmarshaller = jaxbContext
.createUnmarshaller();
o = unmarshaller.unmarshal((Node) o);
} catch (JAXBException e) {
// failed to get the credentials object from the headers
logger.error(
"JaxB error trying to unwrapp credentials", e);
}
}
if (o instanceof Credentials) {
return (Credentials) o;
} else {
logger.error("no Credentials object");
}
}
} else {
logger.error("no headers found");
}
return null;
}
@Override
public DeviceAuthTokenResult refreshAuthToken() throws CustomFault {
// TODO Auto-generated method stub
return null;
}
}
| src/main/java/me/michaeldick/sonosnpr/SonosService.java | package me.michaeldick.sonosnpr;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.jws.WebService;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import javax.xml.soap.Detail;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPFault;
import javax.xml.ws.Holder;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.soap.SOAPFaultException;
import org.apache.cxf.headers.Header;
import org.apache.cxf.helpers.CastUtils;
import org.apache.cxf.jaxb.JAXBDataBinding;
import org.apache.cxf.jaxws.context.WrappedMessageContext;
import org.apache.cxf.message.Message;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Node;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mixpanel.mixpanelapi.ClientDelivery;
import com.mixpanel.mixpanelapi.MessageBuilder;
import com.mixpanel.mixpanelapi.MixpanelAPI;
import com.sonos.services._1.AbstractMedia;
import com.sonos.services._1.AddToContainerResult;
import com.sonos.services._1.AlbumArtUrl;
import com.sonos.services._1.AppLinkResult;
import com.sonos.services._1.ContentKey;
import com.sonos.services._1.CreateContainerResult;
import com.sonos.services._1.Credentials;
import com.sonos.services._1.DeleteContainerResult;
import com.sonos.services._1.DeviceAuthTokenResult;
import com.sonos.services._1.DeviceLinkCodeResult;
import com.sonos.services._1.DynamicData;
import com.sonos.services._1.EncryptionContext;
import com.sonos.services._1.ExtendedMetadata;
import com.sonos.services._1.GetExtendedMetadata;
import com.sonos.services._1.GetExtendedMetadataResponse;
import com.sonos.services._1.GetExtendedMetadataText;
import com.sonos.services._1.GetExtendedMetadataTextResponse;
import com.sonos.services._1.GetMediaMetadata;
import com.sonos.services._1.GetMediaMetadataResponse;
import com.sonos.services._1.GetMetadata;
import com.sonos.services._1.GetMetadataResponse;
import com.sonos.services._1.GetSessionId;
import com.sonos.services._1.GetSessionIdResponse;
import com.sonos.services._1.HttpHeaders;
import com.sonos.services._1.ItemRating;
import com.sonos.services._1.ItemType;
import com.sonos.services._1.LastUpdate;
import com.sonos.services._1.LoginToken;
import com.sonos.services._1.MediaCollection;
import com.sonos.services._1.MediaList;
import com.sonos.services._1.MediaMetadata;
import com.sonos.services._1.MediaUriAction;
import com.sonos.services._1.PositionInformation;
import com.sonos.services._1.Property;
import com.sonos.services._1.RateItem;
import com.sonos.services._1.RateItemResponse;
import com.sonos.services._1.RemoveFromContainerResult;
import com.sonos.services._1.RenameContainerResult;
import com.sonos.services._1.ReorderContainerResult;
import com.sonos.services._1.ReportPlaySecondsResult;
import com.sonos.services._1.Search;
import com.sonos.services._1.SearchResponse;
import com.sonos.services._1.SegmentMetadataList;
import com.sonos.services._1.TrackMetadata;
import com.sonos.services._1.UserInfo;
import com.sonos.services._1_1.CustomFault;
import com.sonos.services._1_1.SonosSoap;
import me.michaeldick.npr.model.Channel;
import me.michaeldick.npr.model.Media;
import me.michaeldick.npr.model.NprAuth;
import me.michaeldick.npr.model.Rating;
import me.michaeldick.npr.model.RatingsList;
@WebService
public class SonosService implements SonosSoap {
public static String NPR_CLIENT_ID = "";
public static String NPR_CLIENT_SECRET = "";
public static String MIXPANEL_PROJECT_TOKEN = "";
public static final String PROGRAM = "program";
public static final String DEFAULT = "default";
public static final String HISTORY = "history";
public static final String PODCAST = "podcasts";
public static final String AGGREGATION = "aggregation";
public static final String MUSIC = "music";
public static final String SESSIONIDTOKEN = "###";
// Error codes
public static final String SESSION_INVALID = "Client.SessionIdInvalid";
public static final String LOGIN_INVALID = "Client.LoginInvalid";
public static final String SERVICE_UNKNOWN_ERROR = "Client.ServiceUnknownError";
public static final String SERVICE_UNAVAILABLE = "Client.ServiceUnavailable";
public static final String ITEM_NOT_FOUND = "Client.ItemNotFound";
public static final String AUTH_TOKEN_EXPIRED = "Client.AuthTokenExpired";
public static final String NOT_LINKED_RETRY = "Client.NOT_LINKED_RETRY";
public static final String NOT_LINKED_FAILURE = "Client.NOT_LINKED_FAILURE";
public static final String PLAYSTATUS_SKIPPED = "skippedTrack";
private static final String RATING_ISINTERESTING = "isliked";
//private static final String IDENTITY_API_URI_DEFAULT = "https://api.npr.org/identity/v2/user";
private static final String LISTENING_API_URI_DEFAULT = "https://api.npr.org/listening/v2";
private static final String DEVICE_LINK_URI_DEFAULT = "https://api.npr.org/authorization/v2/device";
private static final String DEVICE_TOKEN_URI_DEFAULT = "https://api.npr.org/authorization/v2/token";
//private static String IDENTITY_API_URI;
private static String LISTENING_API_URI;
private static String DEVICE_LINK_URI;
private static String DEVICE_TOKEN_URI;
private static boolean isDebug = false;
private static int NUMBER_OF_STORIES_PER_CALL = 3;
private static Cache<String, Media> ListeningResponseCache;
private static Cache<String, List<Rating>> RatingCache;
private static Cache<String, List<AbstractMedia>> LastResponseToPlayer;
// Disable severe log message for SoapFault
private static java.util.logging.Logger COM_ROOT_LOGGER = java.util.logging.Logger.getLogger("com.sun.xml.internal.messaging.saaj.soap.ver1_1");
private static Logger logger = Logger.getLogger(SonosService.class.getSimpleName());
private static MessageBuilder messageBuilder;
@Resource
private WebServiceContext context;
public WebServiceContext getContext() {
return this.context;
}
public SonosService(Properties conf) {
//IDENTITY_API_URI = conf.getProperty("IDENTITY_API_URI", IDENTITY_API_URI_DEFAULT);
LISTENING_API_URI = conf.getProperty("LISTENING_API_URI", LISTENING_API_URI_DEFAULT);
DEVICE_LINK_URI = conf.getProperty("DEVICE_LINK_URI", DEVICE_LINK_URI_DEFAULT);
DEVICE_TOKEN_URI = conf.getProperty("DEVICE_TOKEN_URI", DEVICE_TOKEN_URI_DEFAULT);
isDebug = Boolean.parseBoolean(conf.getProperty("SETDEBUG", "false"));
NPR_CLIENT_ID = conf.getProperty("NPR_CLIENT_ID", System.getenv("NPR_CLIENT_ID"));
NPR_CLIENT_SECRET = conf.getProperty("NPR_CLIENT_SECRET", System.getenv("NPR_CLIENT_SECRET"));
MIXPANEL_PROJECT_TOKEN = conf.getProperty("MIXPANEL_PROJECT_TOKEN", System.getenv("MIXPANEL_PROJECT_TOKEN"));
initializeCaches();
initializeMetrics();
COM_ROOT_LOGGER.setLevel(java.util.logging.Level.OFF);
}
public SonosService () {
//IDENTITY_API_URI = IDENTITY_API_URI_DEFAULT;
LISTENING_API_URI = LISTENING_API_URI_DEFAULT;
DEVICE_LINK_URI = DEVICE_LINK_URI_DEFAULT;
DEVICE_TOKEN_URI = DEVICE_TOKEN_URI_DEFAULT;
MIXPANEL_PROJECT_TOKEN = System.getenv("MIXPANEL_PROJECT_TOKEN");
NPR_CLIENT_ID = System.getenv("NPR_CLIENT_ID");
NPR_CLIENT_SECRET = System.getenv("NPR_CLIENT_SECRET");
initializeCaches();
initializeMetrics();
COM_ROOT_LOGGER.setLevel(java.util.logging.Level.OFF);
}
private void initializeCaches() {
ListeningResponseCache = CacheBuilder.newBuilder()
.maximumSize(600)
.expireAfterWrite(20, TimeUnit.MINUTES).build();
RatingCache = CacheBuilder.newBuilder()
.maximumSize(600)
.expireAfterWrite(20, TimeUnit.MINUTES).build();
LastResponseToPlayer = CacheBuilder.newBuilder()
.maximumSize(600)
.expireAfterWrite(20, TimeUnit.MINUTES).build();
}
public void initializeMetrics() {
messageBuilder = new MessageBuilder(MIXPANEL_PROJECT_TOKEN);
}
@Override
public String getScrollIndices(String id) throws CustomFault {
logger.debug("getScrollIndices id:"+id);
// TODO Auto-generated method stub
return null;
}
@Override
public AddToContainerResult addToContainer(String id, String parentId,
int index, String updateId) throws CustomFault {
logger.debug("addToContainer");
// TODO Auto-generated method stub
return null;
}
@Override
public GetExtendedMetadataResponse getExtendedMetadata(
GetExtendedMetadata parameters) throws CustomFault {
logger.debug("getExtendedMetadata id:"+parameters.getId());
NprAuth auth = getNprAuth();
GetExtendedMetadataResponse response = new GetExtendedMetadataResponse();
Media m = ListeningResponseCache.getIfPresent(auth.getUserId()+parameters.getId());
if (m != null) {
logger.debug("ListeningResponseCache hit");
MediaMetadata mmd = buildMMD(m);
ExtendedMetadata resultWrapper = new ExtendedMetadata();
MediaMetadata result = new MediaMetadata();
result.setId(mmd.getId());
result.setItemType(mmd.getItemType());
result.setTrackMetadata(mmd.getTrackMetadata());
result.setMimeType(mmd.getMimeType());
result.setTitle(mmd.getTitle());
result.setDynamic(mmd.getDynamic());
resultWrapper.setMediaMetadata(result);
response.setGetExtendedMetadataResult(resultWrapper);
return response;
}
throwSoapFault(ITEM_NOT_FOUND);
return null;
}
@Override
public ReportPlaySecondsResult reportPlaySeconds(String id, int seconds, String contextId, String privateData,
Integer offsetMillis) throws CustomFault {
logger.debug("reportPlaySeconds id:"+id+" seconds:"+seconds);
if(seconds <= 1) {
NprAuth auth = getNprAuth();
List<Rating> ratingList = RatingCache.getIfPresent(auth.getUserId());
if(ratingList == null) {
logger.debug("ratingList is empty");
ratingList = new ArrayList<Rating>();
} else {
logger.debug("ratingList cache hit");
for(Rating r : ratingList) {
if(r.getRating().equals(RatingsList.START)) {
logger.debug("rating set to completed");
r.setRating(RatingsList.COMPLETED);
}
}
}
Media media = ListeningResponseCache.getIfPresent(auth.getUserId()+id);
if(media != null) {
Media m = media;
logger.debug("media cache hit");
m.getRating().setRating(RatingsList.START);
ratingList.add(new Rating(m.getRating()));
List<Rating> list = new ArrayList<Rating>();
list.add(new Rating(m.getRating()));
RatingCache.put(auth.getUserId(), list);
sendRecommendations(ratingList, m.getRecommendationLink(), auth);
}
}
ReportPlaySecondsResult result = new ReportPlaySecondsResult();
result.setInterval(0);
return result;
}
@Override
public void reportStatus(String id, int errorCode, String message)
throws CustomFault {
logger.debug("reportStatus");
// TODO Auto-generated method stub
}
@Override
public RateItemResponse rateItem(RateItem parameters) throws CustomFault {
logger.debug("rateItem id:"+parameters.getId()+" rating:"+parameters.getRating());
NprAuth auth = getNprAuth();
List<Rating> list = RatingCache.getIfPresent(auth.getUserId());
if(list != null) {
logger.debug("RatingCache hit");
boolean alreadyThumbed = false;
for(Rating r : list) {
if(r.getMediaId().equals(parameters.getId()) && r.getRating().equals(RatingsList.THUMBUP)) {
alreadyThumbed = true;
}
}
if (!alreadyThumbed) {
for(Rating r : list) {
if(r.getMediaId().equals(parameters.getId())) {
logger.debug("Setting rating");
Rating rnew = new Rating(r);
rnew.setRating(RatingsList.THUMBUP);
list.add(rnew);
RatingCache.put(auth.getUserId(), list);
Gson gson = new GsonBuilder().create();
logger.debug("Rating cache:"+gson.toJson(list));
break;
}
}
}
}
Media media = ListeningResponseCache.getIfPresent(auth.getUserId()+parameters.getId());
if(media != null) {
Media ratedItem = media;
ratedItem.getRating().setRating(RatingsList.THUMBUP);
ListeningResponseCache.put(auth.getUserId()+parameters.getId(), media);
}
ItemRating rating = new ItemRating();
rating.setShouldSkip(false);
RateItemResponse response = new RateItemResponse();
response.setRateItemResult(rating);
return response;
}
@Override
public void reportAccountAction(String type) throws CustomFault {
logger.debug("reportAccountAction");
// TODO Auto-generated method stub
}
@Override
public GetExtendedMetadataTextResponse getExtendedMetadataText(
GetExtendedMetadataText parameters) throws CustomFault {
logger.debug("getExtendedMetadataText id:"+parameters.getId());
// TODO Auto-generated method stub
return null;
}
@Override
public RenameContainerResult renameContainer(String id, String title)
throws CustomFault {
logger.debug("renameContainer");
// TODO Auto-generated method stub
return null;
}
@Override
public void setPlayedSeconds(String id, int seconds, String contextId, String privateData, Integer offsetMillis)
throws CustomFault {
logger.debug("setPlayedSeconds id:"+id+" sec:"+seconds);
NprAuth auth = getNprAuth();
List<Rating> list = RatingCache.getIfPresent(auth.getUserId());
if(list != null) {
logger.debug("RatingCache hit");
for(Rating r : list) {
if(r.getMediaId().equals(id)) {
logger.debug("Setting seconds");
r.setElapsed(seconds);
RatingCache.put(auth.getUserId(), list);
break;
}
}
}
ListeningResponseCache.invalidate(auth.getUserId()+id);
}
@Override
public LastUpdate getLastUpdate() throws CustomFault {
logger.debug("getLastUpdate");
NprAuth auth = getNprAuth();
LastUpdate response = new LastUpdate();
List<Rating> list = RatingCache.getIfPresent(auth.getUserId());
if(list != null)
response.setFavorites(Integer.toString(list.hashCode()));
else
response.setFavorites("1");
response.setCatalog("currentCatalog");
logger.debug("Fav: "+response.getFavorites()+" Cat: "+response.getCatalog());
return response;
}
@Override
public DeviceLinkCodeResult getDeviceLinkCode(String householdId)
throws CustomFault {
logger.debug("getDeviceLinkCode");
JSONObject sentEvent = messageBuilder.event(householdId, "getDeviceLinkCode", null);
ClientDelivery delivery = new ClientDelivery();
delivery.addMessage(sentEvent);
MixpanelAPI mixpanel = new MixpanelAPI();
try {
mixpanel.deliver(delivery);
} catch (IOException e1) {
// TODO Auto-generated catch block
logger.debug("Mixpanel error: getDeviceLinkCode");
}
Form form = new Form();
form.param("client_id", NPR_CLIENT_ID);
form.param("client_secret", NPR_CLIENT_SECRET);
form.param("scope", "identity.readonly "+
"identity.write " +
"listening.readonly " +
"listening.write " +
"localactivation");
String json = "";
try {
Client client = ClientBuilder.newClient();
json = client.target(DEVICE_LINK_URI)
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.form(form), String.class);
client.close();
} catch (NotAuthorizedException e) {
logger.info(householdId.hashCode() +": login NotAuthorized");
logger.debug(householdId.hashCode() +": "+e.getMessage());
throwSoapFault(LOGIN_INVALID);
} catch (BadRequestException e) {
logger.error("Bad request: "+e.getMessage());
logger.error(e.getResponse().readEntity(String.class));
throwSoapFault(SERVICE_UNKNOWN_ERROR);
}
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(json);
String verification_uri = "";
String user_code = "";
String device_code = "";
if (element.isJsonObject()) {
JsonObject root = element.getAsJsonObject();
verification_uri = root.get("verification_uri").getAsString();
user_code = root.get("user_code").getAsString();
device_code = root.get("device_code").getAsString();
logger.info(householdId.hashCode() +": Got verification uri");
}
DeviceLinkCodeResult response = new DeviceLinkCodeResult();
response.setLinkCode(user_code);
response.setRegUrl(verification_uri);
response.setLinkDeviceId(device_code);
response.setShowLinkCode(true);
return response;
}
@Override
public void deleteItem(String favorite) throws CustomFault {
logger.debug("deleteItem");
// TODO Auto-generated method stub
}
@Override
public DeviceAuthTokenResult getDeviceAuthToken(String householdId, String linkCode, String linkDeviceId,
String callbackPath) throws CustomFault {
logger.debug("getDeviceAuthToken");
Form form = new Form();
form.param("client_id", NPR_CLIENT_ID);
form.param("client_secret", NPR_CLIENT_SECRET);
form.param("code", linkDeviceId);
form.param("grant_type", "device_code");
String json = "";
try {
Client client = ClientBuilder.newClient();
json = client.target(DEVICE_TOKEN_URI)
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class);
client.close();
} catch (NotAuthorizedException e) {
logger.info(householdId.hashCode() +": Not linked retry");
logger.debug(householdId.hashCode() +": "+e.getMessage());
logger.debug(householdId.hashCode() +": Detailed response: "+e.getResponse().readEntity(String.class));
throwSoapFault(NOT_LINKED_RETRY, "NOT_LINKED_RETRY", "5");
} catch (BadRequestException e) {
logger.error("Bad request: "+e.getMessage());
throwSoapFault(NOT_LINKED_FAILURE, "NOT_LINKED_FAILURE", "6");
}
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(json);
String access_token = "";
if (element.isJsonObject()) {
JsonObject root = element.getAsJsonObject();
access_token = root.get("access_token").getAsString();
logger.info(householdId.hashCode() +": Got token");
}
JSONObject sentEvent = messageBuilder.event(householdId, "getDeviceAuthToken", null);
ClientDelivery delivery = new ClientDelivery();
delivery.addMessage(sentEvent);
MixpanelAPI mixpanel = new MixpanelAPI();
try {
mixpanel.deliver(delivery);
} catch (IOException e1) {
// TODO Auto-generated catch block
logger.debug("Mixpanel error: getDeviceLinkCode");
}
DeviceAuthTokenResult response = new DeviceAuthTokenResult();
response.setAuthToken(access_token);
response.setPrivateKey("KEY");
return response;
}
@Override
public CreateContainerResult createContainer(String containerType,
String title, String parentId, String seedId) throws CustomFault {
logger.debug("createContainer");
// TODO Auto-generated method stub
return null;
}
@Override
public ReorderContainerResult reorderContainer(String id, String from,
int to, String updateId) throws CustomFault {
logger.debug("reorderContainer");
// TODO Auto-generated method stub
return null;
}
@Override
public SegmentMetadataList getStreamingMetadata(String id,
XMLGregorianCalendar startTime, int duration) throws CustomFault {
logger.debug("getStreamingMetadata");
// TODO Auto-generated method stub
return null;
}
@Override
public void getMediaURI(String id, MediaUriAction action, Integer secondsSinceExplicit,
Holder<String> deviceSessionToken, Holder<String> getMediaURIResult,
Holder<EncryptionContext> deviceSessionKey, Holder<EncryptionContext> contentKey,
Holder<HttpHeaders> httpHeaders, Holder<Integer> uriTimeout,
Holder<PositionInformation> positionInformation, Holder<String> privateDataFieldName) throws CustomFault {
logger.debug("getMediaURI id:"+id);
NprAuth auth = getNprAuth();
Media m = ListeningResponseCache.getIfPresent(auth.getUserId()+id);
if(m != null) {
if(m.getAudioLink() != null) {
getMediaURIResult.value = m.getAudioLink();
} else {
logger.debug("Item not found");
throwSoapFault(ITEM_NOT_FOUND);
}
} else {
logger.debug("MediaURICache miss");
throwSoapFault(ITEM_NOT_FOUND);
}
}
@Override
public GetMediaMetadataResponse getMediaMetadata(GetMediaMetadata parameters)
throws CustomFault {
logger.debug("getMediaMetadata id:"+parameters.getId());
NprAuth auth = getNprAuth();
GetMediaMetadataResponse response = new GetMediaMetadataResponse();
Media m = ListeningResponseCache.getIfPresent(auth.getUserId()+parameters.getId());
if (m != null) {
logger.debug("ListeningResponseCache hit");
MediaMetadata mmd = buildMMD(m);
response.setGetMediaMetadataResult(mmd);
return response;
}
throwSoapFault(ITEM_NOT_FOUND);
return null;
}
@Override
public GetMetadataResponse getMetadata(GetMetadata parameters)
throws CustomFault {
logger.debug("getMetadata id:"+parameters.getId()+" count:"+parameters.getCount()+" index:"+parameters.getIndex());
NprAuth auth = getNprAuth();
// Mixpanel event
if(parameters.getId().equals(SonosService.PROGRAM+":"+SonosService.DEFAULT)
|| parameters.getId().equals(SonosService.PROGRAM+":"+SonosService.HISTORY)
|| parameters.getId().equals(SonosService.PROGRAM+":"+SonosService.MUSIC)
|| parameters.getId().equals(ItemType.SEARCH.value())) {
try {
JSONObject props = new JSONObject();
props.put("Program", parameters.getId());
JSONObject sentEvent = messageBuilder.event(auth.getUserId(), "getMetadata", props);
ClientDelivery delivery = new ClientDelivery();
delivery.addMessage(sentEvent);
MixpanelAPI mixpanel = new MixpanelAPI();
mixpanel.deliver(delivery);
} catch (IOException | JSONException e1) {
// TODO Auto-generated catch block
logger.debug("Mixpanel error: getMetadata");
}
}
GetMetadataResponse response = new GetMetadataResponse();
if(parameters.getId().equals("root")) {
response.setGetMetadataResult(getChannels(auth));
} else if(parameters.getId().startsWith(SonosService.PROGRAM+":"+SonosService.DEFAULT) && parameters.getCount() > 0) {
response.setGetMetadataResult(getProgram(auth));
} else if(parameters.getId().startsWith(SonosService.PROGRAM+":"+SonosService.HISTORY)) {
response.setGetMetadataResult(getHistory(auth));
} else if(parameters.getId().equals(SonosService.PROGRAM+":"+SonosService.MUSIC)) {
response.setGetMetadataResult(getMusicPrograms());
} else if(parameters.getId().startsWith(SonosService.PROGRAM)) {
response.setGetMetadataResult(getChannel(auth, parameters.getId().replaceAll(SonosService.PROGRAM+":", "")));
} else if(parameters.getId().startsWith(SonosService.PODCAST)) {
MediaList ml = getProgram(auth);
Media m = ListeningResponseCache.getIfPresent(auth.getUserId()+parameters.getId().replaceAll(SonosService.PODCAST+":", ""));
if (m != null) {
ml.getMediaCollectionOrMediaMetadata().add(0, buildMMD(m));
ml.setCount(ml.getCount()+1);
ml.setTotal(ml.getTotal()+1);
}
response.setGetMetadataResult(ml);
} else if(parameters.getId().startsWith(SonosService.AGGREGATION)) {
response.setGetMetadataResult(getAggregation(parameters.getId().replaceAll(SonosService.AGGREGATION+":",""), auth));
} else if(parameters.getId().equals(ItemType.SEARCH.value())) {
MediaList ml = new MediaList();
List<AbstractMedia> mcList = ml.getMediaCollectionOrMediaMetadata();
MediaCollection mc1 = new MediaCollection();
mc1.setTitle("Podcasts");
mc1.setId(SonosService.PODCAST);
mc1.setItemType(ItemType.SEARCH);
mcList.add(mc1);
ml.setCount(mcList.size());
ml.setTotal(mcList.size());
ml.setIndex(0);
response.setGetMetadataResult(ml);
} else {
return null;
}
String logLine = auth.getUserId().hashCode() + ": Got Metadata for "+parameters.getId()+", "+response.getGetMetadataResult().getCount();
logLine += " (";
for(AbstractMedia m : response.getGetMetadataResult().getMediaCollectionOrMediaMetadata()) {
logLine += m.getId().substring(m.getId().length() - 2) + " ";
}
logLine += ")";
logger.info(logLine);
return response;
}
private MediaList getChannels(NprAuth auth) {
String json = nprApiGetRequest("channels", "exploreOnly", "true", auth);
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(json);
JsonArray mainResultList = element.getAsJsonObject().getAsJsonArray("items");
MediaList ml = new MediaList();
List<AbstractMedia> mcList = ml.getMediaCollectionOrMediaMetadata();
MediaCollection mc1 = new MediaCollection();
mc1.setTitle("Play NPR One");
mc1.setId(SonosService.PROGRAM+":"+SonosService.DEFAULT);
mc1.setItemType(ItemType.PROGRAM);
mc1.setCanPlay(true);
mc1.setCanEnumerate(true);
mcList.add(mc1);
if (mainResultList != null) {
for (int i = 0; i < mainResultList.size(); i++) {
Channel c = new Channel(mainResultList.get(i).getAsJsonObject());
if(!c.getId().equals("promo") && !c.getId().equals("deepdives")) {
MediaCollection mc = new MediaCollection();
mc.setTitle(c.getFullName());
mc.setId(SonosService.PROGRAM+":"+c.getId());
mc.setItemType(ItemType.COLLECTION);
mc.setCanPlay(false);
mc.setCanEnumerate(true);
mcList.add(mc);
}
}
}
// NPR Music fake node
MediaCollection mc = new MediaCollection();
mc.setTitle("NPR Music");
mc.setId(SonosService.PROGRAM+":"+SonosService.MUSIC);
mc.setItemType(ItemType.COLLECTION);
mc.setCanPlay(false);
mc.setCanEnumerate(true);
mcList.add(mc);
ml.setCount(mcList.size());
ml.setIndex(0);
ml.setTotal(mcList.size());
logger.debug("Got program list: "+mcList.size());
return ml;
}
private MediaList getMusicPrograms() {
MediaList ml = new MediaList();
List<AbstractMedia> mcList = ml.getMediaCollectionOrMediaMetadata();
class nprMusicProgram {
String title;
String id;
String logoUrl;
nprMusicProgram(String t, String i, String l) {
title = t;
id = i;
logoUrl = l;
}
}
List<nprMusicProgram> programs = new ArrayList<nprMusicProgram>();
programs.add(new nprMusicProgram("First Listen", "98679384", null));
programs.add(new nprMusicProgram("All Songs Considered", "510019", "https://media.npr.org/images/podcasts/primary/icon_510019-045e9424ceb1fd4f5ae73df269de73b8094cd25e.jpg?s=600"));
programs.add(new nprMusicProgram("Songs We Love", "122356178", null));
programs.add(new nprMusicProgram("Tiny Desk", "510306","https://media.npr.org/images/podcasts/primary/icon_510306_sq-e07b7d616c85f470d3f723646c10bdfe42b845c2-s400-c85.jpg?s=600"));
programs.add(new nprMusicProgram("Alt.Latino", "192684845","https://media.npr.org/assets/img/2015/03/19/altlatino_sq-1d6a428fce03069afa0ff73c0f8e83aa6075e23f.jpg?s=600"));
programs.add(new nprMusicProgram("From The Top", "510026","https://media.npr.org/images/podcasts/primary/icon_510026-f866286349b685887d938edddea04dd710d21f6d-s400-c85.jpg?s=600"));
programs.add(new nprMusicProgram("Jazz Night In America", "347174538", null));
programs.add(new nprMusicProgram("Metropolis", "216842113", null));
programs.add(new nprMusicProgram("Mountain Stage", "382110109","https://media.npr.org/images/podcasts/primary/icon_382110109-a093242f6974f77af440828c4b538e41c9c1fe19.png?s=600"));
programs.add(new nprMusicProgram("Piano Jazz", "15773266","https://media.npr.org/images/podcasts/primary/icon_510056-98c2e1a249277d0d7c5343b2f2f0d7c487007ef4.jpg?s=600"));
programs.add(new nprMusicProgram("Song Travels", "150560513","https://media.npr.org/images/podcasts/primary/icon_510304-c565bd4967b2c06e2191eb0b6282ed4551dbf536.jpg?s=600"));
programs.add(new nprMusicProgram("The Thistle & Shamrock", "510069", null));
//programs.add(new nprMusicProgram("World Cafe", ""));
for(nprMusicProgram entry : programs) {
MediaCollection mc = new MediaCollection();
mc.setTitle(entry.title);
mc.setId(SonosService.AGGREGATION+":"+entry.id);
mc.setItemType(ItemType.COLLECTION);
mc.setCanPlay(false);
mc.setCanEnumerate(true);
if(entry.logoUrl != null) {
AlbumArtUrl url = new AlbumArtUrl();
url.setValue(entry.logoUrl);
mc.setAlbumArtURI(url);
}
mcList.add(mc);
}
ml.setCount(mcList.size());
ml.setIndex(0);
ml.setTotal(mcList.size());
logger.debug("Got music programs: "+mcList.size());
return ml;
}
// No longer used after switch to oauth
@Override
public GetSessionIdResponse getSessionId(GetSessionId parameters)
throws CustomFault {
logger.error("getSessionId (deprecated)");
throwSoapFault(AUTH_TOKEN_EXPIRED);
return null;
// if(parameters.getUsername().equals("") || parameters.getPassword().equals(""))
// throwSoapFault(LOGIN_INVALID);
//
// logger.debug("Attempting login");
// String authParameter = "{\"username\":\""+parameters.getUsername()+"\",\"password\":\""+parameters.getPassword()+"\"}";
// byte[] encodedAuth = Base64.encodeBase64(authParameter.getBytes());
// Form form = new Form();
// form.param("auth", new String(encodedAuth));
//
// String json = "";
// try {
// Client client = ClientBuilder.newClient();
// json = client.target(IDENTITY_API_URI)
// .request(MediaType.APPLICATION_JSON_TYPE)
// .post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class);
// client.close();
// } catch (NotAuthorizedException e) {
// logger.debug("login NotAuthorized: "+e.getMessage());
// throwSoapFault(LOGIN_INVALID);
// }
//
// JsonParser parser = new JsonParser();
// JsonElement element = parser.parse(json);
// String auth_token = "";
// String userId = "";
// if (element.isJsonObject()) {
// JsonObject root = element.getAsJsonObject();
// JsonObject data = root.getAsJsonObject("data");
// auth_token = data.get("auth_token").getAsString();
// userId = data.getAsJsonObject("user").get("id").getAsString();
// logger.debug("Login successful for: "+userId);
// }
//
// GetSessionIdResponse response = new GetSessionIdResponse();
// response.setGetSessionIdResult(userId+"###"+auth_token);
// return response;
}
@Override
public ContentKey getContentKey(String id, String uri, String deviceSessionToken) throws CustomFault {
// TODO Auto-generated method stub
return null;
}
@Override
public RemoveFromContainerResult removeFromContainer(String id,
String indices, String updateId) throws CustomFault {
logger.debug("removeFromContainer");
// TODO Auto-generated method stub
return null;
}
@Override
public DeleteContainerResult deleteContainer(String id) throws CustomFault {
logger.debug("deleteContainer");
// TODO Auto-generated method stub
return null;
}
@Override
public void reportPlayStatus(String id, String status, String contextId, Integer offsetMillis) throws CustomFault {
logger.debug("reportPlayStatus");
NprAuth auth = getNprAuth();
if(status.equals(PLAYSTATUS_SKIPPED)) {
logger.debug("PlayStatus is skipped");
List<Rating> list = RatingCache.getIfPresent(auth.getUserId());
if(list != null) {
logger.debug("Cache hit");
for(Rating r : list) {
if(r.getMediaId().equals(id)) {
r.setRating(RatingsList.SKIP);
RatingCache.put(auth.getUserId(), list);
logger.debug("Rating set");
break;
}
}
}
ListeningResponseCache.invalidate(auth.getUserId()+id);
}
}
@Override
public String createItem(String favorite) throws CustomFault {
logger.debug("createItem favorite:"+favorite);
// TODO Auto-generated method stub
return null;
}
@Override
public SearchResponse search(Search parameters) throws CustomFault {
logger.debug("search");
if(parameters.getTerm() == null || parameters.getTerm().length() < 4)
{
SearchResponse response = new SearchResponse();
response.setSearchResult(new MediaList());
return response;
}
NprAuth auth = getNprAuth();
String json = nprApiGetRequest("search/recommendations", "searchTerms", parameters.getTerm(), auth);
SearchResponse response = new SearchResponse();
response.setSearchResult(parseMediaListResponse(auth.getUserId(), json));
return response;
}
@Override
public AppLinkResult getAppLink(String householdId, String hardware, String osVersion, String sonosAppName,
String callbackPath) throws CustomFault {
// TODO Auto-generated method stub
return null;
}
@Override
public UserInfo getUserInfo() throws CustomFault {
// TODO Auto-generated method stub
return null;
}
// Private methods
private static MediaList getProgram(NprAuth auth) {
MediaList ml = new MediaList();
List<AbstractMedia> mcList = ml.getMediaCollectionOrMediaMetadata();
String json = nprApiGetRequest("recommendations", "channel", "npr", auth);
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(json);
JsonArray searchResultList = element.getAsJsonObject().getAsJsonArray("items");
List<AbstractMedia> lastProgramCall = LastResponseToPlayer.getIfPresent(auth.getUserId());
if (searchResultList == null)
return new MediaList();
LinkedList<String> newPlayQueue = new LinkedList<String>();
for (int i = 0; i < searchResultList.size(); i++) {
Media m = new Media(searchResultList.get(i).getAsJsonObject());
MediaMetadata mmd = buildMMD(m);
if(mmd != null) {
if(mcList.size() < NUMBER_OF_STORIES_PER_CALL) {
boolean wasInLastCall = false;
if(lastProgramCall != null) {
for(AbstractMedia ele : lastProgramCall) {
if(ele.getId().equals(mmd.getId())) {
wasInLastCall = true;
break;
}
}
}
if(!wasInLastCall)
mcList.add(mmd);
}
newPlayQueue.add(mmd.getId());
logger.debug("adding track id: "+mmd.getId());
ListeningResponseCache.put(auth.getUserId()+mmd.getId(), m);
}
}
ml.setCount(mcList.size());
ml.setIndex(0);
ml.setTotal(mcList.size());
logger.debug("Got program list: "+mcList.size());
LastResponseToPlayer.put(auth.getUserId(), mcList);
return ml;
}
private static String nprApiGetRequest(String path, String queryParamName, String queryParam, NprAuth auth) {
String json = "";
try {
Client client = ClientBuilder.newClient();
WebTarget target = client
.target(LISTENING_API_URI)
.path(path);
if(queryParamName != null && queryParam != null) {
target = target.queryParam(queryParamName, queryParam);
}
json = target.request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Bearer " + auth.getAuth())
.get(String.class);
client.close();
} catch (NotAuthorizedException e) {
logger.debug("request NotAuthorized: "+e.getMessage());
throwSoapFault(AUTH_TOKEN_EXPIRED);
} catch (BadRequestException e) {
logger.error("Bad request: "+e.getMessage());
logger.error(e.getResponse().readEntity(String.class));
}
return json;
}
private static MediaList getChannel(NprAuth auth, String channel) {
String json = nprApiGetRequest("recommendations", "channel", channel, auth);
return parseMediaListResponse(auth.getUserId(), json);
}
private static MediaList getHistory(NprAuth auth) {
String json = nprApiGetRequest("history", null, null, auth);
return parseMediaListResponse(auth.getUserId(), json);
}
private static MediaList parseMediaListResponse(String userId, String json) {
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(json);
JsonArray mainResultList = element.getAsJsonObject().getAsJsonArray("items");
if (mainResultList != null) {
MediaList ml = new MediaList();
List<AbstractMedia> mcList = ml.getMediaCollectionOrMediaMetadata();
for (int i = 0; i < mainResultList.size(); i++) {
Media m = new Media(mainResultList.get(i).getAsJsonObject());
if(m.getType()==Media.AggregationDocumentType.aggregation) {
mcList.add(buildMC(m));
} else {
MediaMetadata mmd = buildMMD(m);
// Trying to avoid duplicates here
if(mmd != null) {
boolean doesExist = false;
for(AbstractMedia cachedM : mcList)
{
if(cachedM.getId().equals(mmd.getId())) {
doesExist = true;
break;
}
}
if(!doesExist) {
mcList.add(buildMC(m));
logger.debug("adding track id: "+mmd.getId());
ListeningResponseCache.put(userId+mmd.getId(), m);
} else {
logger.debug("tracking existing in cache: "+mmd.getId());
}
}
}
}
ml.setCount(mcList.size());
ml.setIndex(0);
ml.setTotal(mcList.size());
logger.debug("Got program list: "+mcList.size());
return ml;
} else {
return new MediaList();
}
}
private static MediaList getAggregation(String id, NprAuth auth) {
String json = nprApiGetRequest("aggregation/"+id+"/recommendations", "startNum", "0", auth);
return parseMediaListResponse(auth.getUserId(), json);
}
public static void main(String[] args) {
Form form = new Form();
form.param("client_id", NPR_CLIENT_ID);
form.param("client_secret", NPR_CLIENT_SECRET);
form.param("scope", "identity.readonly "+
"identity.write " +
"listening.readonly " +
"listening.write " +
"localactivation");
String json = "";
try {
Client client = ClientBuilder.newClient();
json = client.target(DEVICE_LINK_URI)
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.form(form), String.class);
client.close();
} catch (NotAuthorizedException e) {
logger.debug("login NotAuthorized: "+e.getMessage());
} catch (BadRequestException e) {
logger.error("Bad request: "+e.getMessage());
logger.error(e.getResponse().readEntity(String.class));
}
System.out.println(json);
}
private static void sendRecommendations(List<Rating> ratingsToSend, String uri, NprAuth auth) {
if(ratingsToSend != null)
{
logger.debug("sendRecommendations "+ratingsToSend.size()+" to "+uri);
Gson gson = new GsonBuilder().create();
String jsonOutput = gson.toJson(ratingsToSend);
logger.debug("sending :"+jsonOutput);
Client client = ClientBuilder.newClient();
client.target(uri)
.request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Bearer "+ auth.getAuth())
.post(Entity.json(jsonOutput), String.class);
client.close();
}
}
private static MediaCollection buildMC(Media m) {
MediaCollection mc = new MediaCollection();
if(m.getType().equals(Media.AggregationDocumentType.audio)) {
Media audio = m;
mc.setId(SonosService.PODCAST+":"+audio.getUid());
mc.setItemType(ItemType.PROGRAM);
mc.setTitle(audio.getTitle());
mc.setArtist(audio.getProgram());
mc.setCanPlay(true);
mc.setCanEnumerate(true);
if(audio.getImageLinkSquare() != null) {
logger.debug("Album art found");
String albumArtUrlString = audio.getImageLinkSquare();
if(albumArtUrlString != null) {
AlbumArtUrl albumArtUrl = new AlbumArtUrl();
albumArtUrl.setValue(albumArtUrlString);
mc.setAlbumArtURI(albumArtUrl);
}
}
} else if(m.getType().equals(Media.AggregationDocumentType.aggregation)) {
Media agg = m;
mc.setId(SonosService.AGGREGATION+":"+agg.getAffiliationId());
mc.setItemType(ItemType.COLLECTION);
mc.setTitle(agg.getTitle());
mc.setCanPlay(false);
mc.setCanEnumerate(true);
if(agg.getImageLinkLogoSquare() != null) {
logger.debug("Album art found");
String albumArtUrlString = agg.getImageLinkLogoSquare();
if(albumArtUrlString != null) {
AlbumArtUrl albumArtUrl = new AlbumArtUrl();
albumArtUrl.setValue(albumArtUrlString);
mc.setAlbumArtURI(albumArtUrl);
}
}
}
return mc;
}
private static MediaMetadata buildMMD(Media m) {
MediaMetadata mmd = new MediaMetadata();
TrackMetadata tmd = new TrackMetadata();
if(m==null)
return null;
mmd.setId(m.getUid());
if(m.getAudioLink() != null) {
// Just allowing mp3's for now
mmd.setMimeType("audio/mp3");
} else {
logger.debug("No audio links found");
return null;
}
mmd.setItemType(ItemType.TRACK);
mmd.setTitle(m.getTitle());
Property property = new Property();
property.setName(RATING_ISINTERESTING);
if(m.getRating().getRating().equals(RatingsList.THUMBUP)) {
property.setValue("1");
} else {
property.setValue("0");
}
DynamicData dynData = new DynamicData();
dynData.getProperty().add(property);
mmd.setDynamic(dynData);
tmd.setCanSkip(m.isSkippable());
tmd.setArtist(m.getProgram());
if(m.getImageLinkSquare() != null) {
logger.debug("Album art found");
String albumArtUrlString = m.getImageLinkSquare();
if(albumArtUrlString != null) {
AlbumArtUrl albumArtUrl = new AlbumArtUrl();
albumArtUrl.setValue(albumArtUrlString);
tmd.setAlbumArtURI(albumArtUrl);
}
}
tmd.setDuration(m.getDuration());
mmd.setTrackMetadata(tmd);
return mmd;
}
private static void throwSoapFault(String faultMessage) {
throwSoapFault(faultMessage, "", "");
}
private static void throwSoapFault(String faultMessage, String ExceptionDetail, String SonosError) throws RuntimeException {
SOAPFault soapFault;
try {
soapFault = SOAPFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL).createFault();
soapFault.setFaultString(faultMessage);
soapFault.setFaultCode(new QName(faultMessage));
if(!ExceptionDetail.isEmpty() && !SonosError.isEmpty()) {
Detail detail = soapFault.addDetail();
SOAPElement el1 = detail.addChildElement("ExceptionDetail");
el1.setValue(ExceptionDetail);
SOAPElement el = detail.addChildElement("SonosError");
el.setValue(SonosError);
}
} catch (Exception e2) {
throw new RuntimeException("Problem processing SOAP Fault on service-side." + e2.getMessage());
}
throw new SOAPFaultException(soapFault);
}
private NprAuth getNprAuth() {
Credentials creds = getCredentialsFromHeaders();
if(creds == null)
throwSoapFault(SESSION_INVALID);
logger.debug("Got userId from header:"+creds.getLoginToken().getHouseholdId());
return new NprAuth(creds.getLoginToken().getHouseholdId(), creds.getLoginToken().getToken());
}
private Credentials getCredentialsFromHeaders() {
if(isDebug) {
Credentials c = new Credentials();
LoginToken t = new LoginToken();
t.setHouseholdId("[thehouseholdid]");
t.setToken("[thetoken]");
c.setLoginToken(t);
return c;
}
if(context == null)
return null;
MessageContext messageContext = context.getMessageContext();
if (messageContext == null
|| !(messageContext instanceof WrappedMessageContext)) {
logger.error("Message context is null or not an instance of WrappedMessageContext.");
return null;
}
Message message = ((WrappedMessageContext) messageContext)
.getWrappedMessage();
List<Header> headers = CastUtils.cast((List<?>) message
.get(Header.HEADER_LIST));
if (headers != null) {
for (Header h : headers) {
Object o = h.getObject();
// Unwrap the node using JAXB
if (o instanceof Node) {
JAXBContext jaxbContext;
try {
jaxbContext = new JAXBDataBinding(Credentials.class)
.getContext();
Unmarshaller unmarshaller = jaxbContext
.createUnmarshaller();
o = unmarshaller.unmarshal((Node) o);
} catch (JAXBException e) {
// failed to get the credentials object from the headers
logger.error(
"JaxB error trying to unwrapp credentials", e);
}
}
if (o instanceof Credentials) {
return (Credentials) o;
} else {
logger.error("no Credentials object");
}
}
} else {
logger.error("no headers found");
}
return null;
}
@Override
public DeviceAuthTokenResult refreshAuthToken() throws CustomFault {
// TODO Auto-generated method stub
return null;
}
}
| Update NPR endpoints
| src/main/java/me/michaeldick/sonosnpr/SonosService.java | Update NPR endpoints | <ide><path>rc/main/java/me/michaeldick/sonosnpr/SonosService.java
<ide> public static final String PLAYSTATUS_SKIPPED = "skippedTrack";
<ide> private static final String RATING_ISINTERESTING = "isliked";
<ide>
<del> //private static final String IDENTITY_API_URI_DEFAULT = "https://api.npr.org/identity/v2/user";
<del> private static final String LISTENING_API_URI_DEFAULT = "https://api.npr.org/listening/v2";
<del> private static final String DEVICE_LINK_URI_DEFAULT = "https://api.npr.org/authorization/v2/device";
<del> private static final String DEVICE_TOKEN_URI_DEFAULT = "https://api.npr.org/authorization/v2/token";
<add> //private static final String IDENTITY_API_URI_DEFAULT = "https://identity.api.npr.org/v2/user";
<add> private static final String LISTENING_API_URI_DEFAULT = "https://listening.api.npr.org/v2";
<add> private static final String DEVICE_LINK_URI_DEFAULT = "https://authorization.api.npr.org/v2/device";
<add> private static final String DEVICE_TOKEN_URI_DEFAULT = "https://authorization.api.npr.org/v2/token";
<ide>
<ide> //private static String IDENTITY_API_URI;
<ide> private static String LISTENING_API_URI; |
|
Java | bsd-2-clause | d87cc91aa7115022ef701e8fd065c1aeb4852990 | 0 | scijava/scijava-common | /*
* #%L
* SciJava Common shared library for SciJava software.
* %%
* Copyright (C) 2009 - 2016 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package org.scijava.util;
// Portions of this class were adapted from the
// org.apache.commons.lang3.reflect.TypeUtils and
// org.apache.commons.lang3.Validate classes of
// Apache Commons Lang 3.4, which is distributed
// under the Apache 2 license.
// See lines below starting with "BEGIN FORK".
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.scijava.util.ConversionUtils;
import org.scijava.util.GenericUtils;
/**
* Utility class for working with generic types, fields and methods.
* <p>
* Logic and inspiration were drawn from the following excellent libraries:
* <ul>
* <li>Google Guava's {@code com.google.common.reflect} package.</li>
* <li>Apache Commons Lang 3's {@code org.apache.commons.lang3.reflect} package.
* </li>
* <li><a href="https://github.com/coekarts/gentyref">GenTyRef</a> (Generic Type
* Reflector), a library for runtime generic type introspection.</li>
* </ul>
* </p>
*
* @author Curtis Rueden
*/
public final class Types {
private Types() {
// NB: Prevent instantiation of utility class.
}
// TODO: Migrate all GenericUtils methods here.
/**
* Gets a string representation of the given type.
*
* @param t Type whose name is desired.
* @return The name of the given type.
*/
public static String name(final Type t) {
// NB: It is annoying that Class.toString() prepends "class " or
// "interface "; this method exists to work around that behavior.
return t instanceof Class ? ((Class<?>) t).getName() : t.toString();
}
/**
* Gets the (first) raw class of the given type.
* <ul>
* <li>If the type is a {@code Class} itself, the type itself is returned.
* </li>
* <li>If the type is a {@link ParameterizedType}, the raw type of the
* parameterized type is returned.</li>
* <li>If the type is a {@link GenericArrayType}, the returned type is the
* corresponding array class. For example: {@code List<Integer>[] => List[]}.
* </li>
* <li>If the type is a type variable or wildcard type, the raw type of the
* first upper bound is returned. For example:
* {@code <X extends Foo & Bar> => Foo}.</li>
* </ul>
* <p>
* If you want <em>all</em> raw classes of the given type, use {@link #raws}.
* </p>
* @param type The type from which to discern the (first) raw class.
* @return The type's first raw class.
*/
public static Class<?> raw(final Type type) {
// TODO: Consolidate with GenericUtils.
return GenericUtils.getClass(type);
}
/**
* Gets all raw classes corresponding to the given type.
* <p>
* For example, a type parameter {@code A extends Number & Iterable} will
* return both {@link Number} and {@link Iterable} as its raw classes.
* </p>
*
* @param type The type from which to discern the raw classes.
* @return List of the type's raw classes.
* @see #raw
*/
public static List<Class<?>> raws(final Type type) {
// TODO: Consolidate with GenericUtils.
return GenericUtils.getClasses(type);
}
public static Field field(final Class<?> c, final String name) {
if (c == null) throw new IllegalArgumentException("No such field: " + name);
try {
return c.getDeclaredField(name);
}
catch (final NoSuchFieldException e) {}
return field(c.getSuperclass(), name);
}
/**
* Discerns whether it would be legal to assign a reference of type
* {@code source} to a reference of type {@code target}.
*
* @param source The type from which assignment is desired.
* @param target The type to which assignment is desired.
* @return True if the source is assignable to the target.
* @throws NullPointerException if {@code target} is null.
* @see Class#isAssignableFrom(Class)
*/
public static boolean isAssignable(final Type source, final Type target) {
return TypeUtils.isAssignable(source, target);
}
/**
* Creates a new {@link ParameterizedType} of the given class together with
* the specified type arguments.
*
* @param rawType The class of the {@link ParameterizedType}.
* @param typeArgs The type arguments to use in parameterizing it.
* @return The newly created {@link ParameterizedType}.
*/
public static ParameterizedType newParameterizedType(final Class<?> rawType,
final Type... typeArgs)
{
return newParameterizedType(rawType, rawType.getDeclaringClass(), typeArgs);
}
/**
* Creates a new {@link ParameterizedType} of the given class together with
* the specified type arguments.
*
* @param rawType The class of the {@link ParameterizedType}.
* @param ownerType The owner type of the parameterized class.
* @param typeArgs The type arguments to use in parameterizing it.
* @return The newly created {@link ParameterizedType}.
*/
public static ParameterizedType newParameterizedType(final Class<?> rawType,
final Type ownerType, final Type... typeArgs)
{
return new TypeUtils.ParameterizedTypeImpl(rawType, ownerType, typeArgs);
}
/**
* Creates a new {@link WildcardType} with no upper or lower bounds (i.e.,
* {@code ?}).
*
* @return The newly created {@link WildcardType}.
*/
public static WildcardType newWildcardType() {
return newWildcardType(null, null);
}
/**
* Creates a new {@link WildcardType} with the given upper and/or lower bound.
*
* @param upperBound Upper bound of the wildcard, or null for none.
* @param lowerBound Lower bound of the wildcard, or null for none.
* @return The newly created {@link WildcardType}.
*/
public static WildcardType newWildcardType(final Type upperBound,
final Type lowerBound)
{
return new TypeUtils.WildcardTypeImpl(upperBound, lowerBound);
}
/**
* Learn, recursively, whether any of the type parameters associated with
* {@code type} are bound to variables.
*
* @param type the type to check for type variables
* @return boolean
*/
public static boolean containsTypeVars(final Type type) {
return TypeUtils.containsTypeVariables(type);
}
/**
* Gets the type arguments of a class/interface based on a subtype. For
* instance, this method will determine that both of the parameters for the
* interface {@link Map} are {@link Object} for the subtype
* {@link java.util.Properties Properties} even though the subtype does not
* directly implement the {@code Map} interface.
* <p>
* This method returns {@code null} if {@code type} is not assignable to
* {@code toClass}. It returns an empty map if none of the classes or
* interfaces in its inheritance hierarchy specify any type arguments.
* </p>
* <p>
* A side effect of this method is that it also retrieves the type arguments
* for the classes and interfaces that are part of the hierarchy between
* {@code type} and {@code toClass}. So with the above example, this method
* will also determine that the type arguments for {@link java.util.Hashtable
* Hashtable} are also both {@code Object}. In cases where the interface
* specified by {@code toClass} is (indirectly) implemented more than once
* (e.g. where {@code toClass} specifies the interface
* {@link java.lang.Iterable Iterable} and {@code type} specifies a
* parameterized type that implements both {@link java.util.Set Set} and
* {@link java.util.Collection Collection}), this method will look at the
* inheritance hierarchy of only one of the implementations/subclasses; the
* first interface encountered that isn't a subinterface to one of the others
* in the {@code type} to {@code toClass} hierarchy.
* </p>
*
* @param type the type from which to determine the type parameters of
* {@code toClass}
* @param toClass the class whose type parameters are to be determined based
* on the subtype {@code type}
* @return a {@code Map} of the type assignments for the type variables in
* each type in the inheritance hierarchy from {@code type} to
* {@code toClass} inclusive.
*/
public static Map<TypeVariable<?>, Type> args(final Type type,
final Class<?> toClass)
{
return TypeUtils.getTypeArguments(type, toClass);
}
/**
* Tries to determine the type arguments of a class/interface based on a super
* parameterized type's type arguments. This method is the inverse of
* {@link #args(Type, Class)} which gets a class/interface's type arguments
* based on a subtype. It is far more limited in determining the type
* arguments for the subject class's type variables in that it can only
* determine those parameters that map from the subject {@link Class} object
* to the supertype.
* <p>
* Example: {@link java.util.TreeSet TreeSet} sets its parameter as the
* parameter for {@link java.util.NavigableSet NavigableSet}, which in turn
* sets the parameter of {@link java.util.SortedSet}, which in turn sets the
* parameter of {@link Set}, which in turn sets the parameter of
* {@link java.util.Collection}, which in turn sets the parameter of
* {@link java.lang.Iterable}. Since {@code TreeSet}'s parameter maps
* (indirectly) to {@code Iterable}'s parameter, it will be able to determine
* that based on the super type {@code Iterable<? extends
* Map<Integer, ? extends Collection<?>>>}, the parameter of {@code TreeSet}
* is {@code ? extends Map<Integer, ? extends Collection<?>>}.
* </p>
*
* @param c the class whose type parameters are to be determined, not
* {@code null}
* @param superType the super type from which {@code c}'s type arguments are
* to be determined, not {@code null}
* @return a {@code Map} of the type assignments that could be determined for
* the type variables in each type in the inheritance hierarchy from
* {@code type} to {@code c} inclusive.
*/
public static Map<TypeVariable<?>, Type> args(final Class<?> c,
final ParameterizedType superType)
{
return TypeUtils.determineTypeArguments(c, superType);
}
/**
* Create a parameterized type instance.
*
* @param raw the raw class to create a parameterized type instance for
* @param typeArgMappings the mapping used for parameterization
* @return {@link ParameterizedType}
*/
public static final ParameterizedType parameterize(final Class<?> raw,
final Map<TypeVariable<?>, Type> typeArgMappings)
{
return TypeUtils.parameterize(raw, typeArgMappings);
}
// -- BEGIN FORK OF APACHE COMMONS LANG 3.4 CODE --
/*
* 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.
*/
/**
* <p>
* Utility methods focusing on type inspection, particularly with regard to
* generics.
* </p>
*
* @since 3.0
* @version $Id: TypeUtils.java 1606051 2014-06-27 12:22:17Z ggregory $
*/
@SuppressWarnings("unused")
private static class TypeUtils {
/**
* {@link WildcardType} builder.
*
* @since 3.2
*/
public static class WildcardTypeBuilder {
/**
* Constructor
*/
private WildcardTypeBuilder() {}
private Type[] upperBounds;
private Type[] lowerBounds;
/**
* Specify upper bounds of the wildcard type to build.
*
* @param bounds to set
* @return {@code this}
*/
public WildcardTypeBuilder withUpperBounds(final Type... bounds) {
this.upperBounds = bounds;
return this;
}
/**
* Specify lower bounds of the wildcard type to build.
*
* @param bounds to set
* @return {@code this}
*/
public WildcardTypeBuilder withLowerBounds(final Type... bounds) {
this.lowerBounds = bounds;
return this;
}
public WildcardType build() {
return new WildcardTypeImpl(upperBounds, lowerBounds);
}
}
/**
* GenericArrayType implementation class.
*
* @since 3.2
*/
private static final class GenericArrayTypeImpl implements
GenericArrayType
{
private final Type componentType;
/**
* Constructor
*
* @param componentType of this array type
*/
private GenericArrayTypeImpl(final Type componentType) {
this.componentType = componentType;
}
@Override
public Type getGenericComponentType() {
return componentType;
}
@Override
public String toString() {
return TypeUtils.toString(this);
}
@Override
public boolean equals(final Object obj) {
return obj == this || obj instanceof GenericArrayType && TypeUtils
.equals(this, (GenericArrayType) obj);
}
@Override
public int hashCode() {
int result = 67 << 4;
result |= componentType.hashCode();
return result;
}
}
/**
* ParameterizedType implementation class.
*
* @since 3.2
*/
private static final class ParameterizedTypeImpl implements
ParameterizedType
{
private final Class<?> raw;
private final Type useOwner;
private final Type[] typeArguments;
/**
* Constructor
*
* @param raw type
* @param useOwner owner type to use, if any
* @param typeArguments formal type arguments
*/
private ParameterizedTypeImpl(final Class<?> raw, final Type useOwner,
final Type[] typeArguments)
{
this.raw = raw;
this.useOwner = useOwner;
this.typeArguments = typeArguments;
}
@Override
public Type getRawType() {
return raw;
}
@Override
public Type getOwnerType() {
return useOwner;
}
@Override
public Type[] getActualTypeArguments() {
return typeArguments.clone();
}
@Override
public String toString() {
return TypeUtils.toString(this);
}
@Override
public boolean equals(final Object obj) {
return obj == this || obj instanceof ParameterizedType && TypeUtils
.equals(this, ((ParameterizedType) obj));
}
@Override
public int hashCode() {
int result = 71 << 4;
result |= raw.hashCode();
result <<= 4;
result |= Objects.hashCode(useOwner);
result <<= 8;
result |= Arrays.hashCode(typeArguments);
return result;
}
}
/**
* WildcardType implementation class.
*
* @since 3.2
*/
private static final class WildcardTypeImpl implements WildcardType {
private static final Type[] EMPTY_BOUNDS = new Type[0];
private final Type[] upperBounds;
private final Type[] lowerBounds;
/**
* Constructor
*
* @param upperBound of this type
* @param lowerBound of this type
*/
private WildcardTypeImpl(final Type upperBound, final Type lowerBound) {
this(upperBound == null ? null : new Type[] { upperBound },
lowerBound == null ? null : new Type[] { lowerBound });
}
/**
* Constructor
*
* @param upperBounds of this type
* @param lowerBounds of this type
*/
private WildcardTypeImpl(final Type[] upperBounds,
final Type[] lowerBounds)
{
this.upperBounds = upperBounds == null ? EMPTY_BOUNDS : upperBounds;
this.lowerBounds = lowerBounds == null ? EMPTY_BOUNDS : lowerBounds;
}
@Override
public Type[] getUpperBounds() {
return upperBounds.clone();
}
@Override
public Type[] getLowerBounds() {
return lowerBounds.clone();
}
@Override
public String toString() {
return TypeUtils.toString(this);
}
@Override
public boolean equals(final Object obj) {
return obj == this || obj instanceof WildcardType && TypeUtils.equals(
this, (WildcardType) obj);
}
@Override
public int hashCode() {
int result = 73 << 8;
result |= Arrays.hashCode(upperBounds);
result <<= 8;
result |= Arrays.hashCode(lowerBounds);
return result;
}
}
/**
* A wildcard instance matching {@code ?}.
*
* @since 3.2
*/
public static final WildcardType WILDCARD_ALL = //
wildcardType().withUpperBounds(Object.class).build();
/**
* <p>
* Checks if the subject type may be implicitly cast to the target type
* following the Java generics rules. If both types are {@link Class}
* objects, the method returns the result of
* {@link Class#isAssignableFrom(Class)}.
* </p>
*
* @param type the subject type to be assigned to the target type
* @param toType the target type
* @return {@code true} if {@code type} is assignable to {@code toType}.
*/
public static boolean isAssignable(final Type type, final Type toType) {
return isAssignable(type, toType, null);
}
/**
* <p>
* Checks if the subject type may be implicitly cast to the target type
* following the Java generics rules.
* </p>
*
* @param type the subject type to be assigned to the target type
* @param toType the target type
* @param typeVarAssigns optional map of type variable assignments
* @return {@code true} if {@code type} is assignable to {@code toType}.
*/
private static boolean isAssignable(final Type type, final Type toType,
final Map<TypeVariable<?>, Type> typeVarAssigns)
{
if (toType == null || toType instanceof Class) {
return isAssignable(type, (Class<?>) toType);
}
if (toType instanceof ParameterizedType) {
return isAssignable(type, (ParameterizedType) toType, typeVarAssigns);
}
if (toType instanceof GenericArrayType) {
return isAssignable(type, (GenericArrayType) toType, typeVarAssigns);
}
if (toType instanceof WildcardType) {
return isAssignable(type, (WildcardType) toType, typeVarAssigns);
}
if (toType instanceof TypeVariable) {
return isAssignable(type, (TypeVariable<?>) toType, typeVarAssigns);
}
throw new IllegalStateException("found an unhandled type: " + toType);
}
/**
* <p>
* Checks if the subject type may be implicitly cast to the target class
* following the Java generics rules.
* </p>
*
* @param type the subject type to be assigned to the target type
* @param toClass the target class
* @return {@code true} if {@code type} is assignable to {@code toClass}.
*/
private static boolean isAssignable(final Type type,
final Class<?> toClass)
{
if (type == null) {
// consistency with ClassUtils.isAssignable() behavior
return toClass == null || !toClass.isPrimitive();
}
// only a null type can be assigned to null type which
// would have cause the previous to return true
if (toClass == null) {
return false;
}
// all types are assignable to themselves
if (toClass.equals(type)) {
return true;
}
if (type instanceof Class) {
// just comparing two classes
return toClass.isAssignableFrom((Class<?>) type);
}
if (type instanceof ParameterizedType) {
// only have to compare the raw type to the class
return isAssignable(getRawType((ParameterizedType) type), toClass);
}
// *
if (type instanceof TypeVariable) {
// if any of the bounds are assignable to the class, then the
// type is assignable to the class.
for (final Type bound : ((TypeVariable<?>) type).getBounds()) {
if (isAssignable(bound, toClass)) {
return true;
}
}
return false;
}
// the only classes to which a generic array type can be assigned
// are class Object and array classes
if (type instanceof GenericArrayType) {
return toClass.equals(Object.class) || toClass.isArray() &&
isAssignable(((GenericArrayType) type).getGenericComponentType(),
toClass.getComponentType());
}
// wildcard types are not assignable to a class (though one would think
// "? super Object" would be assignable to Object)
if (type instanceof WildcardType) {
return false;
}
throw new IllegalStateException("found an unhandled type: " + type);
}
/**
* <p>
* Checks if the subject type may be implicitly cast to the target
* parameterized type following the Java generics rules.
* </p>
*
* @param type the subject type to be assigned to the target type
* @param toParameterizedType the target parameterized type
* @param typeVarAssigns a map with type variables
* @return {@code true} if {@code type} is assignable to {@code toType}.
*/
private static boolean isAssignable(final Type type,
final ParameterizedType toParameterizedType,
final Map<TypeVariable<?>, Type> typeVarAssigns)
{
if (type == null) {
return true;
}
// only a null type can be assigned to null type which
// would have cause the previous to return true
if (toParameterizedType == null) {
return false;
}
// all types are assignable to themselves
if (toParameterizedType.equals(type)) {
return true;
}
// get the target type's raw type
final Class<?> toClass = getRawType(toParameterizedType);
// get the subject type's type arguments including owner type arguments
// and supertype arguments up to and including the target class.
final Map<TypeVariable<?>, Type> fromTypeVarAssigns = getTypeArguments(
type, toClass, null);
// null means the two types are not compatible
if (fromTypeVarAssigns == null) {
return false;
}
// compatible types, but there's no type arguments. this is equivalent
// to comparing Map< ?, ? > to Map, and raw types are always assignable
// to parameterized types.
if (fromTypeVarAssigns.isEmpty()) {
return true;
}
// get the target type's type arguments including owner type arguments
final Map<TypeVariable<?>, Type> toTypeVarAssigns = getTypeArguments(
toParameterizedType, toClass, typeVarAssigns);
// now to check each type argument
for (final TypeVariable<?> var : toTypeVarAssigns.keySet()) {
final Type toTypeArg = unrollVariableAssignments(var, toTypeVarAssigns);
final Type fromTypeArg = unrollVariableAssignments(var,
fromTypeVarAssigns);
// parameters must either be absent from the subject type, within
// the bounds of the wildcard type, or be an exact match to the
// parameters of the target type.
if (fromTypeArg != null && !toTypeArg.equals(fromTypeArg) &&
!(toTypeArg instanceof WildcardType && isAssignable(fromTypeArg,
toTypeArg, typeVarAssigns)))
{
return false;
}
}
return true;
}
/**
* Look up {@code var} in {@code typeVarAssigns} <em>transitively</em>, i.e.
* keep looking until the value found is <em>not</em> a type variable.
*
* @param var the type variable to look up
* @param typeVarAssigns the map used for the look up
* @return Type or {@code null} if some variable was not in the map
* @since 3.2
*/
private static Type unrollVariableAssignments(TypeVariable<?> var,
final Map<TypeVariable<?>, Type> typeVarAssigns)
{
Type result;
do {
result = typeVarAssigns.get(var);
if (result instanceof TypeVariable && !result.equals(var)) {
var = (TypeVariable<?>) result;
continue;
}
break;
}
while (true);
return result;
}
/**
* <p>
* Checks if the subject type may be implicitly cast to the target generic
* array type following the Java generics rules.
* </p>
*
* @param type the subject type to be assigned to the target type
* @param toGenericArrayType the target generic array type
* @param typeVarAssigns a map with type variables
* @return {@code true} if {@code type} is assignable to
* {@code toGenericArrayType}.
*/
private static boolean isAssignable(final Type type,
final GenericArrayType toGenericArrayType,
final Map<TypeVariable<?>, Type> typeVarAssigns)
{
if (type == null) {
return true;
}
// only a null type can be assigned to null type which
// would have cause the previous to return true
if (toGenericArrayType == null) {
return false;
}
// all types are assignable to themselves
if (toGenericArrayType.equals(type)) {
return true;
}
final Type toComponentType = toGenericArrayType.getGenericComponentType();
if (type instanceof Class) {
final Class<?> cls = (Class<?>) type;
// compare the component types
return cls.isArray() && isAssignable(cls.getComponentType(),
toComponentType, typeVarAssigns);
}
if (type instanceof GenericArrayType) {
// compare the component types
return isAssignable(((GenericArrayType) type).getGenericComponentType(),
toComponentType, typeVarAssigns);
}
if (type instanceof WildcardType) {
// so long as one of the upper bounds is assignable, it's good
for (final Type bound : getImplicitUpperBounds((WildcardType) type)) {
if (isAssignable(bound, toGenericArrayType)) {
return true;
}
}
return false;
}
if (type instanceof TypeVariable) {
// probably should remove the following logic and just return false.
// type variables cannot specify arrays as bounds.
for (final Type bound : getImplicitBounds((TypeVariable<?>) type)) {
if (isAssignable(bound, toGenericArrayType)) {
return true;
}
}
return false;
}
if (type instanceof ParameterizedType) {
// the raw type of a parameterized type is never an array or
// generic array, otherwise the declaration would look like this:
// Collection[]< ? extends String > collection;
return false;
}
throw new IllegalStateException("found an unhandled type: " + type);
}
/**
* <p>
* Checks if the subject type may be implicitly cast to the target wildcard
* type following the Java generics rules.
* </p>
*
* @param type the subject type to be assigned to the target type
* @param toWildcardType the target wildcard type
* @param typeVarAssigns a map with type variables
* @return {@code true} if {@code type} is assignable to
* {@code toWildcardType}.
*/
private static boolean isAssignable(final Type type,
final WildcardType toWildcardType,
final Map<TypeVariable<?>, Type> typeVarAssigns)
{
if (type == null) {
return true;
}
// only a null type can be assigned to null type which
// would have cause the previous to return true
if (toWildcardType == null) {
return false;
}
// all types are assignable to themselves
if (toWildcardType.equals(type)) {
return true;
}
final Type[] toUpperBounds = getImplicitUpperBounds(toWildcardType);
final Type[] toLowerBounds = getImplicitLowerBounds(toWildcardType);
if (type instanceof WildcardType) {
final WildcardType wildcardType = (WildcardType) type;
final Type[] upperBounds = getImplicitUpperBounds(wildcardType);
final Type[] lowerBounds = getImplicitLowerBounds(wildcardType);
for (Type toBound : toUpperBounds) {
// if there are assignments for unresolved type variables,
// now's the time to substitute them.
toBound = substituteTypeVariables(toBound, typeVarAssigns);
// each upper bound of the subject type has to be assignable to
// each
// upper bound of the target type
for (final Type bound : upperBounds) {
if (!isAssignable(bound, toBound, typeVarAssigns)) {
return false;
}
}
}
for (Type toBound : toLowerBounds) {
// if there are assignments for unresolved type variables,
// now's the time to substitute them.
toBound = substituteTypeVariables(toBound, typeVarAssigns);
// each lower bound of the target type has to be assignable to
// each
// lower bound of the subject type
for (final Type bound : lowerBounds) {
if (!isAssignable(toBound, bound, typeVarAssigns)) {
return false;
}
}
}
return true;
}
for (final Type toBound : toUpperBounds) {
// if there are assignments for unresolved type variables,
// now's the time to substitute them.
if (!isAssignable(type, substituteTypeVariables(toBound,
typeVarAssigns), typeVarAssigns))
{
return false;
}
}
for (final Type toBound : toLowerBounds) {
// if there are assignments for unresolved type variables,
// now's the time to substitute them.
if (!isAssignable(substituteTypeVariables(toBound, typeVarAssigns),
type, typeVarAssigns))
{
return false;
}
}
return true;
}
/**
* <p>
* Checks if the subject type may be implicitly cast to the target type
* variable following the Java generics rules.
* </p>
*
* @param type the subject type to be assigned to the target type
* @param toTypeVariable the target type variable
* @param typeVarAssigns a map with type variables
* @return {@code true} if {@code type} is assignable to
* {@code toTypeVariable}.
*/
private static boolean isAssignable(final Type type,
final TypeVariable<?> toTypeVariable,
final Map<TypeVariable<?>, Type> typeVarAssigns)
{
if (type == null) {
return true;
}
// only a null type can be assigned to null type which
// would have cause the previous to return true
if (toTypeVariable == null) {
return false;
}
// all types are assignable to themselves
if (toTypeVariable.equals(type)) {
return true;
}
if (type instanceof TypeVariable) {
// a type variable is assignable to another type variable, if
// and only if the former is the latter, extends the latter, or
// is otherwise a descendant of the latter.
final Type[] bounds = getImplicitBounds((TypeVariable<?>) type);
for (final Type bound : bounds) {
if (isAssignable(bound, toTypeVariable, typeVarAssigns)) {
return true;
}
}
}
if (type instanceof Class || type instanceof ParameterizedType ||
type instanceof GenericArrayType || type instanceof WildcardType)
{
return false;
}
throw new IllegalStateException("found an unhandled type: " + type);
}
/**
* <p>
* Find the mapping for {@code type} in {@code typeVarAssigns}.
* </p>
*
* @param type the type to be replaced
* @param typeVarAssigns the map with type variables
* @return the replaced type
* @throws IllegalArgumentException if the type cannot be substituted
*/
private static Type substituteTypeVariables(final Type type,
final Map<TypeVariable<?>, Type> typeVarAssigns)
{
if (type instanceof TypeVariable && typeVarAssigns != null) {
final Type replacementType = typeVarAssigns.get(type);
if (replacementType == null) {
throw new IllegalArgumentException(
"missing assignment type for type variable " + type);
}
return replacementType;
}
return type;
}
/**
* <p>
* Retrieves all the type arguments for this parameterized type including
* owner hierarchy arguments such as {@code Outer<K,V>.Inner<T>.DeepInner
* <E>} . The arguments are returned in a {@link Map} specifying the
* argument type for each {@link TypeVariable}.
* </p>
*
* @param type specifies the subject parameterized type from which to
* harvest the parameters.
* @return a {@code Map} of the type arguments to their respective type
* variables.
*/
public static Map<TypeVariable<?>, Type> getTypeArguments(
final ParameterizedType type)
{
return getTypeArguments(type, getRawType(type), null);
}
/**
* <p>
* Gets the type arguments of a class/interface based on a subtype. For
* instance, this method will determine that both of the parameters for the
* interface {@link Map} are {@link Object} for the subtype
* {@link java.util.Properties Properties} even though the subtype does not
* directly implement the {@code Map} interface.
* </p>
* <p>
* This method returns {@code null} if {@code type} is not assignable to
* {@code toClass}. It returns an empty map if none of the classes or
* interfaces in its inheritance hierarchy specify any type arguments.
* </p>
* <p>
* A side effect of this method is that it also retrieves the type arguments
* for the classes and interfaces that are part of the hierarchy between
* {@code type} and {@code toClass}. So with the above example, this method
* will also determine that the type arguments for
* {@link java.util.Hashtable Hashtable} are also both {@code Object}. In
* cases where the interface specified by {@code toClass} is (indirectly)
* implemented more than once (e.g. where {@code toClass} specifies the
* interface {@link java.lang.Iterable Iterable} and {@code type} specifies
* a parameterized type that implements both {@link java.util.Set Set} and
* {@link java.util.Collection Collection}), this method will look at the
* inheritance hierarchy of only one of the implementations/subclasses; the
* first interface encountered that isn't a subinterface to one of the
* others in the {@code type} to {@code toClass} hierarchy.
* </p>
*
* @param type the type from which to determine the type parameters of
* {@code toClass}
* @param toClass the class whose type parameters are to be determined based
* on the subtype {@code type}
* @return a {@code Map} of the type assignments for the type variables in
* each type in the inheritance hierarchy from {@code type} to
* {@code toClass} inclusive.
*/
public static Map<TypeVariable<?>, Type> getTypeArguments(final Type type,
final Class<?> toClass)
{
return getTypeArguments(type, toClass, null);
}
/**
* <p>
* Return a map of the type arguments of @{code type} in the context of
* {@code toClass}.
* </p>
*
* @param type the type in question
* @param toClass the class
* @param subtypeVarAssigns a map with type variables
* @return the {@code Map} with type arguments
*/
private static Map<TypeVariable<?>, Type> getTypeArguments(final Type type,
final Class<?> toClass,
final Map<TypeVariable<?>, Type> subtypeVarAssigns)
{
if (type instanceof Class) {
return getTypeArguments((Class<?>) type, toClass, subtypeVarAssigns);
}
if (type instanceof ParameterizedType) {
return getTypeArguments((ParameterizedType) type, toClass,
subtypeVarAssigns);
}
if (type instanceof GenericArrayType) {
return getTypeArguments(((GenericArrayType) type)
.getGenericComponentType(), toClass.isArray() ? toClass
.getComponentType() : toClass, subtypeVarAssigns);
}
// since wildcard types are not assignable to classes, should this just
// return null?
if (type instanceof WildcardType) {
for (final Type bound : getImplicitUpperBounds((WildcardType) type)) {
// find the first bound that is assignable to the target class
if (isAssignable(bound, toClass)) {
return getTypeArguments(bound, toClass, subtypeVarAssigns);
}
}
return null;
}
if (type instanceof TypeVariable) {
for (final Type bound : getImplicitBounds((TypeVariable<?>) type)) {
// find the first bound that is assignable to the target class
if (isAssignable(bound, toClass)) {
return getTypeArguments(bound, toClass, subtypeVarAssigns);
}
}
return null;
}
throw new IllegalStateException("found an unhandled type: " + type);
}
/**
* <p>
* Return a map of the type arguments of a parameterized type in the context
* of {@code toClass}.
* </p>
*
* @param parameterizedType the parameterized type
* @param toClass the class
* @param subtypeVarAssigns a map with type variables
* @return the {@code Map} with type arguments
*/
private static Map<TypeVariable<?>, Type> getTypeArguments(
final ParameterizedType parameterizedType, final Class<?> toClass,
final Map<TypeVariable<?>, Type> subtypeVarAssigns)
{
final Class<?> cls = getRawType(parameterizedType);
// make sure they're assignable
if (!isAssignable(cls, toClass)) {
return null;
}
final Type ownerType = parameterizedType.getOwnerType();
Map<TypeVariable<?>, Type> typeVarAssigns;
if (ownerType instanceof ParameterizedType) {
// get the owner type arguments first
final ParameterizedType parameterizedOwnerType =
(ParameterizedType) ownerType;
typeVarAssigns = getTypeArguments(parameterizedOwnerType, getRawType(
parameterizedOwnerType), subtypeVarAssigns);
}
else {
// no owner, prep the type variable assignments map
typeVarAssigns = subtypeVarAssigns == null ? new HashMap<>()
: new HashMap<>(subtypeVarAssigns);
}
// get the subject parameterized type's arguments
final Type[] typeArgs = parameterizedType.getActualTypeArguments();
// and get the corresponding type variables from the raw class
final TypeVariable<?>[] typeParams = cls.getTypeParameters();
// map the arguments to their respective type variables
for (int i = 0; i < typeParams.length; i++) {
final Type typeArg = typeArgs[i];
typeVarAssigns.put(typeParams[i], typeVarAssigns.containsKey(typeArg)
? typeVarAssigns.get(typeArg) : typeArg);
}
if (toClass.equals(cls)) {
// target class has been reached. Done.
return typeVarAssigns;
}
// walk the inheritance hierarchy until the target class is reached
return getTypeArguments(getClosestParentType(cls, toClass), toClass,
typeVarAssigns);
}
/**
* <p>
* Return a map of the type arguments of a class in the context of @{code
* toClass}.
* </p>
*
* @param cls the class in question
* @param toClass the context class
* @param subtypeVarAssigns a map with type variables
* @return the {@code Map} with type arguments
*/
private static Map<TypeVariable<?>, Type> getTypeArguments(Class<?> cls,
final Class<?> toClass,
final Map<TypeVariable<?>, Type> subtypeVarAssigns)
{
// make sure they're assignable
if (!isAssignable(cls, toClass)) {
return null;
}
// can't work with primitives
if (cls.isPrimitive()) {
// both classes are primitives?
if (toClass.isPrimitive()) {
// dealing with widening here. No type arguments to be
// harvested with these two types.
return new HashMap<>();
}
// work with wrapper the wrapper class instead of the primitive
cls = ConversionUtils.getNonprimitiveType(cls);
}
// create a copy of the incoming map, or an empty one if it's null
final HashMap<TypeVariable<?>, Type> typeVarAssigns =
subtypeVarAssigns == null ? new HashMap<>() : new HashMap<>(
subtypeVarAssigns);
// has target class been reached?
if (toClass.equals(cls)) {
return typeVarAssigns;
}
// walk the inheritance hierarchy until the target class is reached
return getTypeArguments(getClosestParentType(cls, toClass), toClass,
typeVarAssigns);
}
/**
* <p>
* Tries to determine the type arguments of a class/interface based on a
* super parameterized type's type arguments. This method is the inverse of
* {@link #getTypeArguments(Type, Class)} which gets a class/interface's
* type arguments based on a subtype. It is far more limited in determining
* the type arguments for the subject class's type variables in that it can
* only determine those parameters that map from the subject {@link Class}
* object to the supertype.
* </p>
* <p>
* Example: {@link java.util.TreeSet TreeSet} sets its parameter as the
* parameter for {@link java.util.NavigableSet NavigableSet}, which in turn
* sets the parameter of {@link java.util.SortedSet}, which in turn sets the
* parameter of {@link Set}, which in turn sets the parameter of
* {@link java.util.Collection}, which in turn sets the parameter of
* {@link java.lang.Iterable}. Since {@code TreeSet}'s parameter maps
* (indirectly) to {@code Iterable}'s parameter, it will be able to
* determine that based on the super type {@code Iterable<? extends
* Map<Integer, ? extends Collection<?>>>}, the parameter of {@code TreeSet}
* is {@code ? extends Map<Integer, ? extends
* Collection<?>>}.
* </p>
*
* @param cls the class whose type parameters are to be determined, not
* {@code null}
* @param superType the super type from which {@code cls}'s type arguments
* are to be determined, not {@code null}
* @return a {@code Map} of the type assignments that could be determined
* for the type variables in each type in the inheritance hierarchy
* from {@code type} to {@code toClass} inclusive.
*/
public static Map<TypeVariable<?>, Type> determineTypeArguments(
final Class<?> cls, final ParameterizedType superType)
{
validateNotNull(cls, "cls is null");
validateNotNull(superType, "superType is null");
final Class<?> superClass = getRawType(superType);
// compatibility check
if (!isAssignable(cls, superClass)) {
return null;
}
if (cls.equals(superClass)) {
return getTypeArguments(superType, superClass, null);
}
// get the next class in the inheritance hierarchy
final Type midType = getClosestParentType(cls, superClass);
// can only be a class or a parameterized type
if (midType instanceof Class) {
return determineTypeArguments((Class<?>) midType, superType);
}
final ParameterizedType midParameterizedType =
(ParameterizedType) midType;
final Class<?> midClass = getRawType(midParameterizedType);
// get the type variables of the mid class that map to the type
// arguments of the super class
final Map<TypeVariable<?>, Type> typeVarAssigns = determineTypeArguments(
midClass, superType);
// map the arguments of the mid type to the class type variables
mapTypeVariablesToArguments(cls, midParameterizedType, typeVarAssigns);
return typeVarAssigns;
}
/**
* <p>
* Performs a mapping of type variables.
* </p>
*
* @param <T> the generic type of the class in question
* @param cls the class in question
* @param parameterizedType the parameterized type
* @param typeVarAssigns the map to be filled
*/
private static <T> void mapTypeVariablesToArguments(final Class<T> cls,
final ParameterizedType parameterizedType,
final Map<TypeVariable<?>, Type> typeVarAssigns)
{
// capture the type variables from the owner type that have assignments
final Type ownerType = parameterizedType.getOwnerType();
if (ownerType instanceof ParameterizedType) {
// recursion to make sure the owner's owner type gets processed
mapTypeVariablesToArguments(cls, (ParameterizedType) ownerType,
typeVarAssigns);
}
// parameterizedType is a generic interface/class (or it's in the owner
// hierarchy of said interface/class) implemented/extended by the class
// cls. Find out which type variables of cls are type arguments of
// parameterizedType:
final Type[] typeArgs = parameterizedType.getActualTypeArguments();
// of the cls's type variables that are arguments of parameterizedType,
// find out which ones can be determined from the super type's arguments
final TypeVariable<?>[] typeVars = getRawType(parameterizedType)
.getTypeParameters();
// use List view of type parameters of cls so the contains() method can be
// used:
final List<TypeVariable<Class<T>>> typeVarList = Arrays.asList(cls
.getTypeParameters());
for (int i = 0; i < typeArgs.length; i++) {
final TypeVariable<?> typeVar = typeVars[i];
final Type typeArg = typeArgs[i];
// argument of parameterizedType is a type variable of cls
if (typeVarList.contains(typeArg)
// type variable of parameterizedType has an assignment in
// the super type.
&& typeVarAssigns.containsKey(typeVar)) {
// map the assignment to the cls's type variable
typeVarAssigns.put((TypeVariable<?>) typeArg, typeVarAssigns.get(
typeVar));
}
}
}
/**
* <p>
* Get the closest parent type to the super class specified by
* {@code superClass}.
* </p>
*
* @param cls the class in question
* @param superClass the super class
* @return the closes parent type
*/
private static Type getClosestParentType(final Class<?> cls,
final Class<?> superClass)
{
// only look at the interfaces if the super class is also an interface
if (superClass.isInterface()) {
// get the generic interfaces of the subject class
final Type[] interfaceTypes = cls.getGenericInterfaces();
// will hold the best generic interface match found
Type genericInterface = null;
// find the interface closest to the super class
for (final Type midType : interfaceTypes) {
Class<?> midClass = null;
if (midType instanceof ParameterizedType) {
midClass = getRawType((ParameterizedType) midType);
}
else if (midType instanceof Class) {
midClass = (Class<?>) midType;
}
else {
throw new IllegalStateException("Unexpected generic" +
" interface type found: " + midType);
}
// check if this interface is further up the inheritance chain
// than the previously found match
if (isAssignable(midClass, superClass) && isAssignable(
genericInterface, (Type) midClass))
{
genericInterface = midType;
}
}
// found a match?
if (genericInterface != null) {
return genericInterface;
}
}
// none of the interfaces were descendants of the target class, so the
// super class has to be one, instead
return cls.getGenericSuperclass();
}
/**
* <p>
* Checks if the given value can be assigned to the target type following
* the Java generics rules.
* </p>
*
* @param value the value to be checked
* @param type the target type
* @return {@code true} if {@code value} is an instance of {@code type}.
*/
public static boolean isInstance(final Object value, final Type type) {
if (type == null) {
return false;
}
return value == null ? !(type instanceof Class) || !((Class<?>) type)
.isPrimitive() : isAssignable(value.getClass(), type, null);
}
/**
* <p>
* This method strips out the redundant upper bound types in type variable
* types and wildcard types (or it would with wildcard types if multiple
* upper bounds were allowed).
* </p>
* <p>
* Example, with the variable type declaration:
*
* <pre>
* <K extends java.util.Collection<String> &
* java.util.List<String>>
* </pre>
* <p>
* since {@code List} is a subinterface of {@code Collection}, this method
* will return the bounds as if the declaration had been:
* </p>
*
* <pre>
* <K extends java.util.List<String>>
* </pre>
*
* @param bounds an array of types representing the upper bounds of either
* {@link WildcardType} or {@link TypeVariable}, not {@code null}.
* @return an array containing the values from {@code bounds} minus the
* redundant types.
*/
public static Type[] normalizeUpperBounds(final Type[] bounds) {
validateNotNull(bounds, "null value specified for bounds array");
// don't bother if there's only one (or none) type
if (bounds.length < 2) {
return bounds;
}
final Set<Type> types = new HashSet<>(bounds.length);
for (final Type type1 : bounds) {
boolean subtypeFound = false;
for (final Type type2 : bounds) {
if (type1 != type2 && isAssignable(type2, type1, null)) {
subtypeFound = true;
break;
}
}
if (!subtypeFound) {
types.add(type1);
}
}
return types.toArray(new Type[types.size()]);
}
/**
* <p>
* Returns an array containing the sole type of {@link Object} if
* {@link TypeVariable#getBounds()} returns an empty array. Otherwise, it
* returns the result of {@link TypeVariable#getBounds()} passed into
* {@link #normalizeUpperBounds}.
* </p>
*
* @param typeVariable the subject type variable, not {@code null}
* @return a non-empty array containing the bounds of the type variable.
*/
public static Type[] getImplicitBounds(final TypeVariable<?> typeVariable) {
validateNotNull(typeVariable, "typeVariable is null");
final Type[] bounds = typeVariable.getBounds();
return bounds.length == 0 ? new Type[] { Object.class }
: normalizeUpperBounds(bounds);
}
/**
* <p>
* Returns an array containing the sole value of {@link Object} if
* {@link WildcardType#getUpperBounds()} returns an empty array. Otherwise,
* it returns the result of {@link WildcardType#getUpperBounds()} passed
* into {@link #normalizeUpperBounds}.
* </p>
*
* @param wildcardType the subject wildcard type, not {@code null}
* @return a non-empty array containing the upper bounds of the wildcard
* type.
*/
public static Type[] getImplicitUpperBounds(
final WildcardType wildcardType)
{
validateNotNull(wildcardType, "wildcardType is null");
final Type[] bounds = wildcardType.getUpperBounds();
return bounds.length == 0 ? new Type[] { Object.class }
: normalizeUpperBounds(bounds);
}
/**
* <p>
* Returns an array containing a single value of {@code null} if
* {@link WildcardType#getLowerBounds()} returns an empty array. Otherwise,
* it returns the result of {@link WildcardType#getLowerBounds()}.
* </p>
*
* @param wildcardType the subject wildcard type, not {@code null}
* @return a non-empty array containing the lower bounds of the wildcard
* type.
*/
public static Type[] getImplicitLowerBounds(
final WildcardType wildcardType)
{
validateNotNull(wildcardType, "wildcardType is null");
final Type[] bounds = wildcardType.getLowerBounds();
return bounds.length == 0 ? new Type[] { null } : bounds;
}
/**
* <p>
* Determines whether or not specified types satisfy the bounds of their
* mapped type variables. When a type parameter extends another (such as
* {@code <T, S extends T>}), uses another as a type parameter (such as
* {@code <T, S extends Comparable>>}), or otherwise depends on another type
* variable to be specified, the dependencies must be included in
* {@code typeVarAssigns}.
* </p>
*
* @param typeVarAssigns specifies the potential types to be assigned to the
* type variables, not {@code null}.
* @return whether or not the types can be assigned to their respective type
* variables.
*/
public static boolean typesSatisfyVariables(
final Map<TypeVariable<?>, Type> typeVarAssigns)
{
validateNotNull(typeVarAssigns, "typeVarAssigns is null");
// all types must be assignable to all the bounds of the their mapped
// type variable.
for (final Map.Entry<TypeVariable<?>, Type> entry : typeVarAssigns
.entrySet())
{
final TypeVariable<?> typeVar = entry.getKey();
final Type type = entry.getValue();
for (final Type bound : getImplicitBounds(typeVar)) {
if (!isAssignable(type, substituteTypeVariables(bound,
typeVarAssigns), typeVarAssigns))
{
return false;
}
}
}
return true;
}
/**
* <p>
* Transforms the passed in type to a {@link Class} object. Type-checking
* method of convenience.
* </p>
*
* @param parameterizedType the type to be converted
* @return the corresponding {@code Class} object
* @throws IllegalStateException if the conversion fails
*/
private static Class<?> getRawType(
final ParameterizedType parameterizedType)
{
final Type rawType = parameterizedType.getRawType();
// check if raw type is a Class object
// not currently necessary, but since the return type is Type instead of
// Class, there's enough reason to believe that future versions of Java
// may return other Type implementations. And type-safety checking is
// rarely a bad idea.
if (!(rawType instanceof Class)) {
throw new IllegalStateException("Wait... What!? Type of rawType: " +
rawType);
}
return (Class<?>) rawType;
}
/**
* <p>
* Get the raw type of a Java type, given its context. Primarily for use
* with {@link TypeVariable}s and {@link GenericArrayType}s, or when you do
* not know the runtime type of {@code type}: if you know you have a
* {@link Class} instance, it is already raw; if you know you have a
* {@link ParameterizedType}, its raw type is only a method call away.
* </p>
*
* @param type to resolve
* @param assigningType type to be resolved against
* @return the resolved {@link Class} object or {@code null} if the type
* could not be resolved
*/
public static Class<?> getRawType(final Type type,
final Type assigningType)
{
if (type instanceof Class) {
// it is raw, no problem
return (Class<?>) type;
}
if (type instanceof ParameterizedType) {
// simple enough to get the raw type of a ParameterizedType
return getRawType((ParameterizedType) type);
}
if (type instanceof TypeVariable) {
if (assigningType == null) {
return null;
}
// get the entity declaring this type variable
final Object genericDeclaration = ((TypeVariable<?>) type)
.getGenericDeclaration();
// can't get the raw type of a method- or constructor-declared type
// variable
if (!(genericDeclaration instanceof Class)) {
return null;
}
// get the type arguments for the declaring class/interface based
// on the enclosing type
final Map<TypeVariable<?>, Type> typeVarAssigns = getTypeArguments(
assigningType, (Class<?>) genericDeclaration);
// enclosingType has to be a subclass (or subinterface) of the
// declaring type
if (typeVarAssigns == null) {
return null;
}
// get the argument assigned to this type variable
final Type typeArgument = typeVarAssigns.get(type);
if (typeArgument == null) {
return null;
}
// get the argument for this type variable
return getRawType(typeArgument, assigningType);
}
if (type instanceof GenericArrayType) {
// get raw component type
final Class<?> rawComponentType = getRawType(((GenericArrayType) type)
.getGenericComponentType(), assigningType);
// create array type from raw component type and return its class
return Array.newInstance(rawComponentType, 0).getClass();
}
// (hand-waving) this is not the method you're looking for
if (type instanceof WildcardType) {
return null;
}
throw new IllegalArgumentException("unknown type: " + type);
}
/**
* Learn whether the specified type denotes an array type.
*
* @param type the type to be checked
* @return {@code true} if {@code type} is an array class or a
* {@link GenericArrayType}.
*/
public static boolean isArrayType(final Type type) {
return type instanceof GenericArrayType || type instanceof Class &&
((Class<?>) type).isArray();
}
/**
* Get the array component type of {@code type}.
*
* @param type the type to be checked
* @return component type or null if type is not an array type
*/
public static Type getArrayComponentType(final Type type) {
if (type instanceof Class) {
final Class<?> clazz = (Class<?>) type;
return clazz.isArray() ? clazz.getComponentType() : null;
}
if (type instanceof GenericArrayType) {
return ((GenericArrayType) type).getGenericComponentType();
}
return null;
}
/**
* Get a type representing {@code type} with variable assignments
* "unrolled."
*
* @param typeArguments as from
* {@link TypeUtils#getTypeArguments(Type, Class)}
* @param type the type to unroll variable assignments for
* @return Type
* @since 3.2
*/
public static Type unrollVariables(Map<TypeVariable<?>, Type> typeArguments,
final Type type)
{
if (typeArguments == null) {
typeArguments = Collections.<TypeVariable<?>, Type> emptyMap();
}
if (containsTypeVariables(type)) {
if (type instanceof TypeVariable) {
return unrollVariables(typeArguments, typeArguments.get(type));
}
if (type instanceof ParameterizedType) {
final ParameterizedType p = (ParameterizedType) type;
final Map<TypeVariable<?>, Type> parameterizedTypeArguments;
if (p.getOwnerType() == null) {
parameterizedTypeArguments = typeArguments;
}
else {
parameterizedTypeArguments = new HashMap<>(typeArguments);
parameterizedTypeArguments.putAll(TypeUtils.getTypeArguments(p));
}
final Type[] args = p.getActualTypeArguments();
for (int i = 0; i < args.length; i++) {
final Type unrolled = unrollVariables(parameterizedTypeArguments,
args[i]);
if (unrolled != null) {
args[i] = unrolled;
}
}
return parameterizeWithOwner(p.getOwnerType(), (Class<?>) p
.getRawType(), args);
}
if (type instanceof WildcardType) {
final WildcardType wild = (WildcardType) type;
return wildcardType().withUpperBounds(unrollBounds(typeArguments, wild
.getUpperBounds())).withLowerBounds(unrollBounds(typeArguments, wild
.getLowerBounds())).build();
}
}
return type;
}
/**
* Local helper method to unroll variables in a type bounds array.
*
* @param typeArguments assignments {@link Map}
* @param bounds in which to expand variables
* @return {@code bounds} with any variables reassigned
* @since 3.2
*/
private static Type[] unrollBounds(
final Map<TypeVariable<?>, Type> typeArguments, final Type[] bounds)
{
final ArrayList<Type> result = new ArrayList<>();
for (final Type bound : bounds) {
final Type unrolled = unrollVariables(typeArguments, bound);
if (unrolled != null) result.add(unrolled);
}
return result.toArray(new Type[result.size()]);
}
/**
* Learn, recursively, whether any of the type parameters associated with
* {@code type} are bound to variables.
*
* @param type the type to check for type variables
* @return boolean
* @since 3.2
*/
public static boolean containsTypeVariables(final Type type) {
if (type instanceof TypeVariable) {
return true;
}
if (type instanceof Class) {
return ((Class<?>) type).getTypeParameters().length > 0;
}
if (type instanceof ParameterizedType) {
for (final Type arg : ((ParameterizedType) type)
.getActualTypeArguments())
{
if (containsTypeVariables(arg)) {
return true;
}
}
return false;
}
if (type instanceof WildcardType) {
final WildcardType wild = (WildcardType) type;
return containsTypeVariables(TypeUtils.getImplicitLowerBounds(
wild)[0]) || containsTypeVariables(TypeUtils.getImplicitUpperBounds(
wild)[0]);
}
return false;
}
/**
* Create a parameterized type instance.
*
* @param raw the raw class to create a parameterized type instance for
* @param typeArguments the types used for parameterization
* @return {@link ParameterizedType}
* @since 3.2
*/
public static final ParameterizedType parameterize(final Class<?> raw,
final Type... typeArguments)
{
return parameterizeWithOwner(null, raw, typeArguments);
}
/**
* Create a parameterized type instance.
*
* @param raw the raw class to create a parameterized type instance for
* @param typeArgMappings the mapping used for parameterization
* @return {@link ParameterizedType}
* @since 3.2
*/
public static final ParameterizedType parameterize(final Class<?> raw,
final Map<TypeVariable<?>, Type> typeArgMappings)
{
validateNotNull(raw, "raw class is null");
validateNotNull(typeArgMappings, "typeArgMappings is null");
return parameterizeWithOwner(null, raw, extractTypeArgumentsFrom(
typeArgMappings, raw.getTypeParameters()));
}
/**
* Create a parameterized type instance.
*
* @param owner the owning type
* @param raw the raw class to create a parameterized type instance for
* @param typeArguments the types used for parameterization
* @return {@link ParameterizedType}
* @since 3.2
*/
public static final ParameterizedType parameterizeWithOwner(
final Type owner, final Class<?> raw, final Type... typeArguments)
{
validateNotNull(raw, "raw class is null");
final Type useOwner;
if (raw.getEnclosingClass() == null) {
validateIsTrue(owner == null, "no owner allowed for top-level %s", raw);
useOwner = null;
}
else if (owner == null) {
useOwner = raw.getEnclosingClass();
}
else {
validateIsTrue(TypeUtils.isAssignable(owner, raw.getEnclosingClass()),
"%s is invalid owner type for parameterized %s", owner, raw);
useOwner = owner;
}
validateNoNullElements(typeArguments, "null type argument at index %s");
validateIsTrue(raw.getTypeParameters().length == typeArguments.length,
"invalid number of type parameters specified: expected %s, got %s", raw
.getTypeParameters().length, typeArguments.length);
return new ParameterizedTypeImpl(raw, useOwner, typeArguments);
}
/**
* Create a parameterized type instance.
*
* @param owner the owning type
* @param raw the raw class to create a parameterized type instance for
* @param typeArgMappings the mapping used for parameterization
* @return {@link ParameterizedType}
* @since 3.2
*/
public static final ParameterizedType parameterizeWithOwner(
final Type owner, final Class<?> raw,
final Map<TypeVariable<?>, Type> typeArgMappings)
{
validateNotNull(raw, "raw class is null");
validateNotNull(typeArgMappings, "typeArgMappings is null");
return parameterizeWithOwner(owner, raw, extractTypeArgumentsFrom(
typeArgMappings, raw.getTypeParameters()));
}
/**
* Helper method to establish the formal parameters for a parameterized
* type.
*
* @param mappings map containing the assignements
* @param variables expected map keys
* @return array of map values corresponding to specified keys
*/
private static Type[] extractTypeArgumentsFrom(
final Map<TypeVariable<?>, Type> mappings,
final TypeVariable<?>[] variables)
{
final Type[] result = new Type[variables.length];
int index = 0;
for (final TypeVariable<?> var : variables) {
validateIsTrue(mappings.containsKey(var),
"missing argument mapping for %s", toString(var));
result[index++] = mappings.get(var);
}
return result;
}
/**
* Get a {@link WildcardTypeBuilder}.
*
* @return {@link WildcardTypeBuilder}
* @since 3.2
*/
public static WildcardTypeBuilder wildcardType() {
return new WildcardTypeBuilder();
}
/**
* Create a generic array type instance.
*
* @param componentType the type of the elements of the array. For example
* the component type of {@code boolean[]} is {@code boolean}
* @return {@link GenericArrayType}
* @since 3.2
*/
public static GenericArrayType genericArrayType(final Type componentType) {
return new GenericArrayTypeImpl(validateNotNull(componentType,
"componentType is null"));
}
/**
* Check equality of types.
*
* @param t1 the first type
* @param t2 the second type
* @return boolean
* @since 3.2
*/
public static boolean equals(final Type t1, final Type t2) {
if (Objects.equals(t1, t2)) {
return true;
}
if (t1 instanceof ParameterizedType) {
return equals((ParameterizedType) t1, t2);
}
if (t1 instanceof GenericArrayType) {
return equals((GenericArrayType) t1, t2);
}
if (t1 instanceof WildcardType) {
return equals((WildcardType) t1, t2);
}
return false;
}
/**
* Learn whether {@code t} equals {@code p}.
*
* @param p LHS
* @param t RHS
* @return boolean
* @since 3.2
*/
private static boolean equals(final ParameterizedType p, final Type t) {
if (t instanceof ParameterizedType) {
final ParameterizedType other = (ParameterizedType) t;
if (equals(p.getRawType(), other.getRawType()) && equals(p
.getOwnerType(), other.getOwnerType()))
{
return equals(p.getActualTypeArguments(), other
.getActualTypeArguments());
}
}
return false;
}
/**
* Learn whether {@code t} equals {@code a}.
*
* @param a LHS
* @param t RHS
* @return boolean
* @since 3.2
*/
private static boolean equals(final GenericArrayType a, final Type t) {
return t instanceof GenericArrayType && equals(a
.getGenericComponentType(), ((GenericArrayType) t)
.getGenericComponentType());
}
/**
* Learn whether {@code t} equals {@code w}.
*
* @param w LHS
* @param t RHS
* @return boolean
* @since 3.2
*/
private static boolean equals(final WildcardType w, final Type t) {
if (t instanceof WildcardType) {
final WildcardType other = (WildcardType) t;
return equals(getImplicitLowerBounds(w), getImplicitLowerBounds(
other)) && equals(getImplicitUpperBounds(w), getImplicitUpperBounds(
other));
}
return true;
}
/**
* Learn whether {@code t1} equals {@code t2}.
*
* @param t1 LHS
* @param t2 RHS
* @return boolean
* @since 3.2
*/
private static boolean equals(final Type[] t1, final Type[] t2) {
if (t1.length == t2.length) {
for (int i = 0; i < t1.length; i++) {
if (!equals(t1[i], t2[i])) {
return false;
}
}
return true;
}
return false;
}
/**
* Present a given type as a Java-esque String.
*
* @param type the type to create a String representation for, not
* {@code null}
* @return String
* @since 3.2
*/
public static String toString(final Type type) {
return toString(type, new HashSet<>());
}
private static String toString(final Type type, final Set<Type> done) {
validateNotNull(type);
if (type instanceof Class) {
return classToString((Class<?>) type, done);
}
if (type instanceof ParameterizedType) {
return parameterizedTypeToString((ParameterizedType) type, done);
}
if (type instanceof WildcardType) {
return wildcardTypeToString((WildcardType) type, done);
}
if (type instanceof TypeVariable) {
return typeVariableToString((TypeVariable<?>) type, done);
}
if (type instanceof GenericArrayType) {
return genericArrayTypeToString((GenericArrayType) type);
}
throw new IllegalArgumentException("Unknown generic type: " + //
type.getClass().getName());
}
/**
* Format a {@link TypeVariable} including its {@link GenericDeclaration}.
*
* @param var the type variable to create a String representation for, not
* {@code null}
* @return String
* @since 3.2
*/
public static String toLongString(final TypeVariable<?> var) {
validateNotNull(var, "var is null");
final StringBuilder buf = new StringBuilder();
final GenericDeclaration d = ((TypeVariable<?>) var)
.getGenericDeclaration();
if (d instanceof Class) {
Class<?> c = (Class<?>) d;
while (true) {
if (c.getEnclosingClass() == null) {
buf.insert(0, c.getName());
break;
}
buf.insert(0, c.getSimpleName()).insert(0, '.');
c = c.getEnclosingClass();
}
}
else if (d instanceof Type) {// not possible as of now
buf.append(toString((Type) d));
}
else {
buf.append(d);
}
return buf.append(':').append(typeVariableToString(var, new HashSet<>()))
.toString();
}
// /**
// * Wrap the specified {@link Type} in a {@link Typed} wrapper.
// *
// * @param <T> inferred generic type
// * @param type to wrap
// * @return Typed<T>
// * @since 3.2
// */
// public static <T> Typed<T> wrap(final Type type) {
// return new Typed<T>() {
//
// @Override
// public Type getType() {
// return type;
// }
// };
// }
//
// /**
// * Wrap the specified {@link Class} in a {@link Typed} wrapper.
// *
// * @param <T> generic type
// * @param type to wrap
// * @return Typed<T>
// * @since 3.2
// */
// public static <T> Typed<T> wrap(final Class<T> type) {
// return TypeUtils.<T> wrap((Type) type);
// }
/**
* Format a {@link Class} as a {@link String}.
*
* @param c {@code Class} to format
* @param done list of already-encountered types
* @return String
* @since 3.2
*/
private static String classToString(final Class<?> c,
final Set<Type> done)
{
final StringBuilder buf = new StringBuilder();
if (c.getEnclosingClass() != null) {
buf.append(classToString(c.getEnclosingClass(), done)).append('.')
.append(c.getSimpleName());
}
else {
buf.append(c.getName());
}
if (c.getTypeParameters().length > 0) {
buf.append('<');
appendAllTo(buf, ", ", done, c.getTypeParameters());
buf.append('>');
}
return buf.toString();
}
/**
* Format a {@link TypeVariable} as a {@link String}.
*
* @param v {@code TypeVariable} to format
* @param done list of already-encountered types
* @return String
* @since 3.2
*/
private static String typeVariableToString(final TypeVariable<?> v,
final Set<Type> done)
{
final StringBuilder buf = new StringBuilder(v.getName());
if (done.contains(v)) return buf.toString();
done.add(v);
final Type[] bounds = v.getBounds();
if (bounds.length > 0 && !(bounds.length == 1 && Object.class.equals(
bounds[0])))
{
buf.append(" extends ");
appendAllTo(buf, " & ", done, v.getBounds());
}
return buf.toString();
}
/**
* Format a {@link ParameterizedType} as a {@link String}.
*
* @param p {@code ParameterizedType} to format
* @param done list of already-encountered types
* @return String
* @since 3.2
*/
private static String parameterizedTypeToString(final ParameterizedType p,
final Set<Type> done)
{
final StringBuilder buf = new StringBuilder();
final Type useOwner = p.getOwnerType();
final Class<?> raw = (Class<?>) p.getRawType();
final Type[] typeArguments = p.getActualTypeArguments();
if (useOwner == null) {
buf.append(raw.getName());
}
else {
if (useOwner instanceof Class) {
buf.append(((Class<?>) useOwner).getName());
}
else {
buf.append(useOwner.toString());
}
buf.append('.').append(raw.getSimpleName());
}
appendAllTo(buf.append('<'), ", ", done, typeArguments).append('>');
return buf.toString();
}
/**
* Format a {@link WildcardType} as a {@link String}.
*
* @param w {@code WildcardType} to format
* @param done list of already-encountered types
* @return String
* @since 3.2
*/
private static String wildcardTypeToString(final WildcardType w,
final Set<Type> done)
{
final StringBuilder buf = new StringBuilder().append('?');
if (done.contains(w)) return buf.toString();
done.add(w);
final Type[] lowerBounds = w.getLowerBounds();
final Type[] upperBounds = w.getUpperBounds();
if (lowerBounds.length > 1 || lowerBounds.length == 1 &&
lowerBounds[0] != null)
{
appendAllTo(buf.append(" super "), " & ", done, lowerBounds);
}
else if (upperBounds.length > 1 || upperBounds.length == 1 &&
!Object.class.equals(upperBounds[0]))
{
appendAllTo(buf.append(" extends "), " & ", done, upperBounds);
}
return buf.toString();
}
/**
* Format a {@link GenericArrayType} as a {@link String}.
*
* @param g {@code GenericArrayType} to format
* @return String
* @since 3.2
*/
private static String genericArrayTypeToString(final GenericArrayType g) {
return String.format("%s[]", toString(g.getGenericComponentType()));
}
/**
* Append {@code types} to {@code buf} with separator {@code sep}.
*
* @param buf destination
* @param sep separator
* @param done list of already-encountered types
* @param types to append
* @return {@code buf}
* @since 3.2
*/
private static StringBuilder appendAllTo(final StringBuilder buf,
final String sep, final Set<Type> done, final Type... types)
{
validateNotEmpty(validateNoNullElements(types));
if (types.length > 0) {
buf.append(toString(types[0], done));
for (int i = 1; i < types.length; i++) {
buf.append(sep).append(toString(types[i], done));
}
}
return buf;
}
private static final String DEFAULT_IS_NULL_EX_MESSAGE =
"The validated object is null";
/** Forked from {@code org.apache.commons.lang3.Validate#notNull}. */
private static <T> T validateNotNull(final T object) {
return validateNotNull(object, DEFAULT_IS_NULL_EX_MESSAGE);
}
/** Forked from {@code org.apache.commons.lang3.Validate#notNull}. */
private static <T> T validateNotNull(final T object, final String message,
final Object... values)
{
if (object == null) {
throw new NullPointerException(String.format(message, values));
}
return object;
}
/** Forked from {@code org.apache.commons.lang3.Validate#isTrue}. */
private static void validateIsTrue(final boolean expression,
final String message, final Object... values)
{
if (expression == false) {
throw new IllegalArgumentException(String.format(message, values));
}
}
private static final String DEFAULT_NO_NULL_ELEMENTS_ARRAY_EX_MESSAGE =
"The validated array contains null element at index: %d";
/** Forked from {@code org.apache.commons.lang3.Validate#noNullElements}. */
private static <T> T[] validateNoNullElements(final T[] array) {
return validateNoNullElements(array,
DEFAULT_NO_NULL_ELEMENTS_ARRAY_EX_MESSAGE);
}
/** Forked from {@code org.apache.commons.lang3.Validate#noNullElements}. */
private static <T> T[] validateNoNullElements(final T[] array,
final String message, final Object... values)
{
validateNotNull(array);
for (int i = 0; i < array.length; i++) {
if (array[i] == null) {
final Object[] values2 = new Object[values.length + 1];
System.arraycopy(values, 0, values2, 0, values.length);
values2[values.length] = Integer.valueOf(i);
throw new IllegalArgumentException(String.format(message, values2));
}
}
return array;
}
private static final String DEFAULT_NOT_EMPTY_ARRAY_EX_MESSAGE =
"The validated array is empty";
/** Forked from {@code org.apache.commons.lang3.Validate#notEmpty}. */
private static <T> T[] validateNotEmpty(final T[] array) {
return validateNotEmpty(array, DEFAULT_NOT_EMPTY_ARRAY_EX_MESSAGE);
}
/** Forked from {@code org.apache.commons.lang3.Validate#notEmpty}. */
private static <T> T[] validateNotEmpty(final T[] array,
final String message, final Object... values)
{
if (array == null) {
throw new NullPointerException(String.format(message, values));
}
if (array.length == 0) {
throw new IllegalArgumentException(String.format(message, values));
}
return array;
}
}
// -- END FORK OF APACHE COMMONS LANG 3.4 CODE --
}
| src/main/java/org/scijava/util/Types.java | /*
* #%L
* SciJava Common shared library for SciJava software.
* %%
* Copyright (C) 2009 - 2016 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package org.scijava.util;
// Portions of this class were adapted from the
// org.apache.commons.lang3.reflect.TypeUtils and
// org.apache.commons.lang3.Validate classes of
// Apache Commons Lang 3.4, which is distributed
// under the Apache 2 license.
// See lines below starting with "BEGIN FORK".
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.scijava.util.ConversionUtils;
import org.scijava.util.GenericUtils;
/**
* Utility class for working with generic types, fields and methods.
* <p>
* Logic and inspiration were drawn from the following excellent libraries:
* <ul>
* <li>Google Guava's {@code com.google.common.reflect} package.</li>
* <li>Apache Commons Lang 3's {@code org.apache.commons.lang3.reflect} package.
* </li>
* <li><a href="https://github.com/coekarts/gentyref">GenTyRef</a> (Generic Type
* Reflector), a library for runtime generic type introspection.</li>
* </ul>
* </p>
*
* @author Curtis Rueden
*/
public final class Types {
private Types() {
// NB: Prevent instantiation of utility class.
}
// TODO: Migrate all GenericUtils methods here.
public static String name(final Type t) {
// NB: It is annoying that Class.toString() prepends "class " or
// "interface "; this method exists to work around that behavior.
return t instanceof Class ? ((Class<?>) t).getName() : t.toString();
}
/**
* Gets the (first) raw class of the given type.
* <ul>
* <li>If the type is a {@code Class} itself, the type itself is returned.
* </li>
* <li>If the type is a {@link ParameterizedType}, the raw type of the
* parameterized type is returned.</li>
* <li>If the type is a {@link GenericArrayType}, the returned type is the
* corresponding array class. For example: {@code List<Integer>[] => List[]}.
* </li>
* <li>If the type is a type variable or wildcard type, the raw type of the
* first upper bound is returned. For example:
* {@code <X extends Foo & Bar> => Foo}.</li>
* </ul>
* <p>
* If you want <em>all</em> raw classes of the given type, use {@link #raws}.
* </p>
*/
public static Class<?> raw(final Type type) {
// TODO: Consolidate with GenericUtils.
return GenericUtils.getClass(type);
}
/**
* Gets all raw classes corresponding to the given type.
* <p>
* For example, a type parameter {@code A extends Number & Iterable} will
* return both {@link Number} and {@link Iterable} as its raw classes.
* </p>
*
* @see #raw
*/
public static List<Class<?>> raws(final Type type) {
// TODO: Consolidate with GenericUtils.
return GenericUtils.getClasses(type);
}
public static Field field(final Class<?> c, final String name) {
if (c == null) throw new IllegalArgumentException("No such field: " + name);
try {
return c.getDeclaredField(name);
}
catch (final NoSuchFieldException e) {}
return field(c.getSuperclass(), name);
}
/**
* Discerns whether it would be legal to assign a reference of type
* {@code source} to a reference of type {@code target}.
*
* @see Class#isAssignableFrom(Class)
*/
public static boolean isAssignable(final Type source, final Type target) {
return TypeUtils.isAssignable(source, target);
}
/**
* Creates a new {@link ParameterizedType} of the given class together with
* the specified type arguments.
*
* @param rawType The class of the {@link ParameterizedType}.
* @param typeArgs The type arguments to use in parameterizing it.
* @return The newly created {@link ParameterizedType}.
*/
public static ParameterizedType newParameterizedType(final Class<?> rawType,
final Type... typeArgs)
{
return newParameterizedType(rawType, rawType.getDeclaringClass(), typeArgs);
}
/**
* Creates a new {@link ParameterizedType} of the given class together with
* the specified type arguments.
*
* @param rawType The class of the {@link ParameterizedType}.
* @param ownerType The owner type of the parameterized class.
* @param typeArgs The type arguments to use in parameterizing it.
* @return The newly created {@link ParameterizedType}.
*/
public static ParameterizedType newParameterizedType(final Class<?> rawType,
final Type ownerType, final Type... typeArgs)
{
return new TypeUtils.ParameterizedTypeImpl(rawType, ownerType, typeArgs);
}
/**
* Creates a new {@link WildcardType} with no upper or lower bounds (i.e.,
* {@code ?}).
*
* @return The newly created {@link WildcardType}.
*/
public static WildcardType newWildcardType() {
return newWildcardType(null, null);
}
/**
* Creates a new {@link WildcardType} with the given upper and/or lower bound.
*
* @param upperBound Upper bound of the wildcard, or null for none.
* @param lowerBound Lower bound of the wildcard, or null for none.
* @return The newly created {@link WildcardType}.
*/
public static WildcardType newWildcardType(final Type upperBound,
final Type lowerBound)
{
return new TypeUtils.WildcardTypeImpl(upperBound, lowerBound);
}
/**
* Learn, recursively, whether any of the type parameters associated with
* {@code type} are bound to variables.
*
* @param type the type to check for type variables
* @return boolean
*/
public static boolean containsTypeVars(final Type type) {
return TypeUtils.containsTypeVariables(type);
}
/**
* Gets the type arguments of a class/interface based on a subtype. For
* instance, this method will determine that both of the parameters for the
* interface {@link Map} are {@link Object} for the subtype
* {@link java.util.Properties Properties} even though the subtype does not
* directly implement the {@code Map} interface.
* <p>
* This method returns {@code null} if {@code type} is not assignable to
* {@code toClass}. It returns an empty map if none of the classes or
* interfaces in its inheritance hierarchy specify any type arguments.
* </p>
* <p>
* A side effect of this method is that it also retrieves the type arguments
* for the classes and interfaces that are part of the hierarchy between
* {@code type} and {@code toClass}. So with the above example, this method
* will also determine that the type arguments for {@link java.util.Hashtable
* Hashtable} are also both {@code Object}. In cases where the interface
* specified by {@code toClass} is (indirectly) implemented more than once
* (e.g. where {@code toClass} specifies the interface
* {@link java.lang.Iterable Iterable} and {@code type} specifies a
* parameterized type that implements both {@link java.util.Set Set} and
* {@link java.util.Collection Collection}), this method will look at the
* inheritance hierarchy of only one of the implementations/subclasses; the
* first interface encountered that isn't a subinterface to one of the others
* in the {@code type} to {@code toClass} hierarchy.
* </p>
*
* @param type the type from which to determine the type parameters of
* {@code toClass}
* @param toClass the class whose type parameters are to be determined based
* on the subtype {@code type}
* @return a {@code Map} of the type assignments for the type variables in
* each type in the inheritance hierarchy from {@code type} to
* {@code toClass} inclusive.
*/
public static Map<TypeVariable<?>, Type> args(final Type type,
final Class<?> toClass)
{
return TypeUtils.getTypeArguments(type, toClass);
}
/**
* Tries to determine the type arguments of a class/interface based on a super
* parameterized type's type arguments. This method is the inverse of
* {@link #args(Type, Class)} which gets a class/interface's type arguments
* based on a subtype. It is far more limited in determining the type
* arguments for the subject class's type variables in that it can only
* determine those parameters that map from the subject {@link Class} object
* to the supertype.
* <p>
* Example: {@link java.util.TreeSet TreeSet} sets its parameter as the
* parameter for {@link java.util.NavigableSet NavigableSet}, which in turn
* sets the parameter of {@link java.util.SortedSet}, which in turn sets the
* parameter of {@link Set}, which in turn sets the parameter of
* {@link java.util.Collection}, which in turn sets the parameter of
* {@link java.lang.Iterable}. Since {@code TreeSet}'s parameter maps
* (indirectly) to {@code Iterable}'s parameter, it will be able to determine
* that based on the super type {@code Iterable<? extends
* Map<Integer, ? extends Collection<?>>>}, the parameter of {@code TreeSet}
* is {@code ? extends Map<Integer, ? extends Collection<?>>}.
* </p>
*
* @param c the class whose type parameters are to be determined, not
* {@code null}
* @param superType the super type from which {@code c}'s type arguments are
* to be determined, not {@code null}
* @return a {@code Map} of the type assignments that could be determined for
* the type variables in each type in the inheritance hierarchy from
* {@code type} to {@code c} inclusive.
*/
public static Map<TypeVariable<?>, Type> args(final Class<?> c,
final ParameterizedType superType)
{
return TypeUtils.determineTypeArguments(c, superType);
}
/**
* Create a parameterized type instance.
*
* @param raw the raw class to create a parameterized type instance for
* @param typeArgMappings the mapping used for parameterization
* @return {@link ParameterizedType}
*/
public static final ParameterizedType parameterize(final Class<?> raw,
final Map<TypeVariable<?>, Type> typeArgMappings)
{
return TypeUtils.parameterize(raw, typeArgMappings);
}
// -- BEGIN FORK OF APACHE COMMONS LANG 3.4 CODE --
/*
* 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.
*/
/**
* <p>
* Utility methods focusing on type inspection, particularly with regard to
* generics.
* </p>
*
* @since 3.0
* @version $Id: TypeUtils.java 1606051 2014-06-27 12:22:17Z ggregory $
*/
@SuppressWarnings("unused")
private static class TypeUtils {
/**
* {@link WildcardType} builder.
*
* @since 3.2
*/
public static class WildcardTypeBuilder {
/**
* Constructor
*/
private WildcardTypeBuilder() {}
private Type[] upperBounds;
private Type[] lowerBounds;
/**
* Specify upper bounds of the wildcard type to build.
*
* @param bounds to set
* @return {@code this}
*/
public WildcardTypeBuilder withUpperBounds(final Type... bounds) {
this.upperBounds = bounds;
return this;
}
/**
* Specify lower bounds of the wildcard type to build.
*
* @param bounds to set
* @return {@code this}
*/
public WildcardTypeBuilder withLowerBounds(final Type... bounds) {
this.lowerBounds = bounds;
return this;
}
public WildcardType build() {
return new WildcardTypeImpl(upperBounds, lowerBounds);
}
}
/**
* GenericArrayType implementation class.
*
* @since 3.2
*/
private static final class GenericArrayTypeImpl implements
GenericArrayType
{
private final Type componentType;
/**
* Constructor
*
* @param componentType of this array type
*/
private GenericArrayTypeImpl(final Type componentType) {
this.componentType = componentType;
}
@Override
public Type getGenericComponentType() {
return componentType;
}
@Override
public String toString() {
return TypeUtils.toString(this);
}
@Override
public boolean equals(final Object obj) {
return obj == this || obj instanceof GenericArrayType && TypeUtils
.equals(this, (GenericArrayType) obj);
}
@Override
public int hashCode() {
int result = 67 << 4;
result |= componentType.hashCode();
return result;
}
}
/**
* ParameterizedType implementation class.
*
* @since 3.2
*/
private static final class ParameterizedTypeImpl implements
ParameterizedType
{
private final Class<?> raw;
private final Type useOwner;
private final Type[] typeArguments;
/**
* Constructor
*
* @param raw type
* @param useOwner owner type to use, if any
* @param typeArguments formal type arguments
*/
private ParameterizedTypeImpl(final Class<?> raw, final Type useOwner,
final Type[] typeArguments)
{
this.raw = raw;
this.useOwner = useOwner;
this.typeArguments = typeArguments;
}
@Override
public Type getRawType() {
return raw;
}
@Override
public Type getOwnerType() {
return useOwner;
}
@Override
public Type[] getActualTypeArguments() {
return typeArguments.clone();
}
@Override
public String toString() {
return TypeUtils.toString(this);
}
@Override
public boolean equals(final Object obj) {
return obj == this || obj instanceof ParameterizedType && TypeUtils
.equals(this, ((ParameterizedType) obj));
}
@Override
public int hashCode() {
int result = 71 << 4;
result |= raw.hashCode();
result <<= 4;
result |= Objects.hashCode(useOwner);
result <<= 8;
result |= Arrays.hashCode(typeArguments);
return result;
}
}
/**
* WildcardType implementation class.
*
* @since 3.2
*/
private static final class WildcardTypeImpl implements WildcardType {
private static final Type[] EMPTY_BOUNDS = new Type[0];
private final Type[] upperBounds;
private final Type[] lowerBounds;
/**
* Constructor
*
* @param upperBound of this type
* @param lowerBound of this type
*/
private WildcardTypeImpl(final Type upperBound, final Type lowerBound) {
this(upperBound == null ? null : new Type[] { upperBound },
lowerBound == null ? null : new Type[] { lowerBound });
}
/**
* Constructor
*
* @param upperBounds of this type
* @param lowerBounds of this type
*/
private WildcardTypeImpl(final Type[] upperBounds,
final Type[] lowerBounds)
{
this.upperBounds = upperBounds == null ? EMPTY_BOUNDS : upperBounds;
this.lowerBounds = lowerBounds == null ? EMPTY_BOUNDS : lowerBounds;
}
@Override
public Type[] getUpperBounds() {
return upperBounds.clone();
}
@Override
public Type[] getLowerBounds() {
return lowerBounds.clone();
}
@Override
public String toString() {
return TypeUtils.toString(this);
}
@Override
public boolean equals(final Object obj) {
return obj == this || obj instanceof WildcardType && TypeUtils.equals(
this, (WildcardType) obj);
}
@Override
public int hashCode() {
int result = 73 << 8;
result |= Arrays.hashCode(upperBounds);
result <<= 8;
result |= Arrays.hashCode(lowerBounds);
return result;
}
}
/**
* A wildcard instance matching {@code ?}.
*
* @since 3.2
*/
public static final WildcardType WILDCARD_ALL = //
wildcardType().withUpperBounds(Object.class).build();
/**
* <p>
* Checks if the subject type may be implicitly cast to the target type
* following the Java generics rules. If both types are {@link Class}
* objects, the method returns the result of
* {@link Class#isAssignableFrom(Class)}.
* </p>
*
* @param type the subject type to be assigned to the target type
* @param toType the target type
* @return {@code true} if {@code type} is assignable to {@code toType}.
*/
public static boolean isAssignable(final Type type, final Type toType) {
return isAssignable(type, toType, null);
}
/**
* <p>
* Checks if the subject type may be implicitly cast to the target type
* following the Java generics rules.
* </p>
*
* @param type the subject type to be assigned to the target type
* @param toType the target type
* @param typeVarAssigns optional map of type variable assignments
* @return {@code true} if {@code type} is assignable to {@code toType}.
*/
private static boolean isAssignable(final Type type, final Type toType,
final Map<TypeVariable<?>, Type> typeVarAssigns)
{
if (toType == null || toType instanceof Class) {
return isAssignable(type, (Class<?>) toType);
}
if (toType instanceof ParameterizedType) {
return isAssignable(type, (ParameterizedType) toType, typeVarAssigns);
}
if (toType instanceof GenericArrayType) {
return isAssignable(type, (GenericArrayType) toType, typeVarAssigns);
}
if (toType instanceof WildcardType) {
return isAssignable(type, (WildcardType) toType, typeVarAssigns);
}
if (toType instanceof TypeVariable) {
return isAssignable(type, (TypeVariable<?>) toType, typeVarAssigns);
}
throw new IllegalStateException("found an unhandled type: " + toType);
}
/**
* <p>
* Checks if the subject type may be implicitly cast to the target class
* following the Java generics rules.
* </p>
*
* @param type the subject type to be assigned to the target type
* @param toClass the target class
* @return {@code true} if {@code type} is assignable to {@code toClass}.
*/
private static boolean isAssignable(final Type type,
final Class<?> toClass)
{
if (type == null) {
// consistency with ClassUtils.isAssignable() behavior
return toClass == null || !toClass.isPrimitive();
}
// only a null type can be assigned to null type which
// would have cause the previous to return true
if (toClass == null) {
return false;
}
// all types are assignable to themselves
if (toClass.equals(type)) {
return true;
}
if (type instanceof Class) {
// just comparing two classes
return toClass.isAssignableFrom((Class<?>) type);
}
if (type instanceof ParameterizedType) {
// only have to compare the raw type to the class
return isAssignable(getRawType((ParameterizedType) type), toClass);
}
// *
if (type instanceof TypeVariable) {
// if any of the bounds are assignable to the class, then the
// type is assignable to the class.
for (final Type bound : ((TypeVariable<?>) type).getBounds()) {
if (isAssignable(bound, toClass)) {
return true;
}
}
return false;
}
// the only classes to which a generic array type can be assigned
// are class Object and array classes
if (type instanceof GenericArrayType) {
return toClass.equals(Object.class) || toClass.isArray() &&
isAssignable(((GenericArrayType) type).getGenericComponentType(),
toClass.getComponentType());
}
// wildcard types are not assignable to a class (though one would think
// "? super Object" would be assignable to Object)
if (type instanceof WildcardType) {
return false;
}
throw new IllegalStateException("found an unhandled type: " + type);
}
/**
* <p>
* Checks if the subject type may be implicitly cast to the target
* parameterized type following the Java generics rules.
* </p>
*
* @param type the subject type to be assigned to the target type
* @param toParameterizedType the target parameterized type
* @param typeVarAssigns a map with type variables
* @return {@code true} if {@code type} is assignable to {@code toType}.
*/
private static boolean isAssignable(final Type type,
final ParameterizedType toParameterizedType,
final Map<TypeVariable<?>, Type> typeVarAssigns)
{
if (type == null) {
return true;
}
// only a null type can be assigned to null type which
// would have cause the previous to return true
if (toParameterizedType == null) {
return false;
}
// all types are assignable to themselves
if (toParameterizedType.equals(type)) {
return true;
}
// get the target type's raw type
final Class<?> toClass = getRawType(toParameterizedType);
// get the subject type's type arguments including owner type arguments
// and supertype arguments up to and including the target class.
final Map<TypeVariable<?>, Type> fromTypeVarAssigns = getTypeArguments(
type, toClass, null);
// null means the two types are not compatible
if (fromTypeVarAssigns == null) {
return false;
}
// compatible types, but there's no type arguments. this is equivalent
// to comparing Map< ?, ? > to Map, and raw types are always assignable
// to parameterized types.
if (fromTypeVarAssigns.isEmpty()) {
return true;
}
// get the target type's type arguments including owner type arguments
final Map<TypeVariable<?>, Type> toTypeVarAssigns = getTypeArguments(
toParameterizedType, toClass, typeVarAssigns);
// now to check each type argument
for (final TypeVariable<?> var : toTypeVarAssigns.keySet()) {
final Type toTypeArg = unrollVariableAssignments(var, toTypeVarAssigns);
final Type fromTypeArg = unrollVariableAssignments(var,
fromTypeVarAssigns);
// parameters must either be absent from the subject type, within
// the bounds of the wildcard type, or be an exact match to the
// parameters of the target type.
if (fromTypeArg != null && !toTypeArg.equals(fromTypeArg) &&
!(toTypeArg instanceof WildcardType && isAssignable(fromTypeArg,
toTypeArg, typeVarAssigns)))
{
return false;
}
}
return true;
}
/**
* Look up {@code var} in {@code typeVarAssigns} <em>transitively</em>, i.e.
* keep looking until the value found is <em>not</em> a type variable.
*
* @param var the type variable to look up
* @param typeVarAssigns the map used for the look up
* @return Type or {@code null} if some variable was not in the map
* @since 3.2
*/
private static Type unrollVariableAssignments(TypeVariable<?> var,
final Map<TypeVariable<?>, Type> typeVarAssigns)
{
Type result;
do {
result = typeVarAssigns.get(var);
if (result instanceof TypeVariable && !result.equals(var)) {
var = (TypeVariable<?>) result;
continue;
}
break;
}
while (true);
return result;
}
/**
* <p>
* Checks if the subject type may be implicitly cast to the target generic
* array type following the Java generics rules.
* </p>
*
* @param type the subject type to be assigned to the target type
* @param toGenericArrayType the target generic array type
* @param typeVarAssigns a map with type variables
* @return {@code true} if {@code type} is assignable to
* {@code toGenericArrayType}.
*/
private static boolean isAssignable(final Type type,
final GenericArrayType toGenericArrayType,
final Map<TypeVariable<?>, Type> typeVarAssigns)
{
if (type == null) {
return true;
}
// only a null type can be assigned to null type which
// would have cause the previous to return true
if (toGenericArrayType == null) {
return false;
}
// all types are assignable to themselves
if (toGenericArrayType.equals(type)) {
return true;
}
final Type toComponentType = toGenericArrayType.getGenericComponentType();
if (type instanceof Class) {
final Class<?> cls = (Class<?>) type;
// compare the component types
return cls.isArray() && isAssignable(cls.getComponentType(),
toComponentType, typeVarAssigns);
}
if (type instanceof GenericArrayType) {
// compare the component types
return isAssignable(((GenericArrayType) type).getGenericComponentType(),
toComponentType, typeVarAssigns);
}
if (type instanceof WildcardType) {
// so long as one of the upper bounds is assignable, it's good
for (final Type bound : getImplicitUpperBounds((WildcardType) type)) {
if (isAssignable(bound, toGenericArrayType)) {
return true;
}
}
return false;
}
if (type instanceof TypeVariable) {
// probably should remove the following logic and just return false.
// type variables cannot specify arrays as bounds.
for (final Type bound : getImplicitBounds((TypeVariable<?>) type)) {
if (isAssignable(bound, toGenericArrayType)) {
return true;
}
}
return false;
}
if (type instanceof ParameterizedType) {
// the raw type of a parameterized type is never an array or
// generic array, otherwise the declaration would look like this:
// Collection[]< ? extends String > collection;
return false;
}
throw new IllegalStateException("found an unhandled type: " + type);
}
/**
* <p>
* Checks if the subject type may be implicitly cast to the target wildcard
* type following the Java generics rules.
* </p>
*
* @param type the subject type to be assigned to the target type
* @param toWildcardType the target wildcard type
* @param typeVarAssigns a map with type variables
* @return {@code true} if {@code type} is assignable to
* {@code toWildcardType}.
*/
private static boolean isAssignable(final Type type,
final WildcardType toWildcardType,
final Map<TypeVariable<?>, Type> typeVarAssigns)
{
if (type == null) {
return true;
}
// only a null type can be assigned to null type which
// would have cause the previous to return true
if (toWildcardType == null) {
return false;
}
// all types are assignable to themselves
if (toWildcardType.equals(type)) {
return true;
}
final Type[] toUpperBounds = getImplicitUpperBounds(toWildcardType);
final Type[] toLowerBounds = getImplicitLowerBounds(toWildcardType);
if (type instanceof WildcardType) {
final WildcardType wildcardType = (WildcardType) type;
final Type[] upperBounds = getImplicitUpperBounds(wildcardType);
final Type[] lowerBounds = getImplicitLowerBounds(wildcardType);
for (Type toBound : toUpperBounds) {
// if there are assignments for unresolved type variables,
// now's the time to substitute them.
toBound = substituteTypeVariables(toBound, typeVarAssigns);
// each upper bound of the subject type has to be assignable to
// each
// upper bound of the target type
for (final Type bound : upperBounds) {
if (!isAssignable(bound, toBound, typeVarAssigns)) {
return false;
}
}
}
for (Type toBound : toLowerBounds) {
// if there are assignments for unresolved type variables,
// now's the time to substitute them.
toBound = substituteTypeVariables(toBound, typeVarAssigns);
// each lower bound of the target type has to be assignable to
// each
// lower bound of the subject type
for (final Type bound : lowerBounds) {
if (!isAssignable(toBound, bound, typeVarAssigns)) {
return false;
}
}
}
return true;
}
for (final Type toBound : toUpperBounds) {
// if there are assignments for unresolved type variables,
// now's the time to substitute them.
if (!isAssignable(type, substituteTypeVariables(toBound,
typeVarAssigns), typeVarAssigns))
{
return false;
}
}
for (final Type toBound : toLowerBounds) {
// if there are assignments for unresolved type variables,
// now's the time to substitute them.
if (!isAssignable(substituteTypeVariables(toBound, typeVarAssigns),
type, typeVarAssigns))
{
return false;
}
}
return true;
}
/**
* <p>
* Checks if the subject type may be implicitly cast to the target type
* variable following the Java generics rules.
* </p>
*
* @param type the subject type to be assigned to the target type
* @param toTypeVariable the target type variable
* @param typeVarAssigns a map with type variables
* @return {@code true} if {@code type} is assignable to
* {@code toTypeVariable}.
*/
private static boolean isAssignable(final Type type,
final TypeVariable<?> toTypeVariable,
final Map<TypeVariable<?>, Type> typeVarAssigns)
{
if (type == null) {
return true;
}
// only a null type can be assigned to null type which
// would have cause the previous to return true
if (toTypeVariable == null) {
return false;
}
// all types are assignable to themselves
if (toTypeVariable.equals(type)) {
return true;
}
if (type instanceof TypeVariable) {
// a type variable is assignable to another type variable, if
// and only if the former is the latter, extends the latter, or
// is otherwise a descendant of the latter.
final Type[] bounds = getImplicitBounds((TypeVariable<?>) type);
for (final Type bound : bounds) {
if (isAssignable(bound, toTypeVariable, typeVarAssigns)) {
return true;
}
}
}
if (type instanceof Class || type instanceof ParameterizedType ||
type instanceof GenericArrayType || type instanceof WildcardType)
{
return false;
}
throw new IllegalStateException("found an unhandled type: " + type);
}
/**
* <p>
* Find the mapping for {@code type} in {@code typeVarAssigns}.
* </p>
*
* @param type the type to be replaced
* @param typeVarAssigns the map with type variables
* @return the replaced type
* @throws IllegalArgumentException if the type cannot be substituted
*/
private static Type substituteTypeVariables(final Type type,
final Map<TypeVariable<?>, Type> typeVarAssigns)
{
if (type instanceof TypeVariable && typeVarAssigns != null) {
final Type replacementType = typeVarAssigns.get(type);
if (replacementType == null) {
throw new IllegalArgumentException(
"missing assignment type for type variable " + type);
}
return replacementType;
}
return type;
}
/**
* <p>
* Retrieves all the type arguments for this parameterized type including
* owner hierarchy arguments such as {@code Outer<K,V>.Inner<T>.DeepInner
* <E>} . The arguments are returned in a {@link Map} specifying the
* argument type for each {@link TypeVariable}.
* </p>
*
* @param type specifies the subject parameterized type from which to
* harvest the parameters.
* @return a {@code Map} of the type arguments to their respective type
* variables.
*/
public static Map<TypeVariable<?>, Type> getTypeArguments(
final ParameterizedType type)
{
return getTypeArguments(type, getRawType(type), null);
}
/**
* <p>
* Gets the type arguments of a class/interface based on a subtype. For
* instance, this method will determine that both of the parameters for the
* interface {@link Map} are {@link Object} for the subtype
* {@link java.util.Properties Properties} even though the subtype does not
* directly implement the {@code Map} interface.
* </p>
* <p>
* This method returns {@code null} if {@code type} is not assignable to
* {@code toClass}. It returns an empty map if none of the classes or
* interfaces in its inheritance hierarchy specify any type arguments.
* </p>
* <p>
* A side effect of this method is that it also retrieves the type arguments
* for the classes and interfaces that are part of the hierarchy between
* {@code type} and {@code toClass}. So with the above example, this method
* will also determine that the type arguments for
* {@link java.util.Hashtable Hashtable} are also both {@code Object}. In
* cases where the interface specified by {@code toClass} is (indirectly)
* implemented more than once (e.g. where {@code toClass} specifies the
* interface {@link java.lang.Iterable Iterable} and {@code type} specifies
* a parameterized type that implements both {@link java.util.Set Set} and
* {@link java.util.Collection Collection}), this method will look at the
* inheritance hierarchy of only one of the implementations/subclasses; the
* first interface encountered that isn't a subinterface to one of the
* others in the {@code type} to {@code toClass} hierarchy.
* </p>
*
* @param type the type from which to determine the type parameters of
* {@code toClass}
* @param toClass the class whose type parameters are to be determined based
* on the subtype {@code type}
* @return a {@code Map} of the type assignments for the type variables in
* each type in the inheritance hierarchy from {@code type} to
* {@code toClass} inclusive.
*/
public static Map<TypeVariable<?>, Type> getTypeArguments(final Type type,
final Class<?> toClass)
{
return getTypeArguments(type, toClass, null);
}
/**
* <p>
* Return a map of the type arguments of @{code type} in the context of
* {@code toClass}.
* </p>
*
* @param type the type in question
* @param toClass the class
* @param subtypeVarAssigns a map with type variables
* @return the {@code Map} with type arguments
*/
private static Map<TypeVariable<?>, Type> getTypeArguments(final Type type,
final Class<?> toClass,
final Map<TypeVariable<?>, Type> subtypeVarAssigns)
{
if (type instanceof Class) {
return getTypeArguments((Class<?>) type, toClass, subtypeVarAssigns);
}
if (type instanceof ParameterizedType) {
return getTypeArguments((ParameterizedType) type, toClass,
subtypeVarAssigns);
}
if (type instanceof GenericArrayType) {
return getTypeArguments(((GenericArrayType) type)
.getGenericComponentType(), toClass.isArray() ? toClass
.getComponentType() : toClass, subtypeVarAssigns);
}
// since wildcard types are not assignable to classes, should this just
// return null?
if (type instanceof WildcardType) {
for (final Type bound : getImplicitUpperBounds((WildcardType) type)) {
// find the first bound that is assignable to the target class
if (isAssignable(bound, toClass)) {
return getTypeArguments(bound, toClass, subtypeVarAssigns);
}
}
return null;
}
if (type instanceof TypeVariable) {
for (final Type bound : getImplicitBounds((TypeVariable<?>) type)) {
// find the first bound that is assignable to the target class
if (isAssignable(bound, toClass)) {
return getTypeArguments(bound, toClass, subtypeVarAssigns);
}
}
return null;
}
throw new IllegalStateException("found an unhandled type: " + type);
}
/**
* <p>
* Return a map of the type arguments of a parameterized type in the context
* of {@code toClass}.
* </p>
*
* @param parameterizedType the parameterized type
* @param toClass the class
* @param subtypeVarAssigns a map with type variables
* @return the {@code Map} with type arguments
*/
private static Map<TypeVariable<?>, Type> getTypeArguments(
final ParameterizedType parameterizedType, final Class<?> toClass,
final Map<TypeVariable<?>, Type> subtypeVarAssigns)
{
final Class<?> cls = getRawType(parameterizedType);
// make sure they're assignable
if (!isAssignable(cls, toClass)) {
return null;
}
final Type ownerType = parameterizedType.getOwnerType();
Map<TypeVariable<?>, Type> typeVarAssigns;
if (ownerType instanceof ParameterizedType) {
// get the owner type arguments first
final ParameterizedType parameterizedOwnerType =
(ParameterizedType) ownerType;
typeVarAssigns = getTypeArguments(parameterizedOwnerType, getRawType(
parameterizedOwnerType), subtypeVarAssigns);
}
else {
// no owner, prep the type variable assignments map
typeVarAssigns = subtypeVarAssigns == null ? new HashMap<>()
: new HashMap<>(subtypeVarAssigns);
}
// get the subject parameterized type's arguments
final Type[] typeArgs = parameterizedType.getActualTypeArguments();
// and get the corresponding type variables from the raw class
final TypeVariable<?>[] typeParams = cls.getTypeParameters();
// map the arguments to their respective type variables
for (int i = 0; i < typeParams.length; i++) {
final Type typeArg = typeArgs[i];
typeVarAssigns.put(typeParams[i], typeVarAssigns.containsKey(typeArg)
? typeVarAssigns.get(typeArg) : typeArg);
}
if (toClass.equals(cls)) {
// target class has been reached. Done.
return typeVarAssigns;
}
// walk the inheritance hierarchy until the target class is reached
return getTypeArguments(getClosestParentType(cls, toClass), toClass,
typeVarAssigns);
}
/**
* <p>
* Return a map of the type arguments of a class in the context of @{code
* toClass}.
* </p>
*
* @param cls the class in question
* @param toClass the context class
* @param subtypeVarAssigns a map with type variables
* @return the {@code Map} with type arguments
*/
private static Map<TypeVariable<?>, Type> getTypeArguments(Class<?> cls,
final Class<?> toClass,
final Map<TypeVariable<?>, Type> subtypeVarAssigns)
{
// make sure they're assignable
if (!isAssignable(cls, toClass)) {
return null;
}
// can't work with primitives
if (cls.isPrimitive()) {
// both classes are primitives?
if (toClass.isPrimitive()) {
// dealing with widening here. No type arguments to be
// harvested with these two types.
return new HashMap<>();
}
// work with wrapper the wrapper class instead of the primitive
cls = ConversionUtils.getNonprimitiveType(cls);
}
// create a copy of the incoming map, or an empty one if it's null
final HashMap<TypeVariable<?>, Type> typeVarAssigns =
subtypeVarAssigns == null ? new HashMap<>() : new HashMap<>(
subtypeVarAssigns);
// has target class been reached?
if (toClass.equals(cls)) {
return typeVarAssigns;
}
// walk the inheritance hierarchy until the target class is reached
return getTypeArguments(getClosestParentType(cls, toClass), toClass,
typeVarAssigns);
}
/**
* <p>
* Tries to determine the type arguments of a class/interface based on a
* super parameterized type's type arguments. This method is the inverse of
* {@link #getTypeArguments(Type, Class)} which gets a class/interface's
* type arguments based on a subtype. It is far more limited in determining
* the type arguments for the subject class's type variables in that it can
* only determine those parameters that map from the subject {@link Class}
* object to the supertype.
* </p>
* <p>
* Example: {@link java.util.TreeSet TreeSet} sets its parameter as the
* parameter for {@link java.util.NavigableSet NavigableSet}, which in turn
* sets the parameter of {@link java.util.SortedSet}, which in turn sets the
* parameter of {@link Set}, which in turn sets the parameter of
* {@link java.util.Collection}, which in turn sets the parameter of
* {@link java.lang.Iterable}. Since {@code TreeSet}'s parameter maps
* (indirectly) to {@code Iterable}'s parameter, it will be able to
* determine that based on the super type {@code Iterable<? extends
* Map<Integer, ? extends Collection<?>>>}, the parameter of {@code TreeSet}
* is {@code ? extends Map<Integer, ? extends
* Collection<?>>}.
* </p>
*
* @param cls the class whose type parameters are to be determined, not
* {@code null}
* @param superType the super type from which {@code cls}'s type arguments
* are to be determined, not {@code null}
* @return a {@code Map} of the type assignments that could be determined
* for the type variables in each type in the inheritance hierarchy
* from {@code type} to {@code toClass} inclusive.
*/
public static Map<TypeVariable<?>, Type> determineTypeArguments(
final Class<?> cls, final ParameterizedType superType)
{
validateNotNull(cls, "cls is null");
validateNotNull(superType, "superType is null");
final Class<?> superClass = getRawType(superType);
// compatibility check
if (!isAssignable(cls, superClass)) {
return null;
}
if (cls.equals(superClass)) {
return getTypeArguments(superType, superClass, null);
}
// get the next class in the inheritance hierarchy
final Type midType = getClosestParentType(cls, superClass);
// can only be a class or a parameterized type
if (midType instanceof Class) {
return determineTypeArguments((Class<?>) midType, superType);
}
final ParameterizedType midParameterizedType =
(ParameterizedType) midType;
final Class<?> midClass = getRawType(midParameterizedType);
// get the type variables of the mid class that map to the type
// arguments of the super class
final Map<TypeVariable<?>, Type> typeVarAssigns = determineTypeArguments(
midClass, superType);
// map the arguments of the mid type to the class type variables
mapTypeVariablesToArguments(cls, midParameterizedType, typeVarAssigns);
return typeVarAssigns;
}
/**
* <p>
* Performs a mapping of type variables.
* </p>
*
* @param <T> the generic type of the class in question
* @param cls the class in question
* @param parameterizedType the parameterized type
* @param typeVarAssigns the map to be filled
*/
private static <T> void mapTypeVariablesToArguments(final Class<T> cls,
final ParameterizedType parameterizedType,
final Map<TypeVariable<?>, Type> typeVarAssigns)
{
// capture the type variables from the owner type that have assignments
final Type ownerType = parameterizedType.getOwnerType();
if (ownerType instanceof ParameterizedType) {
// recursion to make sure the owner's owner type gets processed
mapTypeVariablesToArguments(cls, (ParameterizedType) ownerType,
typeVarAssigns);
}
// parameterizedType is a generic interface/class (or it's in the owner
// hierarchy of said interface/class) implemented/extended by the class
// cls. Find out which type variables of cls are type arguments of
// parameterizedType:
final Type[] typeArgs = parameterizedType.getActualTypeArguments();
// of the cls's type variables that are arguments of parameterizedType,
// find out which ones can be determined from the super type's arguments
final TypeVariable<?>[] typeVars = getRawType(parameterizedType)
.getTypeParameters();
// use List view of type parameters of cls so the contains() method can be
// used:
final List<TypeVariable<Class<T>>> typeVarList = Arrays.asList(cls
.getTypeParameters());
for (int i = 0; i < typeArgs.length; i++) {
final TypeVariable<?> typeVar = typeVars[i];
final Type typeArg = typeArgs[i];
// argument of parameterizedType is a type variable of cls
if (typeVarList.contains(typeArg)
// type variable of parameterizedType has an assignment in
// the super type.
&& typeVarAssigns.containsKey(typeVar)) {
// map the assignment to the cls's type variable
typeVarAssigns.put((TypeVariable<?>) typeArg, typeVarAssigns.get(
typeVar));
}
}
}
/**
* <p>
* Get the closest parent type to the super class specified by
* {@code superClass}.
* </p>
*
* @param cls the class in question
* @param superClass the super class
* @return the closes parent type
*/
private static Type getClosestParentType(final Class<?> cls,
final Class<?> superClass)
{
// only look at the interfaces if the super class is also an interface
if (superClass.isInterface()) {
// get the generic interfaces of the subject class
final Type[] interfaceTypes = cls.getGenericInterfaces();
// will hold the best generic interface match found
Type genericInterface = null;
// find the interface closest to the super class
for (final Type midType : interfaceTypes) {
Class<?> midClass = null;
if (midType instanceof ParameterizedType) {
midClass = getRawType((ParameterizedType) midType);
}
else if (midType instanceof Class) {
midClass = (Class<?>) midType;
}
else {
throw new IllegalStateException("Unexpected generic" +
" interface type found: " + midType);
}
// check if this interface is further up the inheritance chain
// than the previously found match
if (isAssignable(midClass, superClass) && isAssignable(
genericInterface, (Type) midClass))
{
genericInterface = midType;
}
}
// found a match?
if (genericInterface != null) {
return genericInterface;
}
}
// none of the interfaces were descendants of the target class, so the
// super class has to be one, instead
return cls.getGenericSuperclass();
}
/**
* <p>
* Checks if the given value can be assigned to the target type following
* the Java generics rules.
* </p>
*
* @param value the value to be checked
* @param type the target type
* @return {@code true} if {@code value} is an instance of {@code type}.
*/
public static boolean isInstance(final Object value, final Type type) {
if (type == null) {
return false;
}
return value == null ? !(type instanceof Class) || !((Class<?>) type)
.isPrimitive() : isAssignable(value.getClass(), type, null);
}
/**
* <p>
* This method strips out the redundant upper bound types in type variable
* types and wildcard types (or it would with wildcard types if multiple
* upper bounds were allowed).
* </p>
* <p>
* Example, with the variable type declaration:
*
* <pre>
* <K extends java.util.Collection<String> &
* java.util.List<String>>
* </pre>
* <p>
* since {@code List} is a subinterface of {@code Collection}, this method
* will return the bounds as if the declaration had been:
* </p>
*
* <pre>
* <K extends java.util.List<String>>
* </pre>
*
* @param bounds an array of types representing the upper bounds of either
* {@link WildcardType} or {@link TypeVariable}, not {@code null}.
* @return an array containing the values from {@code bounds} minus the
* redundant types.
*/
public static Type[] normalizeUpperBounds(final Type[] bounds) {
validateNotNull(bounds, "null value specified for bounds array");
// don't bother if there's only one (or none) type
if (bounds.length < 2) {
return bounds;
}
final Set<Type> types = new HashSet<>(bounds.length);
for (final Type type1 : bounds) {
boolean subtypeFound = false;
for (final Type type2 : bounds) {
if (type1 != type2 && isAssignable(type2, type1, null)) {
subtypeFound = true;
break;
}
}
if (!subtypeFound) {
types.add(type1);
}
}
return types.toArray(new Type[types.size()]);
}
/**
* <p>
* Returns an array containing the sole type of {@link Object} if
* {@link TypeVariable#getBounds()} returns an empty array. Otherwise, it
* returns the result of {@link TypeVariable#getBounds()} passed into
* {@link #normalizeUpperBounds}.
* </p>
*
* @param typeVariable the subject type variable, not {@code null}
* @return a non-empty array containing the bounds of the type variable.
*/
public static Type[] getImplicitBounds(final TypeVariable<?> typeVariable) {
validateNotNull(typeVariable, "typeVariable is null");
final Type[] bounds = typeVariable.getBounds();
return bounds.length == 0 ? new Type[] { Object.class }
: normalizeUpperBounds(bounds);
}
/**
* <p>
* Returns an array containing the sole value of {@link Object} if
* {@link WildcardType#getUpperBounds()} returns an empty array. Otherwise,
* it returns the result of {@link WildcardType#getUpperBounds()} passed
* into {@link #normalizeUpperBounds}.
* </p>
*
* @param wildcardType the subject wildcard type, not {@code null}
* @return a non-empty array containing the upper bounds of the wildcard
* type.
*/
public static Type[] getImplicitUpperBounds(
final WildcardType wildcardType)
{
validateNotNull(wildcardType, "wildcardType is null");
final Type[] bounds = wildcardType.getUpperBounds();
return bounds.length == 0 ? new Type[] { Object.class }
: normalizeUpperBounds(bounds);
}
/**
* <p>
* Returns an array containing a single value of {@code null} if
* {@link WildcardType#getLowerBounds()} returns an empty array. Otherwise,
* it returns the result of {@link WildcardType#getLowerBounds()}.
* </p>
*
* @param wildcardType the subject wildcard type, not {@code null}
* @return a non-empty array containing the lower bounds of the wildcard
* type.
*/
public static Type[] getImplicitLowerBounds(
final WildcardType wildcardType)
{
validateNotNull(wildcardType, "wildcardType is null");
final Type[] bounds = wildcardType.getLowerBounds();
return bounds.length == 0 ? new Type[] { null } : bounds;
}
/**
* <p>
* Determines whether or not specified types satisfy the bounds of their
* mapped type variables. When a type parameter extends another (such as
* {@code <T, S extends T>}), uses another as a type parameter (such as
* {@code <T, S extends Comparable>>}), or otherwise depends on another type
* variable to be specified, the dependencies must be included in
* {@code typeVarAssigns}.
* </p>
*
* @param typeVarAssigns specifies the potential types to be assigned to the
* type variables, not {@code null}.
* @return whether or not the types can be assigned to their respective type
* variables.
*/
public static boolean typesSatisfyVariables(
final Map<TypeVariable<?>, Type> typeVarAssigns)
{
validateNotNull(typeVarAssigns, "typeVarAssigns is null");
// all types must be assignable to all the bounds of the their mapped
// type variable.
for (final Map.Entry<TypeVariable<?>, Type> entry : typeVarAssigns
.entrySet())
{
final TypeVariable<?> typeVar = entry.getKey();
final Type type = entry.getValue();
for (final Type bound : getImplicitBounds(typeVar)) {
if (!isAssignable(type, substituteTypeVariables(bound,
typeVarAssigns), typeVarAssigns))
{
return false;
}
}
}
return true;
}
/**
* <p>
* Transforms the passed in type to a {@link Class} object. Type-checking
* method of convenience.
* </p>
*
* @param parameterizedType the type to be converted
* @return the corresponding {@code Class} object
* @throws IllegalStateException if the conversion fails
*/
private static Class<?> getRawType(
final ParameterizedType parameterizedType)
{
final Type rawType = parameterizedType.getRawType();
// check if raw type is a Class object
// not currently necessary, but since the return type is Type instead of
// Class, there's enough reason to believe that future versions of Java
// may return other Type implementations. And type-safety checking is
// rarely a bad idea.
if (!(rawType instanceof Class)) {
throw new IllegalStateException("Wait... What!? Type of rawType: " +
rawType);
}
return (Class<?>) rawType;
}
/**
* <p>
* Get the raw type of a Java type, given its context. Primarily for use
* with {@link TypeVariable}s and {@link GenericArrayType}s, or when you do
* not know the runtime type of {@code type}: if you know you have a
* {@link Class} instance, it is already raw; if you know you have a
* {@link ParameterizedType}, its raw type is only a method call away.
* </p>
*
* @param type to resolve
* @param assigningType type to be resolved against
* @return the resolved {@link Class} object or {@code null} if the type
* could not be resolved
*/
public static Class<?> getRawType(final Type type,
final Type assigningType)
{
if (type instanceof Class) {
// it is raw, no problem
return (Class<?>) type;
}
if (type instanceof ParameterizedType) {
// simple enough to get the raw type of a ParameterizedType
return getRawType((ParameterizedType) type);
}
if (type instanceof TypeVariable) {
if (assigningType == null) {
return null;
}
// get the entity declaring this type variable
final Object genericDeclaration = ((TypeVariable<?>) type)
.getGenericDeclaration();
// can't get the raw type of a method- or constructor-declared type
// variable
if (!(genericDeclaration instanceof Class)) {
return null;
}
// get the type arguments for the declaring class/interface based
// on the enclosing type
final Map<TypeVariable<?>, Type> typeVarAssigns = getTypeArguments(
assigningType, (Class<?>) genericDeclaration);
// enclosingType has to be a subclass (or subinterface) of the
// declaring type
if (typeVarAssigns == null) {
return null;
}
// get the argument assigned to this type variable
final Type typeArgument = typeVarAssigns.get(type);
if (typeArgument == null) {
return null;
}
// get the argument for this type variable
return getRawType(typeArgument, assigningType);
}
if (type instanceof GenericArrayType) {
// get raw component type
final Class<?> rawComponentType = getRawType(((GenericArrayType) type)
.getGenericComponentType(), assigningType);
// create array type from raw component type and return its class
return Array.newInstance(rawComponentType, 0).getClass();
}
// (hand-waving) this is not the method you're looking for
if (type instanceof WildcardType) {
return null;
}
throw new IllegalArgumentException("unknown type: " + type);
}
/**
* Learn whether the specified type denotes an array type.
*
* @param type the type to be checked
* @return {@code true} if {@code type} is an array class or a
* {@link GenericArrayType}.
*/
public static boolean isArrayType(final Type type) {
return type instanceof GenericArrayType || type instanceof Class &&
((Class<?>) type).isArray();
}
/**
* Get the array component type of {@code type}.
*
* @param type the type to be checked
* @return component type or null if type is not an array type
*/
public static Type getArrayComponentType(final Type type) {
if (type instanceof Class) {
final Class<?> clazz = (Class<?>) type;
return clazz.isArray() ? clazz.getComponentType() : null;
}
if (type instanceof GenericArrayType) {
return ((GenericArrayType) type).getGenericComponentType();
}
return null;
}
/**
* Get a type representing {@code type} with variable assignments
* "unrolled."
*
* @param typeArguments as from
* {@link TypeUtils#getTypeArguments(Type, Class)}
* @param type the type to unroll variable assignments for
* @return Type
* @since 3.2
*/
public static Type unrollVariables(Map<TypeVariable<?>, Type> typeArguments,
final Type type)
{
if (typeArguments == null) {
typeArguments = Collections.<TypeVariable<?>, Type> emptyMap();
}
if (containsTypeVariables(type)) {
if (type instanceof TypeVariable) {
return unrollVariables(typeArguments, typeArguments.get(type));
}
if (type instanceof ParameterizedType) {
final ParameterizedType p = (ParameterizedType) type;
final Map<TypeVariable<?>, Type> parameterizedTypeArguments;
if (p.getOwnerType() == null) {
parameterizedTypeArguments = typeArguments;
}
else {
parameterizedTypeArguments = new HashMap<>(typeArguments);
parameterizedTypeArguments.putAll(TypeUtils.getTypeArguments(p));
}
final Type[] args = p.getActualTypeArguments();
for (int i = 0; i < args.length; i++) {
final Type unrolled = unrollVariables(parameterizedTypeArguments,
args[i]);
if (unrolled != null) {
args[i] = unrolled;
}
}
return parameterizeWithOwner(p.getOwnerType(), (Class<?>) p
.getRawType(), args);
}
if (type instanceof WildcardType) {
final WildcardType wild = (WildcardType) type;
return wildcardType().withUpperBounds(unrollBounds(typeArguments, wild
.getUpperBounds())).withLowerBounds(unrollBounds(typeArguments, wild
.getLowerBounds())).build();
}
}
return type;
}
/**
* Local helper method to unroll variables in a type bounds array.
*
* @param typeArguments assignments {@link Map}
* @param bounds in which to expand variables
* @return {@code bounds} with any variables reassigned
* @since 3.2
*/
private static Type[] unrollBounds(
final Map<TypeVariable<?>, Type> typeArguments, final Type[] bounds)
{
final ArrayList<Type> result = new ArrayList<>();
for (final Type bound : bounds) {
final Type unrolled = unrollVariables(typeArguments, bound);
if (unrolled != null) result.add(unrolled);
}
return result.toArray(new Type[result.size()]);
}
/**
* Learn, recursively, whether any of the type parameters associated with
* {@code type} are bound to variables.
*
* @param type the type to check for type variables
* @return boolean
* @since 3.2
*/
public static boolean containsTypeVariables(final Type type) {
if (type instanceof TypeVariable) {
return true;
}
if (type instanceof Class) {
return ((Class<?>) type).getTypeParameters().length > 0;
}
if (type instanceof ParameterizedType) {
for (final Type arg : ((ParameterizedType) type)
.getActualTypeArguments())
{
if (containsTypeVariables(arg)) {
return true;
}
}
return false;
}
if (type instanceof WildcardType) {
final WildcardType wild = (WildcardType) type;
return containsTypeVariables(TypeUtils.getImplicitLowerBounds(
wild)[0]) || containsTypeVariables(TypeUtils.getImplicitUpperBounds(
wild)[0]);
}
return false;
}
/**
* Create a parameterized type instance.
*
* @param raw the raw class to create a parameterized type instance for
* @param typeArguments the types used for parameterization
* @return {@link ParameterizedType}
* @since 3.2
*/
public static final ParameterizedType parameterize(final Class<?> raw,
final Type... typeArguments)
{
return parameterizeWithOwner(null, raw, typeArguments);
}
/**
* Create a parameterized type instance.
*
* @param raw the raw class to create a parameterized type instance for
* @param typeArgMappings the mapping used for parameterization
* @return {@link ParameterizedType}
* @since 3.2
*/
public static final ParameterizedType parameterize(final Class<?> raw,
final Map<TypeVariable<?>, Type> typeArgMappings)
{
validateNotNull(raw, "raw class is null");
validateNotNull(typeArgMappings, "typeArgMappings is null");
return parameterizeWithOwner(null, raw, extractTypeArgumentsFrom(
typeArgMappings, raw.getTypeParameters()));
}
/**
* Create a parameterized type instance.
*
* @param owner the owning type
* @param raw the raw class to create a parameterized type instance for
* @param typeArguments the types used for parameterization
* @return {@link ParameterizedType}
* @since 3.2
*/
public static final ParameterizedType parameterizeWithOwner(
final Type owner, final Class<?> raw, final Type... typeArguments)
{
validateNotNull(raw, "raw class is null");
final Type useOwner;
if (raw.getEnclosingClass() == null) {
validateIsTrue(owner == null, "no owner allowed for top-level %s", raw);
useOwner = null;
}
else if (owner == null) {
useOwner = raw.getEnclosingClass();
}
else {
validateIsTrue(TypeUtils.isAssignable(owner, raw.getEnclosingClass()),
"%s is invalid owner type for parameterized %s", owner, raw);
useOwner = owner;
}
validateNoNullElements(typeArguments, "null type argument at index %s");
validateIsTrue(raw.getTypeParameters().length == typeArguments.length,
"invalid number of type parameters specified: expected %s, got %s", raw
.getTypeParameters().length, typeArguments.length);
return new ParameterizedTypeImpl(raw, useOwner, typeArguments);
}
/**
* Create a parameterized type instance.
*
* @param owner the owning type
* @param raw the raw class to create a parameterized type instance for
* @param typeArgMappings the mapping used for parameterization
* @return {@link ParameterizedType}
* @since 3.2
*/
public static final ParameterizedType parameterizeWithOwner(
final Type owner, final Class<?> raw,
final Map<TypeVariable<?>, Type> typeArgMappings)
{
validateNotNull(raw, "raw class is null");
validateNotNull(typeArgMappings, "typeArgMappings is null");
return parameterizeWithOwner(owner, raw, extractTypeArgumentsFrom(
typeArgMappings, raw.getTypeParameters()));
}
/**
* Helper method to establish the formal parameters for a parameterized
* type.
*
* @param mappings map containing the assignements
* @param variables expected map keys
* @return array of map values corresponding to specified keys
*/
private static Type[] extractTypeArgumentsFrom(
final Map<TypeVariable<?>, Type> mappings,
final TypeVariable<?>[] variables)
{
final Type[] result = new Type[variables.length];
int index = 0;
for (final TypeVariable<?> var : variables) {
validateIsTrue(mappings.containsKey(var),
"missing argument mapping for %s", toString(var));
result[index++] = mappings.get(var);
}
return result;
}
/**
* Get a {@link WildcardTypeBuilder}.
*
* @return {@link WildcardTypeBuilder}
* @since 3.2
*/
public static WildcardTypeBuilder wildcardType() {
return new WildcardTypeBuilder();
}
/**
* Create a generic array type instance.
*
* @param componentType the type of the elements of the array. For example
* the component type of {@code boolean[]} is {@code boolean}
* @return {@link GenericArrayType}
* @since 3.2
*/
public static GenericArrayType genericArrayType(final Type componentType) {
return new GenericArrayTypeImpl(validateNotNull(componentType,
"componentType is null"));
}
/**
* Check equality of types.
*
* @param t1 the first type
* @param t2 the second type
* @return boolean
* @since 3.2
*/
public static boolean equals(final Type t1, final Type t2) {
if (Objects.equals(t1, t2)) {
return true;
}
if (t1 instanceof ParameterizedType) {
return equals((ParameterizedType) t1, t2);
}
if (t1 instanceof GenericArrayType) {
return equals((GenericArrayType) t1, t2);
}
if (t1 instanceof WildcardType) {
return equals((WildcardType) t1, t2);
}
return false;
}
/**
* Learn whether {@code t} equals {@code p}.
*
* @param p LHS
* @param t RHS
* @return boolean
* @since 3.2
*/
private static boolean equals(final ParameterizedType p, final Type t) {
if (t instanceof ParameterizedType) {
final ParameterizedType other = (ParameterizedType) t;
if (equals(p.getRawType(), other.getRawType()) && equals(p
.getOwnerType(), other.getOwnerType()))
{
return equals(p.getActualTypeArguments(), other
.getActualTypeArguments());
}
}
return false;
}
/**
* Learn whether {@code t} equals {@code a}.
*
* @param a LHS
* @param t RHS
* @return boolean
* @since 3.2
*/
private static boolean equals(final GenericArrayType a, final Type t) {
return t instanceof GenericArrayType && equals(a
.getGenericComponentType(), ((GenericArrayType) t)
.getGenericComponentType());
}
/**
* Learn whether {@code t} equals {@code w}.
*
* @param w LHS
* @param t RHS
* @return boolean
* @since 3.2
*/
private static boolean equals(final WildcardType w, final Type t) {
if (t instanceof WildcardType) {
final WildcardType other = (WildcardType) t;
return equals(getImplicitLowerBounds(w), getImplicitLowerBounds(
other)) && equals(getImplicitUpperBounds(w), getImplicitUpperBounds(
other));
}
return true;
}
/**
* Learn whether {@code t1} equals {@code t2}.
*
* @param t1 LHS
* @param t2 RHS
* @return boolean
* @since 3.2
*/
private static boolean equals(final Type[] t1, final Type[] t2) {
if (t1.length == t2.length) {
for (int i = 0; i < t1.length; i++) {
if (!equals(t1[i], t2[i])) {
return false;
}
}
return true;
}
return false;
}
/**
* Present a given type as a Java-esque String.
*
* @param type the type to create a String representation for, not
* {@code null}
* @return String
* @since 3.2
*/
public static String toString(final Type type) {
return toString(type, new HashSet<>());
}
private static String toString(final Type type, final Set<Type> done) {
validateNotNull(type);
if (type instanceof Class) {
return classToString((Class<?>) type, done);
}
if (type instanceof ParameterizedType) {
return parameterizedTypeToString((ParameterizedType) type, done);
}
if (type instanceof WildcardType) {
return wildcardTypeToString((WildcardType) type, done);
}
if (type instanceof TypeVariable) {
return typeVariableToString((TypeVariable<?>) type, done);
}
if (type instanceof GenericArrayType) {
return genericArrayTypeToString((GenericArrayType) type);
}
throw new IllegalArgumentException("Unknown generic type: " + //
type.getClass().getName());
}
/**
* Format a {@link TypeVariable} including its {@link GenericDeclaration}.
*
* @param var the type variable to create a String representation for, not
* {@code null}
* @return String
* @since 3.2
*/
public static String toLongString(final TypeVariable<?> var) {
validateNotNull(var, "var is null");
final StringBuilder buf = new StringBuilder();
final GenericDeclaration d = ((TypeVariable<?>) var)
.getGenericDeclaration();
if (d instanceof Class) {
Class<?> c = (Class<?>) d;
while (true) {
if (c.getEnclosingClass() == null) {
buf.insert(0, c.getName());
break;
}
buf.insert(0, c.getSimpleName()).insert(0, '.');
c = c.getEnclosingClass();
}
}
else if (d instanceof Type) {// not possible as of now
buf.append(toString((Type) d));
}
else {
buf.append(d);
}
return buf.append(':').append(typeVariableToString(var, new HashSet<>()))
.toString();
}
// /**
// * Wrap the specified {@link Type} in a {@link Typed} wrapper.
// *
// * @param <T> inferred generic type
// * @param type to wrap
// * @return Typed<T>
// * @since 3.2
// */
// public static <T> Typed<T> wrap(final Type type) {
// return new Typed<T>() {
//
// @Override
// public Type getType() {
// return type;
// }
// };
// }
//
// /**
// * Wrap the specified {@link Class} in a {@link Typed} wrapper.
// *
// * @param <T> generic type
// * @param type to wrap
// * @return Typed<T>
// * @since 3.2
// */
// public static <T> Typed<T> wrap(final Class<T> type) {
// return TypeUtils.<T> wrap((Type) type);
// }
/**
* Format a {@link Class} as a {@link String}.
*
* @param c {@code Class} to format
* @param done list of already-encountered types
* @return String
* @since 3.2
*/
private static String classToString(final Class<?> c,
final Set<Type> done)
{
final StringBuilder buf = new StringBuilder();
if (c.getEnclosingClass() != null) {
buf.append(classToString(c.getEnclosingClass(), done)).append('.')
.append(c.getSimpleName());
}
else {
buf.append(c.getName());
}
if (c.getTypeParameters().length > 0) {
buf.append('<');
appendAllTo(buf, ", ", done, c.getTypeParameters());
buf.append('>');
}
return buf.toString();
}
/**
* Format a {@link TypeVariable} as a {@link String}.
*
* @param v {@code TypeVariable} to format
* @param done list of already-encountered types
* @return String
* @since 3.2
*/
private static String typeVariableToString(final TypeVariable<?> v,
final Set<Type> done)
{
final StringBuilder buf = new StringBuilder(v.getName());
if (done.contains(v)) return buf.toString();
done.add(v);
final Type[] bounds = v.getBounds();
if (bounds.length > 0 && !(bounds.length == 1 && Object.class.equals(
bounds[0])))
{
buf.append(" extends ");
appendAllTo(buf, " & ", done, v.getBounds());
}
return buf.toString();
}
/**
* Format a {@link ParameterizedType} as a {@link String}.
*
* @param p {@code ParameterizedType} to format
* @param done list of already-encountered types
* @return String
* @since 3.2
*/
private static String parameterizedTypeToString(final ParameterizedType p,
final Set<Type> done)
{
final StringBuilder buf = new StringBuilder();
final Type useOwner = p.getOwnerType();
final Class<?> raw = (Class<?>) p.getRawType();
final Type[] typeArguments = p.getActualTypeArguments();
if (useOwner == null) {
buf.append(raw.getName());
}
else {
if (useOwner instanceof Class) {
buf.append(((Class<?>) useOwner).getName());
}
else {
buf.append(useOwner.toString());
}
buf.append('.').append(raw.getSimpleName());
}
appendAllTo(buf.append('<'), ", ", done, typeArguments).append('>');
return buf.toString();
}
/**
* Format a {@link WildcardType} as a {@link String}.
*
* @param w {@code WildcardType} to format
* @param done list of already-encountered types
* @return String
* @since 3.2
*/
private static String wildcardTypeToString(final WildcardType w,
final Set<Type> done)
{
final StringBuilder buf = new StringBuilder().append('?');
if (done.contains(w)) return buf.toString();
done.add(w);
final Type[] lowerBounds = w.getLowerBounds();
final Type[] upperBounds = w.getUpperBounds();
if (lowerBounds.length > 1 || lowerBounds.length == 1 &&
lowerBounds[0] != null)
{
appendAllTo(buf.append(" super "), " & ", done, lowerBounds);
}
else if (upperBounds.length > 1 || upperBounds.length == 1 &&
!Object.class.equals(upperBounds[0]))
{
appendAllTo(buf.append(" extends "), " & ", done, upperBounds);
}
return buf.toString();
}
/**
* Format a {@link GenericArrayType} as a {@link String}.
*
* @param g {@code GenericArrayType} to format
* @return String
* @since 3.2
*/
private static String genericArrayTypeToString(final GenericArrayType g) {
return String.format("%s[]", toString(g.getGenericComponentType()));
}
/**
* Append {@code types} to {@code buf} with separator {@code sep}.
*
* @param buf destination
* @param sep separator
* @param done list of already-encountered types
* @param types to append
* @return {@code buf}
* @since 3.2
*/
private static StringBuilder appendAllTo(final StringBuilder buf,
final String sep, final Set<Type> done, final Type... types)
{
validateNotEmpty(validateNoNullElements(types));
if (types.length > 0) {
buf.append(toString(types[0], done));
for (int i = 1; i < types.length; i++) {
buf.append(sep).append(toString(types[i], done));
}
}
return buf;
}
private static final String DEFAULT_IS_NULL_EX_MESSAGE =
"The validated object is null";
/** Forked from {@code org.apache.commons.lang3.Validate#notNull}. */
private static <T> T validateNotNull(final T object) {
return validateNotNull(object, DEFAULT_IS_NULL_EX_MESSAGE);
}
/** Forked from {@code org.apache.commons.lang3.Validate#notNull}. */
private static <T> T validateNotNull(final T object, final String message,
final Object... values)
{
if (object == null) {
throw new NullPointerException(String.format(message, values));
}
return object;
}
/** Forked from {@code org.apache.commons.lang3.Validate#isTrue}. */
private static void validateIsTrue(final boolean expression,
final String message, final Object... values)
{
if (expression == false) {
throw new IllegalArgumentException(String.format(message, values));
}
}
private static final String DEFAULT_NO_NULL_ELEMENTS_ARRAY_EX_MESSAGE =
"The validated array contains null element at index: %d";
/** Forked from {@code org.apache.commons.lang3.Validate#noNullElements}. */
private static <T> T[] validateNoNullElements(final T[] array) {
return validateNoNullElements(array,
DEFAULT_NO_NULL_ELEMENTS_ARRAY_EX_MESSAGE);
}
/** Forked from {@code org.apache.commons.lang3.Validate#noNullElements}. */
private static <T> T[] validateNoNullElements(final T[] array,
final String message, final Object... values)
{
validateNotNull(array);
for (int i = 0; i < array.length; i++) {
if (array[i] == null) {
final Object[] values2 = new Object[values.length + 1];
System.arraycopy(values, 0, values2, 0, values.length);
values2[values.length] = Integer.valueOf(i);
throw new IllegalArgumentException(String.format(message, values2));
}
}
return array;
}
private static final String DEFAULT_NOT_EMPTY_ARRAY_EX_MESSAGE =
"The validated array is empty";
/** Forked from {@code org.apache.commons.lang3.Validate#notEmpty}. */
private static <T> T[] validateNotEmpty(final T[] array) {
return validateNotEmpty(array, DEFAULT_NOT_EMPTY_ARRAY_EX_MESSAGE);
}
/** Forked from {@code org.apache.commons.lang3.Validate#notEmpty}. */
private static <T> T[] validateNotEmpty(final T[] array,
final String message, final Object... values)
{
if (array == null) {
throw new NullPointerException(String.format(message, values));
}
if (array.length == 0) {
throw new IllegalArgumentException(String.format(message, values));
}
return array;
}
}
// -- END FORK OF APACHE COMMONS LANG 3.4 CODE --
}
| Types: add missing javadoc
| src/main/java/org/scijava/util/Types.java | Types: add missing javadoc | <ide><path>rc/main/java/org/scijava/util/Types.java
<ide>
<ide> // TODO: Migrate all GenericUtils methods here.
<ide>
<add> /**
<add> * Gets a string representation of the given type.
<add> *
<add> * @param t Type whose name is desired.
<add> * @return The name of the given type.
<add> */
<ide> public static String name(final Type t) {
<ide> // NB: It is annoying that Class.toString() prepends "class " or
<ide> // "interface "; this method exists to work around that behavior.
<ide> * <p>
<ide> * If you want <em>all</em> raw classes of the given type, use {@link #raws}.
<ide> * </p>
<add> * @param type The type from which to discern the (first) raw class.
<add> * @return The type's first raw class.
<ide> */
<ide> public static Class<?> raw(final Type type) {
<ide> // TODO: Consolidate with GenericUtils.
<ide> * return both {@link Number} and {@link Iterable} as its raw classes.
<ide> * </p>
<ide> *
<add> * @param type The type from which to discern the raw classes.
<add> * @return List of the type's raw classes.
<ide> * @see #raw
<ide> */
<ide> public static List<Class<?>> raws(final Type type) {
<ide> * Discerns whether it would be legal to assign a reference of type
<ide> * {@code source} to a reference of type {@code target}.
<ide> *
<add> * @param source The type from which assignment is desired.
<add> * @param target The type to which assignment is desired.
<add> * @return True if the source is assignable to the target.
<add> * @throws NullPointerException if {@code target} is null.
<ide> * @see Class#isAssignableFrom(Class)
<ide> */
<ide> public static boolean isAssignable(final Type source, final Type target) { |
|
Java | epl-1.0 | f155e69609205af3fbe19fab78f300c190e81c48 | 0 | rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,Charling-Huang/birt,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1 |
package org.eclipse.birt.report.tests.engine.api;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Date;
import java.util.Locale;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.birt.report.engine.api.ICascadingParameterGroup;
import org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask;
import org.eclipse.birt.report.engine.api.IParameterDefnBase;
import org.eclipse.birt.report.engine.api.IParameterGroupDefn;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IScalarParameterDefn;
import org.eclipse.birt.report.engine.api.IParameterSelectionChoice;
import org.eclipse.birt.report.tests.engine.EngineCase;
/**
* <b>IGetParameterDefinitionTask API</b>
* <p>
* This test tests all methods in IGetParameterDefinitionTask API
*/
public class IGetParameterDefinitionTaskTest extends EngineCase
{
private String name = "IGetParameterDefinitionTaskTest.rptdesign";
private String input = getClassFolder( ) + "/" + INPUT_FOLDER + "/" + name;
private IGetParameterDefinitionTask task = null;
public IGetParameterDefinitionTaskTest( String name )
{
super( name );
}
/**
* Test suite()
*
* @return
*/
public static Test suite( )
{
return new TestSuite( IGetParameterDefinitionTaskTest.class );
}
protected void setUp( ) throws Exception
{
super.setUp( );
IReportRunnable reportRunnable = engine.openReportDesign( input );
task = engine.createGetParameterDefinitionTask( reportRunnable );
assertTrue( task.getErrors( ).size( ) == 0 );
}
protected void tearDown( ) throws Exception
{
task.close( );
super.tearDown( );
}
/**
* Test getParameterDefns() method
*
* @throws Exception
*/
public void testGetParameterDefns( ) throws Exception
{
boolean includeParameterGroups = true;
ArrayList params = (ArrayList) task
.getParameterDefns( includeParameterGroups );
assertEquals( 6, params.size( ) );
assertTrue( params.get( 0 ) instanceof IScalarParameterDefn );
assertTrue( params.get( 1 ) instanceof IScalarParameterDefn );
assertTrue( params.get( 2 ) instanceof IScalarParameterDefn );
assertTrue( params.get( 3 ) instanceof IParameterGroupDefn );
assertTrue( params.get( 4 ) instanceof ICascadingParameterGroup );
assertTrue( params.get( 5 ) instanceof ICascadingParameterGroup );
includeParameterGroups = false;
params = (ArrayList) task.getParameterDefns( includeParameterGroups );
assertEquals( 10, params.size( ) );
for ( int i = 0; i < params.size( ); i++ )
{
assertTrue( params.get( i ) instanceof IScalarParameterDefn );
}
assertEquals( "p1_string", ( (IScalarParameterDefn) params.get( 0 ) )
.getName( ) );
assertEquals( 0, ( (IScalarParameterDefn) params.get( 0 ) )
.getControlType( ) );
assertEquals( "abc", ( (IScalarParameterDefn) params.get( 0 ) )
.getDefaultValue( ) );
assertEquals( 2, ( (IScalarParameterDefn) params.get( 1 ) )
.getSelectionListType( ) );
assertEquals( 1, ( (IScalarParameterDefn) params.get( 1 ) )
.getControlType( ) );
assertEquals( 1, ( (IScalarParameterDefn) params.get( 2 ) )
.getSelectionListType( ) );
assertEquals( "p42_float", ( (IScalarParameterDefn) params.get( 4 ) )
.getName( ) );
assertEquals( 2, ( (IScalarParameterDefn) params.get( 4 ) )
.getDataType( ) );
assertEquals( "p51", ( (IScalarParameterDefn) params.get( 5 ) )
.getName( ) );
assertEquals( "p61_country", ( (IScalarParameterDefn) params.get( 7 ) )
.getName( ) );
}
/**
* Test getParameterDefn(String) method
*
* @throws Exception
*/
public void testGetParameterDefn( ) throws Exception
{
IParameterDefnBase paramDefn = task.getParameterDefn( "p1_string" );
assertNotNull( paramDefn );
assertEquals( 0, paramDefn.getParameterType( ) );
assertEquals( "scalar", paramDefn.getTypeName( ) );
assertEquals( 6, paramDefn.getHandle( ).getID( ) );
paramDefn.getHandle( ).setDisplayName( "STRINGParameter" );
assertEquals( "STRINGParameter", paramDefn
.getHandle( )
.getDisplayName( ) );
// getDisplayName() from paramDefn
// assertEquals("STRINGParameter",paramDefn.getDisplayName());
paramDefn = task.getParameterDefn( "p2_static_dt" );
assertNotNull( paramDefn );
assertEquals( 0, paramDefn.getParameterType( ) );
assertEquals( "p2_static_dt", paramDefn.getName( ) );
paramDefn = task.getParameterDefn( "p3_dynamic_int" );
assertNotNull( paramDefn );
// what's the difference between the following parameters?
// SCALAR_PARAMETER = 0;
// FILTER_PARAMETER = 1;
// LIST_PARAMETER = 2;
// TABLE_PARAMETER = 3;
assertEquals( 0, paramDefn.getParameterType( ) );
paramDefn = task.getParameterDefn( "p4_group" );
assertNotNull( paramDefn );
assertEquals( 4, paramDefn.getParameterType( ) );
assertEquals( 9, paramDefn.getHandle( ).getID( ) );
paramDefn = task.getParameterDefn( "p41_decimal" );
assertNotNull( paramDefn );
paramDefn = task.getParameterDefn( "p5_CascadingGroup_single" );
assertNotNull( paramDefn );
assertEquals( 5, paramDefn.getParameterType( ) );
paramDefn = task.getParameterDefn( "p51" );
assertNotNull( paramDefn );
paramDefn = task.getParameterDefn( "p6_CascadingGroup_multiple" );
assertNotNull( paramDefn );
paramDefn = task.getParameterDefn( "p62_customernumber" );
assertNotNull( paramDefn );
paramDefn = task.getParameterDefn( "invalid" );
assertNull( paramDefn );
paramDefn = task.getParameterDefn( null );
assertNull( paramDefn );
}
/**
* Test setValue method This method is not implemented at present.
*
* @throws Exception
*/
public void testSetValue( ) throws Exception
{
task.setValue( "p1_string", "aaa" );
Date d = new Date( );
task.setValue( "p2_static_dt", d );
}
/**
* Test getDefaultValues() method
*
* @throws Exception
*/
public void testGetDefaultValues( ) throws Exception
{
HashMap values = task.getDefaultValues( );
assertNotNull( values );
assertEquals( 10, values.size( ) );
assertEquals( "abc", values.get( "p1_string" ) );
assertEquals( "10251", values.get( "p3_dynamic_int" ).toString( ) );
assertEquals( "2.35", values.get( "p41_decimal" ).toString( ) );
assertEquals( "87.16", values.get( "p42_float" ).toString( ) );
setLocale( Locale.CHINA );
assertEquals( null, values.get( "p51" ) );
assertEquals( null, values.get( "p52" ) );
assertNull( values.get( "p61_country" ) );
assertNull( values.get( "p61_customernumber" ) );
assertNull( values.get( "p61_orderno" ) );
}
/**
* Test getDefaultValue(IParameterDefnBase param) method Test
* getDefaultValue(String name) method
*
* @throws Exception
*/
public void testGetDefaultValue( ) throws Exception
{
assertEquals( "abc", task.getDefaultValue( "p1_string" ) );
assertEquals( "10251", task
.getDefaultValue( "p3_dynamic_int" )
.toString( ) );
assertEquals( "2.35", task.getDefaultValue( "p41_decimal" ).toString( ) );
assertEquals( "87.16", task.getDefaultValue( "p42_float" ).toString( ) );
}
public void testGetSelectionList( ) throws Exception
{
ArrayList selist = (ArrayList) task.getSelectionList( "p2_static_dt" );
IParameterSelectionChoice se = (IParameterSelectionChoice) selist
.get( 0 );
assertEquals( "Tue May 11 00:00:00 GMT+08:00 2004", se
.getValue( )
.toString( ) );
se = (IParameterSelectionChoice) selist.get( 1 );
assertEquals( "Tue May 18 00:00:00 GMT+08:00 2004", se
.getValue( )
.toString( ) );
selist = (ArrayList) task.getSelectionList( "p3_dynamic_int" );
se = (IParameterSelectionChoice) selist.get( 0 );
assertEquals( "10250", se.getValue( ).toString( ) );
int listnumb = selist.size( );
assertEquals( 21, listnumb );
// Cascading parameters with single dataset
selist = (ArrayList) task.getSelectionList( "p51" );
se = (IParameterSelectionChoice) selist.get( 0 );
assertEquals( "Cancelled", se.getValue( ).toString( ) );
task.setValue( "p51", "Shipped" );
selist = (ArrayList) task.getSelectionList( "p52" );
se = (IParameterSelectionChoice) selist.get( 0 );
assertEquals( "10250", se.getValue( ).toString( ) );
task.setValue( "p51", "Cancelled" );
selist = (ArrayList) task.getSelectionList( "p52" );
se = (IParameterSelectionChoice) selist.get( 0 );
assertEquals( "10253", se.getValue( ).toString( ) );
// Cascading parameters with multiple datasets
selist = (ArrayList) task.getSelectionList( "p61_country" );
se = (IParameterSelectionChoice) selist.get( 0 );
assertEquals( "Australia", se.getValue( ).toString( ) );
task.setValue( "p61_country", "UK" );
selist = (ArrayList) task.getSelectionList( "p62_customernumber" );
se = (IParameterSelectionChoice) selist.get( 0 );
assertEquals( "187", se.getValue( ).toString( ) );
Integer icustno = new Integer( "240" );
task.setValue( "p62_customernumber", icustno );
selist = (ArrayList) task.getSelectionList( "p63_orderno" );
se = (IParameterSelectionChoice) selist.get( 0 );
assertEquals( "10232", se.getValue( ).toString( ) );
// set the value that not in the list
Integer iorderno = new Integer( "10333" );
task.setValue( "p63_orderno", iorderno );
}
public void testGetSelectionListForCascadingGroup( ) throws Exception
{
task.evaluateQuery( "p5_CascadingGroup_single" );
ArrayList selist = (ArrayList) task.getSelectionListForCascadingGroup(
"p5_CascadingGroup_single",
new Object[]{"Cancelled"} );
IParameterSelectionChoice se = (IParameterSelectionChoice) selist
.get( 0 );
assertEquals( "10253", se.getValue( ).toString( ) );
selist = (ArrayList) task.getSelectionListForCascadingGroup(
"p6_CascadingGroup_multiple",
new Object[]{"UK"} );
se = (IParameterSelectionChoice) selist.get( 0 );
assertEquals( "187", se.getValue( ).toString( ) );
Integer icustnum = new Integer( "187" );
selist = (ArrayList) task.getSelectionListForCascadingGroup(
"p6_CascadingGroup_multiple",
new Object[]{"UK", icustnum} );
se = (IParameterSelectionChoice) selist.get( 0 );
assertEquals( "10110", se.getValue( ).toString( ) );
}
public void testEvaluateQuery( ) throws Exception
{
// TODO;
}
}
| testsuites/org.eclipse.birt.report.tests.engine/src/org/eclipse/birt/report/tests/engine/api/IGetParameterDefinitionTaskTest.java |
package org.eclipse.birt.report.tests.engine.api;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Date;
import java.util.Locale;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.api.ICascadingParameterGroup;
import org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask;
import org.eclipse.birt.report.engine.api.IParameterDefnBase;
import org.eclipse.birt.report.engine.api.IParameterGroupDefn;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IScalarParameterDefn;
import org.eclipse.birt.report.engine.api.IParameterSelectionChoice;
import org.eclipse.birt.report.tests.engine.EngineCase;
/**
* <b>IGetParameterDefinitionTask API</b>
* <p>
* This test tests all methods in IGetParameterDefinitionTask API
*/
public class IGetParameterDefinitionTaskTest extends EngineCase
{
private String name = "IGetParameterDefinitionTaskTest.rptdesign";
private String input = getClassFolder( ) + "/" + INPUT_FOLDER + "/" + name;
private IGetParameterDefinitionTask task = null;
private String outputFileName="output.html";
public IGetParameterDefinitionTaskTest( String name )
{
super( name );
}
/**
* Test suite()
*
* @return
*/
public static Test suite( )
{
return new TestSuite( IGetParameterDefinitionTaskTest.class );
}
protected void setUp( ) throws Exception
{
super.setUp( );
IReportRunnable reportRunnable = engine.openReportDesign( input );
task = engine.createGetParameterDefinitionTask( reportRunnable );
assertTrue( task.getErrors( ).size( ) == 0 );
}
protected void tearDown( ) throws Exception
{
task.close( );
super.tearDown( );
}
/**
* Test getParameterDefns() method
*
* @throws Exception
*/
public void testGetParameterDefns( ) throws Exception
{
boolean includeParameterGroups = true;
ArrayList params = (ArrayList) task
.getParameterDefns( includeParameterGroups );
assertEquals( 6, params.size( ) );
assertTrue( params.get( 0 ) instanceof IScalarParameterDefn );
assertTrue( params.get( 1 ) instanceof IScalarParameterDefn );
assertTrue( params.get( 2 ) instanceof IScalarParameterDefn );
assertTrue( params.get( 3 ) instanceof IParameterGroupDefn );
assertTrue( params.get( 4 ) instanceof ICascadingParameterGroup );
assertTrue( params.get( 5 ) instanceof ICascadingParameterGroup );
includeParameterGroups = false;
params = (ArrayList) task.getParameterDefns( includeParameterGroups );
assertEquals( 10, params.size( ) );
for ( int i = 0; i < params.size( ); i++ )
{
assertTrue( params.get( i ) instanceof IScalarParameterDefn );
}
assertEquals( "p1_string", ( (IScalarParameterDefn) params.get( 0 ) )
.getName( ) );
assertEquals( 0, ( (IScalarParameterDefn) params.get( 0 ) )
.getControlType( ) );
assertEquals( "abc", ( (IScalarParameterDefn) params.get( 0 ) )
.getDefaultValue( ) );
assertEquals( 2, ( (IScalarParameterDefn) params.get( 1 ) )
.getSelectionListType( ) );
assertEquals( 1, ( (IScalarParameterDefn) params.get( 1 ) )
.getControlType( ) );
assertEquals( 1, ( (IScalarParameterDefn) params.get( 2 ) )
.getSelectionListType( ) );
assertEquals( "p42_float", ( (IScalarParameterDefn) params.get( 4 ) )
.getName( ) );
assertEquals( 2, ( (IScalarParameterDefn) params.get( 4 ) )
.getDataType( ) );
assertEquals( "p51", ( (IScalarParameterDefn) params.get( 5 ) )
.getName( ) );
assertEquals( "p61_country", ( (IScalarParameterDefn) params.get( 7 ) )
.getName( ) );
}
/**
* Test getParameterDefn(String) method
*
* @throws Exception
*/
public void testGetParameterDefn( ) throws Exception
{
IParameterDefnBase paramDefn = task.getParameterDefn( "p1_string" );
assertNotNull( paramDefn );
assertEquals( 0, paramDefn.getParameterType( ) );
assertEquals("scalar",paramDefn.getTypeName());
assertEquals( 6, paramDefn.getHandle( ).getID( ) );
paramDefn.getHandle( ).setDisplayName( "STRINGParameter" );
assertEquals( "STRINGParameter", paramDefn
.getHandle( )
.getDisplayName( ) );
// getDisplayName() from paramDefn
// assertEquals("STRINGParameter",paramDefn.getDisplayName());
paramDefn = task.getParameterDefn( "p2_static_dt" );
assertNotNull( paramDefn );
assertEquals( 0, paramDefn.getParameterType( ) );
assertEquals( "p2_static_dt", paramDefn.getName( ) );
paramDefn = task.getParameterDefn( "p3_dynamic_int" );
assertNotNull( paramDefn );
// what's the difference between the following parameters?
// SCALAR_PARAMETER = 0;
// FILTER_PARAMETER = 1;
// LIST_PARAMETER = 2;
// TABLE_PARAMETER = 3;
assertEquals( 0, paramDefn.getParameterType( ) );
paramDefn = task.getParameterDefn( "p4_group" );
assertNotNull( paramDefn );
assertEquals( 4, paramDefn.getParameterType( ) );
assertEquals( 9, paramDefn.getHandle( ).getID( ) );
paramDefn = task.getParameterDefn( "p41_decimal" );
assertNotNull( paramDefn );
paramDefn = task.getParameterDefn( "p5_CascadingGroup_single" );
assertNotNull( paramDefn );
assertEquals( 5, paramDefn.getParameterType( ) );
paramDefn = task.getParameterDefn( "p51" );
assertNotNull( paramDefn );
paramDefn = task.getParameterDefn( "p6_CascadingGroup_multiple" );
assertNotNull( paramDefn );
paramDefn = task.getParameterDefn( "p62_customernumber" );
assertNotNull( paramDefn );
paramDefn = task.getParameterDefn( "invalid" );
assertNull( paramDefn );
paramDefn = task.getParameterDefn( null );
assertNull( paramDefn );
}
/**
* Test setValue method This method is not implemented at present.
*
* @throws Exception
*/
public void testSetValue( ) throws Exception
{
task.setValue( "p1_string", "aaa" );
Date d = new Date( );
task.setValue( "p2_static_dt", d );
}
/**
* Test getDefaultValues() method
*
* @throws Exception
*/
public void testGetDefaultValues( ) throws Exception
{
HashMap values = task.getDefaultValues( );
assertNotNull( values );
assertEquals( 10, values.size( ) );
assertEquals( "abc", values.get( "p1_string" ) );
assertEquals( "10251", values.get( "p3_dynamic_int" ).toString( ) );
assertEquals( "2.35", values.get( "p41_decimal" ).toString( ) );
assertEquals( "87.16", values.get( "p42_float" ).toString( ) );
setLocale( Locale.CHINA );
assertEquals( null, values.get( "p51" ) );
assertEquals( null, values.get( "p52" ) );
assertNull( values.get( "p61_country" ) );
assertNull( values.get( "p61_customernumber" ) );
assertNull( values.get( "p61_orderno" ) );
}
/**
* Test getDefaultValue(IParameterDefnBase param) method Test
* getDefaultValue(String name) method
*
* @throws Exception
*/
public void testGetDefaultValue( ) throws Exception
{
assertEquals( "abc", task.getDefaultValue( "p1_string" ) );
assertEquals( "10251", task
.getDefaultValue( "p3_dynamic_int" )
.toString( ) );
assertEquals( "2.35", task.getDefaultValue( "p41_decimal" ).toString( ) );
assertEquals( "87.16", task.getDefaultValue( "p42_float" ).toString( ) );
}
public void testGetSelectionList( ) throws Exception
{
ArrayList selist = (ArrayList) task.getSelectionList( "p2_static_dt" );
IParameterSelectionChoice se = (IParameterSelectionChoice) selist
.get( 0 );
assertEquals( "Tue May 11 00:00:00 CST 2004", se.getValue( ).toString( ) );
se = (IParameterSelectionChoice) selist.get( 1 );
assertEquals( "Tue May 18 00:00:00 CST 2004", se.getValue( ).toString( ) );
selist = (ArrayList) task.getSelectionList( "p3_dynamic_int" );
se = (IParameterSelectionChoice) selist.get( 0 );
assertEquals( "10250", se.getValue( ).toString( ) );
int listnumb = selist.size( );
assertEquals( 21, listnumb );
// Cascading parameters with single dataset
selist = (ArrayList) task.getSelectionList( "p51" );
se = (IParameterSelectionChoice) selist.get( 0 );
assertEquals( "Cancelled", se.getValue( ).toString( ) );
task.setValue( "p51", "Shipped" );
selist = (ArrayList) task.getSelectionList( "p52" );
se = (IParameterSelectionChoice) selist.get( 0 );
assertEquals( "10250", se.getValue( ).toString( ) );
task.setValue( "p51", "Cancelled" );
selist = (ArrayList) task.getSelectionList( "p52" );
se = (IParameterSelectionChoice) selist.get( 0 );
assertEquals( "10253", se.getValue( ).toString( ) );
// Cascading parameters with multiple datasets
selist = (ArrayList) task.getSelectionList( "p61_country" );
se = (IParameterSelectionChoice) selist.get( 0 );
assertEquals( "Australia", se.getValue( ).toString( ) );
task.setValue( "p61_country", "UK" );
selist = (ArrayList) task.getSelectionList( "p62_customernumber" );
se = (IParameterSelectionChoice) selist.get( 0 );
assertEquals( "187", se.getValue( ).toString( ) );
Integer icustno = new Integer( "240" );
task.setValue( "p62_customernumber", icustno );
selist = (ArrayList) task.getSelectionList( "p63_orderno" );
se = (IParameterSelectionChoice) selist.get( 0 );
assertEquals( "10232", se.getValue( ).toString( ) );
// set the value that not in the list
Integer iorderno = new Integer( "10333" );
task.setValue( "p63_orderno", iorderno );
}
public void testGetSelectionListForCascadingGroup( ) throws Exception
{
task.evaluateQuery( "p5_CascadingGroup_single" );
ArrayList selist = (ArrayList) task.getSelectionListForCascadingGroup(
"p5_CascadingGroup_single",
new Object[]{"Cancelled"} );
IParameterSelectionChoice se = (IParameterSelectionChoice) selist
.get( 0 );
assertEquals( "10253", se.getValue( ).toString( ) );
selist = (ArrayList) task.getSelectionListForCascadingGroup(
"p6_CascadingGroup_multiple",
new Object[]{"UK"} );
se = (IParameterSelectionChoice) selist.get( 0 );
assertEquals( "187", se.getValue( ).toString( ) );
Integer icustnum = new Integer( "187" );
selist = (ArrayList) task.getSelectionListForCascadingGroup(
"p6_CascadingGroup_multiple",
new Object[]{"UK", icustnum} );
se = (IParameterSelectionChoice) selist.get( 0 );
assertEquals( "10110", se.getValue( ).toString( ) );
}
public void testEvaluateQuery( ) throws Exception
{
// TODO;
}
}
| Update returned datetime value in IGetParameterDefinitionTaskTest.java according to DTE codes change.
Correct error codes in ElementTest.java.
Add onPageBreak case to TextItemEventHandlerTest.java because related bug has been fixed.
| testsuites/org.eclipse.birt.report.tests.engine/src/org/eclipse/birt/report/tests/engine/api/IGetParameterDefinitionTaskTest.java | Update returned datetime value in IGetParameterDefinitionTaskTest.java according to DTE codes change. Correct error codes in ElementTest.java. Add onPageBreak case to TextItemEventHandlerTest.java because related bug has been fixed. | <ide><path>estsuites/org.eclipse.birt.report.tests.engine/src/org/eclipse/birt/report/tests/engine/api/IGetParameterDefinitionTaskTest.java
<ide> package org.eclipse.birt.report.tests.engine.api;
<ide>
<ide> import java.util.ArrayList;
<del>import java.util.Collection;
<ide> import java.util.HashMap;
<ide> import java.util.Date;
<ide> import java.util.Locale;
<ide> import junit.framework.Test;
<ide> import junit.framework.TestSuite;
<ide>
<del>import org.eclipse.birt.report.engine.api.EngineException;
<ide> import org.eclipse.birt.report.engine.api.ICascadingParameterGroup;
<ide> import org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask;
<ide> import org.eclipse.birt.report.engine.api.IParameterDefnBase;
<ide> private String name = "IGetParameterDefinitionTaskTest.rptdesign";
<ide> private String input = getClassFolder( ) + "/" + INPUT_FOLDER + "/" + name;
<ide> private IGetParameterDefinitionTask task = null;
<del> private String outputFileName="output.html";
<add>
<ide> public IGetParameterDefinitionTaskTest( String name )
<ide> {
<ide> super( name );
<ide> IParameterDefnBase paramDefn = task.getParameterDefn( "p1_string" );
<ide> assertNotNull( paramDefn );
<ide> assertEquals( 0, paramDefn.getParameterType( ) );
<del> assertEquals("scalar",paramDefn.getTypeName());
<add> assertEquals( "scalar", paramDefn.getTypeName( ) );
<ide> assertEquals( 6, paramDefn.getHandle( ).getID( ) );
<ide>
<ide> paramDefn.getHandle( ).setDisplayName( "STRINGParameter" );
<ide> assertEquals( "87.16", values.get( "p42_float" ).toString( ) );
<ide> setLocale( Locale.CHINA );
<ide>
<del>
<ide> assertEquals( null, values.get( "p51" ) );
<ide> assertEquals( null, values.get( "p52" ) );
<ide>
<ide>
<ide> IParameterSelectionChoice se = (IParameterSelectionChoice) selist
<ide> .get( 0 );
<del> assertEquals( "Tue May 11 00:00:00 CST 2004", se.getValue( ).toString( ) );
<add> assertEquals( "Tue May 11 00:00:00 GMT+08:00 2004", se
<add> .getValue( )
<add> .toString( ) );
<ide> se = (IParameterSelectionChoice) selist.get( 1 );
<del> assertEquals( "Tue May 18 00:00:00 CST 2004", se.getValue( ).toString( ) );
<add> assertEquals( "Tue May 18 00:00:00 GMT+08:00 2004", se
<add> .getValue( )
<add> .toString( ) );
<ide>
<ide> selist = (ArrayList) task.getSelectionList( "p3_dynamic_int" );
<ide> se = (IParameterSelectionChoice) selist.get( 0 ); |
|
Java | mit | 4af1f83474b4c022619b192f6eedf2ac58b9a205 | 0 | PrinceOfAmber/CyclicMagic,PrinceOfAmber/Cyclic | package com.lothrazar.cyclicmagic.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import com.google.common.io.Files;
import com.lothrazar.cyclicmagic.ModCyclic;
import com.lothrazar.cyclicmagic.gui.player.InventoryPlayerExtended;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.event.entity.player.PlayerEvent;
/*Thank you so much for the help azanor
* for basically writing this class and releasing it open source
*
* https://github.com/Azanor/Baubles
*
* which is under Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0) license.
* so i was able to use parts of that to make this
* **/
public class UtilPlayerInventoryFilestorage {
public static HashSet<Integer> playerEntityIds = new HashSet<Integer>();
private static HashMap<String, InventoryPlayerExtended> playerItems = new HashMap<String, InventoryPlayerExtended>();
public static void playerSetupOnLoad(PlayerEvent.LoadFromFile event) {
EntityPlayer player = event.getEntityPlayer();
clearPlayerInventory(player);
File playerFile = getPlayerFile(ext, event.getPlayerDirectory(), event.getEntityPlayer().getDisplayNameString());
if (!playerFile.exists()) {
File fileNew = event.getPlayerFile(ext);
if (fileNew.exists()) {
try {
Files.copy(fileNew, playerFile);
ModCyclic.logger.info("Using and converting UUID savefile for " + player.getDisplayNameString());
fileNew.delete();
File fb = event.getPlayerFile(extback);
if (fb.exists())
fb.delete();
}
catch (IOException e) {
}
}
}
loadPlayerInventory(event.getEntityPlayer(), playerFile, getPlayerFile(extback, event.getPlayerDirectory(), event.getEntityPlayer().getDisplayNameString()));
playerEntityIds.add(event.getEntityPlayer().getEntityId());
}
public static void clearPlayerInventory(EntityPlayer player) {
playerItems.remove(player.getDisplayNameString());
}
public static InventoryPlayerExtended getPlayerInventory(EntityPlayer player) {
if (!playerItems.containsKey(player.getDisplayNameString())) {
InventoryPlayerExtended inventory = new InventoryPlayerExtended(player);
playerItems.put(player.getDisplayNameString(), inventory);
}
return playerItems.get(player.getDisplayNameString());
}
public static ItemStack getPlayerInventoryStack(EntityPlayer player, int slot) {
return getPlayerInventory(player).getStackInSlot(slot);
}
public static void setPlayerInventoryStack(EntityPlayer player, int slot, ItemStack itemStack) {
// UtilPlayerInventoryFilestorage.getPlayerInventory(player).setInventorySlotContents(slot, itemStack);
getPlayerInventory(player).stackList[slot] = itemStack;
}
public static void setPlayerInventory(EntityPlayer player, InventoryPlayerExtended inventory) {
playerItems.put(player.getDisplayNameString(), inventory);
}
public static void loadPlayerInventory(EntityPlayer player, File file1, File file2) {
if (player != null && !player.getEntityWorld().isRemote) {
try {
NBTTagCompound data = null;
boolean save = false;
if (file1 != null && file1.exists()) {
try {
FileInputStream fileinputstream = new FileInputStream(file1);
data = CompressedStreamTools.readCompressed(fileinputstream);
fileinputstream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
if (file1 == null || !file1.exists() || data == null || data.hasNoTags()) {
ModCyclic.logger.warn("Data not found for " + player.getDisplayNameString() + ". Trying to load backup data.");
if (file2 != null && file2.exists()) {
try {
FileInputStream fileinputstream = new FileInputStream(file2);
data = CompressedStreamTools.readCompressed(fileinputstream);
fileinputstream.close();
save = true;
}
catch (Exception e) {
e.printStackTrace();
}
}
}
if (data != null) {
InventoryPlayerExtended inventory = new InventoryPlayerExtended(player);
inventory.readNBT(data);
playerItems.put(player.getDisplayNameString(), inventory);
if (save)
savePlayerItems(player, file1, file2);
}
}
catch (Exception e) {
ModCyclic.logger.error("Error loading player extended inventory");
e.printStackTrace();
}
}
}
public static void savePlayerItems(EntityPlayer player, File file1, File file2) {
if (player != null && !player.getEntityWorld().isRemote) {
try {
if (file1 != null && file1.exists()) {
try {
Files.copy(file1, file2);
}
catch (Exception e) {
ModCyclic.logger.error("Could not backup old file for player " + player.getDisplayNameString());
}
}
try {
if (file1 != null) {
InventoryPlayerExtended inventory = getPlayerInventory(player);
NBTTagCompound data = new NBTTagCompound();
inventory.saveNBT(data);
FileOutputStream fileoutputstream = new FileOutputStream(file1);
CompressedStreamTools.writeCompressed(data, fileoutputstream);
fileoutputstream.close();
}
}
catch (Exception e) {
ModCyclic.logger.error("Could not save file for player " + player.getDisplayNameString());
e.printStackTrace();
if (file1.exists()) {
try {
file1.delete();
}
catch (Exception e2) {
}
}
}
}
catch (Exception exception1) {
ModCyclic.logger.error("Error saving inventory");
exception1.printStackTrace();
}
}
}
public static final String ext = "invo";
public static final String extback = "backup";
public static final String regex = "[^a-zA-Z0-9_]";
public static File getPlayerFile(String suffix, File playerDirectory, String playername) {
// some other mods/servers/plugins add things like "[Owner] > " prefix to player names
//which are invalid filename chars. https://github.com/PrinceOfAmber/Cyclic/issues/188
//mojang username rules https://help.mojang.com/customer/en/portal/articles/928638-minecraft-usernames
String playernameFiltered = playername.replaceAll(regex, "");
return new File(playerDirectory, "_" + playernameFiltered + "." + suffix);
}
public static void syncItems(EntityPlayer player) {
int size = InventoryPlayerExtended.ICOL * InventoryPlayerExtended.IROW;
for (int a = 0; a < size; a++) {
getPlayerInventory(player).syncSlotToClients(a);
}
}
public static void putDataIntoInventory(InventoryPlayerExtended inventory, EntityPlayer player) {
inventory.stackList = getPlayerInventory(player).stackList;
}
}
| src/main/java/com/lothrazar/cyclicmagic/util/UtilPlayerInventoryFilestorage.java | package com.lothrazar.cyclicmagic.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import com.google.common.io.Files;
import com.lothrazar.cyclicmagic.ModCyclic;
import com.lothrazar.cyclicmagic.gui.player.InventoryPlayerExtended;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.event.entity.player.PlayerEvent;
/*Thank you so much for the help azanor
* for basically writing this class and releasing it open source
*
* https://github.com/Azanor/Baubles
*
* which is under Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0) license.
* so i was able to use parts of that to make this
* **/
public class UtilPlayerInventoryFilestorage {
public static HashSet<Integer> playerEntityIds = new HashSet<Integer>();
private static HashMap<String, InventoryPlayerExtended> playerItems = new HashMap<String, InventoryPlayerExtended>();
public static void playerSetupOnLoad(PlayerEvent.LoadFromFile event) {
EntityPlayer player = event.getEntityPlayer();
clearPlayerInventory(player);
File playerFile = getPlayerFile(ext, event.getPlayerDirectory(), event.getEntityPlayer().getDisplayNameString());
if (!playerFile.exists()) {
File fileNew = event.getPlayerFile(ext);
if (fileNew.exists()) {
try {
Files.copy(fileNew, playerFile);
ModCyclic.logger.info("Using and converting UUID savefile for " + player.getDisplayNameString());
fileNew.delete();
File fb = event.getPlayerFile(extback);
if (fb.exists())
fb.delete();
}
catch (IOException e) {
}
}
}
loadPlayerInventory(event.getEntityPlayer(), playerFile, getPlayerFile(extback, event.getPlayerDirectory(), event.getEntityPlayer().getDisplayNameString()));
playerEntityIds.add(event.getEntityPlayer().getEntityId());
}
public static void clearPlayerInventory(EntityPlayer player) {
playerItems.remove(player.getDisplayNameString());
}
public static InventoryPlayerExtended getPlayerInventory(EntityPlayer player) {
if (!playerItems.containsKey(player.getDisplayNameString())) {
InventoryPlayerExtended inventory = new InventoryPlayerExtended(player);
playerItems.put(player.getDisplayNameString(), inventory);
}
return playerItems.get(player.getDisplayNameString());
}
public static ItemStack getPlayerInventoryStack(EntityPlayer player, int slot) {
return getPlayerInventory(player).getStackInSlot(slot);
}
public static void setPlayerInventoryStack(EntityPlayer player, int slot, ItemStack itemStack) {
// UtilPlayerInventoryFilestorage.getPlayerInventory(player).setInventorySlotContents(slot, itemStack);
getPlayerInventory(player).stackList[slot] = itemStack;
}
public static void setPlayerInventory(EntityPlayer player, InventoryPlayerExtended inventory) {
playerItems.put(player.getDisplayNameString(), inventory);
}
public static void loadPlayerInventory(EntityPlayer player, File file1, File file2) {
if (player != null && !player.getEntityWorld().isRemote) {
try {
NBTTagCompound data = null;
boolean save = false;
if (file1 != null && file1.exists()) {
try {
FileInputStream fileinputstream = new FileInputStream(file1);
data = CompressedStreamTools.readCompressed(fileinputstream);
fileinputstream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
if (file1 == null || !file1.exists() || data == null || data.hasNoTags()) {
ModCyclic.logger.warn("Data not found for " + player.getDisplayNameString() + ". Trying to load backup data.");
if (file2 != null && file2.exists()) {
try {
FileInputStream fileinputstream = new FileInputStream(file2);
data = CompressedStreamTools.readCompressed(fileinputstream);
fileinputstream.close();
save = true;
}
catch (Exception e) {
e.printStackTrace();
}
}
}
if (data != null) {
InventoryPlayerExtended inventory = new InventoryPlayerExtended(player);
inventory.readNBT(data);
playerItems.put(player.getDisplayNameString(), inventory);
if (save)
savePlayerItems(player, file1, file2);
}
}
catch (Exception e) {
ModCyclic.logger.error("Error loading player extended inventory");
e.printStackTrace();
}
}
}
public static void savePlayerItems(EntityPlayer player, File file1, File file2) {
if (player != null && !player.getEntityWorld().isRemote) {
try {
if (file1 != null && file1.exists()) {
try {
Files.copy(file1, file2);
}
catch (Exception e) {
ModCyclic.logger.error("Could not backup old file for player " + player.getDisplayNameString());
}
}
try {
if (file1 != null) {
InventoryPlayerExtended inventory = getPlayerInventory(player);
NBTTagCompound data = new NBTTagCompound();
inventory.saveNBT(data);
FileOutputStream fileoutputstream = new FileOutputStream(file1);
CompressedStreamTools.writeCompressed(data, fileoutputstream);
fileoutputstream.close();
}
}
catch (Exception e) {
ModCyclic.logger.error("Could not save file for player " + player.getDisplayNameString());
e.printStackTrace();
if (file1.exists()) {
try {
file1.delete();
}
catch (Exception e2) {
}
}
}
}
catch (Exception exception1) {
ModCyclic.logger.error("Error saving inventory");
exception1.printStackTrace();
}
}
}
public static final String ext = "invo";
public static final String extback = "backup";
public static File getPlayerFile(String suffix, File playerDirectory, String playername) {
return new File(playerDirectory, "_" + playername + "." + suffix);
}
public static void syncItems(EntityPlayer player) {
int size = InventoryPlayerExtended.ICOL * InventoryPlayerExtended.IROW;
for (int a = 0; a < size; a++) {
getPlayerInventory(player).syncSlotToClients(a);
}
}
public static void putDataIntoInventory(InventoryPlayerExtended inventory, EntityPlayer player) {
inventory.stackList = getPlayerInventory(player).stackList;
}
}
| #188 fix extended inventory failing to save when players have invalid characters added
| src/main/java/com/lothrazar/cyclicmagic/util/UtilPlayerInventoryFilestorage.java | #188 fix extended inventory failing to save when players have invalid characters added | <ide><path>rc/main/java/com/lothrazar/cyclicmagic/util/UtilPlayerInventoryFilestorage.java
<ide> }
<ide> public static final String ext = "invo";
<ide> public static final String extback = "backup";
<add> public static final String regex = "[^a-zA-Z0-9_]";
<ide> public static File getPlayerFile(String suffix, File playerDirectory, String playername) {
<del> return new File(playerDirectory, "_" + playername + "." + suffix);
<add> // some other mods/servers/plugins add things like "[Owner] > " prefix to player names
<add> //which are invalid filename chars. https://github.com/PrinceOfAmber/Cyclic/issues/188
<add> //mojang username rules https://help.mojang.com/customer/en/portal/articles/928638-minecraft-usernames
<add> String playernameFiltered = playername.replaceAll(regex, "");
<add> return new File(playerDirectory, "_" + playernameFiltered + "." + suffix);
<ide> }
<ide> public static void syncItems(EntityPlayer player) {
<ide> int size = InventoryPlayerExtended.ICOL * InventoryPlayerExtended.IROW; |
|
JavaScript | mit | 3a5cb780f95b23bc40081f70554d3ed27ca0177c | 0 | soscripted/sox,soscripted/sox,codygray/sox,codygray/sox | /*jshint multistr: true */
//TODO: what are post_contents and author for?
var features = { //ALL the functions must go in here
grayOutVotes: function() {
// Description: Grays out votes AND vote count
if ($('.deleted-answer').length) {
$('.deleted-answer .vote-down-off, .deleted-answer .vote-up-off, .deleted-answer .vote-count-post').css('opacity', '0.5');
}
},
moveBounty: function() {
// Description: For moving bounty to the top
if ($('.bounty-notification').length) {
$('.bounty-notification').insertAfter('.question .fw');
$('.question .bounty-notification .votecell').remove();
}
},
dragBounty: function() {
// Description: Makes the bounty window draggable
$('.bounty-notification').click(function() {
setTimeout(function() {
$('#start-bounty-popup').draggable().css('cursor', 'move');
}, 50);
});
},
renameChat: function() {
// Description: Renames Chat tabs to prepend 'Chat' before the room name
if (SOHelper.getSiteType() === 'chat') {
document.title = 'Chat - ' + document.title;
}
},
exclaim: function() {
// Description: Removes exclamation marks
var old = $('td.comment-actions > div > div > div.message-text');
var newText = old.text().replace("!", ".");
old.html(newText);
},
markEmployees: function() {
// Description: Adds an Stack Overflow logo next to users that *ARE* a Stack Overflow Employee
function unique(list) {
//credit: GUFFA https://stackoverflow.com/questions/12551635/12551709#12551709
var result = [];
$.each(list, function(i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});
return result;
}
var $links = $('.comment a, .deleted-answer-info a, .employee-name a, .started a, .user-details a').filter('a[href^="/users/"]');
var ids = [];
$links.each(function() {
var href = $(this).attr('href'),
id = href.split('/')[2];
ids.push(id);
});
ids = unique(ids);
var url = 'https://api.stackexchange.com/2.2/users/{ids}?site={site}'
.replace('{ids}', ids.join(';'))
.replace('{site}', SOHelper.getApiSiteParameter(StackExchange.options.site.name));
$.ajax({
url: url
}).success(function(data) {
for (var i = 0, len = data.items.length; i < len; i++) {
var userId = data.items[i].user_id,
isEmployee = data.items[i].is_employee;
if (isEmployee) {
$links.filter('a[href^="/users/' + userId + '/"]').append('<i class="fa fa-stack-overflow" title="employee" style="padding: 0 5px"></i>');
}
}
});
},
bulletReplace: function() {
// Description: Replaces disclosure bullets with normal ones
$('.dingus').each(function() {
$(this).html('●');
});
},
addEllipsis: function() {
// Description: Adds an ellipsis to long names
$('.user-info .user-details').css('text-overflow', 'ellipsis');
},
copyCommentsLink: function() {
// Description: Adds the 'show x more comments' link before the commnents
$('.js-show-link.comments-link').each(function() {
var $this2 = $(this);
$('<tr><td></td><td>' + $this2.clone().wrap('<div>').parent().html() + '</td></tr>').insertBefore($(this).parent().closest('tr')).click(function() {
$(this).hide();
});
var commentParent;
// Determine if comment is on a question or an answer
if ($(this).parents('.answer').length) {
commentParent = '.answer';
} else {
commentParent = '.question';
}
$(this).click(function() {
$(this).closest(commentParent).find('.js-show-link.comments-link').hide();
});
});
},
/*unHideAnswer: function() { // For unfading a downvoted answer on hover
$(".downvoted-answer").hover(function() {
$(this).removeClass("downvoted-answer");
}, function() {
$(this).addClass("downvoted-answer");
});
},*/
fixedTopbar: function() {
// Description: For making the topbar fixed (always stay at top of screen)
if (SOHelper.getSiteURL() == 'askubuntu.com') { //AskUbuntu is annoying. UnicornsAreVeryVeryYummy made the below code for AskUbuntu: https://github.com/shu8/Stack-Overflow-Optional-Features/issues/11 Thanks!
var newUbuntuLinks = $('<div/>', {
'class': 'fixedTopbar-links'
}),
linksWrapper = $('<div/>', {
'class': 'fixedTopbar-linksList'
}),
listOfSites = $('<ul/>', {
'class': 'fixedTopbar-siteLink'
}),
more = $('<li/>', {
html: '<a href="#">More</a>',
'class': 'fixedTopbar-siteLink'
}),
sites = {
Ubuntu: 'ubuntu.com',
Community: 'community.ubuntu.com',
'Ask!': 'askubuntu.com',
Developer: 'developer.ubuntu.com',
Design: 'design.ubuntu.com',
Discourse: 'discourse.ubuntu.com',
Hardware: 'www.ubuntu.com/certification',
Insights: 'insights.ubuntu.com',
Juju: 'juju.ubuntu.com',
Shop: 'shop.ubuntu.com'
},
moreSites = {
Apps: 'apps.ubuntu.com',
Help: 'help.ubuntu.com',
Forum: 'ubuntuforums.org',
Launchpad: 'launchpad.net',
MAAS: 'maas.ubuntu.com',
Canonical: 'canonical' //TODO
};
var addSite = function(link, name) {
listOfSites.append($('<li/>', {
html: '<a href="http://' + link + '">' + name + '</a>',
'class': 'fixedTopbar-siteLink'
}));
};
for (var name in sites) {
addSite(sites[name], name);
}
listOfSites.append(more);
var moreList = $('li', $(more));
var addMoreSite = function(link, name) {
moreList.append($('<li/>', {
html: '<a href="http://' + link + '">' + name + '</a>',
'class': 'fixedTopbar-siteLink'
}));
};
for (name in moreSites) {
addMoreSite(moreSites[name], name);
}
$('.nav-global').remove(); //Ubuntu links
$('#custom-header').remove();
linksWrapper.append(listOfSites);
newUbuntuLinks.append(linksWrapper);
$('.topbar-wrapper').after(newUbuntuLinks);
$('.topbar').addClass('fixedTopbar-stickyToolbar');
$('.topbar').before($('<div/>', {
html: '<br/><br/>'
}));
$('#header').css('margin-top', '22px');
} else if (SOHelper.getSiteType() !== 'chat') { //for all the normal, unannoying sites, excluding chat ;)
$('.topbar').css({
'position': 'fixed',
'z-index': '1001'
});
//Thanks ArtOfCode (http://worldbuilding.stackexchange.com/users/2685/artofcode) for fixing the topbar covering the header :)
$('#header').css('margin-top', '34px');
$('.topbar').css('margin-top', '-34px');
} else if (SOHelper.getSiteType() === 'chat') { //chat is a bit different
$('.topbar').css('position', 'fixed');
}
$('#rep-card-next .percent').after($('#rep-card-next .label').css('z-index', 0)).css('position', 'absolute');
$('#badge-card-next .percent').after($('#badge-card-next .label').css('z-index', 0)).css('position', 'absolute');
},
highlightQuestions: function() {
// Description: For highlighting only the tags of favorite questions
var highlightClass = '';
if (/superuser/.test(window.hostname)) { //superuser
highlightClass = 'favorite-tag-su';
} else if (/stackoverflow/.test(window.hostname)) { //stackoverflow
highlightClass = 'favorite-tag-so';
} else { //for all other sites
highlightClass = 'favorite-tag-all';
}
function highlight() {
var interestingTagsDiv = $('#interestingTags').text();
var interesting = interestingTagsDiv.split(' ');
interesting.pop(); //Because there's one extra value at the end
$('.tagged-interesting > .summary > .tags > .post-tag').filter(function(index) {
return interesting.indexOf($(this).text()) > -1;
}).addClass(highlightClass);
$('.tagged-interesting').removeClass('tagged-interesting');
}
setTimeout(function() { //Need delay to make sure the CSS is applied
highlight();
if ($('.question-summary').length) {
new MutationObserver(function(records) {
records.forEach(function(mutation) {
if (mutation.attributeName == 'class') {
highlight();
}
});
}).observe(document.querySelector('.question-summary'), {
childList: true,
attributes: true
});
}
}, 300);
},
displayName: function() {
// Description: For displaying username next to avatar on topbar
var uname = SOHelper.getUsername();
var insertme = '<span class="reputation links-container" style="color:white;" title="' + uname + '">' + uname + '</span>"';
$(insertme).insertBefore('.gravatar-wrapper-24');
},
colorAnswerer: function() {
// Description: For highlighting the names of answerers on comments
$('.answercell').each(function(i, obj) {
var x = $(this).find('.user-details a').text();
$('.answer .comment-user').each(function() {
if ($(this).text() == x) {
$(this).css('background-color', 'orange');
}
});
});
$('.js-show-link.comments-link').click(function() { //Keep CSS when 'show x more comments' is clicked
setTimeout(function() {
features.colorAnswerer();
}, 500);
});
},
kbdAndBullets: function() {
// Description: For adding buttons to the markdown toolbar to surround selected test with KBD or convert selection into a markdown list
function addBullets() {
var list = '- ' + $('[id^="wmd-input"]').getSelection().text.split('\n').join('\n- ');
$('[id^="wmd-input"]').replaceSelectedText(list);
}
function addKbd() {
$('[id^="wmd-input"]').surroundSelectedText("<kbd>", "</kbd>");
}
var kbdBtn = '<li class="wmd-button" title="surround selected text with <kbd> tags" style="left: 400px;"><span id="wmd-kbd-button" style="background-image: none;">kbd</span></li>';
var listBtn = '<li class="wmd-button" title="add dashes (\"-\") before every line to make a bulvar point list" style="left: 425px;"><span id="wmd-bullet-button" style="background-image:none;">●</span></li>';
setTimeout(function() {
$('[id^="wmd-redo-button"]').after(kbdBtn);
$('[id^="wmd-redo-button"]').after(listBtn);
$('#wmd-kbd-button').on('click', function() {
addKbd();
});
$('#wmd-bullet-button').on('click', function() {
addBullets();
});
}, 500);
$('[id^="wmd-input"]').bind('keydown', 'alt+l', function() {
addBullets();
});
$('[id^="wmd-input"]').bind('keydown', 'alt+k', function() {
addKbd();
});
},
editComment: function() {
// Description: For adding checkboxes when editing to add pre-defined edit reasons
function addCheckboxes() {
$('#reasons').remove(); //remove the div containing everything, we're going to add/remove stuff now:
if (!$('[class^="inline-editor"]').length) { //if there is no inline editor, do nothing
return;
}
if (/\/edit/.test(window.location.href) || $('[class^="inline-editor"]').length) { //everything else
$('.form-submit').before('<div id="reasons"></div>');
$.each(JSON.parse(GM_getValue('editReasons')), function(i, obj) {
$('#reasons').append('<label><input type="checkbox" value="' + this[1] + '"</input>' + this[0] + '</label> ');
});
$('#reasons input[type="checkbox"]').css('vertical-align', '-2px');
$('#reasons label').hover(function() {
$(this).css({ //on hover
'background-color': 'gray',
'color': 'white'
});
}, function() {
$(this).css({ //on un-hover
'background-color': 'white',
'color': 'inherit'
});
});
var editCommentField = $('[id^="edit-comment"]');
$('#reasons input[type="checkbox"]').change(function() {
if (this.checked) { //Add it to the summary
if (!editCommentField.val()) {
editCommentField.val(editCommentField.val() + $(this).val().replace(/on$/g, ''));
} else {
editCommentField.val(editCommentField.val() + '; ' + $(this).val().replace(/on$/g, ''));
}
var newEditComment = editCommentField.val(); //Remove the last space and last semicolon
editCommentField.val(newEditComment).focus();
} else if (!this.checked) { //Remove it from the summary
editCommentField.val(editCommentField.val().replace($(this).val() + '; ', '')); //for middle/beginning values
editCommentField.val(editCommentField.val().replace($(this).val(), '')); //for last value
}
});
}
}
function displayDeleteValues() {
//Display the items from list and add buttons to delete them
$('#currentValues').html(' ');
$.each(JSON.parse(GM_getValue('editReasons')), function(i, obj) {
$('#currentValues').append(this[0] + ' - ' + this[1] + '<input type="button" id="' + i + '" value="Delete"><br />');
});
addCheckboxes();
}
var div = '<div id="dialogEditReasons" class="sox-centered wmd-prompt-dialog"><span id="closeDialogEditReasons" style="float:right;">Close</span><span id="resetEditReasons" style="float:left;">Reset</span> \
<h2>View/Remove Edit Reasons</h2> \
<div id="currentValues"></div> \
<br /> \
<h3>Add a custom reason</h3> \
Display Reason: <input type="text" id="displayReason"> \
<br /> \
Actual Reason: <input type="text" id="actualReason"> \
<br /> \
<input type="button" id="submitUpdate" value="Submit"> \
</div>';
$('body').append(div);
$('#dialogEditReasons').draggable().css('position', 'absolute').css('text-align', 'center').css('height', '60%').hide();
$('#closeDialogEditReasons').css('cursor', 'pointer').click(function() {
$(this).parent().hide(500);
});
$('#resetEditReasons').css('cursor', 'pointer').click(function() { //manual reset
var options = [ //Edit these to change the default settings
['formatting', 'Improved Formatting'],
['spelling', 'Corrected Spelling'],
['grammar', 'Fixed grammar'],
['greetings', 'Removed thanks/greetings']
];
if (confirm('Are you sure you want to reset the settings to Formatting, Spelling, Grammar and Greetings')) {
GM_setValue('editReasons', JSON.stringify(options));
alert('Reset options to default. Refreshing...');
location.reload();
}
});
if (GM_getValue('editReasons', -1) == -1) { //If settings haven't been set/are empty
var defaultOptions = [
['formatting', 'Improved Formatting'],
['spelling', 'Corrected Spelling'],
['grammar', 'Fixed grammar'],
['greetings', 'Removed thanks/greetings']
];
GM_setValue('editReasons', JSON.stringify(defaultOptions)); //save the default settings
} else {
var options = JSON.parse(GM_getValue('editReasons')); //If they have, get the options
}
$('#dialogEditReasons').on('click', 'input[value="Delete"]', function() { //Click handler to delete when delete button is pressed
var delMe = $(this).attr('id');
options.splice(delMe, 1); //actually delete it
GM_setValue('editReasons', JSON.stringify(options)); //save it
displayDeleteValues(); //display the items again (update them)
});
$('#submitUpdate').click(function() { //Click handler to update the array with custom value
if (!$('#displayReason').val() || !$('#actualReason').val()) {
alert('Please enter something in both the textboxes!');
} else {
var arrayToAdd = [$('#displayReason').val(), $('#actualReason').val()];
options.push(arrayToAdd); //actually add the value to array
GM_setValue('editReasons', JSON.stringify(options)); //Save the value
// moved display call after setvalue call, list now refreshes when items are added
displayDeleteValues(); //display the items again (update them)
//reset textbox values to empty
$('#displayReason').val('');
$('#actualReason').val('');
}
});
setTimeout(function() {
addCheckboxes();
//Add the button to update and view the values in the help menu:
$('.topbar-dialog.help-dialog.js-help-dialog > .modal-content ul').append("<li><a href='javascript:void(0)' id='editReasonsLink'>Edit Reasons \
<span class='item-summary'>Edit your personal edit reasons for SE sites</span></a></li>");
$('.topbar-dialog.help-dialog.js-help-dialog > .modal-content ul #editReasonsLink').on('click', function() {
displayDeleteValues();
$('#dialogEditReasons').show(500); //Show the dialog to view and update values
});
}, 500);
$('.post-menu > .edit-post').click(function() {
setTimeout(function() {
addCheckboxes();
}, 500);
});
},
shareLinksMarkdown: function() {
// Description: For changing the 'share' button link to the format [name](link)
$('.short-link').click(function() {
setTimeout(function() {
var link = $('.share-tip input').val();
$('.share-tip input').val('[' + $('#question-header a').html() + '](' + link + ')');
$('.share-tip input').select();
}, 500);
});
},
commentShortcuts: function() {
// Description: For adding support in comments for Ctrl+K,I,B to add code backticks, italicise, bolden selection
$('.js-add-link.comments-link').click(function() {
setTimeout(function() {
$('.comments textarea').keydown(function(e) {
if (e.which == 75 && e.ctrlKey) { //ctrl+k (code)
$(this).surroundSelectedText('`', '`');
e.stopPropagation();
e.preventDefault();
return false;
}
if (e.which == 73 && e.ctrlKey) { //ctrl+i (italics)
$(this).surroundSelectedText('*', '*');
e.stopPropagation();
e.preventDefault();
return false;
}
if (e.which == 66 && e.ctrlKey) { //ctrl+b (bold)
$(this).surroundSelectedText('**', '**');
e.stopPropagation();
e.preventDefault();
return false;
}
});
}, 200);
});
},
unspoil: function() {
// Description: For adding a button to reveal all spoilers in a post
$('#answers div[id*="answer"], div[id*="question"]').each(function() {
if ($(this).find('.spoiler').length) {
$(this).find('.post-menu').append('<span class="lsep">|</span><a id="showSpoiler-' + $(this).attr("id") + '" href="javascript:void(0)">unspoil</span>');
}
});
$('a[id*="showSpoiler"]').click(function() {
var x = $(this).attr('id').split(/-(.+)?/)[1];
$('#' + x + ' .spoiler').removeClass('spoiler');
});
},
/*highlightClosedQuestions: function() { // For highlighting and slightly greying out closed questions when viewing question lists
$('.question-summary').each(function() {
if ($(this).find('.summary h3 a').text().indexOf('[on hold]') > -1 || $(this).find('.summary h3 a').text().indexOf('[closed]') > -1) {
if ($('.cp').length) {
$(this).find('.cp').css('border', 'blue').css('border-style', 'dotted').css('border-width', 'thin').css('background-color', '#E0E0E0');
$(this).css('opacity', '0.9');
} else {
$(this).find('.votes').css('border', 'blue').css('border-style', 'dotted').css('border-width', 'thin').css('background-color', '#E0E0E0');
$(this).css('opacity', '0.9');
}
}
});
},*/
quickCommentShortcutsMain: function() {
// Description: For adding shortcuts to insert pre-defined text into comment fields
function parseGM() {
return JSON.parse(GM_getValue('quickCommentShortcutsData'));
}
function saveGM(data) {
GM_setValue('quickCommentShortcutsData', JSON.stringify(data));
}
function replaceVars(text, sitename, siteurl, op, answererName) {
return text.replace(/\$SITENAME\$/gi, sitename).replace(/\$ANSWERER\$/gi, answererName.replace(/\s/gi, '')).replace(/\$OP\$/gi, op).replace(/\$SITEURL\$/gi, siteurl).replace(/\$ANSWERERNORMAL\$/gi, answererName);
}
function resetReminderAndTable() {
$('#quickCommentShortcutsReminder').html('');
$('#quickCommentShortcuts table').html(' ');
$('#quickCommentShortcuts table').append('<tr><th>Name</th><th>Shortcut</th><th>Text</th><th>Delete?</th><th>Edit?</th></tr>');
}
var sitename = SOHelper.getSiteName(),
siteurl = SOHelper.getSiteURL('full'),
op = $('.post-signature.owner .user-info .user-details a').text(),
data = [],
tableCSS = {
'border': '1px solid white',
'padding': '5px',
'vertical-align': 'middle'
};
$('body').append('<div id="quickCommentShortcuts" class="sox-centered wmd-prompt-dialog" style="display:none;"><table></table></div>');
$('#quickCommentShortcuts').css('width', '100%').css('position', 'absolute').draggable();
$('body').append('<div id="quickCommentShortcutsReminder" class="quickCommentShortcutsReminder" style="display:none;"></div>');
if (!GM_getValue('quickCommentShortcutsData') || parseGM().length < 1) {
data = [
//Format: ['name', 'shortcut', 'comment text'],
['How to ping', 'alt+p', 'To ping other users, please start your comment with an `@` followed by the person\'s username (with no spaces). For example, to ping you, I would use `@$ANSWERER$`. For more information, please see [How do comments replies work?](http://meta.stackexchange.com/questions/43019/how-do-comment-replies-work).'],
['Not an answer', 'alt+n', 'This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you need to gain [reputation]($SITEURL$/faq#reputation) before you can comment on others\' posts to prevent abuse; why don\'t you try and get some by [answering a question]($SITEURL$/unanswered)?'],
['Link-only answer', 'alt+l', 'While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes, resulting in your answer being useless and consequently deleted.'],
['Ask a new question', 'alt+d', 'If you have a new question, please ask it by clicking the [Ask Question]($SITEURL$/questions/ask) button. Include a link to this question if it helps provide context. You can also [start a bounty]($SITEURL$/help/privileges/set-bounties) to draw more attention to this question.'],
['Don\'t add "Thank You"', 'alt+t', 'Please don\'t add \'thank you\' as an answer. Instead, vote up the answers that you find helpful. To do so, you need to have reputation. You can read more about reputation [here]($SITEURL$/faq#reputation).']
];
} else {
data = parseGM();
}
$(function() {
$(document).on('click', 'a.js-add-link.comments-link', function() {
var answererName = $(this).parents('div').find('.post-signature:last').first().find('.user-details a').text(),
answererId = $(this).parents('div').find('.post-signature:last').first().find('.user-details a').attr('href').split('/')[2],
apiUrl = 'https://api.stackexchange.com/2.2/users/' + answererId + '?site=' + SOHelper.getAPISiteName();
setTimeout(function() {
$('.comments textarea').attr('placeholder', 'Use comments to ask for clarification or add more information. Avoid answering questions in comments. Press Alt+O to view/edit/delete Quick Comment Shortcuts data, or press Alt+R to open a box to remind you of the shortcuts.');
}, 500);
$.ajax({
dataType: "json",
url: apiUrl,
success: function(json) {
var creationDate = json.items[0].creation_date,
lastAccess = json.items[0].last_access_date,
reputation = json.items[0].reputation,
bronze = json.items[0].badge_counts.bronze,
silver = json.items[0].badge_counts.silver,
gold = json.items[0].badge_counts.gold,
type = json.items[0].user_type;
var welcomeText = '',
newUser = 'No';
if ((new Date().getTime() / 1000) - (creationDate) < 864000) {
welcomeText = 'Welcome to $SITENAME$ $ANSWERERNORMAL$! ';
newUser = 'Yes';
}
var factfile = '<span id="closeQuickCommentShortcuts" style="float:right;">close</span> \
<h3>User "' + answererName + '" - ' + type + ': <br /> \
Creation Date: ' + new Date(creationDate * 1000).toUTCString() + ' <br /> \
New? ' + newUser + '<br /> \
Last seen: ' + new Date(lastAccess * 1000).toUTCString() + ' <br /> \
Reputation: ' + reputation + ' <br /> \
Badges: <span class="badge1"></span>' + gold + '</span> \
<span class="badge2"></span>' + silver + '</span> \
<span class="badge3"></span>' + bronze + '</span></h3>';
var variableList = '<br /><span id="quickCommentShortcutsVariables"><h4>Variables (case-insensitive)</h4> \
<strong>$ANSWERER$</strong> - name of poster of post you\'re commenting on (may be OP) with stripped spaces (eg. JohnDoe)<br /> \
<strong>$ANSWERERNORMAL$</strong> - name of poster of post you\'re commenting on (may be OP) without stripped spaces (eg. John Doe)<br /> \
<strong>$OP$</strong> - name of OP <br /> \
<strong>$SITEURL$</strong> - site URL (eg. http://stackoverflow.com) <br /> \
<strong>$SITENAME$</strong> - site name (eg. Stack Overflow) <br /></span>';
$('#quickCommentShortcuts').prepend(factfile);
$('#quickCommentShortcuts').append(variableList);
$('#closeQuickCommentShortcuts').css('cursor', 'pointer').on('click', function() {
$('#quickCommentShortcuts').hide();
});
$('#quickCommentShortcuts table').append('<tr><th>Name</th><th>Shortcut</th><th>Text</th><th>Delete?</th><th>Edit?</th></tr>');
$('#quickCommentShortcuts table').after('<input type="button" id="newComment" value="New Comment">');
$('#quickCommentShortcutsReminder').html('');
$.each(data, function(i) {
$('#quickCommentShortcutsReminder').append(this[0] + ' - ' + this[1] + '<br />');
var text = welcomeText + this[2];
text = replaceVars(text, sitename, siteurl, op, answererName);
$('.comments textarea').bind('keydown', this[1], function() {
$(this).append(text);
});
$('#quickCommentShortcuts table').append('<tr><td>' + this[0] + '</td><td>' + this[1] + '</td><td>' + text + '</td><td><input type="button" id="' + i + '" value="Delete"></td><td><input type="button" id="' + i + '" value="Edit"></td></tr><br />');
$('#quickCommentShortcuts').find('table, th, td').css(tableCSS);
});
$('.comments textarea').on('keydown', null, 'alt+o', function() {
$('#quickCommentShortcuts').show();
$('body').animate({
scrollTop: 0
}, 'slow');
});
$('.comments textarea').bind('keydown', 'alt+r', function() {
$('#quickCommentShortcutsReminder').show();
});
$('#quickCommentShortcuts').on('click', 'input[value="Delete"]', function() {
data.splice($(this).attr('id'), 1);
saveGM(data);
resetReminderAndTable();
$.each(data, function(i) {
$('#quickCommentShortcutsReminder').append(this[0] + ' - ' + this[1] + '<br />');
var text = welcomeText + this[2];
$('#quickCommentShortcuts table').append('<tr><td>' + this[0] + '</td><td>' + this[1] + '</td><td>' + text + '</td><td><input type="button" id="' + i + '" value="Delete"></td><td><input type="button" id="' + i + '" value="Edit"></td></tr><br />');
$('#quickCommentShortcuts').find('table, th, td').css(tableCSS);
});
});
$('#quickCommentShortcuts').on('click', '#newComment', function() {
$(this).hide();
$(this).before('<div id="newCommentStuff">Name:<input type="text" id="newCommentName"> \
<br /> Shortcut:<input type="text" id="newCommentShortcut"> \
<br /> Text:<textarea id="newCommentText"></textarea> \
<br /> <input type="button" id="newCommentSave" value="Save"></div>');
$('#quickCommentShortcuts #newCommentSave').click(function() {
var newName = $('#newCommentName').val(),
newShortcut = $('#newCommentShortcut').val(),
newText = $('#newCommentText').val();
data.push([newName, newShortcut, newText]);
saveGM(data);
resetReminderAndTable();
$.each(data, function(i) {
$('#quickCommentShortcutsReminder').append(this[0] + ' - ' + this[1] + '<br />');
var text = welcomeText + this[2];
$('#quickCommentShortcuts table').append('<tr><td>' + this[0] + '</td><td>' + this[1] + '</td><td>' + text + '</td><td><input type="button" id="' + i + '" value="Delete"></td><td><input type="button" id="' + i + '" value="Edit"></td></tr><br />');
$('#quickCommentShortcuts').find('table, th, td').css(tableCSS);
});
$('#newCommentStuff').remove();
$('#quickCommentShortcuts #newComment').show();
});
});
$('#quickCommentShortcuts').on('click', 'input[value="Edit"]', function() {
var id = $(this).attr('id');
for (var i = 0; i < 3; i++) {
$(this).parent().parent().find('td:eq(' + i + ')').replaceWith('<td><input style="width:90%;" type="text" id="' + id + '" value="' + data[id][i].replace(/"/g, '"').replace(/'/g, '’') + '"></td>');
}
$(this).after('<input type="button" value="Save" id="saveEdits">');
$(this).hide();
$('#quickCommentShortcuts #saveEdits').click(function() {
for (var i = 0; i < 3; i++) {
data[id][i] = $(this).parent().parent().find('input[type="text"]:eq(' + i + ')').val();
saveGM(data);
}
resetReminderAndTable();
$.each(data, function(i) {
$('#quickCommentShortcutsReminder').append(this[0] + ' - ' + this[1] + '<br />');
var text = welcomeText + this[2];
$('#quickCommentShortcuts table').append('<tr><td>' + this[0] + '</td><td>' + this[1] + '</td><td>' + text + '</td><td><input type="button" id="' + i + '" value="Delete"></td><td><input type="button" id="' + i + '" value="Edit"></td></tr><br />');
$('#quickCommentShortcuts').find('table, th, td').css(tableCSS);
});
$(this).remove();
$('#quickCommentShortcuts input[value="Edit"]').show();
});
});
$('.comments textarea').blur(function() {
$('#quickCommentShortcutsReminder').hide();
});
}
});
});
});
},
spoilerTip: function() {
// Description: For adding some text to spoilers to tell people to hover over it
$('.spoiler').prepend('<div id="isSpoiler" style="color:red; font-size:smaller; float:right;">hover to show spoiler<div>');
$('.spoiler').hover(function() {
$(this).find('#isSpoiler').hide(500);
}, function() {
$(this).find('#isSpoiler').show(500);
});
},
commentReplies: function() {
// Description: For adding reply links to comments
$('.comment').each(function() {
if ($('.topbar-links a span:eq(0)').text() != $(this).find('.comment-text a.comment-user').text()) { //make sure the link is not added to your own comments
$(this).append('<span id="replyLink" title="reply to this user">↵</span>');
}
});
$('span[id="replyLink"]').css('cursor', 'pointer').on('click', function() {
var parentDiv = $(this).parent().parent().parent().parent();
var textToAdd = '@' + $(this).parent().find('.comment-text a.comment-user').text().replace(/\s/g, '').replace(/♦/, '') + ' '; //eg. @USERNAME [space]
if (parentDiv.find('textarea').length) {
parentDiv.find('textarea').append(textToAdd); //add the name
} else {
parentDiv.next('div').find('a').trigger('click'); //show the textarea
parentDiv.find('textarea').append(textToAdd); //add the name
}
});
},
parseCrossSiteLinks: function() {
// Description: For converting cross-site links to their titles
var sites = ['stackexchange', 'stackoverflow', 'superuser', 'serverfault', 'askubuntu', 'stackapps', 'mathoverflow', 'programmers', 'bitcoin'];
$('.post-text a').each(function() {
var anchor = $(this);
if (sites.indexOf($(this).attr('href').split('/')[2].split('.')[0]) > -1) { //if the link is to an SE site (not, for example, to google), do the necessary stuff
if ($(this).text() == $(this).attr('href')) { //if there isn't text on it (ie. bare url)
var sitename = $(this).attr('href').split('/')[2].split('.')[0],
id = $(this).attr('href').split('/')[4];
SOHelper.getFromAPI('questions', id, sitename, function(json) {
anchor.html(json.items[0].title); //Get the title and add it in
}, 'activity');
}
}
});
},
/*answerCountSidebar: function() { //For adding the answer count as a tooltip to questions in the sidebar
$('.sidebar-linked .linked .spacer a, .sidebar-related .related .spacer a').each(function(i) {
if (!i % 2 == 0) { //odd only (ie. question title)
var id = $(this).attr('href').split('/')[2],
sitename = $(location).attr('hostname').split('.')[0],
that = $(this);
SOHelper.getFromAPI('questions', id, sitename, function(json) {
answers = json.items[0].answer_count;
that.attr('title', answers + (answers == 1 ? ' answer' : ' answers'));
}, 'activity');
}
});
},*/
linkQuestionAuthorName: function() {
// Description: For adding a button to the editor toolbar to insert a link to a post and automatically add the author's name
var div = '<div id="addLinkAuthorName" class="wmd-prompt-dialog sox-centered" style="display:none"> \
<h5>Insert hyperlink with author\'s name</h5> \
<br /> \
<input id="link" placeholder="http://example.com/ \"optional title\"" size="50"> \
<input id="addLinkOk" value="OK" type="button" style="margin: 10px; display: inline; width: 7em;"><input id="addLinkCancel" value="Cancel" type="button" style="margin: 10px; display: inline; width: 7em;"> \
</div>';
$('body').append(div);
$('#addLinkAuthorName').css('top', '50%').css('position', 'fixed').css('height', '20%');
$('#addLinkAuthorName #addLinkCancel').on('click', function() {
$(this).parent().hide();
});
$('#addLinkAuthorName #addLinkOk').on('click', function() {
var textarea = $('#post-editor #wmd-input'),
link = $('#addLinkAuthorName #link').val(),
id = link.split('/')[4],
sitename = link.split('/')[2].split('.')[0],
title = link.split('"')[1];
if (link.split('/')[3].substr(0, 1) == 'a') { //for answers
SOHelper.getFromAPI('answers', id, sitename, function(json) {
//Insert at caret thanks to http://stackoverflow.com/a/15977052/3541881
var caretPos = document.getElementById('wmd-input').selectionStart,
textAreaTxt = textarea.val(),
txtToAdd;
if (title) {
txtToAdd = '[@' + json.items[0].owner.display_name + ' says](' + link + ' "' + title + '")';
} else {
txtToAdd = '[@' + json.items[0].owner.display_name + ' says](' + link + ')';
}
textarea.val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos));
$('#addLinkAuthorName').hide();
}, 'activity');
} else { //for questions
SOHelper.getFromAPI('questions', id, sitename, function(json) {
//Insert at caret thanks to http://stackoverflow.com/a/15977052/3541881
var caretPos = document.getElementById('wmd-input').selectionStart,
textAreaTxt = textarea.val(),
txtToAdd;
if (title) {
txtToAdd = '[@' + json.items[0].owner.display_name + ' says](' + json.items[0].link + ' "' + title + '")';
} else {
txtToAdd = '[@' + json.items[0].owner.display_name + ' says](' + json.items[0].link + ')';
}
textarea.val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos));
$('#addLinkAuthorName').hide();
}, 'activity');
}
});
var liSpan = '<li class="wmd-button" title="Hyperlink (with author name)" style="left: 450px;"><span id="wmd-author-link-button" style="background-position: -40px 0px;"></span></li>';
setTimeout(function() {
$('[id^="wmd-redo-button"]').after(liSpan);
$('#wmd-author-link-button').on('click', function() {
$('#addLinkAuthorName').show();
});
}, 1000);
},
confirmNavigateAway: function() {
// Description: For adding a 'are you ure you want to go away' confirmation on pages where you have started writing something
if (window.location.href.indexOf('questions/') >= 0) {
$(window).bind('beforeunload', function() {
if ($('.comment-form textarea').length && $('.comment-form textarea').val()) {
return 'Do you really want to navigate away? Anything you have written will be lost!';
} else {
return;
}
});
}
},
sortByBountyAmount: function() {
// Description: For adding some buttons to sort bounty's by size
if (!SOHelper.isOnUserProfile()) { //not on the user profile page
if ($('.bounty-indicator').length) { //if there is at least one bounty on the page
$('.question-summary').each(function() {
var bountyAmount = $(this).find('.bounty-indicator').text().replace('+', '');
$(this).attr('data-bountyamount', bountyAmount); //add a 'bountyamount' attribute to all the questions
});
var $wrapper = $('#question-mini-list').length ? $('#question-mini-list') : $wrapper = $('#questions'); //homepage/questions tab
setTimeout(function() {
//filter buttons:
$('.subheader').after('<span>sort by bounty amount: </span><span id="largestFirst">largest first </span><span id="smallestFirst">smallest first</span>');
//Thanks: http://stackoverflow.com/a/14160529/3541881
$('#largestFirst').css('cursor', 'pointer').on('click', function() { //largest first
$wrapper.find('.question-summary').sort(function(a, b) {
return +b.getAttribute('data-bountyamount') - +a.getAttribute('data-bountyamount');
}).prependTo($wrapper);
});
//Thanks: http://stackoverflow.com/a/14160529/3541881
$('#smallestFirst').css('cursor', 'pointer').on('click', function() { //smallest first
$wrapper.find('.question-summary').sort(function(a, b) {
return +a.getAttribute('data-bountyamount') - +b.getAttribute('data-bountyamount');
}).prependTo($wrapper);
});
}, 500);
}
}
},
isQuestionHot: function() {
// Description: For adding some text to questions that are in the 30 most recent hot network questions
function addHotText() {
$('#feed').html('<p>In the top 30 most recent hot network questions!</p>');
$('#question-header').prepend('<div title="this question is in the top 30 most recent hot network questions!" class="sox-hot">HOT<div>');
}
$('#qinfo').after('<div id="feed"></div>');
setTimeout(function() {
$.ajax({
type: 'get',
url: 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20feed%20where%20url%3D"http%3A%2F%2Fstackexchange.com%2Ffeeds%2Fquestions"&format=json',
success: function(d) {
var results = d.query.results.entry;
$.each(results, function(i, result) {
if (document.URL == result.link.href) {
addHotText();
}
});
}
});
}, 500);
},
autoShowCommentImages: function() {
// Description: For auto-inlining any links to imgur images in comments
$('.comment .comment-text .comment-copy a').each(function() {
if ($(this).attr('href').indexOf('imgur.com') != -1) {
var image = $(this).attr('href');
if (image.indexOf($(this).text()) != -1) {
$(this).replaceWith('<img src="' + image + '" width="100%">');
} else {
$(this).after('<img src="' + image + '" width="100%">');
}
}
});
},
showCommentScores: function() {
// Description: For adding a button on your profile comment history pages to show your comment's scores
var sitename = SOHelper.getAPISiteName();
$('.history-table td b a[href*="#comment"]').each(function() {
var id = $(this).attr('href').split('#')[1].split('_')[0].replace('comment', '');
$(this).after('<span class="showCommentScore" id="' + id + '"> show comment score</span>');
});
$('.showCommentScore').css('cursor', 'pointer').on('click', function() {
var $that = $(this);
SOHelper.getFromAPI('comments', $that.attr('id'), sitename, function(json) {
$that.html(' ' + json.items[0].score);
});
});
},
answerTagsSearch: function() {
// Description: For adding tags to answers in search
if (window.location.href.indexOf('search?q=') > -1) { //ONLY ON SEARCH PAGES!
var sitename = SOHelper.getAPISiteName(),
ids = [],
idsAndTags = {};
$.each($('div[id*="answer"]'), function() { //loop through all *answers*
ids.push($(this).find('.result-link a').attr('href').split('/')[2]); //Get the IDs for the questions for all the *answers*
});
$.getJSON('https://api.stackexchange.com/2.2/questions/' + ids.join(';') + '?site=' + sitename, function(json) {
var itemsLength = json.items.length;
for (var i = 0; i < itemsLength; i++) {
idsAndTags[json.items[i].question_id] = json.items[i].tags;
}
console.log(idsAndTags);
$.each($('div[id*="answer"]'), function() { //loop through all *answers*
var id = $(this).find('.result-link a').attr('href').split('/')[2]; //get their ID
var $that = $(this);
for (var x = 0; x < idsAndTags[id].length; x++) { //Add the appropiate tags for the appropiate answer
$that.find('.summary .tags').append('<a href="/questions/tagged/' + idsAndTags[id][x] + '" class="post-tag">' + idsAndTags[id][x] + '</a>'); //add the tags and their link to the answers
}
$that.find('.summary .tags a').each(function() {
if ($(this).text().indexOf('status-') > -1) { //if it's a mod tag
$(this).addClass('moderator-tag'); //add appropiate class
} else if ($(this).text().match(/(discussion|feature-request|support|bug)/)) { //if it's a required tag
$(this).addClass('required-tag'); //add appropiate class
}
});
});
});
}
},
stickyVoteButtons: function() {
// Description: For making the vote buttons stick to the screen as you scroll through a post
//https://github.com/shu8/SE_OptionalFeatures/pull/14:
//https://github.com/shu8/Stack-Overflow-Optional-Features/issues/28: Thanks @SnoringFrog for fixing this!
var $votecells = $(".votecell");
$votecells.css("width", "61px");
stickcells();
$(window).scroll(function() {
stickcells();
});
function stickcells() {
$votecells.each(function() {
var $topbar = $('.topbar'),
topbarHeight = $topbar.outerHeight(),
offset = 10;
if ($topbar.css('position') == 'fixed') {
offset += topbarHeight;
}
var $voteCell = $(this),
$vote = $voteCell.find('.vote'),
vcOfset = $voteCell.offset(),
scrollTop = $(window).scrollTop();
if (vcOfset.top - scrollTop - offset <= 0) {
if (vcOfset.top + $voteCell.height() - scrollTop - offset - $vote.height() > topbarHeight) {
$vote.css({
position: 'fixed',
left: vcOfset.left + 4,
top: offset
});
} else {
$vote.removeAttr("style");
}
} else {
$vote.removeAttr("style");
}
});
}
},
titleEditDiff: function() {
// Description: For showing the new version of a title in a diff separately rather than loads of crossing outs in red and additions in green
setTimeout(function() {
var $questionHyperlink = $('.summary h2 .question-hyperlink').clone(),
$questionHyperlinkTwo = $('.summary h2 .question-hyperlink').clone(),
link = $('.summary h2 .question-hyperlink').attr('href'),
added = ($questionHyperlinkTwo.find('.diff-delete').remove().end().text()),
removed = ($questionHyperlink.find('.diff-add').remove().end().text());
if ($('.summary h2 .question-hyperlink').find('.diff-delete, .diff-add').length) {
$('.summary h2 .question-hyperlink').hide();
$('.summary h2 .question-hyperlink').after('<a href="' + link + '" class="question-hyperlink"><span class="diff-delete">' + removed + '</span><span class="diff-add">' + added + '</span></a>');
}
}, 2000);
},
metaChatBlogStackExchangeButton: function() {
// Description: For adding buttons next to sites under the StackExchange button that lead to that site's meta, chat and blog
var blogSites = ['math', 'serverfault', 'english', 'stats', 'diy', 'bicycles', 'webapps', 'mathematica', 'christianity', 'cooking', 'fitness', 'cstheory', 'scifi', 'tex', 'security', 'islam', 'superuser', 'gaming', 'programmers', 'gis', 'apple', 'photo', 'dba'],
link,
blogLink = '//' + 'blog.stackexchange.com';
$('#your-communities-section > ul > li > a').hover(function() {
if ($(this).attr('href').substr(0, 6).indexOf('meta') == -1) {
link = 'http://meta.' + $(this).attr('href').substr(2, $(this).attr('href').length - 1);
if (blogSites.indexOf($(this).attr('href').split('/')[2].split('.')[0]) != -1) {
blogLink = '//' + $(this).attr('href').split('/')[2].split('.')[0] + '.blogoverflow.com';
}
$(this).find('.rep-score').hide();
$(this).append('<div class="related-links" style="float: right;"> \
<a href="' + link + '">meta</a> \
<a href="http://chat.stackexchange.com">chat</a> \
<a href="' + blogLink + '">blog</a> \
</div>');
}
}, function() {
$(this).find('.rep-score').show();
$(this).find('.related-links').remove();
});
},
metaNewQuestionAlert: function() {
// Description: For adding a fake mod diamond that notifies you if there has been a new post posted on the current site's meta
if (SOHelper.getSiteType() != 'main' || !$('.related-site').length) return; //DO NOT RUN ON META OR CHAT OR SITES WITHOUT A META
var NEWQUESTIONS = 'metaNewQuestionAlert-lastQuestions',
DIAMONDON = 'new-meta-questions-diamondOn',
DIAMONDOFF = 'new-meta-questions-diamondOff';
var favicon = $(".current-site a[href*='meta'] .site-icon").attr('class').split('favicon-')[1];
var metaName = 'meta.' + SOHelper.getAPISiteName(),
lastQuestions = {},
apiLink = 'https://api.stackexchange.com/2.2/questions?pagesize=5&order=desc&sort=activity&site=' + metaName;
var $dialog = $('<div/>', {
id: 'new-meta-questions-dialog',
'class': 'topbar-dialog achievements-dialog dno'
});
var $header = $('<div/>', {
'class': 'header'
}).append($('<h3/>', {
text: 'new meta posts'
}));
var $content = $('<div/>', {
'class': 'modal-content'
});
var $questions = $('<ul/>', {
id: 'new-meta-questions-dialog-list',
'class': 'js-items items'
});
var $diamond = $('<a/>', {
id: 'new-meta-questions-button',
'class': 'topbar-icon yes-hover new-meta-questions-diamondOff',
click: function() {
$diamond.toggleClass('topbar-icon-on');
$dialog.toggle();
}
});
$dialog.append($header).append($content.append($questions)).prependTo('.js-topbar-dialog-corral');
$('#soxSettingsButton').after($diamond);
$(document).mouseup(function(e) {
if (!$dialog.is(e.target) &&
$dialog.has(e.target).length === 0 &&
!$(e.target).is('#new-meta-questions-button')) {
$dialog.hide();
$diamond.removeClass("topbar-icon-on");
}
});
if (GM_getValue(NEWQUESTIONS, -1) == -1) {
GM_setValue(NEWQUESTIONS, JSON.stringify(lastQuestions));
} else {
lastQuestions = JSON.parse(GM_getValue(NEWQUESTIONS));
}
$.getJSON(apiLink, function(json) {
var latestQuestion = json.items[0].title;
if (latestQuestion == lastQuestions[metaName]) {
//if you've already seen the stuff
$diamond.removeClass(DIAMONDON).addClass(DIAMONDOFF);
} else {
$diamond.removeClass(DIAMONDOFF).addClass(DIAMONDON);
for (var i = 0; i < json.items.length; i++) {
var title = json.items[i].title,
link = json.items[i].link;
//author = json.items[i].owner.display_name;
addQuestion(title, link);
}
lastQuestions[metaName] = latestQuestion;
$diamond.click(function() {
GM_setValue(NEWQUESTIONS, JSON.stringify(lastQuestions));
});
}
});
function addQuestion(title, link) {
var $li = $('<li/>');
var $link = $('<a/>', {
href: link
});
var $icon = $('<div/>', {
'class': 'site-icon favicon favicon-' + favicon
});
var $message = $('<div/>', {
'class': 'message-text'
}).append($('<h4/>', {
html: title
}));
$link.append($icon).append($message).appendTo($li);
$questions.append($li);
}
},
betterCSS: function() {
// Description: For adding the better CSS for the voting buttons and favourite button
$('head').append('<link rel="stylesheet" href="https://cdn.rawgit.com/shu8/SE-Answers_scripts/master/coolMaterialDesignCss.css" type="text/css" />');
},
standOutDupeCloseMigrated: function() {
// Description: For adding cooler signs that a questions has been closed/migrated/put on hod/is a dupe
var questions = {};
$.each($('.question-summary'), function() { //Find the questions and add their id's and statuses to an object
if ($(this).find('.summary a:eq(0)').text().trim().substr($(this).find('.summary a:eq(0)').text().trim().length - 11) == '[duplicate]') {
questions[$(this).attr('id').split('-')[2]] = 'duplicate';
$(this).find('.summary a:eq(0)').text($(this).find('.summary a:eq(0)').text().trim().substr(0, $(this).find('.summary a:eq(0)').text().trim().length - 11)); //remove [duplicate]
} else if ($(this).find('.summary a:eq(0)').text().trim().substr($(this).find('.summary a:eq(0)').text().trim().length - 8) == '[closed]') {
questions[$(this).attr('id').split('-')[2]] = 'closed';
$(this).find('.summary a:eq(0)').text($(this).find('.summary a:eq(0)').text().trim().substr(0, $(this).find('.summary a:eq(0)').text().trim().length - 8)); //remove [closed]
} else if ($(this).find('.summary a:eq(0)').text().trim().substr($(this).find('.summary a:eq(0)').text().trim().length - 10) == '[migrated]') {
questions[$(this).attr('id').split('-')[2]] = 'migrated';
$(this).find('.summary a:eq(0)').text($(this).find('.summary a:eq(0)').text().trim().substr(0, $(this).find('.summary a:eq(0)').text().trim().length - 10)); //remove [migrated]
} else if ($(this).find('.summary a:eq(0)').text().trim().substr($(this).find('.summary a:eq(0)').text().trim().length - 9) == '[on hold]') {
questions[$(this).attr('id').split('-')[2]] = 'onhold';
$(this).find('.summary a:eq(0)').text($(this).find('.summary a:eq(0)').text().trim().substr(0, $(this).find('.summary a:eq(0)').text().trim().length - 9)); //remove [on hold]
}
});
$.each($('.question-summary'), function() { //loop through questions
var $that = $(this);
$.each(questions, function(key, val) { //loop through object of questions closed/dupes/migrated
if ($that.attr('id').split('-')[2] == key) {
$that.find('.summary a:eq(0)').after(' <span class="standOutDupeCloseMigrated-' + val + '"> ' + val + ' </span>'); //add appropiate message
}
});
});
},
editReasonTooltip: function() {
// Description: For showing the latest revision's comment as a tooltip on 'edit [date] at [time]'
function getComment(url, $that) {
$.get(url, function(responseText, textStatus, XMLHttpRequest) {
$that.find('.sox-revision-comment').attr('title', $(XMLHttpRequest.responseText).find('.revision-comment:eq(0)')[0].innerHTML);
});
}
$('.question, .answer').each(function() {
if ($(this).find('.post-signature').length > 1) {
var id = $(this).attr('data-questionid') || $(this).attr('data-answerid');
$(this).find('.post-signature:eq(0)').find('.user-action-time a').wrapInner('<span class="sox-revision-comment"></span>');
var $that = $(this);
getComment('http://' + SOHelper.getSiteURL() + '/posts/' + id + '/revisions', $that);
}
});
},
addSBSBtn: function() {
// Description: For adding a button to the editor toolbar to toggle side-by-side editing
// Thanks szego (@https://github.com/szego) for completely rewriting this! https://github.com/shu8/SE-Answers_scripts/pull/2
function startSBS(toAppend) {
//variables to reduce DOM searches
var wmdinput = $('#wmd-input' + toAppend);
var wmdpreview = $('#wmd-preview' + toAppend);
var posteditor = $('#post-editor' + toAppend);
var draftsaved = $('#draft-saved' + toAppend);
var draftdiscarded = $('#draft-discarded' + toAppend);
$('#wmd-button-bar' + toAppend).toggleClass('sbs-on');
draftsaved.toggleClass('sbs-on');
draftdiscarded.toggleClass('sbs-on');
posteditor.toggleClass('sbs-on');
wmdinput.parent().toggleClass('sbs-on'); //wmdinput.parent() has class wmd-container
wmdpreview.toggleClass('sbs-on');
if (toAppend.length > 0) { //options specific to making edits on existing questions/answers
posteditor.find('.hide-preview').toggleClass('sbs-on');
//hack: float nuttiness for "Edit Summary" box
var editcommentp1 = $('#edit-comment' + toAppend).parent().parent().parent().parent().parent();
editcommentp1.toggleClass('edit-comment-p1 sbs-on');
editcommentp1.parent().toggleClass('edit-comment-p2 sbs-on');
} else if (window.location.pathname.indexOf('questions/ask') > -1) { //extra CSS for 'ask' page
wmdpreview.toggleClass('sbs-newq');
draftsaved.toggleClass('sbs-newq');
draftdiscarded.toggleClass('sbs-newq');
$('.tag-editor').parent().toggleClass('tag-editor-p sbs-on sbs-newq');
$('#question-only-section').children('.form-item').toggleClass('sbs-on sbs-newq');
//swap the order of things to prevent draft saved/discarded messages from
// moving the preview pane around
if (wmdpreview.hasClass('sbs-on')) {
draftsaved.before(wmdpreview);
} else {
draftdiscarded.after(wmdpreview);
}
}
if (wmdpreview.hasClass('sbs-on')) { //sbs was toggled on
$('#sidebar').addClass('sbs-on');
$('#content').addClass('sbs-on');
if (toAppend.length > 0) { //current sbs toggle is for an edit
$('.votecell').addClass('sbs-on');
}
//stretch the text input window to match the preview length
// - "215" came from trial and error
// - Can this be done using toggleClass?
var previewHeight = wmdpreview.height();
if (previewHeight > 215) { //default input box is 200px tall, only scale if necessary
wmdinput.height(previewHeight - 15);
}
} else { //sbs was toggled off
//check if sbs is off for all existing questions and answers
if (!$('.question').find('.wmd-preview.sbs-on').length && !$('.answer').find('.wmd-preview.sbs-on').length) {
$('.votecell').removeClass('sbs-on');
if (!($('#wmd-preview').hasClass('sbs-on'))) { //sbs is off for everything
$('#sidebar').removeClass('sbs-on');
$('#content').removeClass('sbs-on');
}
}
//return input text window to original size
// - Can this be done using toggleClass?
wmdinput.height(200);
}
}
function SBS(jNode) {
var itemid = jNode[0].id.replace(/^\D+/g, '');
var toAppend = (itemid.length > 0 ? '-' + itemid : ''); //helps select tags specific to the question/answer being
// edited (or new question/answer being written)
setTimeout(function() {
var sbsBtn = '<li class="wmd-button" title="side-by-side-editing" style="left: 500px;width: 170px;"> \
<div id="wmd-sbs-button' + toAppend + '" style="background-image: none;"> \
Toggle SBS?</div></li>';
jNode.after(sbsBtn);
//add click listener to sbsBtn
jNode.next().on('click', function() {
startSBS(toAppend);
});
//add click listeners for "Save Edits" and "cancel" buttons
// - also gets added to the "Post New Question" and "Post New Answer" button as an innocuous (I think) side effect
$('#post-editor' + toAppend).siblings('.form-submit').children().on('click', function() {
if ($(this).parent().siblings('.sbs-on').length) { //sbs was on, so turn it off
startSBS(toAppend);
}
});
}, 1000);
}
//Adding script dynamically because @requiring causes the page load to hang -- don't know how to fix! :(
var script = document.createElement('script');
script.src = 'https://cdn.rawgit.com/BrockA/2625891/raw/9c97aa67ff9c5d56be34a55ad6c18a314e5eb548/waitForKeyElements.js';
document.getElementsByTagName('head')[0].appendChild(script);
//This is a heavily modified version by szego <https://github.com/szego/SE-Answers_scripts/blob/master/side-by-side-editing.user.js>:
setTimeout(function() {
if (window.location.pathname.indexOf('questions/ask') < 0) { //not posting a new question
//get question and answer IDs for keeping track of the event listeners
var anchorList = $('#answers > a'); //answers have anchor tags before them of the form <a name="#">,
// where # is the answer ID
// TODO: test
var numAnchors = anchorList.length;
var itemIDs = [];
for (var i = 1; i <= numAnchors - 2; i++) { //the first and last anchors aren't answers
itemIDs.push(anchorList[i].name);
}
itemIDs.push($('.question').data('questionid'));
//event listeners for adding the sbs toggle buttons for editing existing questions or answers
for (i = 0; i <= numAnchors - 2; i++) {
waitForKeyElements('#wmd-redo-button-' + itemIDs[i], SBS);
}
}
//event listener for adding the sbs toggle button for posting new questions or answers
waitForKeyElements('#wmd-redo-button', SBS);
}, 2000);
},
alwaysShowImageUploadLinkBox: function() {
// Description: For always showing the 'Link from the web' box when uploading an image.
var body = document.getElementById('body'); //Code courtesy of Siguza <http://meta.stackoverflow.com/a/306901/3541881>! :)
if (body) {
new MutationObserver(function(records) {
records.forEach(function(r) {
Array.prototype.forEach.call(r.addedNodes, function(n) {
if (n.classList.contains('image-upload')) {
new MutationObserver(function(records, self) {
var link = n.querySelector('.modal-options-default.tab-page a');
if (link) {
link.click();
self.disconnect();
}
}).observe(n, {
childList: true
});
}
});
});
}).observe(body, {
childList: true
});
}
},
addAuthorNameToInboxNotifications: function() {
// Description: To add the author's name to inbox notifications
function getAuthorName($node) {
var type = $node.find('.item-header .item-type').text(),
sitename = $node.find('a').eq(0).attr('href').split('/')[2].split('.')[0],
link = $node.find('a').eq(0).attr('href'),
apiurl,
id;
switch (type) {
case 'comment':
id = link.split('/')[5].split('?')[0],
apiurl = 'https://api.stackexchange.com/2.2/comments/' + id + '?order=desc&sort=creation&site=' + sitename
break;
case 'answer':
id = link.split('/')[4].split('?')[0];
apiurl = 'https://api.stackexchange.com/2.2/answers/' + id + '?order=desc&sort=creation&site=' + sitename
break;
case 'edit suggested':
id = link.split('/')[4],
apiurl = 'https://api.stackexchange.com/2.2/suggested-edits/' + id + '?order=desc&sort=creation&site=' + sitename
break;
default:
console.log('sox does not currently support get author information for type' + type)
return;
}
$.getJSON(apiurl, function(json) {
var author = json.items[0].owner.display_name,
$author = $('<span/>', {
class: 'author',
style: 'padding-left: 5px;',
text: author
});
console.log(author);
var $header = $node.find('.item-header'),
$type = $header.find('.item-type').clone(),
$creation = $header.find('.item-creation').clone();
//fix conflict with soup fix mse207526 - https://github.com/vyznev/soup/blob/master/SOUP.user.js#L489
$header.empty().append($type).append($author).append($creation);
});
};
new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var length = mutation.addedNodes.length;
for (var i = 0; i < length; i++) {
var $addedNode = $(mutation.addedNodes[i]);
if (!$addedNode.hasClass('inbox-dialog')) {
return;
}
for (var x = 0; x < 21; x++) { //first 20 items
getAuthorName($addedNode.find('.inbox-item').eq(x));
}
}
});
}).observe(document.body, {
childList: true,
attributes: true,
subtree: true
});
},
flagOutcomeTime: function() {
// Description: For adding the flag outcome time to the flag page
//https://github.com/shu8/Stack-Overflow-Optional-Features/pull/32
$('.flag-outcome').each(function() {
$(this).append(' – ' + $(this).attr('title'));
});
},
scrollToTop: function() {
// Description: For adding a button at the bottom right part of the screen to scroll back to the top
//https://github.com/shu8/Stack-Overflow-Optional-Features/pull/34
if (SOHelper.getSiteType() !== 'chat') { // don't show scrollToTop button while in chat.
$('<div/>', {
id: 'sox-scrollToTop',
click: function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: 0
}, 800);
return false;
}
}).append($('<i/>', {
'class': 'fa fa-angle-double-up fa-3x'
})).appendTo('div.container');
if ($(window).scrollTop() < 200) {
$('#sox-scrollToTop').hide();
}
$(window).scroll(function() {
if ($(this).scrollTop() > 200) {
$('#sox-scrollToTop').fadeIn();
} else {
$('#sox-scrollToTop').fadeOut();
}
});
}
},
flagPercentages: function() {
// Description: For adding percentages to the flag summary on the flag page
//By @enki; https://github.com/shu8/Stack-Overflow-Optional-Features/pull/38, http://meta.stackoverflow.com/q/310881/3541881, http://stackapps.com/q/6773/26088
var group = {
POST: 1,
SPAM: 2,
OFFENSIVE: 3,
COMMENT: 4
};
var type = {
TOTAL: 'flags',
WAITING: 'waiting',
HELPFUL: 'helpful',
DECLINED: 'declined',
DISPUTED: 'disputed',
AGEDAWAY: 'aged away'
};
var count,
percentage;
function addPercentage(group, type, percentage) {
var $span = $('<span/>', {
text: '({0}%)'.replace('{0}', percentage),
style: 'margin-left:5px; color: #999; font-size: 12px;'
});
$('td > a[href*="group=' + group + '"]:contains("' + type + '")').after($span);
}
function calculatePercentage(count, total) {
var percent = (count / total) * 100;
return +percent.toFixed(2);
}
function getFlagCount(group, type) {
var flagCount = 0;
flagCount += Number($('td > a[href*="group=' + group + '"]:contains("' + type + '")')
.parent()
.prev()
.text()
.replace(',', ''));
return flagCount;
}
// add percentages
for (var groupKey in group) {
var item = group[groupKey],
total = getFlagCount(item, type.TOTAL);
for (var typeKey in type) {
var typeItem = type[typeKey];
if (typeKey !== 'TOTAL') {
count = getFlagCount(item, typeItem);
percentage = calculatePercentage(count, total);
//console.log(groupKey + ": " + typeKey + " Flags -- " + count);
addPercentage(item, typeItem, percentage);
}
}
}
},
linkedPostsInline: function() {
// Description: Displays linked posts inline with an arrow
function getIdFromUrl(url) {
if (url.indexOf('/a/') > -1) { //eg. http://meta.stackexchange.com/a/26764/260841
return url.split('/a/')[1].split('/')[0];
} else if (url.indexOf('/q/') > -1) { //eg. http://meta.stackexchange.com/q/26756/260841
return url.split('/q/')[1].split('/')[0];
} else if (url.indexOf('/questions/') > -1) {
if (url.indexOf('#') > -1) { //then it's probably an answer, eg. http://meta.stackexchange.com/questions/26756/how-do-i-use-a-small-font-size-in-questions-and-answers/26764#26764
return url.split('#')[1];
} else { //then it's a question
return url.split('/questions/')[1].split('/')[0];
}
}
}
$('.post-text a, .comments .comment-copy a').each(function() {
var url = $(this).attr('href');
if (url && url.indexOf(SOHelper.getSiteURL()) > -1 & url.indexOf('#comment') == -1) {
$(this).css('color', '#0033ff');
$(this).before('<a class="expander-arrow-small-hide expand-post-sox"></a>');
}
});
$(document).on('click', 'a.expand-post-sox', function() {
if ($(this).hasClass('expander-arrow-small-show')) {
$(this).removeClass('expander-arrow-small-show');
$(this).addClass('expander-arrow-small-hide');
$('.linkedPostsInline-loaded-body-sox').remove();
} else if ($(this).hasClass('expander-arrow-small-hide')) {
$(this).removeClass('expander-arrow-small-hide');
$(this).addClass('expander-arrow-small-show');
var $that = $(this);
var id = getIdFromUrl($(this).next().attr('href'));
$.get(location.protocol + '//' + SOHelper.getSiteURL() + '/posts/' + id + '/body', function(d) {
var div = '<div class="linkedPostsInline-loaded-body-sox" style="background-color: #ffffcc;">' + d + '</div>';
$that.next().after(div);
});
}
});
},
hideHotNetworkQuestions: function() {
// Description: Hides the Hot Network Questions module from the sidebar
$('#hot-network-questions').remove();
},
hideHireMe: function() {
// Description: Hides the Looking for a Job module from the sidebar
$('#hireme').remove();
},
hideCommunityBulletin: function() {
// Description: Hides the Community Bulletin module from the sidebar
$('#sidebar .community-bulletin').remove();
},
hideSearchBar: function() {
// Description: Replace the search box with a button that takes you to the search page
var $topbar = $('.topbar'),
$links = $topbar.find('.topbar-menu-links'),
$searchbar = $topbar.find('.search-container'),
$search = $('<a/>', {
href: '/search',
title: 'Search ' + SOHelper.getSiteName()
}).append($('<i/>', {
'class': 'fa fa-search'
}));
$searchbar.remove();
$links.append($search);
},
enhancedEditor: function() {
// Description: Add a bunch of features to the standard markdown editor (autocorrect, find+replace, Ace editor, and more!)
enhancedEditor.startFeature();
},
downvotedPostsEditAlert: function() {
// Description: Adds a notification to the inbox if a question you downvoted and watched is edited
function addNotification(link, title) { //add the notification
var favicon = SOHelper.getSiteIcon();
$('div.topbar .icon-inbox').click(function() { //add the actual notification
setTimeout(function() {
$('div.topbar div.topbar-dialog.inbox-dialog.dno ul').prepend("<li class='inbox-item unread-item question-close-notification'> \
<a href='" + link + "'> \
<div class='site-icon favicon favicon-" + favicon + "' title=''></div> \
<div class='item-content'> \
<div class='item-header'> \
<span class='item-type'>post edit</span> \
<span class='item-creation'><span style='color:blue;border: 1px solid gray;' onclick='javascript:void(0)' id='markAsRead_" + sitename + '-' + id + "'>mark as read</span></span> \
</div> \
<div class='item-location'>" + title + "</div> \
<div class='item-summary'>A post you downvoted has been edited since. Go check it out, and see if you should retract your downvote!</div> \
</div> \
</a> \
</li>");
}, 500);
});
}
function addNumber() { //count the number of elements in the 'unread' object, and display that number on the inbox icon
var count = 0;
for (i in unread) {
if (unread.hasOwnProperty(i)) {
count++;
}
}
if (count != 0 && $('div.topbar .icon-inbox span.unread-count').text() == '') { //display the number
$('div.topbar .icon-inbox span.unread-count').css('display', 'inline-block').text(count);
}
}
var posts = JSON.parse(GM_getValue("downvotedPostsEditAlert", "[]"));
var unread = JSON.parse(GM_getValue("downvotedPostsEditAlert-unreadItems", "{}"));
var lastCheckedDate = GM_getValue("downvotedPostsEditAlert-lastCheckedDate", 0);
var key = ")2kXF9IR5OHnfGRPDahCVg((";
var access_token = SOHelper.getAccessToken('downvotedPostsEditAlert');
$('td.votecell > div.vote').find(':last-child').not('b').after("<i class='downvotedPostsEditAlert-watchPostForEdits fa fa-eye'></i>");
$('.downvotedPostsEditAlert-watchPostForEdits').click(function() {
var $that = $(this);
var $parent = $(this).closest('table').parent();
var id;
if ($parent.attr('data-questionid')) {
id = $parent.attr('data-questionid');
} else if ($parent.attr('data-answerid')) {
id = $parent.attr('data-answerid');
}
var stringToAdd = SOHelper.getAPISiteName() + '-' + id;
var index = posts.indexOf(stringToAdd);
if (index == -1) {
$that.css('color', 'green');
posts.push(stringToAdd);
GM_setValue('downvotedPostsEditAlert', JSON.stringify(posts));
} else {
$that.removeAttr('style');
posts.splice(index, 1);
GM_setValue('downvotedPostsEditAlert', JSON.stringify(posts));
}
});
for (var i = 0; i < posts.length; i++) {
var sitename = posts[i].split('-')[0];
var id = posts[i].split('-')[1];
var url = "https://api.stackexchange.com/2.2/posts/" + id + "?order=desc&sort=activity&site=" + sitename + "&filter=!9YdnSEBb8&key=" + key + "&access_token=" + access_token;
if (new Date().getDate() != new Date(lastCheckedDate).getDate()) {
$.getJSON(url, function(json) {
if (json.items[0].last_edit_date > ((lastCheckedDate / 1000) - 86400)) {
unread[sitename + '-' + json.items[0].post_id] = [json.items[0].link, json.items[0].title];
GM_setValue('downvotedPostsEditAlert-unreadItems', JSON.stringify(unread));
}
lastCheckedDate = new Date().getTime();
GM_setValue('downvotedPostsEditAlert-lastCheckedDate', lastCheckedDate);
});
}
$.each(unread, function(siteAndId, details) {
addNotification(details[0], details[1]);
});
addNumber();
}
$(document).on('click', 'span[id^=markAsRead]', function(e) { //click handler for the 'mark as read' button
e.preventDefault(); //don't go to questionn
var siteAndId = $(this).attr('id').split('_')[1];
delete unread[siteAndId]; //delete the question from the object
GM_setValue('downvotedPostsEditAlert-unreadItems', JSON.stringify(unread)); //save the object again
$(this).parent().parent().parent().parent().parent().hide(); //hide the notification in the inbox dropdown
});
$(document).mouseup(function(e) { //hide on click off
var container = $('div.topbar-dialog.inbox-dialog.dno > div.modal-content');
if (!container.is(e.target) && container.has(e.target).length === 0) {
container.find('.question-close-notification').remove();
}
});
},
chatEasyAccess: function() {
// Description: Adds options to give a user read/write/no access in chat from their user popup dialog
new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var newNodes = mutation.addedNodes;
if (newNodes !== null) {
var $nodes = $(newNodes);
$nodes.each(function() {
var $node = $(this);
if ($node.hasClass("user-popup")) {
setTimeout(function() {
var id = $node.find('a')[0].href.split('/')[4];
if ($('.chatEasyAccess').length) {
$('.chatEasyAccess').remove();
}
$node.find('div:last-child').after('<div class="chatEasyAccess">give <b id="read-only">read</b> / <b id="read-write">write</b> / <b id="remove">no</b> access</div>');
$(document).on('click', '.chatEasyAccess b', function() {
$that = $(this);
$.ajax({
url: 'http://chat.stackexchange.com/rooms/setuseraccess/' + location.href.split('/')[4],
type: 'post',
data: {
'fkey': fkey().fkey,
'userAccess': $that.attr('id'),
'aclUserId': id
},
success: function(d) {
if (d == '') {
alert('Successfully changed user access');
} else {
alert(d);
}
}
});
});
}, 1000);
}
});
}
});
}).observe(document.getElementById('chat-body'), {
childList: true,
attributes: true
});
},
topAnswers: function() {
// Description: Adds a box above answers to show the most highly-scoring answers
var count = 0;
var $topAnswers = $('<div/>', {
id: 'sox-top-answers',
style: 'padding-bottom: 10px; border-bottom: 1px solid #eaebec;'
}),
$table = $('<table/>', {
style: 'margin:0 auto;'
}),
$row = $('<tr/>');
$table.append($row).appendTo($topAnswers);
function score(e) {
return new Number($(e).parent().find('.vote-count-post').text());
}
function compareByScore(a, b) {
return score(b) - score(a);
}
$(':not(.deleted-answer) .answercell').slice(1).sort(compareByScore).slice(0, 5).each(function() {
count++;
var id = $(this).find('.short-link').attr('id').replace('link-post-', ''),
score = $(this).prev().find('.vote-count-post').text(),
icon = 'vote-up-off';
if (score > 0) {
icon = 'vote-up-on';
}
if (score < 0) {
icon = 'vote-down-on';
}
var $column = $('<td/>', {
style: 'width: 100px; text-align: center;'
}),
$link = $('<a/>', {
href: '#' + id
}),
$icon = $('<i/>', {
class: icon,
style: 'margin-bottom: 0; padding-right: 5px;'
});
$link.append($icon).append('Score: ' + score);
$column.append($link).appendTo($row);
});
if (count > 0) {
$('#answers div.answer:first').before($topAnswers);
$table.css('width', count * 100 + 'px');
}
},
tabularReviewerStats: function() {
// Description: Adds a notification to the inbox if a question you downvoted and watched is edited
// Idea by lolreppeatlol @ http://meta.stackexchange.com/a/277446/260841 :)
if(location.href.indexOf('/review/suggested-edits') > -1) {
var info = {};
$('.review-more-instructions ul:eq(0) li').each(function() {
var text = $(this).text(),
username = $(this).find('a').text(),
link = $(this).find('a').attr('href'),
approved = text.match(/approved (.*?)[a-zA-Z]/)[1],
rejected = text.match(/rejected (.*?)[a-zA-Z]/)[1],
improved = text.match(/improved (.*?)[a-zA-Z]/)[1];
info[username] = {
'link': link,
'approved': approved,
'rejected': rejected,
'improved': improved
};
});
var $editor = $('.review-more-instructions ul:eq(1) li'),
editorName = $editor.find('a').text(),
editorLink = $editor.find('a').attr('href'),
editorApproved = $editor.text().match(/([0-9])/g)[0],
editorRejected = $editor.text().match(/([0-9])/g)[1];
info[editorName] = {
'editorLink': link,
'approved': editorApproved,
'rejected': editorRejected
};
var table = "<table><tbody><tr><th style='padding: 4px;'>User</th><th style='padding: 4px;'>Approved</th><th style='padding: 4px;'>Rejected</th><th style='padding: 4px;'>Improved</th style='padding: 4px;'></tr>";
$.each(info, function(user, details) {
table += "<tr><td style='padding: 4px;'><a href='" + details.link + "'>" + user + "</a></td><td style='padding: 4px;'>" + details.approved + "</td><td style='padding: 4px;'>" + details.rejected + "</td><td style='padding: 4px;'>" + (details.improved ? details.improved : 'N/A') + "</td></tr>";
});
table += "</tbody></table>";
$('.review-more-instructions p, .review-more-instructions ul').remove();
$('.review-more-instructions').append(table);
}
},
linkedToFrom: function() {
// Description: Add an arrow to linked posts in the sidebar to show whether they are linked to or linked from
if(location.href.indexOf('/questions/') > -1) {
$('.linked .spacer a.question-hyperlink').each(function() {
var id = $(this).attr('href').split('/')[4].split('?')[0];
if($('a[href*="' + id + '"]').not('.spacer a').length) {
$(this).append('<span title="Current question links to this question" style="color:black;font-size:15px;margin-left:5px;">↗</span>');
} else {
$(this).append('<span title="Current question is linked from this question" style="color:black;font-size:15px;margin-left:5px;">↙</span>');
}
});
}
}
};
| sox.features.js | /*jshint multistr: true */
//TODO: what are post_contents and author for?
var features = { //ALL the functions must go in here
grayOutVotes: function() {
// Description: Grays out votes AND vote count
if ($('.deleted-answer').length) {
$('.deleted-answer .vote-down-off, .deleted-answer .vote-up-off, .deleted-answer .vote-count-post').css('opacity', '0.5');
}
},
moveBounty: function() {
// Description: For moving bounty to the top
if ($('.bounty-notification').length) {
$('.bounty-notification').insertAfter('.question .fw');
$('.question .bounty-notification .votecell').remove();
}
},
dragBounty: function() {
// Description: Makes the bounty window draggable
$('.bounty-notification').click(function() {
setTimeout(function() {
$('#start-bounty-popup').draggable().css('cursor', 'move');
}, 50);
});
},
renameChat: function() {
// Description: Renames Chat tabs to prepend 'Chat' before the room name
if (SOHelper.getSiteType() === 'chat') {
document.title = 'Chat - ' + document.title;
}
},
exclaim: function() {
// Description: Removes exclamation marks
var old = $('td.comment-actions > div > div > div.message-text');
var newText = old.text().replace("!", ".");
old.html(newText);
},
markEmployees: function() {
// Description: Adds an Stack Overflow logo next to users that *ARE* a Stack Overflow Employee
function unique(list) {
//credit: GUFFA https://stackoverflow.com/questions/12551635/12551709#12551709
var result = [];
$.each(list, function(i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});
return result;
}
var $links = $('.comment a, .deleted-answer-info a, .employee-name a, .started a, .user-details a').filter('a[href^="/users/"]');
var ids = [];
$links.each(function() {
var href = $(this).attr('href'),
id = href.split('/')[2];
ids.push(id);
});
ids = unique(ids);
var url = 'https://api.stackexchange.com/2.2/users/{ids}?site={site}'
.replace('{ids}', ids.join(';'))
.replace('{site}', SOHelper.getApiSiteParameter(StackExchange.options.site.name));
$.ajax({
url: url
}).success(function(data) {
for (var i = 0, len = data.items.length; i < len; i++) {
var userId = data.items[i].user_id,
isEmployee = data.items[i].is_employee;
if (isEmployee) {
$links.filter('a[href^="/users/' + userId + '/"]').append('<i class="fa fa-stack-overflow" title="employee" style="padding: 0 5px"></i>');
}
}
});
},
bulletReplace: function() {
// Description: Replaces disclosure bullets with normal ones
$('.dingus').each(function() {
$(this).html('●');
});
},
addEllipsis: function() {
// Description: Adds an ellipsis to long names
$('.user-info .user-details').css('text-overflow', 'ellipsis');
},
copyCommentsLink: function() {
// Description: Adds the 'show x more comments' link before the commnents
$('.js-show-link.comments-link').each(function() {
var $this2 = $(this);
$('<tr><td></td><td>' + $this2.clone().wrap('<div>').parent().html() + '</td></tr>').insertBefore($(this).parent().closest('tr')).click(function() {
$(this).hide();
});
var commentParent;
// Determine if comment is on a question or an answer
if ($(this).parents('.answer').length) {
commentParent = '.answer';
} else {
commentParent = '.question';
}
$(this).click(function() {
$(this).closest(commentParent).find('.js-show-link.comments-link').hide();
});
});
},
/*unHideAnswer: function() { // For unfading a downvoted answer on hover
$(".downvoted-answer").hover(function() {
$(this).removeClass("downvoted-answer");
}, function() {
$(this).addClass("downvoted-answer");
});
},*/
fixedTopbar: function() {
// Description: For making the topbar fixed (always stay at top of screen)
if (SOHelper.getSiteURL() == 'askubuntu.com') { //AskUbuntu is annoying. UnicornsAreVeryVeryYummy made the below code for AskUbuntu: https://github.com/shu8/Stack-Overflow-Optional-Features/issues/11 Thanks!
var newUbuntuLinks = $('<div/>', {
'class': 'fixedTopbar-links'
}),
linksWrapper = $('<div/>', {
'class': 'fixedTopbar-linksList'
}),
listOfSites = $('<ul/>', {
'class': 'fixedTopbar-siteLink'
}),
more = $('<li/>', {
html: '<a href="#">More</a>',
'class': 'fixedTopbar-siteLink'
}),
sites = {
Ubuntu: 'ubuntu.com',
Community: 'community.ubuntu.com',
'Ask!': 'askubuntu.com',
Developer: 'developer.ubuntu.com',
Design: 'design.ubuntu.com',
Discourse: 'discourse.ubuntu.com',
Hardware: 'www.ubuntu.com/certification',
Insights: 'insights.ubuntu.com',
Juju: 'juju.ubuntu.com',
Shop: 'shop.ubuntu.com'
},
moreSites = {
Apps: 'apps.ubuntu.com',
Help: 'help.ubuntu.com',
Forum: 'ubuntuforums.org',
Launchpad: 'launchpad.net',
MAAS: 'maas.ubuntu.com',
Canonical: 'canonical' //TODO
};
var addSite = function(link, name) {
listOfSites.append($('<li/>', {
html: '<a href="http://' + link + '">' + name + '</a>',
'class': 'fixedTopbar-siteLink'
}));
};
for (var name in sites) {
addSite(sites[name], name);
}
listOfSites.append(more);
var moreList = $('li', $(more));
var addMoreSite = function(link, name) {
moreList.append($('<li/>', {
html: '<a href="http://' + link + '">' + name + '</a>',
'class': 'fixedTopbar-siteLink'
}));
};
for (name in moreSites) {
addMoreSite(moreSites[name], name);
}
$('.nav-global').remove(); //Ubuntu links
$('#custom-header').remove();
linksWrapper.append(listOfSites);
newUbuntuLinks.append(linksWrapper);
$('.topbar-wrapper').after(newUbuntuLinks);
$('.topbar').addClass('fixedTopbar-stickyToolbar');
$('.topbar').before($('<div/>', {
html: '<br/><br/>'
}));
$('#header').css('margin-top', '22px');
} else if (SOHelper.getSiteType() !== 'chat') { //for all the normal, unannoying sites, excluding chat ;)
$('.topbar').css({
'position': 'fixed',
'z-index': '1001'
});
//Thanks ArtOfCode (http://worldbuilding.stackexchange.com/users/2685/artofcode) for fixing the topbar covering the header :)
$('#header').css('margin-top', '34px');
$('.topbar').css('margin-top', '-34px');
} else if (SOHelper.getSiteType() === 'chat') { //chat is a bit different
$('.topbar').css('position', 'fixed');
}
$('#rep-card-next .percent').after($('#rep-card-next .label').css('z-index', 0)).css('position', 'absolute');
$('#badge-card-next .percent').after($('#badge-card-next .label').css('z-index', 0)).css('position', 'absolute');
},
highlightQuestions: function() {
// Description: For highlighting only the tags of favorite questions
var highlightClass = '';
if (/superuser/.test(window.hostname)) { //superuser
highlightClass = 'favorite-tag-su';
} else if (/stackoverflow/.test(window.hostname)) { //stackoverflow
highlightClass = 'favorite-tag-so';
} else { //for all other sites
highlightClass = 'favorite-tag-all';
}
function highlight() {
var interestingTagsDiv = $('#interestingTags').text();
var interesting = interestingTagsDiv.split(' ');
interesting.pop(); //Because there's one extra value at the end
$('.tagged-interesting > .summary > .tags > .post-tag').filter(function(index) {
return interesting.indexOf($(this).text()) > -1;
}).addClass(highlightClass);
$('.tagged-interesting').removeClass('tagged-interesting');
}
setTimeout(function() { //Need delay to make sure the CSS is applied
highlight();
if ($('.question-summary').length) {
new MutationObserver(function(records) {
records.forEach(function(mutation) {
if (mutation.attributeName == 'class') {
highlight();
}
});
}).observe(document.querySelector('.question-summary'), {
childList: true,
attributes: true
});
}
}, 300);
},
displayName: function() {
// Description: For displaying username next to avatar on topbar
var uname = SOHelper.getUsername();
var insertme = '<span class="reputation links-container" style="color:white;" title="' + uname + '">' + uname + '</span>"';
$(insertme).insertBefore('.gravatar-wrapper-24');
},
colorAnswerer: function() {
// Description: For highlighting the names of answerers on comments
$('.answercell').each(function(i, obj) {
var x = $(this).find('.user-details a').text();
$('.answer .comment-user').each(function() {
if ($(this).text() == x) {
$(this).css('background-color', 'orange');
}
});
});
$('.js-show-link.comments-link').click(function() { //Keep CSS when 'show x more comments' is clicked
setTimeout(function() {
features.colorAnswerer();
}, 500);
});
},
kbdAndBullets: function() {
// Description: For adding buttons to the markdown toolbar to surround selected test with KBD or convert selection into a markdown list
function addBullets() {
var list = '- ' + $('[id^="wmd-input"]').getSelection().text.split('\n').join('\n- ');
$('[id^="wmd-input"]').replaceSelectedText(list);
}
function addKbd() {
$('[id^="wmd-input"]').surroundSelectedText("<kbd>", "</kbd>");
}
var kbdBtn = '<li class="wmd-button" title="surround selected text with <kbd> tags" style="left: 400px;"><span id="wmd-kbd-button" style="background-image: none;">kbd</span></li>';
var listBtn = '<li class="wmd-button" title="add dashes (\"-\") before every line to make a bulvar point list" style="left: 425px;"><span id="wmd-bullet-button" style="background-image:none;">●</span></li>';
setTimeout(function() {
$('[id^="wmd-redo-button"]').after(kbdBtn);
$('[id^="wmd-redo-button"]').after(listBtn);
$('#wmd-kbd-button').on('click', function() {
addKbd();
});
$('#wmd-bullet-button').on('click', function() {
addBullets();
});
}, 500);
$('[id^="wmd-input"]').bind('keydown', 'alt+l', function() {
addBullets();
});
$('[id^="wmd-input"]').bind('keydown', 'alt+k', function() {
addKbd();
});
},
editComment: function() {
// Description: For adding checkboxes when editing to add pre-defined edit reasons
function addCheckboxes() {
$('#reasons').remove(); //remove the div containing everything, we're going to add/remove stuff now:
if (!$('[class^="inline-editor"]').length) { //if there is no inline editor, do nothing
return;
}
if (/\/edit/.test(window.location.href) || $('[class^="inline-editor"]').length) { //everything else
$('.form-submit').before('<div id="reasons"></div>');
$.each(JSON.parse(GM_getValue('editReasons')), function(i, obj) {
$('#reasons').append('<label><input type="checkbox" value="' + this[1] + '"</input>' + this[0] + '</label> ');
});
$('#reasons input[type="checkbox"]').css('vertical-align', '-2px');
$('#reasons label').hover(function() {
$(this).css({ //on hover
'background-color': 'gray',
'color': 'white'
});
}, function() {
$(this).css({ //on un-hover
'background-color': 'white',
'color': 'inherit'
});
});
var editCommentField = $('[id^="edit-comment"]');
$('#reasons input[type="checkbox"]').change(function() {
if (this.checked) { //Add it to the summary
if (!editCommentField.val()) {
editCommentField.val(editCommentField.val() + $(this).val().replace(/on$/g, ''));
} else {
editCommentField.val(editCommentField.val() + '; ' + $(this).val().replace(/on$/g, ''));
}
var newEditComment = editCommentField.val(); //Remove the last space and last semicolon
editCommentField.val(newEditComment).focus();
} else if (!this.checked) { //Remove it from the summary
editCommentField.val(editCommentField.val().replace($(this).val() + '; ', '')); //for middle/beginning values
editCommentField.val(editCommentField.val().replace($(this).val(), '')); //for last value
}
});
}
}
function displayDeleteValues() {
//Display the items from list and add buttons to delete them
$('#currentValues').html(' ');
$.each(JSON.parse(GM_getValue('editReasons')), function(i, obj) {
$('#currentValues').append(this[0] + ' - ' + this[1] + '<input type="button" id="' + i + '" value="Delete"><br />');
});
addCheckboxes();
}
var div = '<div id="dialogEditReasons" class="sox-centered wmd-prompt-dialog"><span id="closeDialogEditReasons" style="float:right;">Close</span><span id="resetEditReasons" style="float:left;">Reset</span> \
<h2>View/Remove Edit Reasons</h2> \
<div id="currentValues"></div> \
<br /> \
<h3>Add a custom reason</h3> \
Display Reason: <input type="text" id="displayReason"> \
<br /> \
Actual Reason: <input type="text" id="actualReason"> \
<br /> \
<input type="button" id="submitUpdate" value="Submit"> \
</div>';
$('body').append(div);
$('#dialogEditReasons').draggable().css('position', 'absolute').css('text-align', 'center').css('height', '60%').hide();
$('#closeDialogEditReasons').css('cursor', 'pointer').click(function() {
$(this).parent().hide(500);
});
$('#resetEditReasons').css('cursor', 'pointer').click(function() { //manual reset
var options = [ //Edit these to change the default settings
['formatting', 'Improved Formatting'],
['spelling', 'Corrected Spelling'],
['grammar', 'Fixed grammar'],
['greetings', 'Removed thanks/greetings']
];
if (confirm('Are you sure you want to reset the settings to Formatting, Spelling, Grammar and Greetings')) {
GM_setValue('editReasons', JSON.stringify(options));
alert('Reset options to default. Refreshing...');
location.reload();
}
});
if (GM_getValue('editReasons', -1) == -1) { //If settings haven't been set/are empty
var defaultOptions = [
['formatting', 'Improved Formatting'],
['spelling', 'Corrected Spelling'],
['grammar', 'Fixed grammar'],
['greetings', 'Removed thanks/greetings']
];
GM_setValue('editReasons', JSON.stringify(defaultOptions)); //save the default settings
} else {
var options = JSON.parse(GM_getValue('editReasons')); //If they have, get the options
}
$('#dialogEditReasons').on('click', 'input[value="Delete"]', function() { //Click handler to delete when delete button is pressed
var delMe = $(this).attr('id');
options.splice(delMe, 1); //actually delete it
GM_setValue('editReasons', JSON.stringify(options)); //save it
displayDeleteValues(); //display the items again (update them)
});
$('#submitUpdate').click(function() { //Click handler to update the array with custom value
if (!$('#displayReason').val() || !$('#actualReason').val()) {
alert('Please enter something in both the textboxes!');
} else {
var arrayToAdd = [$('#displayReason').val(), $('#actualReason').val()];
options.push(arrayToAdd); //actually add the value to array
GM_setValue('editReasons', JSON.stringify(options)); //Save the value
// moved display call after setvalue call, list now refreshes when items are added
displayDeleteValues(); //display the items again (update them)
//reset textbox values to empty
$('#displayReason').val('');
$('#actualReason').val('');
}
});
setTimeout(function() {
addCheckboxes();
//Add the button to update and view the values in the help menu:
$('.topbar-dialog.help-dialog.js-help-dialog > .modal-content ul').append("<li><a href='javascript:void(0)' id='editReasonsLink'>Edit Reasons \
<span class='item-summary'>Edit your personal edit reasons for SE sites</span></a></li>");
$('.topbar-dialog.help-dialog.js-help-dialog > .modal-content ul #editReasonsLink').on('click', function() {
displayDeleteValues();
$('#dialogEditReasons').show(500); //Show the dialog to view and update values
});
}, 500);
$('.post-menu > .edit-post').click(function() {
setTimeout(function() {
addCheckboxes();
}, 500);
});
},
shareLinksMarkdown: function() {
// Description: For changing the 'share' button link to the format [name](link)
$('.short-link').click(function() {
setTimeout(function() {
var link = $('.share-tip input').val();
$('.share-tip input').val('[' + $('#question-header a').html() + '](' + link + ')');
$('.share-tip input').select();
}, 500);
});
},
commentShortcuts: function() {
// Description: For adding support in comments for Ctrl+K,I,B to add code backticks, italicise, bolden selection
$('.js-add-link.comments-link').click(function() {
setTimeout(function() {
$('.comments textarea').keydown(function(e) {
if (e.which == 75 && e.ctrlKey) { //ctrl+k (code)
$(this).surroundSelectedText('`', '`');
e.stopPropagation();
e.preventDefault();
return false;
}
if (e.which == 73 && e.ctrlKey) { //ctrl+i (italics)
$(this).surroundSelectedText('*', '*');
e.stopPropagation();
e.preventDefault();
return false;
}
if (e.which == 66 && e.ctrlKey) { //ctrl+b (bold)
$(this).surroundSelectedText('**', '**');
e.stopPropagation();
e.preventDefault();
return false;
}
});
}, 200);
});
},
unspoil: function() {
// Description: For adding a button to reveal all spoilers in a post
$('#answers div[id*="answer"], div[id*="question"]').each(function() {
if ($(this).find('.spoiler').length) {
$(this).find('.post-menu').append('<span class="lsep">|</span><a id="showSpoiler-' + $(this).attr("id") + '" href="javascript:void(0)">unspoil</span>');
}
});
$('a[id*="showSpoiler"]').click(function() {
var x = $(this).attr('id').split(/-(.+)?/)[1];
$('#' + x + ' .spoiler').removeClass('spoiler');
});
},
/*highlightClosedQuestions: function() { // For highlighting and slightly greying out closed questions when viewing question lists
$('.question-summary').each(function() {
if ($(this).find('.summary h3 a').text().indexOf('[on hold]') > -1 || $(this).find('.summary h3 a').text().indexOf('[closed]') > -1) {
if ($('.cp').length) {
$(this).find('.cp').css('border', 'blue').css('border-style', 'dotted').css('border-width', 'thin').css('background-color', '#E0E0E0');
$(this).css('opacity', '0.9');
} else {
$(this).find('.votes').css('border', 'blue').css('border-style', 'dotted').css('border-width', 'thin').css('background-color', '#E0E0E0');
$(this).css('opacity', '0.9');
}
}
});
},*/
quickCommentShortcutsMain: function() {
// Description: For adding shortcuts to insert pre-defined text into comment fields
function parseGM() {
return JSON.parse(GM_getValue('quickCommentShortcutsData'));
}
function saveGM(data) {
GM_setValue('quickCommentShortcutsData', JSON.stringify(data));
}
function replaceVars(text, sitename, siteurl, op, answererName) {
return text.replace(/\$SITENAME\$/gi, sitename).replace(/\$ANSWERER\$/gi, answererName.replace(/\s/gi, '')).replace(/\$OP\$/gi, op).replace(/\$SITEURL\$/gi, siteurl).replace(/\$ANSWERERNORMAL\$/gi, answererName);
}
function resetReminderAndTable() {
$('#quickCommentShortcutsReminder').html('');
$('#quickCommentShortcuts table').html(' ');
$('#quickCommentShortcuts table').append('<tr><th>Name</th><th>Shortcut</th><th>Text</th><th>Delete?</th><th>Edit?</th></tr>');
}
var sitename = SOHelper.getSiteName(),
siteurl = SOHelper.getSiteURL('full'),
op = $('.post-signature.owner .user-info .user-details a').text(),
data = [],
tableCSS = {
'border': '1px solid white',
'padding': '5px',
'vertical-align': 'middle'
};
$('body').append('<div id="quickCommentShortcuts" class="sox-centered wmd-prompt-dialog" style="display:none;"><table></table></div>');
$('#quickCommentShortcuts').css('width', '100%').css('position', 'absolute').draggable();
$('body').append('<div id="quickCommentShortcutsReminder" class="quickCommentShortcutsReminder" style="display:none;"></div>');
if (!GM_getValue('quickCommentShortcutsData') || parseGM().length < 1) {
data = [
//Format: ['name', 'shortcut', 'comment text'],
['How to ping', 'alt+p', 'To ping other users, please start your comment with an `@` followed by the person\'s username (with no spaces). For example, to ping you, I would use `@$ANSWERER$`. For more information, please see [How do comments replies work?](http://meta.stackexchange.com/questions/43019/how-do-comment-replies-work).'],
['Not an answer', 'alt+n', 'This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you need to gain [reputation]($SITEURL$/faq#reputation) before you can comment on others\' posts to prevent abuse; why don\'t you try and get some by [answering a question]($SITEURL$/unanswered)?'],
['Link-only answer', 'alt+l', 'While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes, resulting in your answer being useless and consequently deleted.'],
['Ask a new question', 'alt+d', 'If you have a new question, please ask it by clicking the [Ask Question]($SITEURL$/questions/ask) button. Include a link to this question if it helps provide context. You can also [start a bounty]($SITEURL$/help/privileges/set-bounties) to draw more attention to this question.'],
['Don\'t add "Thank You"', 'alt+t', 'Please don\'t add \'thank you\' as an answer. Instead, vote up the answers that you find helpful. To do so, you need to have reputation. You can read more about reputation [here]($SITEURL$/faq#reputation).']
];
} else {
data = parseGM();
}
$(function() {
$(document).on('click', 'a.js-add-link.comments-link', function() {
var answererName = $(this).parents('div').find('.post-signature:last').first().find('.user-details a').text(),
answererId = $(this).parents('div').find('.post-signature:last').first().find('.user-details a').attr('href').split('/')[2],
apiUrl = 'https://api.stackexchange.com/2.2/users/' + answererId + '?site=' + SOHelper.getAPISiteName();
setTimeout(function() {
$('.comments textarea').attr('placeholder', 'Use comments to ask for clarification or add more information. Avoid answering questions in comments. Press Alt+O to view/edit/delete Quick Comment Shortcuts data, or press Alt+R to open a box to remind you of the shortcuts.');
}, 500);
$.ajax({
dataType: "json",
url: apiUrl,
success: function(json) {
var creationDate = json.items[0].creation_date,
lastAccess = json.items[0].last_access_date,
reputation = json.items[0].reputation,
bronze = json.items[0].badge_counts.bronze,
silver = json.items[0].badge_counts.silver,
gold = json.items[0].badge_counts.gold,
type = json.items[0].user_type;
var welcomeText = '',
newUser = 'No';
if ((new Date().getTime() / 1000) - (creationDate) < 864000) {
welcomeText = 'Welcome to $SITENAME$ $ANSWERERNORMAL$! ';
newUser = 'Yes';
}
var factfile = '<span id="closeQuickCommentShortcuts" style="float:right;">close</span> \
<h3>User "' + answererName + '" - ' + type + ': <br /> \
Creation Date: ' + new Date(creationDate * 1000).toUTCString() + ' <br /> \
New? ' + newUser + '<br /> \
Last seen: ' + new Date(lastAccess * 1000).toUTCString() + ' <br /> \
Reputation: ' + reputation + ' <br /> \
Badges: <span class="badge1"></span>' + gold + '</span> \
<span class="badge2"></span>' + silver + '</span> \
<span class="badge3"></span>' + bronze + '</span></h3>';
var variableList = '<br /><span id="quickCommentShortcutsVariables"><h4>Variables (case-insensitive)</h4> \
<strong>$ANSWERER$</strong> - name of poster of post you\'re commenting on (may be OP) with stripped spaces (eg. JohnDoe)<br /> \
<strong>$ANSWERERNORMAL$</strong> - name of poster of post you\'re commenting on (may be OP) without stripped spaces (eg. John Doe)<br /> \
<strong>$OP$</strong> - name of OP <br /> \
<strong>$SITEURL$</strong> - site URL (eg. http://stackoverflow.com) <br /> \
<strong>$SITENAME$</strong> - site name (eg. Stack Overflow) <br /></span>';
$('#quickCommentShortcuts').prepend(factfile);
$('#quickCommentShortcuts').append(variableList);
$('#closeQuickCommentShortcuts').css('cursor', 'pointer').on('click', function() {
$('#quickCommentShortcuts').hide();
});
$('#quickCommentShortcuts table').append('<tr><th>Name</th><th>Shortcut</th><th>Text</th><th>Delete?</th><th>Edit?</th></tr>');
$('#quickCommentShortcuts table').after('<input type="button" id="newComment" value="New Comment">');
$('#quickCommentShortcutsReminder').html('');
$.each(data, function(i) {
$('#quickCommentShortcutsReminder').append(this[0] + ' - ' + this[1] + '<br />');
var text = welcomeText + this[2];
text = replaceVars(text, sitename, siteurl, op, answererName);
$('.comments textarea').bind('keydown', this[1], function() {
$(this).append(text);
});
$('#quickCommentShortcuts table').append('<tr><td>' + this[0] + '</td><td>' + this[1] + '</td><td>' + text + '</td><td><input type="button" id="' + i + '" value="Delete"></td><td><input type="button" id="' + i + '" value="Edit"></td></tr><br />');
$('#quickCommentShortcuts').find('table, th, td').css(tableCSS);
});
$('.comments textarea').on('keydown', null, 'alt+o', function() {
$('#quickCommentShortcuts').show();
$('body').animate({
scrollTop: 0
}, 'slow');
});
$('.comments textarea').bind('keydown', 'alt+r', function() {
$('#quickCommentShortcutsReminder').show();
});
$('#quickCommentShortcuts').on('click', 'input[value="Delete"]', function() {
data.splice($(this).attr('id'), 1);
saveGM(data);
resetReminderAndTable();
$.each(data, function(i) {
$('#quickCommentShortcutsReminder').append(this[0] + ' - ' + this[1] + '<br />');
var text = welcomeText + this[2];
$('#quickCommentShortcuts table').append('<tr><td>' + this[0] + '</td><td>' + this[1] + '</td><td>' + text + '</td><td><input type="button" id="' + i + '" value="Delete"></td><td><input type="button" id="' + i + '" value="Edit"></td></tr><br />');
$('#quickCommentShortcuts').find('table, th, td').css(tableCSS);
});
});
$('#quickCommentShortcuts').on('click', '#newComment', function() {
$(this).hide();
$(this).before('<div id="newCommentStuff">Name:<input type="text" id="newCommentName"> \
<br /> Shortcut:<input type="text" id="newCommentShortcut"> \
<br /> Text:<textarea id="newCommentText"></textarea> \
<br /> <input type="button" id="newCommentSave" value="Save"></div>');
$('#quickCommentShortcuts #newCommentSave').click(function() {
var newName = $('#newCommentName').val(),
newShortcut = $('#newCommentShortcut').val(),
newText = $('#newCommentText').val();
data.push([newName, newShortcut, newText]);
saveGM(data);
resetReminderAndTable();
$.each(data, function(i) {
$('#quickCommentShortcutsReminder').append(this[0] + ' - ' + this[1] + '<br />');
var text = welcomeText + this[2];
$('#quickCommentShortcuts table').append('<tr><td>' + this[0] + '</td><td>' + this[1] + '</td><td>' + text + '</td><td><input type="button" id="' + i + '" value="Delete"></td><td><input type="button" id="' + i + '" value="Edit"></td></tr><br />');
$('#quickCommentShortcuts').find('table, th, td').css(tableCSS);
});
$('#newCommentStuff').remove();
$('#quickCommentShortcuts #newComment').show();
});
});
$('#quickCommentShortcuts').on('click', 'input[value="Edit"]', function() {
var id = $(this).attr('id');
for (var i = 0; i < 3; i++) {
$(this).parent().parent().find('td:eq(' + i + ')').replaceWith('<td><input style="width:90%;" type="text" id="' + id + '" value="' + data[id][i].replace(/"/g, '"').replace(/'/g, '’') + '"></td>');
}
$(this).after('<input type="button" value="Save" id="saveEdits">');
$(this).hide();
$('#quickCommentShortcuts #saveEdits').click(function() {
for (var i = 0; i < 3; i++) {
data[id][i] = $(this).parent().parent().find('input[type="text"]:eq(' + i + ')').val();
saveGM(data);
}
resetReminderAndTable();
$.each(data, function(i) {
$('#quickCommentShortcutsReminder').append(this[0] + ' - ' + this[1] + '<br />');
var text = welcomeText + this[2];
$('#quickCommentShortcuts table').append('<tr><td>' + this[0] + '</td><td>' + this[1] + '</td><td>' + text + '</td><td><input type="button" id="' + i + '" value="Delete"></td><td><input type="button" id="' + i + '" value="Edit"></td></tr><br />');
$('#quickCommentShortcuts').find('table, th, td').css(tableCSS);
});
$(this).remove();
$('#quickCommentShortcuts input[value="Edit"]').show();
});
});
$('.comments textarea').blur(function() {
$('#quickCommentShortcutsReminder').hide();
});
}
});
});
});
},
spoilerTip: function() {
// Description: For adding some text to spoilers to tell people to hover over it
$('.spoiler').prepend('<div id="isSpoiler" style="color:red; font-size:smaller; float:right;">hover to show spoiler<div>');
$('.spoiler').hover(function() {
$(this).find('#isSpoiler').hide(500);
}, function() {
$(this).find('#isSpoiler').show(500);
});
},
commentReplies: function() {
// Description: For adding reply links to comments
$('.comment').each(function() {
if ($('.topbar-links a span:eq(0)').text() != $(this).find('.comment-text a.comment-user').text()) { //make sure the link is not added to your own comments
$(this).append('<span id="replyLink" title="reply to this user">↵</span>');
}
});
$('span[id="replyLink"]').css('cursor', 'pointer').on('click', function() {
var parentDiv = $(this).parent().parent().parent().parent();
var textToAdd = '@' + $(this).parent().find('.comment-text a.comment-user').text().replace(/\s/g, '').replace(/♦/, '') + ' '; //eg. @USERNAME [space]
if (parentDiv.find('textarea').length) {
parentDiv.find('textarea').append(textToAdd); //add the name
} else {
parentDiv.next('div').find('a').trigger('click'); //show the textarea
parentDiv.find('textarea').append(textToAdd); //add the name
}
});
},
parseCrossSiteLinks: function() {
// Description: For converting cross-site links to their titles
var sites = ['stackexchange', 'stackoverflow', 'superuser', 'serverfault', 'askubuntu', 'stackapps', 'mathoverflow', 'programmers', 'bitcoin'];
$('.post-text a').each(function() {
var anchor = $(this);
if (sites.indexOf($(this).attr('href').split('/')[2].split('.')[0]) > -1) { //if the link is to an SE site (not, for example, to google), do the necessary stuff
if ($(this).text() == $(this).attr('href')) { //if there isn't text on it (ie. bare url)
var sitename = $(this).attr('href').split('/')[2].split('.')[0],
id = $(this).attr('href').split('/')[4];
SOHelper.getFromAPI('questions', id, sitename, function(json) {
anchor.html(json.items[0].title); //Get the title and add it in
}, 'activity');
}
}
});
},
/*answerCountSidebar: function() { //For adding the answer count as a tooltip to questions in the sidebar
$('.sidebar-linked .linked .spacer a, .sidebar-related .related .spacer a').each(function(i) {
if (!i % 2 == 0) { //odd only (ie. question title)
var id = $(this).attr('href').split('/')[2],
sitename = $(location).attr('hostname').split('.')[0],
that = $(this);
SOHelper.getFromAPI('questions', id, sitename, function(json) {
answers = json.items[0].answer_count;
that.attr('title', answers + (answers == 1 ? ' answer' : ' answers'));
}, 'activity');
}
});
},*/
linkQuestionAuthorName: function() {
// Description: For adding a button to the editor toolbar to insert a link to a post and automatically add the author's name
var div = '<div id="addLinkAuthorName" class="wmd-prompt-dialog sox-centered" style="display:none"> \
<h5>Insert hyperlink with author\'s name</h5> \
<br /> \
<input id="link" placeholder="http://example.com/ \"optional title\"" size="50"> \
<input id="addLinkOk" value="OK" type="button" style="margin: 10px; display: inline; width: 7em;"><input id="addLinkCancel" value="Cancel" type="button" style="margin: 10px; display: inline; width: 7em;"> \
</div>';
$('body').append(div);
$('#addLinkAuthorName').css('top', '50%').css('position', 'fixed').css('height', '20%');
$('#addLinkAuthorName #addLinkCancel').on('click', function() {
$(this).parent().hide();
});
$('#addLinkAuthorName #addLinkOk').on('click', function() {
var textarea = $('#post-editor #wmd-input'),
link = $('#addLinkAuthorName #link').val(),
id = link.split('/')[4],
sitename = link.split('/')[2].split('.')[0],
title = link.split('"')[1];
if (link.split('/')[3].substr(0, 1) == 'a') { //for answers
SOHelper.getFromAPI('answers', id, sitename, function(json) {
//Insert at caret thanks to http://stackoverflow.com/a/15977052/3541881
var caretPos = document.getElementById('wmd-input').selectionStart,
textAreaTxt = textarea.val(),
txtToAdd;
if (title) {
txtToAdd = '[@' + json.items[0].owner.display_name + ' says](' + link + ' "' + title + '")';
} else {
txtToAdd = '[@' + json.items[0].owner.display_name + ' says](' + link + ')';
}
textarea.val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos));
$('#addLinkAuthorName').hide();
}, 'activity');
} else { //for questions
SOHelper.getFromAPI('questions', id, sitename, function(json) {
//Insert at caret thanks to http://stackoverflow.com/a/15977052/3541881
var caretPos = document.getElementById('wmd-input').selectionStart,
textAreaTxt = textarea.val(),
txtToAdd;
if (title) {
txtToAdd = '[@' + json.items[0].owner.display_name + ' says](' + json.items[0].link + ' "' + title + '")';
} else {
txtToAdd = '[@' + json.items[0].owner.display_name + ' says](' + json.items[0].link + ')';
}
textarea.val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos));
$('#addLinkAuthorName').hide();
}, 'activity');
}
});
var liSpan = '<li class="wmd-button" title="Hyperlink (with author name)" style="left: 450px;"><span id="wmd-author-link-button" style="background-position: -40px 0px;"></span></li>';
setTimeout(function() {
$('[id^="wmd-redo-button"]').after(liSpan);
$('#wmd-author-link-button').on('click', function() {
$('#addLinkAuthorName').show();
});
}, 1000);
},
confirmNavigateAway: function() {
// Description: For adding a 'are you ure you want to go away' confirmation on pages where you have started writing something
if (window.location.href.indexOf('questions/') >= 0) {
$(window).bind('beforeunload', function() {
if ($('.comment-form textarea').length && $('.comment-form textarea').val()) {
return 'Do you really want to navigate away? Anything you have written will be lost!';
} else {
return;
}
});
}
},
sortByBountyAmount: function() {
// Description: For adding some buttons to sort bounty's by size
if (!SOHelper.isOnUserProfile()) { //not on the user profile page
if ($('.bounty-indicator').length) { //if there is at least one bounty on the page
$('.question-summary').each(function() {
var bountyAmount = $(this).find('.bounty-indicator').text().replace('+', '');
$(this).attr('data-bountyamount', bountyAmount); //add a 'bountyamount' attribute to all the questions
});
var $wrapper = $('#question-mini-list').length ? $('#question-mini-list') : $wrapper = $('#questions'); //homepage/questions tab
setTimeout(function() {
//filter buttons:
$('.subheader').after('<span>sort by bounty amount: </span><span id="largestFirst">largest first </span><span id="smallestFirst">smallest first</span>');
//Thanks: http://stackoverflow.com/a/14160529/3541881
$('#largestFirst').css('cursor', 'pointer').on('click', function() { //largest first
$wrapper.find('.question-summary').sort(function(a, b) {
return +b.getAttribute('data-bountyamount') - +a.getAttribute('data-bountyamount');
}).prependTo($wrapper);
});
//Thanks: http://stackoverflow.com/a/14160529/3541881
$('#smallestFirst').css('cursor', 'pointer').on('click', function() { //smallest first
$wrapper.find('.question-summary').sort(function(a, b) {
return +a.getAttribute('data-bountyamount') - +b.getAttribute('data-bountyamount');
}).prependTo($wrapper);
});
}, 500);
}
}
},
isQuestionHot: function() {
// Description: For adding some text to questions that are in the 30 most recent hot network questions
function addHotText() {
$('#feed').html('<p>In the top 30 most recent hot network questions!</p>');
$('#question-header').prepend('<div title="this question is in the top 30 most recent hot network questions!" class="sox-hot">HOT<div>');
}
$('#qinfo').after('<div id="feed"></div>');
setTimeout(function() {
$.ajax({
type: 'get',
url: 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20feed%20where%20url%3D"http%3A%2F%2Fstackexchange.com%2Ffeeds%2Fquestions"&format=json',
success: function(d) {
var results = d.query.results.entry;
$.each(results, function(i, result) {
if (document.URL == result.link.href) {
addHotText();
}
});
}
});
}, 500);
},
autoShowCommentImages: function() {
// Description: For auto-inlining any links to imgur images in comments
$('.comment .comment-text .comment-copy a').each(function() {
if ($(this).attr('href').indexOf('imgur.com') != -1) {
var image = $(this).attr('href');
if (image.indexOf($(this).text()) != -1) {
$(this).replaceWith('<img src="' + image + '" width="100%">');
} else {
$(this).after('<img src="' + image + '" width="100%">');
}
}
});
},
showCommentScores: function() {
// Description: For adding a button on your profile comment history pages to show your comment's scores
var sitename = SOHelper.getAPISiteName();
$('.history-table td b a[href*="#comment"]').each(function() {
var id = $(this).attr('href').split('#')[1].split('_')[0].replace('comment', '');
$(this).after('<span class="showCommentScore" id="' + id + '"> show comment score</span>');
});
$('.showCommentScore').css('cursor', 'pointer').on('click', function() {
var $that = $(this);
SOHelper.getFromAPI('comments', $that.attr('id'), sitename, function(json) {
$that.html(' ' + json.items[0].score);
});
});
},
answerTagsSearch: function() {
// Description: For adding tags to answers in search
if (window.location.href.indexOf('search?q=') > -1) { //ONLY ON SEARCH PAGES!
var sitename = SOHelper.getAPISiteName(),
ids = [],
idsAndTags = {};
$.each($('div[id*="answer"]'), function() { //loop through all *answers*
ids.push($(this).find('.result-link a').attr('href').split('/')[2]); //Get the IDs for the questions for all the *answers*
});
$.getJSON('https://api.stackexchange.com/2.2/questions/' + ids.join(';') + '?site=' + sitename, function(json) {
var itemsLength = json.items.length;
for (var i = 0; i < itemsLength; i++) {
idsAndTags[json.items[i].question_id] = json.items[i].tags;
}
console.log(idsAndTags);
$.each($('div[id*="answer"]'), function() { //loop through all *answers*
var id = $(this).find('.result-link a').attr('href').split('/')[2]; //get their ID
var $that = $(this);
for (var x = 0; x < idsAndTags[id].length; x++) { //Add the appropiate tags for the appropiate answer
$that.find('.summary .tags').append('<a href="/questions/tagged/' + idsAndTags[id][x] + '" class="post-tag">' + idsAndTags[id][x] + '</a>'); //add the tags and their link to the answers
}
$that.find('.summary .tags a').each(function() {
if ($(this).text().indexOf('status-') > -1) { //if it's a mod tag
$(this).addClass('moderator-tag'); //add appropiate class
} else if ($(this).text().match(/(discussion|feature-request|support|bug)/)) { //if it's a required tag
$(this).addClass('required-tag'); //add appropiate class
}
});
});
});
}
},
stickyVoteButtons: function() {
// Description: For making the vote buttons stick to the screen as you scroll through a post
//https://github.com/shu8/SE_OptionalFeatures/pull/14:
//https://github.com/shu8/Stack-Overflow-Optional-Features/issues/28: Thanks @SnoringFrog for fixing this!
var $votecells = $(".votecell");
$votecells.css("width", "61px");
stickcells();
$(window).scroll(function() {
stickcells();
});
function stickcells() {
$votecells.each(function() {
var $topbar = $('.topbar'),
topbarHeight = $topbar.outerHeight(),
offset = 10;
if ($topbar.css('position') == 'fixed') {
offset += topbarHeight;
}
var $voteCell = $(this),
$vote = $voteCell.find('.vote'),
vcOfset = $voteCell.offset(),
scrollTop = $(window).scrollTop();
if (vcOfset.top - scrollTop - offset <= 0) {
if (vcOfset.top + $voteCell.height() - scrollTop - offset - $vote.height() > topbarHeight) {
$vote.css({
position: 'fixed',
left: vcOfset.left + 4,
top: offset
});
} else {
$vote.removeAttr("style");
}
} else {
$vote.removeAttr("style");
}
});
}
},
titleEditDiff: function() {
// Description: For showing the new version of a title in a diff separately rather than loads of crossing outs in red and additions in green
setTimeout(function() {
var $questionHyperlink = $('.summary h2 .question-hyperlink').clone(),
$questionHyperlinkTwo = $('.summary h2 .question-hyperlink').clone(),
link = $('.summary h2 .question-hyperlink').attr('href'),
added = ($questionHyperlinkTwo.find('.diff-delete').remove().end().text()),
removed = ($questionHyperlink.find('.diff-add').remove().end().text());
if ($('.summary h2 .question-hyperlink').find('.diff-delete, .diff-add').length) {
$('.summary h2 .question-hyperlink').hide();
$('.summary h2 .question-hyperlink').after('<a href="' + link + '" class="question-hyperlink"><span class="diff-delete">' + removed + '</span><span class="diff-add">' + added + '</span></a>');
}
}, 2000);
},
metaChatBlogStackExchangeButton: function() {
// Description: For adding buttons next to sites under the StackExchange button that lead to that site's meta, chat and blog
var blogSites = ['math', 'serverfault', 'english', 'stats', 'diy', 'bicycles', 'webapps', 'mathematica', 'christianity', 'cooking', 'fitness', 'cstheory', 'scifi', 'tex', 'security', 'islam', 'superuser', 'gaming', 'programmers', 'gis', 'apple', 'photo', 'dba'],
link,
blogLink = '//' + 'blog.stackexchange.com';
$('#your-communities-section > ul > li > a').hover(function() {
if ($(this).attr('href').substr(0, 6).indexOf('meta') == -1) {
link = 'http://meta.' + $(this).attr('href').substr(2, $(this).attr('href').length - 1);
if (blogSites.indexOf($(this).attr('href').split('/')[2].split('.')[0]) != -1) {
blogLink = '//' + $(this).attr('href').split('/')[2].split('.')[0] + '.blogoverflow.com';
}
$(this).find('.rep-score').hide();
$(this).append('<div class="related-links" style="float: right;"> \
<a href="' + link + '">meta</a> \
<a href="http://chat.stackexchange.com">chat</a> \
<a href="' + blogLink + '">blog</a> \
</div>');
}
}, function() {
$(this).find('.rep-score').show();
$(this).find('.related-links').remove();
});
},
metaNewQuestionAlert: function() {
// Description: For adding a fake mod diamond that notifies you if there has been a new post posted on the current site's meta
if (SOHelper.getSiteType() != 'main' || !$('.related-site').length) return; //DO NOT RUN ON META OR CHAT OR SITES WITHOUT A META
var NEWQUESTIONS = 'metaNewQuestionAlert-lastQuestions',
DIAMONDON = 'new-meta-questions-diamondOn',
DIAMONDOFF = 'new-meta-questions-diamondOff';
var favicon = $(".current-site a[href*='meta'] .site-icon").attr('class').split('favicon-')[1];
var metaName = 'meta.' + SOHelper.getAPISiteName(),
lastQuestions = {},
apiLink = 'https://api.stackexchange.com/2.2/questions?pagesize=5&order=desc&sort=activity&site=' + metaName;
var $dialog = $('<div/>', {
id: 'new-meta-questions-dialog',
'class': 'topbar-dialog achievements-dialog dno'
});
var $header = $('<div/>', {
'class': 'header'
}).append($('<h3/>', {
text: 'new meta posts'
}));
var $content = $('<div/>', {
'class': 'modal-content'
});
var $questions = $('<ul/>', {
id: 'new-meta-questions-dialog-list',
'class': 'js-items items'
});
var $diamond = $('<a/>', {
id: 'new-meta-questions-button',
'class': 'topbar-icon yes-hover new-meta-questions-diamondOff',
click: function() {
$diamond.toggleClass('topbar-icon-on');
$dialog.toggle();
}
});
$dialog.append($header).append($content.append($questions)).prependTo('.js-topbar-dialog-corral');
$('#soxSettingsButton').after($diamond);
$(document).mouseup(function(e) {
if (!$dialog.is(e.target) &&
$dialog.has(e.target).length === 0 &&
!$(e.target).is('#new-meta-questions-button')) {
$dialog.hide();
$diamond.removeClass("topbar-icon-on");
}
});
if (GM_getValue(NEWQUESTIONS, -1) == -1) {
GM_setValue(NEWQUESTIONS, JSON.stringify(lastQuestions));
} else {
lastQuestions = JSON.parse(GM_getValue(NEWQUESTIONS));
}
$.getJSON(apiLink, function(json) {
var latestQuestion = json.items[0].title;
if (latestQuestion == lastQuestions[metaName]) {
//if you've already seen the stuff
$diamond.removeClass(DIAMONDON).addClass(DIAMONDOFF);
} else {
$diamond.removeClass(DIAMONDOFF).addClass(DIAMONDON);
for (var i = 0; i < json.items.length; i++) {
var title = json.items[i].title,
link = json.items[i].link;
//author = json.items[i].owner.display_name;
addQuestion(title, link);
}
lastQuestions[metaName] = latestQuestion;
$diamond.click(function() {
GM_setValue(NEWQUESTIONS, JSON.stringify(lastQuestions));
});
}
});
function addQuestion(title, link) {
var $li = $('<li/>');
var $link = $('<a/>', {
href: link
});
var $icon = $('<div/>', {
'class': 'site-icon favicon favicon-' + favicon
});
var $message = $('<div/>', {
'class': 'message-text'
}).append($('<h4/>', {
html: title
}));
$link.append($icon).append($message).appendTo($li);
$questions.append($li);
}
},
betterCSS: function() {
// Description: For adding the better CSS for the voting buttons and favourite button
$('head').append('<link rel="stylesheet" href="https://cdn.rawgit.com/shu8/SE-Answers_scripts/master/coolMaterialDesignCss.css" type="text/css" />');
},
standOutDupeCloseMigrated: function() {
// Description: For adding cooler signs that a questions has been closed/migrated/put on hod/is a dupe
var questions = {};
$.each($('.question-summary'), function() { //Find the questions and add their id's and statuses to an object
if ($(this).find('.summary a:eq(0)').text().trim().substr($(this).find('.summary a:eq(0)').text().trim().length - 11) == '[duplicate]') {
questions[$(this).attr('id').split('-')[2]] = 'duplicate';
$(this).find('.summary a:eq(0)').text($(this).find('.summary a:eq(0)').text().trim().substr(0, $(this).find('.summary a:eq(0)').text().trim().length - 11)); //remove [duplicate]
} else if ($(this).find('.summary a:eq(0)').text().trim().substr($(this).find('.summary a:eq(0)').text().trim().length - 8) == '[closed]') {
questions[$(this).attr('id').split('-')[2]] = 'closed';
$(this).find('.summary a:eq(0)').text($(this).find('.summary a:eq(0)').text().trim().substr(0, $(this).find('.summary a:eq(0)').text().trim().length - 8)); //remove [closed]
} else if ($(this).find('.summary a:eq(0)').text().trim().substr($(this).find('.summary a:eq(0)').text().trim().length - 10) == '[migrated]') {
questions[$(this).attr('id').split('-')[2]] = 'migrated';
$(this).find('.summary a:eq(0)').text($(this).find('.summary a:eq(0)').text().trim().substr(0, $(this).find('.summary a:eq(0)').text().trim().length - 10)); //remove [migrated]
} else if ($(this).find('.summary a:eq(0)').text().trim().substr($(this).find('.summary a:eq(0)').text().trim().length - 9) == '[on hold]') {
questions[$(this).attr('id').split('-')[2]] = 'onhold';
$(this).find('.summary a:eq(0)').text($(this).find('.summary a:eq(0)').text().trim().substr(0, $(this).find('.summary a:eq(0)').text().trim().length - 9)); //remove [on hold]
}
});
$.each($('.question-summary'), function() { //loop through questions
var $that = $(this);
$.each(questions, function(key, val) { //loop through object of questions closed/dupes/migrated
if ($that.attr('id').split('-')[2] == key) {
$that.find('.summary a:eq(0)').after(' <span class="standOutDupeCloseMigrated-' + val + '"> ' + val + ' </span>'); //add appropiate message
}
});
});
},
editReasonTooltip: function() {
// Description: For showing the latest revision's comment as a tooltip on 'edit [date] at [time]'
function getComment(url, $that) {
$.get(url, function(responseText, textStatus, XMLHttpRequest) {
$that.find('.sox-revision-comment').attr('title', $(XMLHttpRequest.responseText).find('.revision-comment:eq(0)')[0].innerHTML);
});
}
$('.question, .answer').each(function() {
if ($(this).find('.post-signature').length > 1) {
var id = $(this).attr('data-questionid') || $(this).attr('data-answerid');
$(this).find('.post-signature:eq(0)').find('.user-action-time a').wrapInner('<span class="sox-revision-comment"></span>');
var $that = $(this);
getComment('http://' + SOHelper.getSiteURL() + '/posts/' + id + '/revisions', $that);
}
});
},
addSBSBtn: function() {
// Description: For adding a button to the editor toolbar to toggle side-by-side editing
// Thanks szego (@https://github.com/szego) for completely rewriting this! https://github.com/shu8/SE-Answers_scripts/pull/2
function startSBS(toAppend) {
//variables to reduce DOM searches
var wmdinput = $('#wmd-input' + toAppend);
var wmdpreview = $('#wmd-preview' + toAppend);
var posteditor = $('#post-editor' + toAppend);
var draftsaved = $('#draft-saved' + toAppend);
var draftdiscarded = $('#draft-discarded' + toAppend);
$('#wmd-button-bar' + toAppend).toggleClass('sbs-on');
draftsaved.toggleClass('sbs-on');
draftdiscarded.toggleClass('sbs-on');
posteditor.toggleClass('sbs-on');
wmdinput.parent().toggleClass('sbs-on'); //wmdinput.parent() has class wmd-container
wmdpreview.toggleClass('sbs-on');
if (toAppend.length > 0) { //options specific to making edits on existing questions/answers
posteditor.find('.hide-preview').toggleClass('sbs-on');
//hack: float nuttiness for "Edit Summary" box
var editcommentp1 = $('#edit-comment' + toAppend).parent().parent().parent().parent().parent();
editcommentp1.toggleClass('edit-comment-p1 sbs-on');
editcommentp1.parent().toggleClass('edit-comment-p2 sbs-on');
} else if (window.location.pathname.indexOf('questions/ask') > -1) { //extra CSS for 'ask' page
wmdpreview.toggleClass('sbs-newq');
draftsaved.toggleClass('sbs-newq');
draftdiscarded.toggleClass('sbs-newq');
$('.tag-editor').parent().toggleClass('tag-editor-p sbs-on sbs-newq');
$('#question-only-section').children('.form-item').toggleClass('sbs-on sbs-newq');
//swap the order of things to prevent draft saved/discarded messages from
// moving the preview pane around
if (wmdpreview.hasClass('sbs-on')) {
draftsaved.before(wmdpreview);
} else {
draftdiscarded.after(wmdpreview);
}
}
if (wmdpreview.hasClass('sbs-on')) { //sbs was toggled on
$('#sidebar').addClass('sbs-on');
$('#content').addClass('sbs-on');
if (toAppend.length > 0) { //current sbs toggle is for an edit
$('.votecell').addClass('sbs-on');
}
//stretch the text input window to match the preview length
// - "215" came from trial and error
// - Can this be done using toggleClass?
var previewHeight = wmdpreview.height();
if (previewHeight > 215) { //default input box is 200px tall, only scale if necessary
wmdinput.height(previewHeight - 15);
}
} else { //sbs was toggled off
//check if sbs is off for all existing questions and answers
if (!$('.question').find('.wmd-preview.sbs-on').length && !$('.answer').find('.wmd-preview.sbs-on').length) {
$('.votecell').removeClass('sbs-on');
if (!($('#wmd-preview').hasClass('sbs-on'))) { //sbs is off for everything
$('#sidebar').removeClass('sbs-on');
$('#content').removeClass('sbs-on');
}
}
//return input text window to original size
// - Can this be done using toggleClass?
wmdinput.height(200);
}
}
function SBS(jNode) {
var itemid = jNode[0].id.replace(/^\D+/g, '');
var toAppend = (itemid.length > 0 ? '-' + itemid : ''); //helps select tags specific to the question/answer being
// edited (or new question/answer being written)
setTimeout(function() {
var sbsBtn = '<li class="wmd-button" title="side-by-side-editing" style="left: 500px;width: 170px;"> \
<div id="wmd-sbs-button' + toAppend + '" style="background-image: none;"> \
Toggle SBS?</div></li>';
jNode.after(sbsBtn);
//add click listener to sbsBtn
jNode.next().on('click', function() {
startSBS(toAppend);
});
//add click listeners for "Save Edits" and "cancel" buttons
// - also gets added to the "Post New Question" and "Post New Answer" button as an innocuous (I think) side effect
$('#post-editor' + toAppend).siblings('.form-submit').children().on('click', function() {
if ($(this).parent().siblings('.sbs-on').length) { //sbs was on, so turn it off
startSBS(toAppend);
}
});
}, 1000);
}
//Adding script dynamically because @requiring causes the page load to hang -- don't know how to fix! :(
var script = document.createElement('script');
script.src = 'https://cdn.rawgit.com/BrockA/2625891/raw/9c97aa67ff9c5d56be34a55ad6c18a314e5eb548/waitForKeyElements.js';
document.getElementsByTagName('head')[0].appendChild(script);
//This is a heavily modified version by szego <https://github.com/szego/SE-Answers_scripts/blob/master/side-by-side-editing.user.js>:
setTimeout(function() {
if (window.location.pathname.indexOf('questions/ask') < 0) { //not posting a new question
//get question and answer IDs for keeping track of the event listeners
var anchorList = $('#answers > a'); //answers have anchor tags before them of the form <a name="#">,
// where # is the answer ID
// TODO: test
var numAnchors = anchorList.length;
var itemIDs = [];
for (var i = 1; i <= numAnchors - 2; i++) { //the first and last anchors aren't answers
itemIDs.push(anchorList[i].name);
}
itemIDs.push($('.question').data('questionid'));
//event listeners for adding the sbs toggle buttons for editing existing questions or answers
for (i = 0; i <= numAnchors - 2; i++) {
waitForKeyElements('#wmd-redo-button-' + itemIDs[i], SBS);
}
}
//event listener for adding the sbs toggle button for posting new questions or answers
waitForKeyElements('#wmd-redo-button', SBS);
}, 2000);
},
alwaysShowImageUploadLinkBox: function() {
// Description: For always showing the 'Link from the web' box when uploading an image.
var body = document.getElementById('body'); //Code courtesy of Siguza <http://meta.stackoverflow.com/a/306901/3541881>! :)
if (body) {
new MutationObserver(function(records) {
records.forEach(function(r) {
Array.prototype.forEach.call(r.addedNodes, function(n) {
if (n.classList.contains('image-upload')) {
new MutationObserver(function(records, self) {
var link = n.querySelector('.modal-options-default.tab-page a');
if (link) {
link.click();
self.disconnect();
}
}).observe(n, {
childList: true
});
}
});
});
}).observe(body, {
childList: true
});
}
},
addAuthorNameToInboxNotifications: function() {
// Description: To add the author's name to inbox notifications
function getAuthorName($node) {
var type = $node.find('.item-header .item-type').text(),
sitename = $node.find('a').eq(0).attr('href').split('/')[2].split('.')[0],
link = $node.find('a').eq(0).attr('href'),
apiurl,
id;
switch (type) {
case 'comment':
id = link.split('/')[5].split('?')[0],
apiurl = 'https://api.stackexchange.com/2.2/comments/' + id + '?order=desc&sort=creation&site=' + sitename
break;
case 'answer':
id = link.split('/')[4].split('?')[0];
apiurl = 'https://api.stackexchange.com/2.2/answers/' + id + '?order=desc&sort=creation&site=' + sitename
break;
case 'edit suggested':
id = link.split('/')[4],
apiurl = 'https://api.stackexchange.com/2.2/suggested-edits/' + id + '?order=desc&sort=creation&site=' + sitename
break;
default:
console.log('sox does not currently support get author information for type' + type)
return;
}
$.getJSON(apiurl, function(json) {
var author = json.items[0].owner.display_name,
$author = $('<span/>', {
class: 'author',
style: 'padding-left: 5px;',
text: author
});
console.log(author);
var $header = $node.find('.item-header'),
$type = $header.find('.item-type').clone(),
$creation = $header.find('.item-creation').clone();
//fix conflict with soup fix mse207526 - https://github.com/vyznev/soup/blob/master/SOUP.user.js#L489
$header.empty().append($type).append($author).append($creation);
});
};
new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var length = mutation.addedNodes.length;
for (var i = 0; i < length; i++) {
var $addedNode = $(mutation.addedNodes[i]);
if (!$addedNode.hasClass('inbox-dialog')) {
return;
}
for (var x = 0; x < 21; x++) { //first 20 items
getAuthorName($addedNode.find('.inbox-item').eq(x));
}
}
});
}).observe(document.body, {
childList: true,
attributes: true,
subtree: true
});
},
flagOutcomeTime: function() {
// Description: For adding the flag outcome time to the flag page
//https://github.com/shu8/Stack-Overflow-Optional-Features/pull/32
$('.flag-outcome').each(function() {
$(this).append(' – ' + $(this).attr('title'));
});
},
scrollToTop: function() {
// Description: For adding a button at the bottom right part of the screen to scroll back to the top
//https://github.com/shu8/Stack-Overflow-Optional-Features/pull/34
if (SOHelper.getSiteType() !== 'chat') { // don't show scrollToTop button while in chat.
$('<div/>', {
id: 'sox-scrollToTop',
click: function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: 0
}, 800);
return false;
}
}).append($('<i/>', {
'class': 'fa fa-angle-double-up fa-3x'
})).appendTo('div.container');
if ($(window).scrollTop() < 200) {
$('#sox-scrollToTop').hide();
}
$(window).scroll(function() {
if ($(this).scrollTop() > 200) {
$('#sox-scrollToTop').fadeIn();
} else {
$('#sox-scrollToTop').fadeOut();
}
});
}
},
flagPercentages: function() {
// Description: For adding percentages to the flag summary on the flag page
//By @enki; https://github.com/shu8/Stack-Overflow-Optional-Features/pull/38, http://meta.stackoverflow.com/q/310881/3541881, http://stackapps.com/q/6773/26088
var group = {
POST: 1,
SPAM: 2,
OFFENSIVE: 3,
COMMENT: 4
};
var type = {
TOTAL: 'flags',
WAITING: 'waiting',
HELPFUL: 'helpful',
DECLINED: 'declined',
DISPUTED: 'disputed',
AGEDAWAY: 'aged away'
};
var count,
percentage;
function addPercentage(group, type, percentage) {
var $span = $('<span/>', {
text: '({0}%)'.replace('{0}', percentage),
style: 'margin-left:5px; color: #999; font-size: 12px;'
});
$('td > a[href*="group=' + group + '"]:contains("' + type + '")').after($span);
}
function calculatePercentage(count, total) {
var percent = (count / total) * 100;
return +percent.toFixed(2);
}
function getFlagCount(group, type) {
var flagCount = 0;
flagCount += Number($('td > a[href*="group=' + group + '"]:contains("' + type + '")')
.parent()
.prev()
.text()
.replace(',', ''));
return flagCount;
}
// add percentages
for (var groupKey in group) {
var item = group[groupKey],
total = getFlagCount(item, type.TOTAL);
for (var typeKey in type) {
var typeItem = type[typeKey];
if (typeKey !== 'TOTAL') {
count = getFlagCount(item, typeItem);
percentage = calculatePercentage(count, total);
//console.log(groupKey + ": " + typeKey + " Flags -- " + count);
addPercentage(item, typeItem, percentage);
}
}
}
},
linkedPostsInline: function() {
// Description: Displays linked posts inline with an arrow
function getIdFromUrl(url) {
if (url.indexOf('/a/') > -1) { //eg. http://meta.stackexchange.com/a/26764/260841
return url.split('/a/')[1].split('/')[0];
} else if (url.indexOf('/q/') > -1) { //eg. http://meta.stackexchange.com/q/26756/260841
return url.split('/q/')[1].split('/')[0];
} else if (url.indexOf('/questions/') > -1) {
if (url.indexOf('#') > -1) { //then it's probably an answer, eg. http://meta.stackexchange.com/questions/26756/how-do-i-use-a-small-font-size-in-questions-and-answers/26764#26764
return url.split('#')[1];
} else { //then it's a question
return url.split('/questions/')[1].split('/')[0];
}
}
}
$('.post-text a, .comments .comment-copy a').each(function() {
var url = $(this).attr('href');
if (url && url.indexOf(SOHelper.getSiteURL()) > -1 & url.indexOf('#comment') == -1) {
$(this).css('color', '#0033ff');
$(this).before('<a class="expander-arrow-small-hide expand-post-sox"></a>');
}
});
$(document).on('click', 'a.expand-post-sox', function() {
if ($(this).hasClass('expander-arrow-small-show')) {
$(this).removeClass('expander-arrow-small-show');
$(this).addClass('expander-arrow-small-hide');
$('.linkedPostsInline-loaded-body-sox').remove();
} else if ($(this).hasClass('expander-arrow-small-hide')) {
$(this).removeClass('expander-arrow-small-hide');
$(this).addClass('expander-arrow-small-show');
var $that = $(this);
var id = getIdFromUrl($(this).next().attr('href'));
$.get(location.protocol + '//' + SOHelper.getSiteURL() + '/posts/' + id + '/body', function(d) {
var div = '<div class="linkedPostsInline-loaded-body-sox" style="background-color: #ffffcc;">' + d + '</div>';
$that.next().after(div);
});
}
});
},
hideHotNetworkQuestions: function() {
// Description: Hides the Hot Network Questions module from the sidebar
$('#hot-network-questions').remove();
},
hideHireMe: function() {
// Description: Hides the Looking for a Job module from the sidebar
$('#hireme').remove();
},
hideCommunityBulletin: function() {
// Description: Hides the Community Bulletin module from the sidebar
$('#sidebar .community-bulletin').remove();
},
hideSearchBar: function() {
// Description: Replace the search box with a button that takes you to the search page
var $topbar = $('.topbar'),
$links = $topbar.find('.topbar-menu-links'),
$searchbar = $topbar.find('.search-container'),
$search = $('<a/>', {
href: '/search',
title: 'Search ' + SOHelper.getSiteName()
}).append($('<i/>', {
'class': 'fa fa-search'
}));
$searchbar.remove();
$links.append($search);
},
enhancedEditor: function() {
// Description: Add a bunch of features to the standard markdown editor (autocorrect, find+replace, Ace editor, and more!)
enhancedEditor.startFeature();
},
downvotedPostsEditAlert: function() {
// Description: Adds a notification to the inbox if a question you downvoted and watched is edited
function addNotification(link, title) { //add the notification
var favicon = SOHelper.getSiteIcon();
$('div.topbar .icon-inbox').click(function() { //add the actual notification
setTimeout(function() {
$('div.topbar div.topbar-dialog.inbox-dialog.dno ul').prepend("<li class='inbox-item unread-item question-close-notification'> \
<a href='" + link + "'> \
<div class='site-icon favicon favicon-" + favicon + "' title=''></div> \
<div class='item-content'> \
<div class='item-header'> \
<span class='item-type'>post edit</span> \
<span class='item-creation'><span style='color:blue;border: 1px solid gray;' onclick='javascript:void(0)' id='markAsRead_" + sitename + '-' + id + "'>mark as read</span></span> \
</div> \
<div class='item-location'>" + title + "</div> \
<div class='item-summary'>A post you downvoted has been edited since. Go check it out, and see if you should retract your downvote!</div> \
</div> \
</a> \
</li>");
}, 500);
});
}
function addNumber() { //count the number of elements in the 'unread' object, and display that number on the inbox icon
var count = 0;
for (i in unread) {
if (unread.hasOwnProperty(i)) {
count++;
}
}
if (count != 0 && $('div.topbar .icon-inbox span.unread-count').text() == '') { //display the number
$('div.topbar .icon-inbox span.unread-count').css('display', 'inline-block').text(count);
}
}
var posts = JSON.parse(GM_getValue("downvotedPostsEditAlert", "[]"));
var unread = JSON.parse(GM_getValue("downvotedPostsEditAlert-unreadItems", "{}"));
var lastCheckedDate = GM_getValue("downvotedPostsEditAlert-lastCheckedDate", 0);
var key = ")2kXF9IR5OHnfGRPDahCVg((";
var access_token = SOHelper.getAccessToken('downvotedPostsEditAlert');
$('td.votecell > div.vote').find(':last-child').not('b').after("<i class='downvotedPostsEditAlert-watchPostForEdits fa fa-eye'></i>");
$('.downvotedPostsEditAlert-watchPostForEdits').click(function() {
var $that = $(this);
var $parent = $(this).closest('table').parent();
var id;
if ($parent.attr('data-questionid')) {
id = $parent.attr('data-questionid');
} else if ($parent.attr('data-answerid')) {
id = $parent.attr('data-answerid');
}
var stringToAdd = SOHelper.getAPISiteName() + '-' + id;
var index = posts.indexOf(stringToAdd);
if (index == -1) {
$that.css('color', 'green');
posts.push(stringToAdd);
GM_setValue('downvotedPostsEditAlert', JSON.stringify(posts));
} else {
$that.removeAttr('style');
posts.splice(index, 1);
GM_setValue('downvotedPostsEditAlert', JSON.stringify(posts));
}
});
for (var i = 0; i < posts.length; i++) {
var sitename = posts[i].split('-')[0];
var id = posts[i].split('-')[1];
var url = "https://api.stackexchange.com/2.2/posts/" + id + "?order=desc&sort=activity&site=" + sitename + "&filter=!9YdnSEBb8&key=" + key + "&access_token=" + access_token;
if (new Date().getDate() != new Date(lastCheckedDate).getDate()) {
$.getJSON(url, function(json) {
if (json.items[0].last_edit_date > ((lastCheckedDate / 1000) - 86400)) {
unread[sitename + '-' + json.items[0].post_id] = [json.items[0].link, json.items[0].title];
GM_setValue('downvotedPostsEditAlert-unreadItems', JSON.stringify(unread));
}
lastCheckedDate = new Date().getTime();
GM_setValue('downvotedPostsEditAlert-lastCheckedDate', lastCheckedDate);
});
}
$.each(unread, function(siteAndId, details) {
addNotification(details[0], details[1]);
});
addNumber();
}
$(document).on('click', 'span[id^=markAsRead]', function(e) { //click handler for the 'mark as read' button
e.preventDefault(); //don't go to questionn
var siteAndId = $(this).attr('id').split('_')[1];
delete unread[siteAndId]; //delete the question from the object
GM_setValue('downvotedPostsEditAlert-unreadItems', JSON.stringify(unread)); //save the object again
$(this).parent().parent().parent().parent().parent().hide(); //hide the notification in the inbox dropdown
});
$(document).mouseup(function(e) { //hide on click off
var container = $('div.topbar-dialog.inbox-dialog.dno > div.modal-content');
if (!container.is(e.target) && container.has(e.target).length === 0) {
container.find('.question-close-notification').remove();
}
});
},
chatEasyAccess: function() {
// Description: Adds options to give a user read/write/no access in chat from their user popup dialog
new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var newNodes = mutation.addedNodes;
if (newNodes !== null) {
var $nodes = $(newNodes);
$nodes.each(function() {
var $node = $(this);
if ($node.hasClass("user-popup")) {
setTimeout(function() {
var id = $node.find('a')[0].href.split('/')[4];
if ($('.chatEasyAccess').length) {
$('.chatEasyAccess').remove();
}
$node.find('div:last-child').after('<div class="chatEasyAccess">give <b id="read-only">read</b> / <b id="read-write">write</b> / <b id="remove">no</b> access</div>');
$(document).on('click', '.chatEasyAccess b', function() {
$that = $(this);
$.ajax({
url: 'http://chat.stackexchange.com/rooms/setuseraccess/' + location.href.split('/')[4],
type: 'post',
data: {
'fkey': fkey().fkey,
'userAccess': $that.attr('id'),
'aclUserId': id
},
success: function(d) {
if (d == '') {
alert('Successfully changed user access');
} else {
alert(d);
}
}
});
});
}, 1000);
}
});
}
});
}).observe(document.getElementById('chat-body'), {
childList: true,
attributes: true
});
},
topAnswers: function() {
// Description: Adds a box above answers to show the most highly-scoring answers
var count = 0;
var $topAnswers = $('<div/>', {
id: 'sox-top-answers',
style: 'padding-bottom: 10px; border-bottom: 1px solid #eaebec;'
}),
$table = $('<table/>', {
style: 'margin:0 auto;'
}),
$row = $('<tr/>');
$table.append($row).appendTo($topAnswers);
function score(e) {
return new Number($(e).parent().find('.vote-count-post').text());
}
function compareByScore(a, b) {
return score(b) - score(a);
}
$(':not(.deleted-answer) .answercell').slice(1).sort(compareByScore).slice(0, 5).each(function() {
count++;
var id = $(this).find('.short-link').attr('id').replace('link-post-', ''),
score = $(this).prev().find('.vote-count-post').text(),
icon = 'vote-up-off';
if (score > 0) {
icon = 'vote-up-on';
}
if (score < 0) {
icon = 'vote-down-on';
}
var $column = $('<td/>', {
style: 'width: 100px; text-align: center;'
}),
$link = $('<a/>', {
href: '#' + id
}),
$icon = $('<i/>', {
class: icon,
style: 'margin-bottom: 0; padding-right: 5px;'
});
$link.append($icon).append('Score: ' + score);
$column.append($link).appendTo($row);
});
if (count > 0) {
$('#answers div.answer:first').before($topAnswers);
$table.css('width', count * 100 + 'px');
}
},
tabularReviewerStats: function() {
// Description: Adds a notification to the inbox if a question you downvoted and watched is edited
// Idea by lolreppeatlol @ http://meta.stackexchange.com/a/277446/260841 :)
if(location.href.indexOf('/review/suggested-edits') > -1) {
var info = {};
$('.review-more-instructions ul:eq(0) li').each(function() {
var text = $(this).text(),
username = $(this).find('a').text(),
link = $(this).find('a').attr('href'),
approved = text.match(/approved (.*?)[a-zA-Z]/)[1],
rejected = text.match(/rejected (.*?)[a-zA-Z]/)[1],
improved = text.match(/improved (.*?)[a-zA-Z]/)[1];
info[username] = {
'link': link,
'approved': approved,
'rejected': rejected,
'improved': improved
};
});
var $editor = $('.review-more-instructions ul:eq(1) li'),
editorName = $editor.find('a').text(),
editorLink = $editor.find('a').attr('href'),
editorApproved = $editor.text().match(/([0-9])/g)[0],
editorRejected = $editor.text().match(/([0-9])/g)[1];
info[editorName] = {
'editorLink': link,
'approved': editorApproved,
'rejected': editorRejected
};
var table = "<table><tbody><tr><th style='padding: 4px;'>User</th><th style='padding: 4px;'>Approved</th><th style='padding: 4px;'>Rejected</th><th style='padding: 4px;'>Improved</th style='padding: 4px;'></tr>";
$.each(info, function(user, details) {
table += "<tr><td style='padding: 4px;'><a href='" + details.link + "'>" + user + "</a></td><td style='padding: 4px;'>" + details.approved + "</td><td style='padding: 4px;'>" + details.rejected + "</td><td style='padding: 4px;'>" + (details.improved ? details.improved : 'N/A') + "</td></tr>";
});
table += "</tbody></table>";
$('.review-more-instructions p, .review-more-instructions ul').remove();
$('.review-more-instructions').append(table);
}
},
linkedToFrom: function() {
// Description: Add an arrow to linked posts in the sidebar to show whether they are linked to or linked from
$('.linked .spacer a.question-hyperlink').each(function() {
var id = $(this).attr('href').split('/')[4].split('?')[0];
if($('a[href*="' + id + '"]').not('.spacer a').length) {
$(this).append('<span title="Current question links to this question" style="color:black;font-size:15px;margin-left:5px;">↗</span>');
} else {
$(this).append('<span title="Current question is linked from this question" style="color:black;font-size:15px;margin-left:5px;">↙</span>');
}
});
}
};
| big fix in linkedToFrom | sox.features.js | big fix in linkedToFrom | <ide><path>ox.features.js
<ide> linkedToFrom: function() {
<ide> // Description: Add an arrow to linked posts in the sidebar to show whether they are linked to or linked from
<ide>
<del> $('.linked .spacer a.question-hyperlink').each(function() {
<del> var id = $(this).attr('href').split('/')[4].split('?')[0];
<del> if($('a[href*="' + id + '"]').not('.spacer a').length) {
<del> $(this).append('<span title="Current question links to this question" style="color:black;font-size:15px;margin-left:5px;">↗</span>');
<del> } else {
<del> $(this).append('<span title="Current question is linked from this question" style="color:black;font-size:15px;margin-left:5px;">↙</span>');
<del> }
<del> });
<add> if(location.href.indexOf('/questions/') > -1) {
<add> $('.linked .spacer a.question-hyperlink').each(function() {
<add> var id = $(this).attr('href').split('/')[4].split('?')[0];
<add> if($('a[href*="' + id + '"]').not('.spacer a').length) {
<add> $(this).append('<span title="Current question links to this question" style="color:black;font-size:15px;margin-left:5px;">↗</span>');
<add> } else {
<add> $(this).append('<span title="Current question is linked from this question" style="color:black;font-size:15px;margin-left:5px;">↙</span>');
<add> }
<add> });
<add> }
<ide> }
<ide> }; |
|
Java | apache-2.0 | 50b4e759b45a1a07b131967578f9ef8112bea57b | 0 | agilemobiledev/workflow,NirmataOSS/workflow | package com.nirmata.workflow.details;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import com.google.common.collect.Queues;
import com.google.common.collect.Sets;
import com.nirmata.workflow.details.internalmodels.RunnableTask;
import com.nirmata.workflow.details.internalmodels.StartedTask;
import com.nirmata.workflow.models.ExecutableTask;
import com.nirmata.workflow.models.RunId;
import com.nirmata.workflow.models.TaskExecutionResult;
import com.nirmata.workflow.models.TaskId;
import com.nirmata.workflow.models.TaskType;
import com.nirmata.workflow.queue.Queue;
import com.nirmata.workflow.queue.QueueFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.utils.CloseableUtils;
import org.apache.zookeeper.KeeperException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Clock;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
class Scheduler
{
private final Logger log = LoggerFactory.getLogger(getClass());
private final WorkflowManagerImpl workflowManager;
private final QueueFactory queueFactory;
private final PathChildrenCache completedTasksCache;
private final PathChildrenCache startedTasksCache;
private final PathChildrenCache runsCache;
private final LoadingCache<TaskType, Queue> queues = CacheBuilder.newBuilder()
.expireAfterAccess(1, TimeUnit.MINUTES)
.removalListener(new RemovalListener<TaskType, Queue>()
{
@Override
public void onRemoval(RemovalNotification<TaskType, Queue> notification)
{
CloseableUtils.closeQuietly(notification.getValue());
}
})
.build(new CacheLoader<TaskType, Queue>()
{
@Override
public Queue load(TaskType taskType) throws Exception
{
Queue queue = queueFactory.createQueue(workflowManager, taskType);
queue.start();
return queue;
}
});
Scheduler(WorkflowManagerImpl workflowManager, QueueFactory queueFactory, List<TaskExecutorSpec> specs)
{
this.workflowManager = workflowManager;
this.queueFactory = queueFactory;
completedTasksCache = new PathChildrenCache(workflowManager.getCurator(), ZooKeeperConstants.getCompletedTaskParentPath(), true);
startedTasksCache = new PathChildrenCache(workflowManager.getCurator(), ZooKeeperConstants.getStartedTasksParentPath(), false);
runsCache = new PathChildrenCache(workflowManager.getCurator(), ZooKeeperConstants.getRunParentPath(), true);
}
void run()
{
BlockingQueue<RunId> updatedRunIds = Queues.newLinkedBlockingQueue();
completedTasksCache.getListenable().addListener((client, event) -> {
if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED )
{
RunId runId = new RunId(ZooKeeperConstants.getRunIdFromCompletedTasksPath(event.getData().getPath()));
updatedRunIds.add(runId);
}
});
runsCache.getListenable().addListener((client, event) -> {
if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED )
{
RunId runId = new RunId(ZooKeeperConstants.getRunIdFromRunPath(event.getData().getPath()));
updatedRunIds.add(runId);
}
else if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED )
{
RunnableTask runnableTask = JsonSerializer.getRunnableTask(JsonSerializer.fromBytes(event.getData().getData()));
if ( runnableTask.getParentRunId().isPresent() )
{
updatedRunIds.add(runnableTask.getParentRunId().get());
}
}
});
try
{
completedTasksCache.start(PathChildrenCache.StartMode.NORMAL);
startedTasksCache.start(PathChildrenCache.StartMode.NORMAL);
runsCache.start(PathChildrenCache.StartMode.NORMAL);
while ( !Thread.currentThread().isInterrupted() )
{
RunId runId = updatedRunIds.take();
updateTasks(runId);
}
}
catch ( InterruptedException dummy )
{
Thread.currentThread().interrupt();
}
catch ( Throwable e )
{
log.error("Error while running scheduler", e);
}
finally
{
queues.invalidateAll();
queues.cleanUp();
CloseableUtils.closeQuietly(completedTasksCache);
CloseableUtils.closeQuietly(startedTasksCache);
CloseableUtils.closeQuietly(runsCache);
}
}
private boolean hasCanceledTasks(RunId runId, RunnableTask runnableTask)
{
return runnableTask.getTasks().keySet().stream().anyMatch(taskId -> {
String completedTaskPath = ZooKeeperConstants.getCompletedTaskPath(runId, taskId);
ChildData currentData = completedTasksCache.getCurrentData(completedTaskPath);
if ( currentData != null )
{
TaskExecutionResult taskExecutionResult = JsonSerializer.getTaskExecutionResult(JsonSerializer.fromBytes(currentData.getData()));
return taskExecutionResult.getStatus().isCancelingStatus();
}
return false;
});
}
static void completeRunnableTask(Logger log, WorkflowManagerImpl workflowManager, RunId runId, RunnableTask runnableTask, int version)
{
try
{
RunId parentRunId = runnableTask.getParentRunId().orElse(null);
RunnableTask completedRunnableTask = new RunnableTask(runnableTask.getTasks(), runnableTask.getTaskDags(), runnableTask.getStartTimeUtc(), LocalDateTime.now(Clock.systemUTC()), parentRunId);
String runPath = ZooKeeperConstants.getRunPath(runId);
byte[] json = JsonSerializer.toBytes(JsonSerializer.newRunnableTask(completedRunnableTask));
workflowManager.getCurator().setData().withVersion(version).forPath(runPath, json);
}
catch ( Exception e )
{
String message = "Could not write completed task data for run: " + runId;
log.error(message, e);
throw new RuntimeException(message, e);
}
}
private void updateTasks(RunId runId)
{
RunnableTask runnableTask = getRunnableTask(runId);
if ( runnableTask == null )
{
String message = "Could not find run for RunId: " + runId;
log.error(message);
throw new RuntimeException(message);
}
if ( runnableTask.getCompletionTimeUtc().isPresent() )
{
return;
}
if ( hasCanceledTasks(runId, runnableTask) )
{
completeRunnableTask(log, workflowManager, runId, runnableTask, -1);
return; // one or more tasks has canceled the entire run
}
Set<TaskId> completedTasks = Sets.newHashSet();
runnableTask.getTaskDags().forEach(entry -> {
TaskId taskId = entry.getTaskId();
ExecutableTask task = runnableTask.getTasks().get(taskId);
if ( task == null )
{
log.error(String.format("Could not find task: %s for run: %s", taskId, runId));
return;
}
boolean taskIsComplete = taskIsComplete(completedTasksCache, runId, task);
if ( taskIsComplete )
{
completedTasks.add(taskId);
}
else if ( !taskIsStarted(startedTasksCache, runId, taskId) )
{
boolean allDependenciesAreComplete = entry
.getDependencies()
.stream()
.allMatch(id -> taskIsComplete(completedTasksCache, runId, runnableTask.getTasks().get(id)));
if ( allDependenciesAreComplete )
{
queueTask(runId, task);
}
}
});
if ( completedTasks.equals(runnableTask.getTasks().keySet()))
{
completeRunnableTask(log, workflowManager, runId, runnableTask, -1);
}
}
private RunnableTask getRunnableTask(RunId runId)
{
ChildData currentData = runsCache.getCurrentData(ZooKeeperConstants.getRunPath(runId));
if ( currentData != null )
{
return JsonSerializer.getRunnableTask(JsonSerializer.fromBytes(currentData.getData()));
}
return null;
}
private void queueTask(RunId runId, ExecutableTask task)
{
String path = ZooKeeperConstants.getStartedTaskPath(runId, task.getTaskId());
try
{
StartedTask startedTask = new StartedTask(workflowManager.getInstanceName(), LocalDateTime.now(Clock.systemUTC()));
byte[] data = JsonSerializer.toBytes(JsonSerializer.newStartedTask(startedTask));
workflowManager.getCurator().create().creatingParentsIfNeeded().forPath(path, data);
Queue queue = queues.get(task.getTaskType());
queue.put(task);
log.info("Queued task: " + task);
}
catch ( KeeperException.NodeExistsException ignore )
{
log.debug("Task already queued: " + task);
// race due to caching latency - task already started
}
catch ( Exception e )
{
String message = "Could not start task " + task;
log.error(message, e);
throw new RuntimeException(e);
}
}
private boolean taskIsStarted(PathChildrenCache startedTasksCache, RunId runId, TaskId taskId)
{
String startedTaskPath = ZooKeeperConstants.getStartedTaskPath(runId, taskId);
return (startedTasksCache.getCurrentData(startedTaskPath) != null);
}
private boolean taskIsComplete(PathChildrenCache completedTasksCache, RunId runId, ExecutableTask task)
{
if ( (task == null) || !task.isExecutable() )
{
return true;
}
String completedTaskPath = ZooKeeperConstants.getCompletedTaskPath(runId, task.getTaskId());
ChildData currentData = completedTasksCache.getCurrentData(completedTaskPath);
if ( currentData != null )
{
TaskExecutionResult result = JsonSerializer.getTaskExecutionResult(JsonSerializer.fromBytes(currentData.getData()));
if ( result.getSubTaskRunId().isPresent() )
{
RunnableTask runnableTask = getRunnableTask(result.getSubTaskRunId().get());
return (runnableTask != null) && runnableTask.getCompletionTimeUtc().isPresent();
}
return true;
}
return false;
}
}
| src/main/java/com/nirmata/workflow/details/Scheduler.java | package com.nirmata.workflow.details;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Queues;
import com.google.common.collect.Sets;
import com.nirmata.workflow.details.internalmodels.RunnableTask;
import com.nirmata.workflow.details.internalmodels.StartedTask;
import com.nirmata.workflow.models.ExecutableTask;
import com.nirmata.workflow.models.RunId;
import com.nirmata.workflow.models.TaskExecutionResult;
import com.nirmata.workflow.models.TaskId;
import com.nirmata.workflow.models.TaskType;
import com.nirmata.workflow.queue.Queue;
import com.nirmata.workflow.queue.QueueFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.utils.CloseableUtils;
import org.apache.zookeeper.KeeperException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Clock;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
class Scheduler
{
private final Logger log = LoggerFactory.getLogger(getClass());
private final WorkflowManagerImpl workflowManager;
private final QueueFactory queueFactory;
private final Map<TaskType, Queue> queues;
private final PathChildrenCache completedTasksCache;
private final PathChildrenCache startedTasksCache;
private final PathChildrenCache runsCache;
Scheduler(WorkflowManagerImpl workflowManager, QueueFactory queueFactory, List<TaskExecutorSpec> specs)
{
this.workflowManager = workflowManager;
this.queueFactory = queueFactory;
queues = makeTaskQueues(specs);
completedTasksCache = new PathChildrenCache(workflowManager.getCurator(), ZooKeeperConstants.getCompletedTaskParentPath(), true);
startedTasksCache = new PathChildrenCache(workflowManager.getCurator(), ZooKeeperConstants.getStartedTasksParentPath(), false);
runsCache = new PathChildrenCache(workflowManager.getCurator(), ZooKeeperConstants.getRunParentPath(), true);
}
void run()
{
BlockingQueue<RunId> updatedRunIds = Queues.newLinkedBlockingQueue();
completedTasksCache.getListenable().addListener((client, event) -> {
if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED )
{
RunId runId = new RunId(ZooKeeperConstants.getRunIdFromCompletedTasksPath(event.getData().getPath()));
updatedRunIds.add(runId);
}
});
runsCache.getListenable().addListener((client, event) -> {
if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED )
{
RunId runId = new RunId(ZooKeeperConstants.getRunIdFromRunPath(event.getData().getPath()));
updatedRunIds.add(runId);
}
else if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED )
{
RunnableTask runnableTask = JsonSerializer.getRunnableTask(JsonSerializer.fromBytes(event.getData().getData()));
if ( runnableTask.getParentRunId().isPresent() )
{
updatedRunIds.add(runnableTask.getParentRunId().get());
}
}
});
try
{
queues.values().forEach(Queue::start);
completedTasksCache.start(PathChildrenCache.StartMode.NORMAL);
startedTasksCache.start(PathChildrenCache.StartMode.NORMAL);
runsCache.start(PathChildrenCache.StartMode.NORMAL);
while ( !Thread.currentThread().isInterrupted() )
{
RunId runId = updatedRunIds.take();
updateTasks(runId);
}
}
catch ( InterruptedException dummy )
{
Thread.currentThread().interrupt();
}
catch ( Throwable e )
{
log.error("Error while running scheduler", e);
}
finally
{
queues.values().forEach(CloseableUtils::closeQuietly);
CloseableUtils.closeQuietly(completedTasksCache);
CloseableUtils.closeQuietly(startedTasksCache);
CloseableUtils.closeQuietly(runsCache);
}
}
private boolean hasCanceledTasks(RunId runId, RunnableTask runnableTask)
{
return runnableTask.getTasks().keySet().stream().anyMatch(taskId -> {
String completedTaskPath = ZooKeeperConstants.getCompletedTaskPath(runId, taskId);
ChildData currentData = completedTasksCache.getCurrentData(completedTaskPath);
if ( currentData != null )
{
TaskExecutionResult taskExecutionResult = JsonSerializer.getTaskExecutionResult(JsonSerializer.fromBytes(currentData.getData()));
return taskExecutionResult.getStatus().isCancelingStatus();
}
return false;
});
}
static void completeRunnableTask(Logger log, WorkflowManagerImpl workflowManager, RunId runId, RunnableTask runnableTask, int version)
{
try
{
RunId parentRunId = runnableTask.getParentRunId().orElse(null);
RunnableTask completedRunnableTask = new RunnableTask(runnableTask.getTasks(), runnableTask.getTaskDags(), runnableTask.getStartTimeUtc(), LocalDateTime.now(Clock.systemUTC()), parentRunId);
String runPath = ZooKeeperConstants.getRunPath(runId);
byte[] json = JsonSerializer.toBytes(JsonSerializer.newRunnableTask(completedRunnableTask));
workflowManager.getCurator().setData().withVersion(version).forPath(runPath, json);
}
catch ( Exception e )
{
String message = "Could not write completed task data for run: " + runId;
log.error(message, e);
throw new RuntimeException(message, e);
}
}
private void updateTasks(RunId runId)
{
RunnableTask runnableTask = getRunnableTask(runId);
if ( runnableTask == null )
{
String message = "Could not find run for RunId: " + runId;
log.error(message);
throw new RuntimeException(message);
}
if ( runnableTask.getCompletionTimeUtc().isPresent() )
{
return;
}
if ( hasCanceledTasks(runId, runnableTask) )
{
completeRunnableTask(log, workflowManager, runId, runnableTask, -1);
return; // one or more tasks has canceled the entire run
}
Set<TaskId> completedTasks = Sets.newHashSet();
runnableTask.getTaskDags().forEach(entry -> {
TaskId taskId = entry.getTaskId();
ExecutableTask task = runnableTask.getTasks().get(taskId);
if ( task == null )
{
log.error(String.format("Could not find task: %s for run: %s", taskId, runId));
return;
}
boolean taskIsComplete = taskIsComplete(completedTasksCache, runId, task);
if ( taskIsComplete )
{
completedTasks.add(taskId);
}
else if ( !taskIsStarted(startedTasksCache, runId, taskId) )
{
boolean allDependenciesAreComplete = entry
.getDependencies()
.stream()
.allMatch(id -> taskIsComplete(completedTasksCache, runId, runnableTask.getTasks().get(id)));
if ( allDependenciesAreComplete )
{
queueTask(runId, task);
}
}
});
if ( completedTasks.equals(runnableTask.getTasks().keySet()))
{
completeRunnableTask(log, workflowManager, runId, runnableTask, -1);
}
}
private RunnableTask getRunnableTask(RunId runId)
{
ChildData currentData = runsCache.getCurrentData(ZooKeeperConstants.getRunPath(runId));
if ( currentData != null )
{
return JsonSerializer.getRunnableTask(JsonSerializer.fromBytes(currentData.getData()));
}
return null;
}
private void queueTask(RunId runId, ExecutableTask task)
{
String path = ZooKeeperConstants.getStartedTaskPath(runId, task.getTaskId());
try
{
StartedTask startedTask = new StartedTask(workflowManager.getInstanceName(), LocalDateTime.now(Clock.systemUTC()));
byte[] data = JsonSerializer.toBytes(JsonSerializer.newStartedTask(startedTask));
workflowManager.getCurator().create().creatingParentsIfNeeded().forPath(path, data);
Queue queue = queues.get(task.getTaskType());
if ( queue == null )
{
throw new Exception("Could not find a queue for the type: " + task.getTaskType());
}
queue.put(task);
log.info("Queued task: " + task);
}
catch ( KeeperException.NodeExistsException ignore )
{
log.debug("Task already queued: " + task);
// race due to caching latency - task already started
}
catch ( Exception e )
{
String message = "Could not start task " + task;
log.error(message, e);
throw new RuntimeException(e);
}
}
private boolean taskIsStarted(PathChildrenCache startedTasksCache, RunId runId, TaskId taskId)
{
String startedTaskPath = ZooKeeperConstants.getStartedTaskPath(runId, taskId);
return (startedTasksCache.getCurrentData(startedTaskPath) != null);
}
private boolean taskIsComplete(PathChildrenCache completedTasksCache, RunId runId, ExecutableTask task)
{
if ( (task == null) || !task.isExecutable() )
{
return true;
}
String completedTaskPath = ZooKeeperConstants.getCompletedTaskPath(runId, task.getTaskId());
ChildData currentData = completedTasksCache.getCurrentData(completedTaskPath);
if ( currentData != null )
{
TaskExecutionResult result = JsonSerializer.getTaskExecutionResult(JsonSerializer.fromBytes(currentData.getData()));
if ( result.getSubTaskRunId().isPresent() )
{
RunnableTask runnableTask = getRunnableTask(result.getSubTaskRunId().get());
return (runnableTask != null) && runnableTask.getCompletionTimeUtc().isPresent();
}
return true;
}
return false;
}
private Map<TaskType, Queue> makeTaskQueues(List<TaskExecutorSpec> specs)
{
ImmutableMap.Builder<TaskType, Queue> builder = ImmutableMap.builder();
specs.forEach(spec -> {
Queue queue = queueFactory.createQueue(workflowManager, spec.getTaskType());
builder.put(spec.getTaskType(), queue);
});
return builder.build();
}
}
| Cannot pre-create producer queues as we can't know which types will be used in this instance. So, create them lazily on demand
| src/main/java/com/nirmata/workflow/details/Scheduler.java | Cannot pre-create producer queues as we can't know which types will be used in this instance. So, create them lazily on demand | <ide><path>rc/main/java/com/nirmata/workflow/details/Scheduler.java
<ide> package com.nirmata.workflow.details;
<ide>
<del>import com.google.common.collect.ImmutableMap;
<add>import com.google.common.cache.CacheBuilder;
<add>import com.google.common.cache.CacheLoader;
<add>import com.google.common.cache.LoadingCache;
<add>import com.google.common.cache.RemovalListener;
<add>import com.google.common.cache.RemovalNotification;
<ide> import com.google.common.collect.Queues;
<ide> import com.google.common.collect.Sets;
<ide> import com.nirmata.workflow.details.internalmodels.RunnableTask;
<ide> import java.time.Clock;
<ide> import java.time.LocalDateTime;
<ide> import java.util.List;
<del>import java.util.Map;
<ide> import java.util.Set;
<ide> import java.util.concurrent.BlockingQueue;
<add>import java.util.concurrent.TimeUnit;
<ide>
<ide> class Scheduler
<ide> {
<ide> private final Logger log = LoggerFactory.getLogger(getClass());
<ide> private final WorkflowManagerImpl workflowManager;
<ide> private final QueueFactory queueFactory;
<del> private final Map<TaskType, Queue> queues;
<ide> private final PathChildrenCache completedTasksCache;
<ide> private final PathChildrenCache startedTasksCache;
<ide> private final PathChildrenCache runsCache;
<add> private final LoadingCache<TaskType, Queue> queues = CacheBuilder.newBuilder()
<add> .expireAfterAccess(1, TimeUnit.MINUTES)
<add> .removalListener(new RemovalListener<TaskType, Queue>()
<add> {
<add> @Override
<add> public void onRemoval(RemovalNotification<TaskType, Queue> notification)
<add> {
<add> CloseableUtils.closeQuietly(notification.getValue());
<add> }
<add> })
<add> .build(new CacheLoader<TaskType, Queue>()
<add> {
<add> @Override
<add> public Queue load(TaskType taskType) throws Exception
<add> {
<add> Queue queue = queueFactory.createQueue(workflowManager, taskType);
<add> queue.start();
<add> return queue;
<add> }
<add> });
<ide>
<ide> Scheduler(WorkflowManagerImpl workflowManager, QueueFactory queueFactory, List<TaskExecutorSpec> specs)
<ide> {
<ide> this.workflowManager = workflowManager;
<ide> this.queueFactory = queueFactory;
<del> queues = makeTaskQueues(specs);
<ide>
<ide> completedTasksCache = new PathChildrenCache(workflowManager.getCurator(), ZooKeeperConstants.getCompletedTaskParentPath(), true);
<ide> startedTasksCache = new PathChildrenCache(workflowManager.getCurator(), ZooKeeperConstants.getStartedTasksParentPath(), false);
<ide>
<ide> try
<ide> {
<del> queues.values().forEach(Queue::start);
<ide> completedTasksCache.start(PathChildrenCache.StartMode.NORMAL);
<ide> startedTasksCache.start(PathChildrenCache.StartMode.NORMAL);
<ide> runsCache.start(PathChildrenCache.StartMode.NORMAL);
<ide> }
<ide> finally
<ide> {
<del> queues.values().forEach(CloseableUtils::closeQuietly);
<add> queues.invalidateAll();
<add> queues.cleanUp();
<ide> CloseableUtils.closeQuietly(completedTasksCache);
<ide> CloseableUtils.closeQuietly(startedTasksCache);
<ide> CloseableUtils.closeQuietly(runsCache);
<ide> byte[] data = JsonSerializer.toBytes(JsonSerializer.newStartedTask(startedTask));
<ide> workflowManager.getCurator().create().creatingParentsIfNeeded().forPath(path, data);
<ide> Queue queue = queues.get(task.getTaskType());
<del> if ( queue == null )
<del> {
<del> throw new Exception("Could not find a queue for the type: " + task.getTaskType());
<del> }
<ide> queue.put(task);
<ide> log.info("Queued task: " + task);
<ide> }
<ide> }
<ide> return false;
<ide> }
<del>
<del> private Map<TaskType, Queue> makeTaskQueues(List<TaskExecutorSpec> specs)
<del> {
<del> ImmutableMap.Builder<TaskType, Queue> builder = ImmutableMap.builder();
<del> specs.forEach(spec -> {
<del> Queue queue = queueFactory.createQueue(workflowManager, spec.getTaskType());
<del> builder.put(spec.getTaskType(), queue);
<del> });
<del> return builder.build();
<del> }
<ide> } |
|
Java | apache-2.0 | 135581102100dcb1ae7eb48c82ac21f9159b3be4 | 0 | ChristianWulf/teetime,teetime-framework/teetime,teetime-framework/teetime,ChristianWulf/teetime | package teetime.framework;
import org.apache.commons.math3.util.Pair;
import teetime.framework.pipe.IPipe;
import teetime.framework.signal.ISignal;
import teetime.util.divideAndConquer.Identifiable;
class DivideAndConquerRecursivePipe<P extends Identifiable, S extends Identifiable> implements IPipe<P> {
protected final AbstractDCStage<P, S> cachedTargetStage;
private final OutputPort<? extends P> sourcePort;
private final InputPort<S> targetPort;
@SuppressWarnings("PMD.AvoidFieldNameMatchingMethodName")
private final int capacity;
private boolean closed;
private S element;
@SuppressWarnings("unchecked")
protected DivideAndConquerRecursivePipe(final OutputPort<? extends P> sourcePort, final InputPort<S> targetPort) {
if (sourcePort == null) {
throw new IllegalArgumentException("sourcePort may not be null");
}
if (targetPort == null) {
throw new IllegalArgumentException("targetPort may not be null");
}
sourcePort.setPipe(this);
targetPort.setPipe(this);
this.sourcePort = sourcePort;
this.targetPort = targetPort;
this.capacity = 1;
this.cachedTargetStage = (AbstractDCStage<P, S>) targetPort.getOwningStage();
}
@Override
public final OutputPort<? extends P> getSourcePort() {
return sourcePort;
}
@SuppressWarnings("unchecked")
@Override
public final InputPort<P> getTargetPort() {
return (InputPort<P>) targetPort;
}
@Override
public final boolean hasMore() {
return !isEmpty();
}
@Override
public final int capacity() {
return capacity;
}
@Override
public String toString() {
return sourcePort.getOwningStage().getId() + " -> " + targetPort.getOwningStage().getId() + " (" + super.toString() + ")";
}
@Override
public final void sendSignal(final ISignal signal) {
// do nothing
}
@SuppressWarnings("PMD.EmptyMethodInAbstractClassShouldBeAbstract")
@Override
public void waitForStartSignal() throws InterruptedException {
// do nothing
}
@Override
public final void reportNewElement() {
this.cachedTargetStage.executeStage();
}
@Override
public boolean isClosed() {
return closed;
}
@Override
public void close() {
closed = true;
}
@Override
public boolean addNonBlocking(final Object element) {
return this.add(element);
}
@Override
public Object removeLast() {
final Object temp = this.element;
this.element = null;
return temp;
}
@Override
public boolean isEmpty() {
return this.element == null;
}
@Override
public int size() {
return (this.element == null) ? 0 : 1;
}
@SuppressWarnings("unchecked")
@Override
public boolean add(final Object element) {
if (null == element) {
throw new IllegalArgumentException("Parameter 'element' is null, but must be non-null.");
}
this.element = divideAndConquer((P) element);
this.reportNewElement();
return true;
}
private S divideAndConquer(final P problem) {
final AbstractDCStage<P, S> tempTargetStage = cachedTargetStage;
if (tempTargetStage.isBaseCase(problem)) {
return tempTargetStage.solve(problem);
} else {
Pair<P, P> problems = tempTargetStage.divide(problem);
S firstSolution = divideAndConquer(problems.getFirst()); // recursive call
S secondSolution = divideAndConquer(problems.getSecond()); // recursive call
return tempTargetStage.combine(firstSolution, secondSolution);
}
}
}
| src/main/java/teetime/framework/DivideAndConquerRecursivePipe.java | package teetime.framework;
import org.apache.commons.math3.util.Pair;
import teetime.framework.pipe.IPipe;
import teetime.framework.signal.ISignal;
import teetime.util.divideAndConquer.Identifiable;
public class DivideAndConquerRecursivePipe<P extends Identifiable, S extends Identifiable> implements IPipe<P> {
protected final AbstractDCStage<P, S> cachedTargetStage;
private final OutputPort<? extends P> sourcePort;
private final InputPort<S> targetPort;
@SuppressWarnings("PMD.AvoidFieldNameMatchingMethodName")
private final int capacity;
private boolean closed;
private S element;
@SuppressWarnings("unchecked")
protected DivideAndConquerRecursivePipe(final OutputPort<? extends P> sourcePort, final InputPort<S> targetPort) {
if (sourcePort == null) {
throw new IllegalArgumentException("sourcePort may not be null");
}
if (targetPort == null) {
throw new IllegalArgumentException("targetPort may not be null");
}
sourcePort.setPipe(this);
targetPort.setPipe(this);
this.sourcePort = sourcePort;
this.targetPort = targetPort;
this.capacity = 1;
this.cachedTargetStage = (AbstractDCStage<P, S>) targetPort.getOwningStage();
}
@Override
public final OutputPort<? extends P> getSourcePort() {
return sourcePort;
}
@SuppressWarnings("unchecked")
@Override
public final InputPort<P> getTargetPort() {
return (InputPort<P>) targetPort;
}
@Override
public final boolean hasMore() {
return !isEmpty();
}
@Override
public final int capacity() {
return capacity;
}
@Override
public String toString() {
return sourcePort.getOwningStage().getId() + " -> " + targetPort.getOwningStage().getId() + " (" + super.toString() + ")";
}
@Override
public final void sendSignal(final ISignal signal) {
// do nothing
}
@SuppressWarnings("PMD.EmptyMethodInAbstractClassShouldBeAbstract")
@Override
public void waitForStartSignal() throws InterruptedException {
// do nothing
}
@Override
public final void reportNewElement() {
this.cachedTargetStage.executeStage();
}
@Override
public boolean isClosed() {
return closed;
}
@Override
public void close() {
closed = true;
}
@Override
public boolean addNonBlocking(final Object element) {
return this.add(element);
}
@Override
public Object removeLast() {
final Object temp = this.element;
this.element = null;
return temp;
}
@Override
public boolean isEmpty() {
return this.element == null;
}
@Override
public int size() {
return (this.element == null) ? 0 : 1;
}
@SuppressWarnings("unchecked")
@Override
public boolean add(final Object element) {
if (null == element) {
throw new IllegalArgumentException("Parameter 'element' is null, but must be non-null.");
}
this.element = divideAndConquer((P) element);
this.reportNewElement();
return true;
}
private S divideAndConquer(final P problem) {
final AbstractDCStage<P, S> tempTargetStage = cachedTargetStage;
if (tempTargetStage.isBaseCase(problem)) {
return tempTargetStage.solve(problem);
} else {
Pair<P, P> problems = tempTargetStage.divide(problem);
S firstSolution = divideAndConquer(problems.getFirst()); // recursive call
S secondSolution = divideAndConquer(problems.getSecond()); // recursive call
return tempTargetStage.combine(firstSolution, secondSolution);
}
}
}
| reduced visibility | src/main/java/teetime/framework/DivideAndConquerRecursivePipe.java | reduced visibility | <ide><path>rc/main/java/teetime/framework/DivideAndConquerRecursivePipe.java
<ide> import teetime.framework.signal.ISignal;
<ide> import teetime.util.divideAndConquer.Identifiable;
<ide>
<del>public class DivideAndConquerRecursivePipe<P extends Identifiable, S extends Identifiable> implements IPipe<P> {
<add>class DivideAndConquerRecursivePipe<P extends Identifiable, S extends Identifiable> implements IPipe<P> {
<ide>
<ide> protected final AbstractDCStage<P, S> cachedTargetStage;
<ide> |
|
JavaScript | mit | 17490f1612b47183feb4d72842814171d6f95be3 | 0 | tidoust/reffy,tidoust/reffy | #!/usr/bin/env node
/**
* The spec crawler takes a list of spec URLs as input, gathers some knowledge
* about these specs (published versions, URL of the Editor's Draft, etc.),
* fetches these specs, parses them, extracts relevant information that they
* contain (such as the WebIDL they define, the list of specifications that they
* reference, and links to external specs), and produces a crawl report with the
* results of these investigations.
*
* The spec crawler can be called directly through:
*
* `node crawl-specs.js [listfile] [crawl folder] [option]`
*
* where `listfile` is the name of a JSON file that contains the list of specs
* to crawl, `crawl folder` is the name of the folder where the crawl report
* will be created, and `option` is an optional parameter that can be set to
* `tr` to tell the crawler to crawl the published version of W3C specifications
* instead of the Editor's Draft.
*
* The JSON file that contains the list of specs to crawl must be an array whose
* individual items are either:
* 1. a string that gets interpreted as the URL or the shortname of the spec to
* crawl. The spec must exist in w3c/browser-specs
* 2. an object that follows the w3c/browser-specs model:
* https://github.com/w3c/browser-specs#spec-object
*
* @module crawler
*/
const fs = require('fs');
const path = require('path');
const specs = require('browser-specs');
const webidlParser = require('./parse-webidl');
const cssDfnParser = require('../lib/css-grammar-parser');
const fetch = require('../lib/util').fetch;
const requireFromWorkingDirectory = require('../lib/util').requireFromWorkingDirectory;
const completeWithAlternativeUrls = require('../lib/util').completeWithAlternativeUrls;
const isLatestLevelThatPasses = require('../lib/util').isLatestLevelThatPasses;
const processSpecification = require('../lib/util').processSpecification;
/**
* Flattens an array
*/
const flatten = arr => arr.reduce(
(acc, val) => acc.concat(Array.isArray(val) ? flatten(val) : val),
[]);
/**
* Compares specs for ordering by URL
*/
const byURL = (a, b) => a.url.localeCompare(b.url);
/**
* Load and parse the given spec.
*
* @function
* @param {Object} spec The spec to load (must already have been completed with
* useful info, as returned by "createInitialSpecDescriptions")
* @param {Object} crawlOptions Crawl options
* @return {Promise<Object>} The promise to get a spec object with crawl info
*/
async function crawlSpec(spec, crawlOptions) {
spec.crawled = crawlOptions.publishedVersion ?
(spec.release ? spec.release.url : spec.nightly.url) :
spec.nightly.url;
spec.date = "";
spec.links = [];
spec.refs = {};
spec.idl = {};
if (spec.error) {
return spec;
}
try {
const result = await processSpecification(spec.crawled, () => {
return {
crawled: window.location.toString(),
title: window.reffy.getTitle(),
generator: window.reffy.getGenerator(),
date: window.reffy.getLastModifiedDate(),
links: window.reffy.extractLinks(),
dfns: window.reffy.extractDefinitions(),
refs: window.reffy.extractReferences(),
idl: window.reffy.extractWebIdl(),
css: window.reffy.extractCSS()
};
});
// Parse the extracted WebIdl content
try {
const parsedIdl = await webidlParser.parse(result.idl);
parsedIdl.hasObsoleteIdl = webidlParser.hasObsoleteIdl(result.idl);
parsedIdl.idl = result.idl;
result.idl = parsedIdl;
}
catch (err) {
// IDL content is invalid and cannot be parsed.
// Let's return the error, along with the raw IDL
// content so that it may be saved to a file.
err.idl = result.idl;
result.idl = err;
}
// Parse extracted CSS definitions
Object.keys(result.css.properties || {}).forEach(prop => {
try {
result.css.properties[prop].parsedValue = cssDfnParser.parsePropDefValue(
result.css.properties[prop].value || result.css.properties[prop].newValues);
} catch (e) {
result.css.properties[prop].valueParseError = e.message;
}
});
Object.keys(result.css.descriptors || {}).forEach(desc => {
try {
result.css.descriptors[desc].parsedValue = cssDfnParser.parsePropDefValue(
result.css.descriptors[desc].value);
} catch (e) {
result.css.descriptors[desc].valueParseError = e.message;
}
});
Object.keys(result.css.valuespaces || {}).forEach(vs => {
if (result.css.valuespaces[vs].value) {
try {
result.css.valuespaces[vs].parsedValue = cssDfnParser.parsePropDefValue(
result.css.valuespaces[vs].value);
} catch (e) {
result.css.valuespaces[vs].valueParseError = e.message;
}
}
});
// Copy results back into initial spec object
spec.crawled = result.crawled;
spec.title = result.title ? result.title : spec.title;
spec.generator = result.generator;
spec.date = result.date;
spec.links = result.links;
spec.refs = result.refs;
spec.idl = result.idl;
spec.css = result.css;
spec.dfns = result.dfns;
}
catch (err) {
spec.title = spec.title || '[Could not be determined, see error]';
spec.error = err.toString() + (err.stack ? ' ' + err.stack : '');
}
return spec;
}
/**
* Main method that crawls the list of specification URLs and return a structure
* that full describes its title, URLs, references, and IDL definitions.
*
* @function
* @param {Array(String)} speclist List of URLs to parse
* @param {Object} crawlOptions Crawl options
* @return {Promise<Array(Object)} The promise to get an array of complete
* specification descriptions
*/
async function crawlList(speclist, crawlOptions, resultsPath) {
crawlOptions = crawlOptions || {};
const list = speclist.map(completeWithAlternativeUrls);
const listAndPromise = list.map(spec => {
let resolve = null;
let reject = null;
let readyToCrawl = new Promise((resolveFunction, rejectFunction) => {
resolve = resolveFunction;
reject = rejectFunction;
});
return { spec, readyToCrawl, resolve, reject };
});
// In debug mode, specs are processed one by one. In normal mode,
// specs are processing in chunks
const chunkSize = Math.min((crawlOptions.debug ? 1 : 4), list.length);
let pos = 0;
function flagNextSpecAsReadyToCrawl() {
if (pos < listAndPromise.length) {
listAndPromise[pos].resolve();
pos += 1;
}
}
for (let i = 0; i < chunkSize; i++) {
flagNextSpecAsReadyToCrawl();
}
const nbStr = '' + listAndPromise.length;
async function crawlSpecAndPromise(specAndPromise, idx) {
await specAndPromise.readyToCrawl;
const spec = specAndPromise.spec;
const logCounter = ('' + (idx + 1)).padStart(nbStr.length, ' ') + '/' + nbStr;
console.log(`${logCounter} - ${spec.url} - crawling`);
const result = await crawlSpec(spec, crawlOptions);
console.log(`${logCounter} - ${spec.url} - done`);
flagNextSpecAsReadyToCrawl();
return result;
}
const results = await Promise.all(listAndPromise.map(crawlSpecAndPromise));
return results;
}
/**
* Append the resulting data to the given file.
*
* Note results are sorted by URL to guarantee that the crawl report produced
* will always follow the same order.
*
* The function also dumps raw CSS/IDL extracts for each spec to the css and
* idl folders. Note that if the crawl contains multiple levels of a given spec
* that contain the same type of definitions (css, or idl), the dump is for the
* latest level.
*
* @function
* @param {Object} crawlOptions Crawl options
* @param {Array(Object)} data The list of specification structures to save
* @param {String} folder The path to the report folder
* @return {Promise<void>} The promise to have saved the data
*/
async function saveResults(crawlOptions, data, folder) {
async function getSubfolder(name) {
let subfolder = path.join(folder, name);
try {
await fs.promises.mkdir(subfolder);
}
catch (err) {
if (err.code !== 'EEXIST') {
throw err;
}
}
return subfolder;
}
const idlFolder = await getSubfolder('idl');
const cssFolder = await getSubfolder('css');
const dfnsFolder = await getSubfolder('dfns');
async function saveIdl(spec) {
let idlHeader = `
// GENERATED CONTENT - DO NOT EDIT
// Content was automatically extracted by Reffy into reffy-reports
// (https://github.com/tidoust/reffy-reports)
// Source: ${spec.title} (${spec.crawled})`;
idlHeader = idlHeader.replace(/^\s+/gm, '').trim() + '\n\n';
let idl = spec.idl.idl
.replace(/\s+$/gm, '\n')
.replace(/\t/g, ' ')
.trim();
idl = idlHeader + idl + '\n';
delete spec.idl.idl;
try {
await fs.promises.writeFile(
path.join(idlFolder, spec.series.shortname + '.idl'), idl);
}
catch (err) {
console.log(err);
}
};
async function saveCss(spec) {
// There are no comments in JSON, so include the spec title+URL as the
// first property instead.
const css = Object.assign({
spec: {
title: spec.title,
url: spec.crawled
}
}, spec.css);
const json = JSON.stringify(css, (key, val) => {
if ((key === 'parsedValue') || (key === 'valueParseError')) {
return undefined;
}
else {
return val;
}
}, 2) + '\n';
try {
await fs.promises.writeFile(
path.join(cssFolder, spec.series.shortname + '.json'), json);
}
catch (err) {
console.log(err);
}
};
async function saveDfns(spec) {
const dfns = {
spec: {
title: spec.title,
url: spec.crawled
},
dfns: spec.dfns
};
try {
await fs.promises.writeFile(
path.join(dfnsFolder, spec.shortname + '.json'),
JSON.stringify(dfns, null, 2));
}
catch (err) {
console.log(err);
}
}
// Save IDL dumps for the latest level of a spec to the idl folder
function defineIDLContent(spec) {
return spec.idl && spec.idl.idl;
}
await Promise.all(data
.filter(spec => isLatestLevelThatPasses(spec, data, defineIDLContent))
.map(saveIdl));
// Save CSS dumps for the latest level of a spec to the css folder
function defineCSSContent(spec) {
return spec.css && (
(Object.keys(spec.css.properties || {}).length > 0) ||
(Object.keys(spec.css.descriptors || {}).length > 0) ||
(Object.keys(spec.css.valuespaces || {}).length > 0));
}
await Promise.all(data
.filter(spec => isLatestLevelThatPasses(spec, data, defineCSSContent))
.map(saveCss));
// Save definitions for all specs
await Promise.all(data
.filter(spec => spec.dfns && spec.dfns.length > 0)
.map(saveDfns));
// Save all results to the crawl.json file
let reportFilename = path.join(folder, 'crawl.json');
return new Promise((resolve, reject) =>
fs.readFile(reportFilename, function(err, content) {
if (err) return reject(err);
let filedata = {};
try {
filedata = JSON.parse(content);
} catch (e) {}
filedata.type = filedata.type || 'crawl';
filedata.title = 'Reffy crawl';
filedata.date = filedata.date || (new Date()).toJSON();
filedata.options = crawlOptions;
filedata.stats = {};
filedata.results = (filedata.results || []).concat(data);
filedata.results.sort(byURL);
filedata.stats = {
crawled: filedata.results.length,
errors: filedata.results.filter(spec => !!spec.error).length
};
fs.writeFile(reportFilename, JSON.stringify(filedata, null, 2),
err => { if (err) return reject(err); return resolve();});
})
);
}
/**
* Crawls the specifications listed in the given JSON file and generates a
* crawl report in the given folder.
*
* @function
* @param {String} resultsPath Folder that is to contain the crawl report
* @param {Object} options Crawl options
* @return {Promise<void>} The promise that the crawl will have been made
*/
function crawlSpecs(resultsPath, options) {
if (!resultsPath) {
return Promise.reject('Required folder parameter missing');
}
try {
fs.writeFileSync(path.join(resultsPath, 'crawl.json'), '');
} catch (err) {
return Promise.reject('Impossible to write to ' + resultsPath + ': ' + err);
}
function prepareListOfSpecs(list) {
return list
.map(spec => (typeof spec === 'string') ?
specs.find(s => s.url === spec || s.shortname === spec) :
spec)
.filter(spec => !!spec);
}
const requestedList = (options && options.specFile) ?
prepareListOfSpecs(requireFromWorkingDirectory(options.specFile)) :
specs;
return crawlList(requestedList, options, resultsPath)
.then(results => saveResults(options, results, resultsPath));
}
/**************************************************
Export methods for use as module
**************************************************/
module.exports.crawlList = crawlList;
module.exports.crawlSpecs = crawlSpecs;
/**************************************************
Code run if the code is run as a stand-alone module
**************************************************/
if (require.main === module) {
var resultsPath = (process.argv[2] && process.argv[2].endsWith('.json')) ?
process.argv[3] : process.argv[2];
var crawlOptions = {
specFile: process.argv.find(arg => arg.endsWith('.json')),
publishedVersion: !!process.argv.find(arg => arg === 'tr'),
debug: !!process.argv.find(arg => arg === 'debug')
};
// Process the file and crawl specifications it contains
crawlSpecs(resultsPath, crawlOptions)
.then(data => {
console.log('finished');
process.exit(0);
})
.catch(err => {
console.error(err);
process.exit(1);
});
}
| src/cli/crawl-specs.js | #!/usr/bin/env node
/**
* The spec crawler takes a list of spec URLs as input, gathers some knowledge
* about these specs (published versions, URL of the Editor's Draft, etc.),
* fetches these specs, parses them, extracts relevant information that they
* contain (such as the WebIDL they define, the list of specifications that they
* reference, and links to external specs), and produces a crawl report with the
* results of these investigations.
*
* The spec crawler can be called directly through:
*
* `node crawl-specs.js [listfile] [crawl folder] [option]`
*
* where `listfile` is the name of a JSON file that contains the list of specs
* to crawl, `crawl folder` is the name of the folder where the crawl report
* will be created, and `option` is an optional parameter that can be set to
* `tr` to tell the crawler to crawl the published version of W3C specifications
* instead of the Editor's Draft.
*
* The JSON file that contains the list of specs to crawl must be an array whose
* individual items are either:
* 1. a string that gets interpreted as the URL or the shortname of the spec to
* crawl. The spec must exist in w3c/browser-specs
* 2. an object that follows the w3c/browser-specs model:
* https://github.com/w3c/browser-specs#spec-object
*
* @module crawler
*/
const fs = require('fs');
const path = require('path');
const specs = require('browser-specs');
const webidlParser = require('./parse-webidl');
const cssDfnParser = require('../lib/css-grammar-parser');
const fetch = require('../lib/util').fetch;
const requireFromWorkingDirectory = require('../lib/util').requireFromWorkingDirectory;
const completeWithAlternativeUrls = require('../lib/util').completeWithAlternativeUrls;
const isLatestLevelThatPasses = require('../lib/util').isLatestLevelThatPasses;
const processSpecification = require('../lib/util').processSpecification;
/**
* Flattens an array
*/
const flatten = arr => arr.reduce(
(acc, val) => acc.concat(Array.isArray(val) ? flatten(val) : val),
[]);
/**
* Compares specs for ordering by URL
*/
const byURL = (a, b) => a.url.localeCompare(b.url);
/**
* Load and parse the given spec.
*
* @function
* @param {Object} spec The spec to load (must already have been completed with
* useful info, as returned by "createInitialSpecDescriptions")
* @param {Object} crawlOptions Crawl options
* @return {Promise<Object>} The promise to get a spec object with crawl info
*/
async function crawlSpec(spec, crawlOptions) {
spec.crawled = crawlOptions.publishedVersion ?
(spec.release ? spec.release.url : spec.nightly.url) :
spec.nightly.url;
spec.date = "";
spec.links = [];
spec.refs = {};
spec.idl = {};
if (spec.error) {
return spec;
}
try {
const result = await processSpecification(spec.crawled, () => {
return {
crawled: window.location.toString(),
title: window.reffy.getTitle(),
date: window.reffy.getLastModifiedDate(),
links: window.reffy.extractLinks(),
dfns: window.reffy.extractDefinitions(),
refs: window.reffy.extractReferences(),
idl: window.reffy.extractWebIdl(),
css: window.reffy.extractCSS()
};
});
// Parse the extracted WebIdl content
try {
const parsedIdl = await webidlParser.parse(result.idl);
parsedIdl.hasObsoleteIdl = webidlParser.hasObsoleteIdl(result.idl);
parsedIdl.idl = result.idl;
result.idl = parsedIdl;
}
catch (err) {
// IDL content is invalid and cannot be parsed.
// Let's return the error, along with the raw IDL
// content so that it may be saved to a file.
err.idl = result.idl;
result.idl = err;
}
// Parse extracted CSS definitions
Object.keys(result.css.properties || {}).forEach(prop => {
try {
result.css.properties[prop].parsedValue = cssDfnParser.parsePropDefValue(
result.css.properties[prop].value || result.css.properties[prop].newValues);
} catch (e) {
result.css.properties[prop].valueParseError = e.message;
}
});
Object.keys(result.css.descriptors || {}).forEach(desc => {
try {
result.css.descriptors[desc].parsedValue = cssDfnParser.parsePropDefValue(
result.css.descriptors[desc].value);
} catch (e) {
result.css.descriptors[desc].valueParseError = e.message;
}
});
Object.keys(result.css.valuespaces || {}).forEach(vs => {
if (result.css.valuespaces[vs].value) {
try {
result.css.valuespaces[vs].parsedValue = cssDfnParser.parsePropDefValue(
result.css.valuespaces[vs].value);
} catch (e) {
result.css.valuespaces[vs].valueParseError = e.message;
}
}
});
// Copy results back into initial spec object
spec.crawled = result.crawled;
spec.title = result.title ? result.title : spec.title;
spec.date = result.date;
spec.links = result.links;
spec.refs = result.refs;
spec.idl = result.idl;
spec.css = result.css;
spec.dfns = result.dfns;
}
catch (err) {
spec.title = spec.title || '[Could not be determined, see error]';
spec.error = err.toString() + (err.stack ? ' ' + err.stack : '');
}
return spec;
}
/**
* Main method that crawls the list of specification URLs and return a structure
* that full describes its title, URLs, references, and IDL definitions.
*
* @function
* @param {Array(String)} speclist List of URLs to parse
* @param {Object} crawlOptions Crawl options
* @return {Promise<Array(Object)} The promise to get an array of complete
* specification descriptions
*/
async function crawlList(speclist, crawlOptions, resultsPath) {
crawlOptions = crawlOptions || {};
const list = speclist.map(completeWithAlternativeUrls);
const listAndPromise = list.map(spec => {
let resolve = null;
let reject = null;
let readyToCrawl = new Promise((resolveFunction, rejectFunction) => {
resolve = resolveFunction;
reject = rejectFunction;
});
return { spec, readyToCrawl, resolve, reject };
});
// In debug mode, specs are processed one by one. In normal mode,
// specs are processing in chunks
const chunkSize = Math.min((crawlOptions.debug ? 1 : 4), list.length);
let pos = 0;
function flagNextSpecAsReadyToCrawl() {
if (pos < listAndPromise.length) {
listAndPromise[pos].resolve();
pos += 1;
}
}
for (let i = 0; i < chunkSize; i++) {
flagNextSpecAsReadyToCrawl();
}
const nbStr = '' + listAndPromise.length;
async function crawlSpecAndPromise(specAndPromise, idx) {
await specAndPromise.readyToCrawl;
const spec = specAndPromise.spec;
const logCounter = ('' + (idx + 1)).padStart(nbStr.length, ' ') + '/' + nbStr;
console.log(`${logCounter} - ${spec.url} - crawling`);
const result = await crawlSpec(spec, crawlOptions);
console.log(`${logCounter} - ${spec.url} - done`);
flagNextSpecAsReadyToCrawl();
return result;
}
const results = await Promise.all(listAndPromise.map(crawlSpecAndPromise));
return results;
}
/**
* Append the resulting data to the given file.
*
* Note results are sorted by URL to guarantee that the crawl report produced
* will always follow the same order.
*
* The function also dumps raw CSS/IDL extracts for each spec to the css and
* idl folders. Note that if the crawl contains multiple levels of a given spec
* that contain the same type of definitions (css, or idl), the dump is for the
* latest level.
*
* @function
* @param {Object} crawlOptions Crawl options
* @param {Array(Object)} data The list of specification structures to save
* @param {String} folder The path to the report folder
* @return {Promise<void>} The promise to have saved the data
*/
async function saveResults(crawlOptions, data, folder) {
async function getSubfolder(name) {
let subfolder = path.join(folder, name);
try {
await fs.promises.mkdir(subfolder);
}
catch (err) {
if (err.code !== 'EEXIST') {
throw err;
}
}
return subfolder;
}
const idlFolder = await getSubfolder('idl');
const cssFolder = await getSubfolder('css');
const dfnsFolder = await getSubfolder('dfns');
async function saveIdl(spec) {
let idlHeader = `
// GENERATED CONTENT - DO NOT EDIT
// Content was automatically extracted by Reffy into reffy-reports
// (https://github.com/tidoust/reffy-reports)
// Source: ${spec.title} (${spec.crawled})`;
idlHeader = idlHeader.replace(/^\s+/gm, '').trim() + '\n\n';
let idl = spec.idl.idl
.replace(/\s+$/gm, '\n')
.replace(/\t/g, ' ')
.trim();
idl = idlHeader + idl + '\n';
delete spec.idl.idl;
try {
await fs.promises.writeFile(
path.join(idlFolder, spec.series.shortname + '.idl'), idl);
}
catch (err) {
console.log(err);
}
};
async function saveCss(spec) {
// There are no comments in JSON, so include the spec title+URL as the
// first property instead.
const css = Object.assign({
spec: {
title: spec.title,
url: spec.crawled
}
}, spec.css);
const json = JSON.stringify(css, (key, val) => {
if ((key === 'parsedValue') || (key === 'valueParseError')) {
return undefined;
}
else {
return val;
}
}, 2) + '\n';
try {
await fs.promises.writeFile(
path.join(cssFolder, spec.series.shortname + '.json'), json);
}
catch (err) {
console.log(err);
}
};
async function saveDfns(spec) {
const dfns = {
spec: {
title: spec.title,
url: spec.crawled
},
dfns: spec.dfns
};
try {
await fs.promises.writeFile(
path.join(dfnsFolder, spec.shortname + '.json'),
JSON.stringify(dfns, null, 2));
}
catch (err) {
console.log(err);
}
}
// Save IDL dumps for the latest level of a spec to the idl folder
function defineIDLContent(spec) {
return spec.idl && spec.idl.idl;
}
await Promise.all(data
.filter(spec => isLatestLevelThatPasses(spec, data, defineIDLContent))
.map(saveIdl));
// Save CSS dumps for the latest level of a spec to the css folder
function defineCSSContent(spec) {
return spec.css && (
(Object.keys(spec.css.properties || {}).length > 0) ||
(Object.keys(spec.css.descriptors || {}).length > 0) ||
(Object.keys(spec.css.valuespaces || {}).length > 0));
}
await Promise.all(data
.filter(spec => isLatestLevelThatPasses(spec, data, defineCSSContent))
.map(saveCss));
// Save definitions for all specs
await Promise.all(data
.filter(spec => spec.dfns && spec.dfns.length > 0)
.map(saveDfns));
// Save all results to the crawl.json file
let reportFilename = path.join(folder, 'crawl.json');
return new Promise((resolve, reject) =>
fs.readFile(reportFilename, function(err, content) {
if (err) return reject(err);
let filedata = {};
try {
filedata = JSON.parse(content);
} catch (e) {}
filedata.type = filedata.type || 'crawl';
filedata.title = 'Reffy crawl';
filedata.date = filedata.date || (new Date()).toJSON();
filedata.options = crawlOptions;
filedata.stats = {};
filedata.results = (filedata.results || []).concat(data);
filedata.results.sort(byURL);
filedata.stats = {
crawled: filedata.results.length,
errors: filedata.results.filter(spec => !!spec.error).length
};
fs.writeFile(reportFilename, JSON.stringify(filedata, null, 2),
err => { if (err) return reject(err); return resolve();});
})
);
}
/**
* Crawls the specifications listed in the given JSON file and generates a
* crawl report in the given folder.
*
* @function
* @param {String} resultsPath Folder that is to contain the crawl report
* @param {Object} options Crawl options
* @return {Promise<void>} The promise that the crawl will have been made
*/
function crawlSpecs(resultsPath, options) {
if (!resultsPath) {
return Promise.reject('Required folder parameter missing');
}
try {
fs.writeFileSync(path.join(resultsPath, 'crawl.json'), '');
} catch (err) {
return Promise.reject('Impossible to write to ' + resultsPath + ': ' + err);
}
function prepareListOfSpecs(list) {
return list
.map(spec => (typeof spec === 'string') ?
specs.find(s => s.url === spec || s.shortname === spec) :
spec)
.filter(spec => !!spec);
}
const requestedList = (options && options.specFile) ?
prepareListOfSpecs(requireFromWorkingDirectory(options.specFile)) :
specs;
return crawlList(requestedList, options, resultsPath)
.then(results => saveResults(options, results, resultsPath));
}
/**************************************************
Export methods for use as module
**************************************************/
module.exports.crawlList = crawlList;
module.exports.crawlSpecs = crawlSpecs;
/**************************************************
Code run if the code is run as a stand-alone module
**************************************************/
if (require.main === module) {
var resultsPath = (process.argv[2] && process.argv[2].endsWith('.json')) ?
process.argv[3] : process.argv[2];
var crawlOptions = {
specFile: process.argv.find(arg => arg.endsWith('.json')),
publishedVersion: !!process.argv.find(arg => arg === 'tr'),
debug: !!process.argv.find(arg => arg === 'debug')
};
// Process the file and crawl specifications it contains
crawlSpecs(resultsPath, crawlOptions)
.then(data => {
console.log('finished');
process.exit(0);
})
.catch(err => {
console.error(err);
process.exit(1);
});
}
| Include the generator (Bikeshed, ReSpec, etc.) in crawl.json (#319)
| src/cli/crawl-specs.js | Include the generator (Bikeshed, ReSpec, etc.) in crawl.json (#319) | <ide><path>rc/cli/crawl-specs.js
<ide> return {
<ide> crawled: window.location.toString(),
<ide> title: window.reffy.getTitle(),
<add> generator: window.reffy.getGenerator(),
<ide> date: window.reffy.getLastModifiedDate(),
<ide> links: window.reffy.extractLinks(),
<ide> dfns: window.reffy.extractDefinitions(),
<ide> // Copy results back into initial spec object
<ide> spec.crawled = result.crawled;
<ide> spec.title = result.title ? result.title : spec.title;
<add> spec.generator = result.generator;
<ide> spec.date = result.date;
<ide> spec.links = result.links;
<ide> spec.refs = result.refs; |
|
JavaScript | mit | 2a6696a1f7804505520804fcf74798fd409a5d06 | 0 | reinforce/KC3Kai,sinsinpub/KC3Kai,Madobe/KC3Kai,Yukinyaa/KC3Kai,rephira/KC3Kai,DynamicSTOP/KC3Kai,DynamicSTOP/KC3Kai,kololz/KC3Kai,sinsinpub/KC3Kai,kololz/KC3Kai,Adrymne/KC3Kai,Javran/KC3Kai,rephira/KC3Kai,c933103/KC3Kai,KC3Kai/KC3Kai,Javran/KC3Kai,dragonjet/KC3Kai,reinforce/KC3Kai,dragonjet/KC3Kai,rephira/KC3Kai,Adrymne/KC3Kai,Adrymne/KC3Kai,Javran/KC3Kai,Tibo442/KC3Kai,kololz/KC3Kai,reinforce/KC3Kai,KC3Kai/KC3Kai,Madobe/KC3Kai,c933103/KC3Kai,Tibo442/KC3Kai,sinsinpub/KC3Kai,Tibo442/KC3Kai,Madobe/KC3Kai,Yukinyaa/KC3Kai,DynamicSTOP/KC3Kai,c933103/KC3Kai,KC3Kai/KC3Kai | /* Node.js
KC3改 Node Object
Represents a single battle on a node
Used by SortieManager
*/
(function(){
"use strict";
window.KC3Node = function(sortie_id, id, UTCTime){
this.sortie = (sortie_id || 0);
this.id = (id || 0);
this.type = "";
this.stime = UTCTime;
this.isPvP = false;
};
/**
// Return predicted battle rank letter. Static function.
// @param beginHPs, endHPs in following structure:
// { ally: [array of hps],
// enemy: [array of hps]
// }
// arrays are all begins at 0.
// @param battleName - optional, the API call name invoked currently
*/
KC3Node.predictRank = function(beginHPs, endHPs, battleName) {
console.assert(
beginHPs.ally.length === endHPs.ally.length,
"ally data length mismatched");
console.assert(
beginHPs.enemy.length === endHPs.enemy.length,
"enemy data length mismatched");
// Removes "-1"s in begin HPs
// also removes data from same position
// in end HPs
// in addition, negative end HP values are set to 0
function normalizeHP(begins, ends) {
var nBegins = [];
var nEnds = [];
for (var i=0; i<begins.length; ++i) {
if (begins[i] !== -1) {
console.assert(
begins[i] > 0,
"wrong begin HP");
nBegins.push(begins[i]);
nEnds.push( ends[i]<0 ? 0 : ends[i] );
}
}
return [nBegins,nEnds];
}
// perform normalization
var result1, result2;
result1 = normalizeHP(beginHPs.ally, endHPs.ally);
result2 = normalizeHP(beginHPs.enemy, endHPs.enemy);
// create new objs leaving old data intact
beginHPs = {
ally: result1[0],
enemy: result2[0]
};
endHPs = {
ally: result1[1],
enemy: result2[1]
};
var allySunkCount = endHPs.ally.filter(function(x){return x===0;}).length;
var allyCount = endHPs.ally.length;
var enemySunkCount = endHPs.enemy.filter(function(x){return x===0;}).length;
var enemyCount = endHPs.enemy.length;
var requiredSunk = enemyCount === 6 ? 4 : Math.ceil( enemyCount / 2);
var i;
// damage taken by ally
var allyGauge = 0;
var allyBeginHP = 0;
for (i=0; i<allyCount; ++i) {
allyGauge += beginHPs.ally[i] - endHPs.ally[i];
allyBeginHP += beginHPs.ally[i];
}
var enemyGauge = 0;
var enemyBeginHP = 0;
for (i=0; i<enemyCount; ++i) {
enemyGauge += beginHPs.enemy[i] - endHPs.enemy[i];
enemyBeginHP += beginHPs.enemy[i];
}
// Related comments:
// - https://github.com/KC3Kai/KC3Kai/issues/728#issuecomment-139681987
// - https://github.com/KC3Kai/KC3Kai/issues/1766#issuecomment-275883784
// - https://github.com/andanteyk/ElectronicObserver/blob/master/ElectronicObserver/Other/Information/kcmemo.md#%E6%88%A6%E9%97%98%E5%8B%9D%E5%88%A9%E5%88%A4%E5%AE%9A
// The flooring behavior is intended and important.
// Please do not change it unless it's proved to be more accurate than
// the formula referred to by the comments above.
var allyGaugeRate = Math.floor(allyGauge / allyBeginHP * 100);
var enemyGaugeRate = Math.floor(enemyGauge / enemyBeginHP * 100);
var equalOrMore = enemyGaugeRate > (0.9 * allyGaugeRate);
var superior = enemyGaugeRate > 0 && enemyGaugeRate > (2.5 * allyGaugeRate);
// For long distance air raid
if ( (battleName||"").indexOf("ld_airbattle") >-1 ) {
// Based on long distance air raid rules from:
// https://github.com/andanteyk/ElectronicObserver/blob/master/ElectronicObserver/Other/Information/kcmemo.md#%E9%95%B7%E8%B7%9D%E9%9B%A2%E7%A9%BA%E8%A5%B2%E6%88%A6%E3%81%A7%E3%81%AE%E5%8B%9D%E5%88%A9%E5%88%A4%E5%AE%9A
// Also referenced:
// - http://kancolle.wikia.com/wiki/Events/Mechanics (as of 2017-01-28)
// - http://nga.178.com/read.php?tid=8989155
return (allyGauge === 0) ? "SS"
: (allyGaugeRate < 10) ? "A"
: (allyGaugeRate < 20) ? "B"
: (allyGaugeRate < 50) ? "C"
: (allyGaugeRate < 80) ? "D"
: /* otherwise */ "E";
}
if (allySunkCount === 0) {
if (enemySunkCount === enemyCount) {
return allyGauge === 0 ? "SS" : "S";
}
if (enemySunkCount >= requiredSunk)
return "A";
if (endHPs.enemy[0] === 0)
return "B";
if (superior)
return "B";
} else {
if (enemySunkCount === enemyCount)
return "B";
if (endHPs.enemy[0] === 0 && allySunkCount < enemySunkCount)
return "B";
if (superior)
return "B";
if (endHPs.enemy[0] === 0)
return "C";
}
if (enemyGauge > 0 && equalOrMore)
return "C";
if (allySunkCount > 0 && allyCount === 1)
return "E";
return "D";
};
KC3Node.prototype.defineAsBattle = function( nodeData ){
this.type = "battle";
this.startNight = false;
// If passed initial values
if(typeof nodeData != "undefined"){
// If passed raw data from compass
//"api_event_id":4,"api_event_kind":1
if(typeof nodeData.api_event_kind != "undefined"){
this.eships = [];
this.eventKind = nodeData.api_event_kind;
this.eventId = nodeData.api_event_id;
this.gaugeDamage = 0; // calculate this on result screen. make it fair :D
}
// If passed formatted enemy list from PVP
if(typeof nodeData.pvp_opponents != "undefined"){
this.eships = nodeData.pvp_opponents;
this.gaugeDamage = -1;
}
}
this.enemySunk = [false, false, false, false, false, false];
this.enemyHP = [0,0,0,0,0,0];
this.originalHPs = [0,0,0,0,0,0,0,0,0,0,0,0,0];
this.allyNoDamage = true;
this.nodalXP = 0;
this.lostShips = [[],[]];
this.mvps = [];
this.dameConConsumed = [];
this.dameConConsumedEscort = [];
return this;
};
// Building up resource / item gain / loss descriptions
KC3Node.prototype.buildItemNodeDesc = function(itemInfoArray) {
var resourceNameMap = {
"1": 31, "2": 32, "3": 33, "4": 34, // Fuel, Ammo, Steel, Bauxite
"5": 2 , "6": 1 , "7": 3 // Blowtorch, Bucket, DevMat, Compass
};
var resourceDescs = [];
itemInfoArray.forEach(function(item) {
var rescKeyDesc = KC3Meta.useItemName(
resourceNameMap[item.api_icon_id] || item.api_icon_id
);
if (!rescKeyDesc)
return;
if (typeof item.api_getcount !== "undefined")
resourceDescs.push( rescKeyDesc + ": " + item.api_getcount );
else if (typeof item.api_count !== "undefined")
resourceDescs.push( rescKeyDesc + ": -" + item.api_count );
});
return resourceDescs.join("\n");
};
KC3Node.prototype.defineAsResource = function( nodeData ){
var self = this;
this.type = "resource";
this.item = [];
this.icon = [];
this.amount = [];
if (typeof nodeData.api_itemget == "object" && typeof nodeData.api_itemget.api_id != "undefined") {
nodeData.api_itemget = [nodeData.api_itemget];
}
this.nodeDesc = this.buildItemNodeDesc( nodeData.api_itemget );
nodeData.api_itemget.forEach(function(itemget){
var icon_id = itemget.api_icon_id;
var getcount = itemget.api_getcount;
self.item.push(icon_id);
self.icon.push(function(folder){
return folder+(
["fuel","ammo","steel","bauxite","ibuild","bucket","devmat","compass","","box1","box2","box3"]
[icon_id - 1]
)+".png";
});
self.amount.push(getcount);
if(icon_id < 8)
KC3SortieManager.materialGain[icon_id-1] += getcount;
});
return this;
};
KC3Node.prototype.defineAsBounty = function( nodeData ){
var
self = this,
maps = JSON.parse(localStorage.maps),
ckey = ["m",KC3SortieManager.map_world,KC3SortieManager.map_num].join("");
this.type = "bounty";
this.item = nodeData.api_itemget_eo_comment.api_id;
this.icon = function(folder){
return folder+(
["fuel","ammo","steel","bauxite","ibuild","bucket","devmat","compass"]
[self.item-1]
)+".png";
};
this.nodeDesc = this.buildItemNodeDesc([
{ api_icon_id: nodeData.api_itemget_eo_comment.api_id,
api_getcount: nodeData.api_itemget_eo_comment.api_getcount
}
]);
this.amount = nodeData.api_itemget_eo_comment.api_getcount;
KC3SortieManager.materialGain[this.item-1] += this.amount;
maps[ckey].clear |= (++maps[ckey].kills) >= KC3Meta.gauge(ckey.replace("m",""));
localStorage.maps = JSON.stringify(maps);
return this;
};
KC3Node.prototype.defineAsMaelstrom = function( nodeData ){
this.type = "maelstrom";
this.item = nodeData.api_happening.api_icon_id;
this.icon = function(folder){
return folder+(
["fuel","ammo","steel","bauxite","ibuild","bucket","devmat","compass"]
[nodeData.api_happening.api_icon_id-1]
)+".png";
};
this.nodeDesc = this.buildItemNodeDesc( [nodeData.api_happening] );
this.amount = nodeData.api_happening.api_count;
return this;
};
KC3Node.prototype.defineAsSelector = function( nodeData ){
console.log("defining as selector", nodeData);
this.type = "select";
this.choices = [
KC3Meta.nodeLetter(
KC3SortieManager.map_world,
KC3SortieManager.map_num,
nodeData.api_select_route.api_select_cells[0] ),
KC3Meta.nodeLetter(
KC3SortieManager.map_world,
KC3SortieManager.map_num,
nodeData.api_select_route.api_select_cells[1] )
];
console.log("choices", this.choices);
return this;
};
KC3Node.prototype.defineAsTransport = function( nodeData ){
this.type = "transport";
this.amount = Math.floor(KC3SortieManager.getSortieFleet().map(function(fleetId){
return PlayerManager.fleets[fleetId].ship().map(function(ship){
return ship.obtainTP();
}).reduce(function(pre,cur){ return pre.add(cur); },KC3Meta.tpObtained());
}).reduce(function(pre,cur){ return pre.add(cur); },KC3Meta.tpObtained())
.value);
return this;
};
KC3Node.prototype.defineAsDud = function( nodeData ){
this.type = "";
return this;
};
/* BATTLE FUNCTIONS
---------------------------------------------*/
KC3Node.prototype.engage = function( battleData, fleetSent ){
this.battleDay = battleData;
//console.log("battleData", battleData);
var enemyships = battleData.api_ship_ke;
if(enemyships[0]==-1){ enemyships.splice(0,1); }
var isEnemyCombined = (typeof battleData.api_ship_ke_combined !== "undefined");
var enemyEscortList = battleData.api_ship_ke_combined;
if (typeof enemyEscortList != "undefined") {
if(enemyEscortList[0]==-1){ enemyEscortList.splice(0,1); }
enemyships = enemyships.concat(enemyEscortList);
}
this.eships = enemyships;
// Reserved for combined enemy ships if eships re-assigned on night battle
this.ecships = undefined;
this.eformation = battleData.api_formation[1];
this.eParam = battleData.api_eParam;
if (typeof battleData.api_eParam_combined != "undefined") {
this.eParam = this.eParam.concat(battleData.api_eParam_combined);
}
this.eKyouka = battleData.api_eKyouka || [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1];
this.eSlot = battleData.api_eSlot;
if (typeof battleData.api_eSlot_combined != "undefined") {
this.eSlot = this.eSlot.concat(battleData.api_eSlot_combined);
}
this.supportFlag = (battleData.api_support_flag>0);
if(this.supportFlag){
this.supportInfo = battleData.api_support_info;
this.supportInfo.api_support_flag = battleData.api_support_flag;
}
this.yasenFlag = (battleData.api_midnight_flag>0);
this.originalHPs = battleData.api_nowhps;
this.maxHPs = {
ally: battleData.api_maxhps.slice(1,7),
enemy: battleData.api_maxhps.slice(7,13)
};
if (typeof battleData.api_maxhps_combined != "undefined") {
this.maxHPs.ally = this.maxHPs.ally.concat(battleData.api_maxhps_combined.slice(1,7));
this.maxHPs.enemy = this.maxHPs.enemy.concat(battleData.api_maxhps_combined.slice(7,13));
}
var beginHPs = {
ally: battleData.api_nowhps.slice(1,7),
enemy: battleData.api_nowhps.slice(7,13)
};
if (typeof battleData.api_nowhps_combined != "undefined") {
beginHPs.ally = beginHPs.ally.concat(battleData.api_nowhps_combined.slice(1,7));
beginHPs.enemy = beginHPs.enemy.concat(battleData.api_nowhps_combined.slice(7,13));
}
this.dayBeginHPs = beginHPs;
this.detection = KC3Meta.detection( battleData.api_search[0] );
this.engagement = KC3Meta.engagement( battleData.api_formation[2] );
// LBAS attack phase, including jet plane assault
this.lbasFlag = typeof battleData.api_air_base_attack != "undefined";
if(this.lbasFlag){
// Array of engaged land bases
this.airBaseAttack = battleData.api_air_base_attack;
// No plane from, just injecting from far away air base :)
this.airBaseJetInjection = battleData.api_air_base_injection;
}
// Air phases
var
planePhase = battleData.api_kouku.api_stage1 || {
api_touch_plane:[-1,-1],
api_f_count :0,
api_f_lostcount:0,
api_e_count :0,
api_e_lostcount:0,
},
attackPhase = battleData.api_kouku.api_stage2;
this.fcontactId = planePhase.api_touch_plane[0];
this.fcontact = this.fcontactId > 0 ? KC3Meta.term("BattleContactYes") : KC3Meta.term("BattleContactNo");
this.econtactId = planePhase.api_touch_plane[1];
this.econtact = this.econtactId > 0 ? KC3Meta.term("BattleContactYes") : KC3Meta.term("BattleContactNo");
this.airbattle = KC3Meta.airbattle( planePhase.api_disp_seiku );
if(!!attackPhase && !!attackPhase.api_air_fire){
this.antiAirFire = [ attackPhase.api_air_fire ];
}
// Fighter phase 1
this.planeFighters = {
player:[
planePhase.api_f_count,
planePhase.api_f_lostcount
],
abyssal:[
planePhase.api_e_count,
planePhase.api_e_lostcount
]
};
if(
this.planeFighters.player[0]===0
&& this.planeFighters.abyssal[0]===0
&& attackPhase===null
){
this.airbattle = KC3Meta.airbattle(5);
}
// Bombing phase 1
this.planeBombers = { player:[0,0], abyssal:[0,0] };
if(attackPhase !== null){
this.planeBombers.player[0] = attackPhase.api_f_count;
this.planeBombers.player[1] = attackPhase.api_f_lostcount;
this.planeBombers.abyssal[0] = attackPhase.api_e_count;
this.planeBombers.abyssal[1] = attackPhase.api_e_lostcount;
}
// Fighter phase 2
if(typeof battleData.api_kouku2 != "undefined"){
this.planeFighters.player[1] += battleData.api_kouku2.api_stage1.api_f_lostcount;
this.planeFighters.abyssal[1] += battleData.api_kouku2.api_stage1.api_e_lostcount;
// Bombine phase 2
if(battleData.api_kouku2.api_stage2 !== null){
this.planeBombers.player[1] += battleData.api_kouku2.api_stage2.api_f_lostcount;
this.planeBombers.abyssal[1] += battleData.api_kouku2.api_stage2.api_e_lostcount;
if(!!battleData.api_kouku2.api_stage2.api_air_fire){
if(!this.antiAirFire || this.antiAirFire.length<1){
this.antiAirFire = [null];
}
this.antiAirFire[1] = battleData.api_kouku2.api_stage2.api_air_fire;
}
}
}
// Jet plane phase, happen before fighter attack phase
if(typeof battleData.api_injection_kouku != "undefined"){
var jetPlanePhase = battleData.api_injection_kouku;
this.planeJetFighters = { player:[0,0], abyssal:[0,0] };
this.planeJetBombers = { player:[0,0], abyssal:[0,0] };
this.planeJetFighters.player[0] = jetPlanePhase.api_stage1.api_f_count;
this.planeJetFighters.player[1] = jetPlanePhase.api_stage1.api_f_lostcount;
this.planeJetFighters.abyssal[0] = jetPlanePhase.api_stage1.api_e_count;
this.planeJetFighters.abyssal[1] = jetPlanePhase.api_stage1.api_e_lostcount;
if(!!jetPlanePhase.api_stage2){
this.planeJetBombers.player[0] = jetPlanePhase.api_stage2.api_f_count;
this.planeJetBombers.player[1] = jetPlanePhase.api_stage2.api_f_lostcount;
this.planeJetBombers.abyssal[0] = jetPlanePhase.api_stage2.api_e_count;
this.planeJetBombers.abyssal[1] = jetPlanePhase.api_stage2.api_e_lostcount;
}
// Jet planes consume steels each battle based on:
// pendingConsumingSteel = floor(jetMaster.api_cost * ship.slots[jetIdx] * 0.2)
if(this.planeJetFighters.player[0] > 0
&& (KC3SortieManager.onSortie > 0 || KC3SortieManager.isPvP())){
var consumedSteel = PlayerManager.fleets[
(parseInt(fleetSent) || KC3SortieManager.fleetSent) - 1
].calcJetsSteelCost(KC3SortieManager.sortieName(2));
console.log("Jets consumed steel:", consumedSteel);
}
}
// Boss Debuffed
this.debuffed = typeof battleData.api_boss_damaged != "undefined" ?
(battleData.api_boss_damaged == 1) ? true : false
: false;
var i = 0;
// Battle analysis only if on sortie or PvP, not applied to sortielogs
if(KC3SortieManager.onSortie > 0 || KC3SortieManager.isPvP()){
var PS = window.PS;
var DA = PS["KanColle.DamageAnalysis.FFI"];
var result = null;
var fleet;
var dameConCode;
var shipNum;
var ship;
var fleetId = parseInt(fleetSent) || KC3SortieManager.fleetSent;
var enemyMain, enemyEscort, mainFleet, escortFleet;
// PLAYER SINGLE FLEET
if ((typeof PlayerManager.combinedFleet === "undefined") || (PlayerManager.combinedFleet === 0) || fleetId>1){
// single fleet: not combined, or sent fleet is not first fleet
// Update our fleet
fleet = PlayerManager.fleets[fleetId - 1];
// damecon ignored for PvP
dameConCode = KC3SortieManager.isPvP()
? [0,0,0,0,0,0]
: fleet.getDameConCodes();
var endHPs = {
ally: beginHPs.ally.slice(),
enemy: beginHPs.enemy.slice()
};
// ONLY ENEMY IS COMBINED
if (isEnemyCombined) {
this.ecships = this.eships;
result = DA.analyzeAbyssalCTFBattleJS(dameConCode, battleData);
console.log("only enemy is combined", result);
// Update enemy ships
for (i = 7; i < 13; i++) {
this.enemyHP[i-7] = result.enemyMain[i-7];
endHPs.enemy[i-7] = result.enemyMain[i-7] ? result.enemyMain[i-7].hp : -1;
this.enemySunk[i-7] = result.enemyMain[i-7] ? result.enemyMain[i-7].sunk : true;
}
for (i = 13; i < 19; i++) {
this.enemyHP[i-7] = result.enemyEscort[i-13];
endHPs.enemy[i-7] = result.enemyEscort[i-13] ? result.enemyEscort[i-13].hp : -1;
this.enemySunk[i-7] = result.enemyEscort[i-13] ? result.enemyEscort[i-13].sunk : true;
}
// BOTH SINGLE FLEET
} else {
// regular day-battle
result = DA.analyzeBattleJS(dameConCode, battleData);
console.log("both single fleet", result);
// Update enemy ships
for (i = 7; i < 13; i++) {
this.enemyHP[i-7] = result.enemy[i-7];
endHPs.enemy[i-7] = result.enemy[i-7] ? result.enemy[i-7].hp : -1;
this.enemySunk[i-7] = result.enemy[i-7] ? result.enemy[i-7].sunk : true;
}
}
// update player ships
shipNum = fleet.countShips();
for(i = 0; i < shipNum; i++) {
ship = fleet.ship(i);
ship.afterHp[0] = result.main[i].hp;
this.allyNoDamage &= ship.hp[0]==ship.afterHp[0];
ship.afterHp[1] = ship.hp[1];
endHPs.ally[i] = result.main[i].hp;
// Check if damecon consumed, if yes, get item consumed
if (result.main[i].dameConConsumed){
this.dameConConsumed[i] = ship.findDameCon();
} else {
this.dameConConsumed[i] = false;
}
}
if(ConfigManager.info_btrank
// long distance aerial battle not accurate for now, see #1333
// but go for aerial battle (eventKind:4) possible Yasen
//&& [6].indexOf(this.eventKind)<0
){
this.predictedRank = KC3Node.predictRank( beginHPs, endHPs, battleData.api_name );
// console.debug("Rank Predict:", this.predictedRank);
}
// PLAYER COMBINED FLEET
} else {
dameConCode = PlayerManager.fleets[0].getDameConCodes()
.concat( PlayerManager.fleets[1].getDameConCodes() );
console.assert(dameConCode.length === 12, "dameConCode length should be 12 for combined fleets");
// BOTH COMBINED FLEET
if (isEnemyCombined) {
this.ecships = this.eships;
if (PlayerManager.combinedFleet === 1 || PlayerManager.combinedFleet === 3) {
// Carrier Task Force or Transport Escort
result = DA.analyzeBothCombinedCTFBattleJS(dameConCode,battleData);
console.log("CTF both combined", result);
} else if (PlayerManager.combinedFleet === 2) {
// Surface Task Force
result = DA.analyzeBothCombinedSTFBattleJS(dameConCode,battleData);
console.log("STF both combined", result);
} else {
console.error( "Unknown combined fleet code: " + PlayerManager.combinedFleet );
}
// Update enemy
for(i = 1; i <= 6; i++) {
enemyMain = result.enemyMain[i-1];
if (enemyMain !== null) {
this.enemyHP[i-1] = enemyMain;
this.enemySunk[i-1] = enemyMain.sunk;
}
}
for(i = 1; i <= 6; i++) {
enemyEscort = result.enemyEscort[i-1];
if (enemyEscort !== null) {
this.enemyHP[i+5] = enemyEscort;
this.enemySunk[i+5] = enemyEscort.sunk;
}
}
// Update main fleet
fleet = PlayerManager.fleets[0];
shipNum = fleet.countShips();
mainFleet = result.allyMain;
for(i = 0; i < shipNum; i++) {
ship = fleet.ship(i);
ship.afterHp[0] = mainFleet[i].hp;
this.allyNoDamage &= ship.hp[0]==ship.afterHp[0];
ship.afterHp[1] = ship.hp[1];
// Check if damecon consumed, if yes, get item consumed
if (mainFleet[i].dameConConsumed){
this.dameConConsumed[i] = ship.findDameCon();
} else {
this.dameConConsumed[i] = false;
}
}
// Update escort fleet
fleet = PlayerManager.fleets[1];
shipNum = fleet.countShips();
escortFleet = result.allyEscort;
for(i = 0; i < shipNum; i++) {
ship = fleet.ship(i);
ship.afterHp[0] = escortFleet[i].hp;
this.allyNoDamage &= ship.hp[0]==ship.afterHp[0];
ship.afterHp[1] = ship.hp[1];
// Check if damecon consumed, if yes, get item consumed
if (escortFleet[i].dameConConsumed){
this.dameConConsumedEscort[i] = ship.findDameCon();
} else {
this.dameConConsumedEscort[i] = false;
}
}
// ONLY PLAYER IS COMBINED
} else {
if (PlayerManager.combinedFleet === 1) {
// Carrier Task Force
result = DA.analyzeCTFBattleJS(dameConCode,battleData);
console.log("CTF only player is combined", result);
} else if (PlayerManager.combinedFleet === 2) {
// Surface Task Force
result = DA.analyzeSTFBattleJS(dameConCode,battleData);
console.log("STF only player is combined", result);
} else if (PlayerManager.combinedFleet === 3) {
// Transport Escort
result = DA.analyzeTECFBattleJS(dameConCode,battleData);
console.log("TECF only player is combined", result);
} else {
console.error( "Unknown combined fleet code: " + PlayerManager.combinedFleet );
}
// Update enemy
for(i = 1; i <= 6; i++) {
enemyMain = result.enemy[i-1];
if (enemyMain !== null) {
this.enemyHP[i-1] = enemyMain;
this.enemySunk[i-1] = enemyMain.sunk;
}
}
// Update main fleet
fleet = PlayerManager.fleets[0];
shipNum = fleet.countShips();
mainFleet = result.main;
for(i = 0; i < shipNum; i++) {
ship = fleet.ship(i);
ship.afterHp[0] = mainFleet[i].hp;
this.allyNoDamage &= ship.hp[0]==ship.afterHp[0];
ship.afterHp[1] = ship.hp[1];
// Check if damecon consumed, if yes, get item consumed
if (mainFleet[i].dameConConsumed){
this.dameConConsumed[i] = ship.findDameCon();
} else {
this.dameConConsumed[i] = false;
}
}
// Update escort fleet
fleet = PlayerManager.fleets[1];
shipNum = fleet.countShips();
escortFleet = result.escort;
for(i = 0; i < shipNum; i++) {
ship = fleet.ship(i);
ship.afterHp[0] = escortFleet[i].hp;
this.allyNoDamage &= ship.hp[0]==ship.afterHp[0];
ship.afterHp[1] = ship.hp[1];
// Check if damecon consumed, if yes, get item consumed
if (escortFleet[i].dameConConsumed){
this.dameConConsumedEscort[i] = ship.findDameCon();
} else {
this.dameConConsumedEscort[i] = false;
}
}
}
}
}
if(this.gaugeDamage > -1) {
this.gaugeDamage = Math.min(this.originalHPs[7],this.originalHPs[7] - this.enemyHP[0].hp);
(function(sortieData){
var
maps = localStorage.getObject('maps'),
desg = ['m',sortieData.map_world,sortieData.map_num].join('');
if(this.isBoss() && maps[desg].kind == 'gauge-hp') {
maps[desg].baseHp = maps[desg].baseHp || this.originalHPs[7];
}
localStorage.setObject('maps',maps);
}).call(this,KC3SortieManager);
}
// Record encoutners only if on sortie
if(KC3SortieManager.onSortie > 0) {
this.saveEnemyEncounterInfo(this.battleDay);
}
};
KC3Node.prototype.engageNight = function( nightData, fleetSent, setAsOriginalHP ){
if(typeof setAsOriginalHP == "undefined"){ setAsOriginalHP = true; }
this.battleNight = nightData;
this.startNight = !!fleetSent;
var enemyships = nightData.api_ship_ke;
if(enemyships[0]==-1){ enemyships.splice(0,1); }
var isEnemyCombined = (typeof nightData.api_ship_ke_combined !== "undefined");
this.eships = enemyships;
this.eformation = this.eformation || nightData.api_formation[1];
this.eParam = nightData.api_eParam;
this.eKyouka = nightData.api_eKyouka || [-1,-1,-1,-1,-1,-1];
this.eSlot = nightData.api_eSlot;
this.maxHPs = {
ally: nightData.api_maxhps.slice(1,7),
enemy: nightData.api_maxhps.slice(7,13)
};
if (typeof nightData.api_maxhps_combined != "undefined") {
this.maxHPs.ally = this.maxHPs.ally.concat(nightData.api_maxhps_combined.slice(1,7));
this.maxHPs.enemy = this.maxHPs.enemy.concat(nightData.api_maxhps_combined.slice(7,13));
}
// if we did not started at night, at this point dayBeginHPs should be available
var beginHPs = {
ally: [],
enemy: []
};
if (this.dayBeginHPs) {
beginHPs = this.dayBeginHPs;
} else {
beginHPs.ally = nightData.api_nowhps.slice(1,7);
beginHPs.enemy = nightData.api_nowhps.slice(7,13);
}
if(setAsOriginalHP){
this.originalHPs = nightData.api_nowhps;
}
this.engagement = this.engagement || KC3Meta.engagement( nightData.api_formation[2] );
this.fcontactId = nightData.api_touch_plane[0]; // masterId of slotitem, starts from 1
this.fcontact = this.fcontactId > 0 ? KC3Meta.term("BattleContactYes") : KC3Meta.term("BattleContactNo");
this.econtactId = nightData.api_touch_plane[1];
this.econtact = this.econtactId > 0 ? KC3Meta.term("BattleContactYes") : KC3Meta.term("BattleContactNo");
this.flarePos = nightData.api_flare_pos[0]; // Star shell user pos 1-6
this.eFlarePos = nightData.api_flare_pos[1]; // PvP opponent only, abyss star shell not existed yet
var PS = window.PS;
var DA = PS["KanColle.DamageAnalysis.FFI"];
var result = null;
var i = 0;
var fleet;
var dameConCode;
var shipNum;
var ship;
var fleetId = parseInt(fleetSent) || KC3SortieManager.fleetSent;
var endHPs = {
ally: beginHPs.ally.slice(),
enemy: beginHPs.enemy.slice()
};
// PLAYER COMBINED FLEET
if (PlayerManager.combinedFleet && (fleetId <= 1)) {
// player combined fleet yasen, escort always fleet #2
fleet = PlayerManager.fleets[1];
dameConCode = fleet.getDameConCodes();
// BOTH COMBINED FLEET
if (isEnemyCombined) {
// still needs 12-element array for dameConCode
if (dameConCode.length < 7) {
dameConCode = dameConCode.concat([0,0,0,0,0,0]);
}
console.log("dameConCode", dameConCode);
result = DA.analyzeBothCombinedNightBattleJS(dameConCode, nightData);
console.log("player combined", "enemy combined", result);
// enemy info, enemy main fleet in yasen
if (nightData.api_active_deck[1] == 1) {
console.log("enemy main fleet in yasen", result.enemyMain);
for (i = 7; i < 13; i++) {
this.enemyHP[i-7] = result.enemyMain[i-7];
endHPs.enemy[i-7] = result.enemyMain[i-7] ? result.enemyMain[i-7].hp : -1;
this.enemySunk[i-7] = result.enemyMain[i-7] ? result.enemyMain[i-7].sunk : true;
}
// enemy info, enemy escort fleet in yasen
} else {
console.log("enemy escort fleet in yasen", result.enemyEscort);
enemyships = nightData.api_ship_ke_combined;
if(enemyships[0]==-1){ enemyships.splice(0,1); }
this.eships = enemyships;
this.eParam = nightData.api_eParam_combined;
this.eSlot = nightData.api_eSlot_combined;
for (i = 7; i < 13; i++) {
this.enemyHP[i-7] = result.enemyEscort[i-7];
endHPs.enemy[i-7] = result.enemyEscort[i-7] ? result.enemyEscort[i-7].hp : -1;
this.enemySunk[i-7] = result.enemyEscort[i-7] ? result.enemyEscort[i-7].sunk : true;
}
}
// player fleet
shipNum = fleet.countShips();
for(i = 0; i < shipNum; i++) {
ship = fleet.ship(i);
ship.hp = [ship.afterHp[0], ship.afterHp[1]];
ship.morale = Math.max(0,Math.min(100,ship.morale+(fleetSent ? 1 : -3 )));
ship.afterHp[0] = result.allyEscort[i].hp;
this.allyNoDamage &= ship.hp[0]==ship.afterHp[0];
ship.afterHp[1] = ship.hp[1];
endHPs.ally[i] = result.allyEscort[i].hp;
}
// ONLY PLAYER IS COMBINED
} else {
// only player is combined fleet
result = DA.analyzeCombinedNightBattleJS(dameConCode, nightData);
console.log("player combined", "enemy single", result);
// update enemy info
for (i = 7; i < 13; i++) {
this.enemyHP[i-7] = result.enemy[i-7];
endHPs.enemy[i-7] = result.enemy[i-7] ? result.enemy[i-7].hp : -1;
this.enemySunk[i-7] = result.enemy[i-7] ? result.enemy[i-7].sunk : true;
}
// player fleet
shipNum = fleet.countShips();
for(i = 0; i < shipNum; i++) {
ship = fleet.ship(i);
ship.hp = [ship.afterHp[0], ship.afterHp[1]];
ship.morale = Math.max(0,Math.min(100,ship.morale+(fleetSent ? 1 : -3 )));
ship.afterHp[0] = result.main[i].hp;
this.allyNoDamage &= ship.hp[0]==ship.afterHp[0];
ship.afterHp[1] = ship.hp[1];
endHPs.ally[i] = result.main[i].hp;
}
}
// PLAYER SINGLE FLEET
} else {
fleet = PlayerManager.fleets[fleetId - 1];
// damecon ignored for PvP
dameConCode = KC3SortieManager.isPvP() ? [0,0,0, 0,0,0] : fleet.getDameConCodes();
// ONLY ENEMY IS COMBINED
if (isEnemyCombined) {
// enemy combined fleet
result = DA.analyzeAbyssalCTFNightBattleJS(dameConCode, nightData);
console.log("player single", "enemy combined", result);
// enemy info, enemy main fleet in yasen
if (nightData.api_active_deck[1] == 1) {
console.log("enemy main fleet in yasen", result.enemyMain);
for (i = 7; i < 13; i++) {
this.enemyHP[i-7] = result.enemyMain[i-7];
endHPs.enemy[i-7] = result.enemyMain[i-7] ? result.enemyMain[i-7].hp : -1;
this.enemySunk[i-7] = result.enemyMain[i-7] ? result.enemyMain[i-7].sunk : true;
}
// enemy info, enemy escort fleet in yasen
} else {
console.log("enemy escort fleet in yasen", result.enemyEscort);
enemyships = nightData.api_ship_ke_combined;
if(enemyships[0]==-1){ enemyships.splice(0,1); }
this.eships = enemyships;
this.eParam = nightData.api_eParam_combined;
this.eSlot = nightData.api_eSlot_combined;
for (i = 7; i < 13; i++) {
this.enemyHP[i-7] = result.enemyEscort[i-7];
endHPs.enemy[i-7] = result.enemyEscort[i-7] ? result.enemyEscort[i-7].hp : -1;
this.enemySunk[i-7] = result.enemyEscort[i-7] ? result.enemyEscort[i-7].sunk : true;
}
}
// BOTH SINGLE FLEET
} else {
// regular yasen
result = DA.analyzeNightBattleJS(dameConCode, nightData);
console.log("player single", "enemy single", result);
// regular yasen enemy info
for (i = 7; i < 13; i++) {
this.enemyHP[i-7] = result.enemy[i-7];
endHPs.enemy[i-7] = result.enemy[i-7] ? result.enemy[i-7].hp : -1;
this.enemySunk[i-7] = result.enemy[i-7] ? result.enemy[i-7].sunk : true;
}
}
// regular yasen fleet info
shipNum = fleet.countShips();
for(i = 0; i < shipNum; i++) {
ship = fleet.ship(i);
ship.hp = [ship.afterHp[0], ship.afterHp[1]];
ship.morale = Math.max(0,Math.min(100,ship.morale+(fleetSent ? 1 : -3 )));
ship.afterHp[0] = result.main[i].hp;
this.allyNoDamage &= ship.hp[0]==ship.afterHp[0];
ship.afterHp[1] = ship.hp[1];
endHPs.ally[i] = result.main[i].hp;
}
}
console.log("enemyHP", this.enemyHP);
console.log("enemySunk", this.enemySunk);
if(ConfigManager.info_btrank){
this.predictedRankNight = KC3Node.predictRank( beginHPs, endHPs );
// console.debug("Rank Predict (Night):", this.predictedRankNight);
}
if(this.gaugeDamage > -1
&& (!isEnemyCombined || nightData.api_active_deck[1] == 1) ){
this.gaugeDamage = this.gaugeDamage +
Math.min(nightData.api_nowhps[7],nightData.api_nowhps[7] - this.enemyHP[0].hp);
}
// Record encoutners only if on sortie and starts from night
if(this.startNight && KC3SortieManager.onSortie > 0) {
this.saveEnemyEncounterInfo(this.battleNight);
}
};
KC3Node.prototype.night = function( nightData ){
this.engageNight(nightData, null, false);
};
KC3Node.prototype.results = function( resultData ){
try {
this.rating = resultData.api_win_rank;
this.nodalXP = resultData.api_get_base_exp;
if(this.allyNoDamage && this.rating === "S")
this.rating = "SS";
console.log("This battle, the ally fleet has no damage:",this.allyNoDamage);
if(this.isBoss()) {
var
maps = localStorage.getObject('maps'),
ckey = ["m",KC3SortieManager.map_world,KC3SortieManager.map_num].join(""),
stat = maps[ckey].stat,
srid = KC3SortieManager.onSortie;
/* DESPAIR STATISTICS ==> */
if(stat) {
var
fs = [this.gaugeDamage,this.originalHPs[7]],
pt = 'dummy',
sb = stat.onBoss,
oc = 0;
fs.push(fs[0]/fs[1]);
fs.push(fs[1]-fs[0]);
switch(true){
case (fs[0] === 0): pt = 'fresh'; break;
case (fs[2] < 0.25): pt = 'graze'; break;
case (fs[2] < 0.50): pt = 'light'; break;
case (fs[2] < 0.75): pt = 'modrt'; break;
case (fs[3] > 9): pt = 'heavy'; break;
case (fs[3] > 1): pt = 'despe'; break;
case (fs[3] == 1): pt = 'endur'; break;
case (fs[3] < 1): pt = 'destr'; break;
}
sb[pt].push(srid);
oc = sb[pt].length;
console.info('Current sortie recorded as',pt);
console.info('You\'ve done this',oc,'time'+(oc != 1 ? 's' : '')+'.','Good luck, see you next time!');
}
/* ==> DESPAIR STATISTICS */
/* FLAGSHIP ATTACKING ==> */
console.log("Damaged Flagship",this.gaugeDamage,"/",maps[ckey].curhp || 0,"pts");
switch(maps[ckey].kind) {
case 'single': /* Single Victory */
break;
case 'multiple': /* Kill-based */
if((KC3Meta.gauge(ckey.replace("m","")) - (maps[ckey].kills || 0)) > 0)
maps[ckey].kills += resultData.api_destsf;
break;
case 'gauge-hp': /* HP-Gauge */
if((this.gaugeDamage >= 0) && (maps[ckey].curhp || 0) > 0) {
maps[ckey].curhp -= this.gaugeDamage;
if(maps[ckey].curhp <= 0) // if last kill -- check whether flagship is killed or not -- flagship killed = map clear
maps[ckey].curhp = 1-(maps[ckey].clear = resultData.api_destsf);
}
break;
case 'gauge-tp': /* TP-Gauge */
/* TP Gauge */
if (typeof resultData.api_landing_hp != "undefined") {
var TPdata = resultData.api_landing_hp;
this.gaugeDamage = Math.min(TPdata.api_now_hp,TPdata.api_sub_value);
maps[ckey].curhp = TPdata.api_now_hp - this.gaugeDamage;
maps[ckey].maxhp = TPdata.api_max_hp - 0;
} else {
maps[ckey].curhp = 0;
}
console.log("Landing get",this.gaugeDamage,"->",maps[ckey].curhp,"/",maps[ckey].maxhp,"TP");
break;
default: /* Undefined */
break;
}
maps[ckey].clear |= resultData.api_first_clear; // obtaining clear once
if(stat) {
stat.onBoss.hpdat[srid] = [maps[ckey].curhp,maps[ckey].maxhp];
if(resultData.api_first_clear)
stat.onClear = srid; // retrieve sortie ID for first clear mark
}
/* ==> FLAGSHIP ATTACKING */
localStorage.setObject('maps',maps);
}
var
ship_get = [];
if(typeof resultData.api_get_ship != "undefined"){
this.drop = resultData.api_get_ship.api_ship_id;
KC3ShipManager.pendingShipNum += 1;
KC3GearManager.pendingGearNum += KC3Meta.defaultEquip(this.drop);
console.log("Drop " + resultData.api_get_ship.api_ship_name + " (" + this.drop + ") Equip " + KC3Meta.defaultEquip(this.drop));
ship_get.push(this.drop);
}else{
this.drop = 0;
}
/*
api_get_eventitem :海域攻略報酬 イベント海域突破時のみ存在
api_type :報酬種別 1=アイテム, 2=艦娘, 3=装備
api_id :ID
api_value :個数?
*/
(function(resultEventItems){
console.log("event result",resultEventItems);
(resultEventItems || []).forEach(function(eventItem){
switch(eventItem.api_type){
case 1: // Item
if(eventItem.api_id.inside(1,4)) {
KC3SortieManager.materialGain[eventItem.api_id+3] += eventItem.api_value;
}
break;
case 2: // Ship
ship_get.push(eventItem.api_id);
break;
case 3: // Equip
break;
default:
console.log("unknown type",eventItem);
break;
}
});
}).call(this,resultData.api_get_eventitem);
ConfigManager.loadIfNecessary();
ship_get.forEach(function(newShipId){
var wish_kind = ["salt","wish"];
wish_kind.some(function(wishType){
var
wish_key = [wishType,'list'].join('_'),
wish_id = ConfigManager[wish_key].indexOf(newShipId)+1;
if(wish_id){
ConfigManager[wish_key].splice(wish_id-1,1);
console.warn("Removed",KC3Meta.shipName(KC3Master.ship(newShipId).api_name),"from",wishType,"list");
ConfigManager.lock_prep.push(newShipId);
return true;
} else {
return false;
}
});
});
ConfigManager.save();
this.mvps = [resultData.api_mvp || 0,resultData.api_mvp_combined || 0].filter(function(x){return !!x;});
var
lostCheck = (resultData.api_lost_flag) ?
[resultData.api_lost_flag,null] : /* if api_lost_flag is explicitly specified */
[resultData.api_get_ship_exp,resultData.api_get_ship_exp_combined].map(function(expData,fleetId){
return expData ? expData.slice(1) : []; // filter out first dummy element, be aware for undefined item
}).map(function(expData,fleetId){
/* Example data:
"api_get_ship_exp":[-1,420,140,140,140,-1,-1],
"api_get_exp_lvup":[[177,300,600],[236,300,600],[118,300],[118,300]],
"api_get_ship_exp_combined":[-1,420,140,140,-1,-1,-1],
"api_get_exp_lvup_combined":[[177,300,600],[236,300,600],[118,300],[118,300]]
Logic :
- for ship_exp indices, start from 1.
- compare ship_exp data, check it if -1
- (fail condition) ignore, set as non-sink and skip to next one
- compare the current index with the neighboring array (exp_lvup),
check if an array exists on that index
- if it exists, mark as sunk
Source: https://gitter.im/KC3Kai/Public?at=5662e448c15bca7e3c96376f
*/
return expData.map(function(data,slotId){
return (data == -1) && !!resultData[['api_get','exp_lvup','combined'].slice(0,fleetId+2).join('_')][slotId];
});
}),
fleetDesg = [KC3SortieManager.fleetSent - 1,1]; // designated fleet (fleet mapping)
this.lostShips = lostCheck.map(function(lostFlags,fleetNum){
console.log("lostFlags",fleetNum, lostFlags);
return (lostFlags || []).filter(function(x){return x>=0;}).map(function(checkSunk,rosterPos){
if(!!checkSunk) {
var rtv = PlayerManager.fleets[fleetDesg[fleetNum]].ships[rosterPos];
if(KC3ShipManager.get(rtv).didFlee) return 0;
console.log("このクソ提督、深海に%c%s%cが沈んだ (ID:%d)",
'color:red,font-weight:bold',
KC3ShipManager.get(rtv).master().api_name,
'color:initial,font-weight:initial',
rtv
);
return rtv;
} else {
return 0;
}
}).filter(function(shipId){return shipId;});
});
//var enemyCVL = [510, 523, 560];
//var enemyCV = [512, 525, 528, 565, 579];
//var enemySS = [530, 532, 534, 531, 533, 535, 570, 571, 572];
//var enemyAP = [513, 526, 558];
var eshipCnt = (this.ecships || []).length || 6;
for(var i = 0; i < eshipCnt; i++) {
if (this.enemySunk[i]) {
var enemyShip = KC3Master.ship( (this.ecships || this.eships)[i] );
if (!enemyShip) {
console.log("Cannot find enemy " + this.eships[i]);
} else if (this.eships[i] < 500) {
console.log("Enemy ship is not Abyssal!");
} else {
switch(enemyShip.api_stype) {
case 7: // 7 = CVL
case 11: // 11 = CV
console.log("You sunk a CV"+((enemyShip.api_stype==7)?"L":""));
KC3QuestManager.get(217).increment();
KC3QuestManager.get(211).increment();
KC3QuestManager.get(220).increment();
break;
case 13: // 13 = SS
console.log("You sunk a SS");
KC3QuestManager.get(230).increment();
KC3QuestManager.get(228).increment();
break;
case 15: // 15 = AP
console.log("You sunk a AP");
KC3QuestManager.get(218).increment();
KC3QuestManager.get(212).increment();
KC3QuestManager.get(213).increment();
KC3QuestManager.get(221).increment();
break;
}
}
}
}
// Save enemy deck name for encounter
var name = resultData.api_enemy_info.api_deck_name;
if(KC3SortieManager.onSortie > 0 && !!name){
this.saveEnemyEncounterInfo(null, name);
}
} catch (e) {
console.error("Captured an exception ==>", e,"\n==> proceeds safely");
} finally {
this.saveBattleOnDB(resultData);
}
};
KC3Node.prototype.resultsPvP = function( resultData ){
try {
this.rating = resultData.api_win_rank;
this.nodalXP = resultData.api_get_base_exp;
if(this.allyNoDamage && this.rating === "S")
this.rating = "SS";
this.mvps = [resultData.api_mvp || 0];
} catch (e) {
console.error("Captured an exception ==>", e,"\n==> proceeds safely");
} finally {
this.savePvPOnDB(resultData);
}
};
/**
* Builds a complex long message for results of Exped/LBAS support attack,
* Used as a tooltip by devtools panel or SRoom Maps History for now.
* return a empty string if no any support triggered.
*/
KC3Node.prototype.buildSupportAttackMessage = function(){
var thisNode = this;
var supportTips = "";
if(thisNode.supportFlag && !!thisNode.supportInfo){
var fleetId = "", supportDamage = 0;
var attackType = thisNode.supportInfo.api_support_flag;
if(attackType === 1){
var airatack = thisNode.supportInfo.api_support_airatack;
fleetId = airatack.api_deck_id;
supportDamage = !airatack.api_stage3 ? 0 :
Math.floor(airatack.api_stage3.api_edam.slice(1).reduce(function(a,b){return a+b;},0));
// Support air attack has the same structure with kouku/LBAS
// So disp_seiku, plane xxx_count are also possible to be displayed
// Should break BattleSupportTips into another type for air attack
} else if([2,3].indexOf(attackType) > -1){
var hourai = thisNode.supportInfo.api_support_hourai;
fleetId = hourai.api_deck_id;
supportDamage = !hourai.api_damage ? 0 :
Math.floor(hourai.api_damage.slice(1).reduce(function(a,b){return a+b;},0));
}
supportTips = KC3Meta.term("BattleSupportTips").format(fleetId, KC3Meta.support(attackType), supportDamage);
}
var lbasTips = "";
if(thisNode.lbasFlag && !!thisNode.airBaseAttack){
if(!!thisNode.airBaseJetInjection){
var jet = thisNode.airBaseJetInjection;
var jetStage2 = jet.api_stage2 || {};
var jetPlanes = jet.api_stage1.api_f_count;
var jetShotdown = jet.api_stage1.api_e_lostcount + (jetStage2.api_e_lostcount || 0);
var jetDamage = !jet.api_stage3 ? 0 :
Math.floor(jet.api_stage3.api_edam.slice(1).reduce(function(a,b){return a+b;},0));
jetDamage += !jet.api_stage3_combined ? 0 :
Math.floor(jet.api_stage3_combined.api_edam.slice(1).reduce(function(a,b){return a+b;},0));
var jetLost = jet.api_stage1.api_f_lostcount + (jetStage2.api_f_lostcount || 0);
var jetEnemyPlanes = jet.api_stage1.api_e_count;
if(jetEnemyPlanes > 0) {
jetShotdown = "{0:eLostCount} / {1:eTotalCount}".format(jetShotdown, jetEnemyPlanes);
}
lbasTips += KC3Meta.term("BattleLbasJetSupportTips").format(jetPlanes, jetShotdown, jetDamage, jetLost);
}
$.each(thisNode.airBaseAttack, function(i, ab){
var baseId = ab.api_base_id;
var stage2 = ab.api_stage2 || {};
var airBattle = KC3Meta.airbattle(ab.api_stage1.api_disp_seiku)[2];
airBattle += ab.api_stage1.api_touch_plane[0] > 0 ? "+" + KC3Meta.term("BattleContact") : "";
var planes = ab.api_stage1.api_f_count;
var shotdown = ab.api_stage1.api_e_lostcount + (stage2.api_e_lostcount || 0);
var damage = !ab.api_stage3 ? 0 :
Math.floor(ab.api_stage3.api_edam.slice(1).reduce(function(a,b){return a+b;},0));
damage += !ab.api_stage3_combined ? 0 :
Math.floor(ab.api_stage3_combined.api_edam.slice(1).reduce(function(a,b){return a+b;},0));
var lost = ab.api_stage1.api_f_lostcount + (stage2.api_f_lostcount || 0);
var enemyPlanes = ab.api_stage1.api_e_count;
if(enemyPlanes > 0) {
shotdown = "{0:eLostCount} / {1:eTotalCount}".format(shotdown, enemyPlanes);
}
if(!!lbasTips) { lbasTips += "\n"; }
lbasTips += KC3Meta.term("BattleLbasSupportTips").format(planes, baseId, shotdown, damage, lost, airBattle);
});
if(!!supportTips && !!lbasTips) { supportTips += "\n"; }
}
return supportTips + lbasTips;
};
/**
* Builds a complex long message for results of AACI fire,
* Used as a tooltip by devtools panel or SRoom Maps History for now.
* return a empty string if no any AACI triggered.
*/
KC3Node.prototype.buildAntiAirCutinMessage = function(){
var thisNode = this;
var aaciTips = "";
if(!!thisNode.antiAirFire && thisNode.antiAirFire.length > 0){
thisNode.antiAirFire.forEach(function(fire){
if(!!fire){
var fireShipPos = fire.api_idx; // starts from 0
// fireShipPos = [0,5]: in normal fleet or main fleet
// fireShipPos = [6,11]: in escort fleet
if(fireShipPos >= 0 && fireShipPos < 12){
var sentFleet = PlayerManager.fleets[fireShipPos >= 6 ? 1 : KC3SortieManager.fleetSent-1];
var shipName = KC3ShipManager.get(sentFleet.ships[fireShipPos % 6]).name();
aaciTips += (!!aaciTips ? "\n" : "") + shipName;
var aaciType = AntiAir.AACITable[fire.api_kind];
if(!!aaciType){
aaciTips += "\n[{0}] +{1} (x{2})"
.format(aaciType.id, aaciType.fixed, aaciType.modifier);
}
}
var itemList = fire.api_use_items;
if(!!itemList && itemList.length > 0){
for(var itemIdx = 0; itemIdx < Math.min(itemList.length,4); itemIdx++) {
if(itemList[itemIdx] > -1) aaciTips += "\n" +
KC3Meta.gearName(KC3Master.slotitem(itemList[itemIdx]).api_name);
}
}
}
});
}
return aaciTips;
};
/**
* Not real battle on this node in fact. Enemy raid just randomly occurs before entering node.
* See: http://kancolle.wikia.com/wiki/Land-Base_Aerial_Support#Enemy_Raid
*/
KC3Node.prototype.airBaseRaid = function( battleData ){
this.battleDestruction = battleData;
console.log("AirBaseRaidBattle", battleData);
this.lostKind = battleData.api_lost_kind;
this.eships = battleData.api_ship_ke.slice(1);
this.eformation = battleData.api_formation[1];
this.eSlot = battleData.api_eSlot;
this.engagement = KC3Meta.engagement(battleData.api_formation[2]);
var planePhase = battleData.api_air_base_attack.api_stage1 || {
api_touch_plane:[-1,-1],
api_f_count :0,
api_f_lostcount:0,
api_e_count :0,
api_e_lostcount:0,
},
attackPhase = battleData.api_air_base_attack.api_stage2,
bomberPhase = battleData.api_air_base_attack.api_stage3;
this.fplaneFrom = battleData.api_air_base_attack.api_plane_from[0];
this.fcontactId = planePhase.api_touch_plane[0];
this.fcontact = this.fcontactId > 0 ? KC3Meta.term("BattleContactYes") : KC3Meta.term("BattleContactNo");
this.eplaneFrom = battleData.api_air_base_attack.api_plane_from[1];
this.econtactId = planePhase.api_touch_plane[1];
this.econtact = this.econtactId > 0 ? KC3Meta.term("BattleContactYes") : KC3Meta.term("BattleContactNo");
this.airbattle = KC3Meta.airbattle(planePhase.api_disp_seiku);
this.planeFighters = {
player:[
planePhase.api_f_count,
planePhase.api_f_lostcount
],
abyssal:[
planePhase.api_e_count,
planePhase.api_e_lostcount
]
};
if(
this.planeFighters.player[0]===0
&& this.planeFighters.abyssal[0]===0
&& attackPhase===null
){
this.airbattle = KC3Meta.airbattle(5);
}
this.planeBombers = { player:[0,0], abyssal:[0,0] };
if(attackPhase !== null){
this.planeBombers.player[0] = attackPhase.api_f_count;
this.planeBombers.player[1] = attackPhase.api_f_lostcount;
this.planeBombers.abyssal[0] = attackPhase.api_e_count;
this.planeBombers.abyssal[1] = attackPhase.api_e_lostcount;
}
this.baseDamage = bomberPhase && bomberPhase.api_fdam ? Math.floor(
bomberPhase.api_fdam.slice(1).reduce(function(a,b){return a+b;},0)
) : 0;
};
KC3Node.prototype.isBoss = function(){
// Normal BOSS node starts from day battle
return (this.eventKind === 1 && this.eventId === 5)
// Combined BOSS node, see advanceNode()@SortieManager.js
|| (this.eventKind === 5 && this.eventId === 5);
};
KC3Node.prototype.saveEnemyEncounterInfo = function(battleData, updatedName){
// Update name only if new name offered
if(!battleData && !!updatedName){
if(!!this.enemyEncounter){
this.enemyEncounter.name = updatedName;
KC3Database.Encounter(this.enemyEncounter, false);
return true;
}
return false;
}
// Validate map values
if(KC3SortieManager.map_world < 1){ return false; }
if(KC3SortieManager.map_num < 1){ return false; }
// Save the enemy encounter
var ed = {
world: KC3SortieManager.map_world,
map: KC3SortieManager.map_num,
diff: KC3SortieManager.map_difficulty,
node: this.id,
form: this.eformation,
ke: JSON.stringify(this.eships)
};
ed.uniqid = [ed.world,ed.map,ed.diff,ed.node,ed.form,ed.ke]
.filter(function(v){return !!v;}).join("/");
KC3Database.Encounter(ed, true);
this.enemyEncounter = ed;
var i, enemyId;
// Save enemy info
for(i = 0; i < 6; i++) {
enemyId = this.eships[i] || -1;
// Only record ships with ID more than 500 coz abyss only
if (enemyId > 500) {
KC3Database.Enemy({
id: enemyId,
hp: battleData.api_maxhps[i+7],
fp: battleData.api_eParam[i][0],
tp: battleData.api_eParam[i][1],
aa: battleData.api_eParam[i][2],
ar: battleData.api_eParam[i][3],
eq1: battleData.api_eSlot[i][0],
eq2: battleData.api_eSlot[i][1],
eq3: battleData.api_eSlot[i][2],
eq4: battleData.api_eSlot[i][3]
});
}
}
// Save combined enemy info
if(this.eships.length > 6) {
for(i = 6; i < 13; i++) {
enemyId = this.eships[i] || -1;
if (enemyId > 500) {
KC3Database.Enemy({
id: enemyId,
hp: battleData.api_maxhps_combined[i+1],
fp: battleData.api_eParam_combined[i-6][0],
tp: battleData.api_eParam_combined[i-6][1],
aa: battleData.api_eParam_combined[i-6][2],
ar: battleData.api_eParam_combined[i-6][3],
eq1: battleData.api_eSlot_combined[i-6][0],
eq2: battleData.api_eSlot_combined[i-6][1],
eq3: battleData.api_eSlot_combined[i-6][2],
eq4: battleData.api_eSlot_combined[i-6][3]
});
}
}
}
return true;
};
KC3Node.prototype.saveBattleOnDB = function( resultData ){
KC3Database.Battle({
sortie_id: (this.sortie || KC3SortieManager.onSortie || 0),
node: this.id,
enemyId: (this.epattern || 0),
data: (this.battleDay || {}),
yasen: (this.battleNight || {}),
airRaid: (this.battleDestruction || {}),
rating: this.rating,
drop: this.drop,
time: this.stime,
baseEXP: this.nodalXP,
hqEXP: resultData.api_get_exp || 0,
shizunde: this.lostShips.map(function(fleetLost){
return fleetLost.map(function(shipSunk){
return KC3ShipManager.get(shipSunk).masterId;
});
}),
mvp: this.mvps
});
};
KC3Node.prototype.savePvPOnDB = function( resultData ){
console.log("savePvPOnDB", KC3SortieManager);
KC3Database.PvP({
fleet: PlayerManager.fleets[KC3SortieManager.fleetSent-1].sortieJson(),
enemy: [],
data: (this.battleDay || {}),
yasen: (this.battleNight || {}),
rating: this.rating,
baseEXP: this.nodalXP,
mvp: this.mvps,
time: KC3SortieManager.sortieTime
});
};
})();
| src/library/objects/Node.js | /* Node.js
KC3改 Node Object
Represents a single battle on a node
Used by SortieManager
*/
(function(){
"use strict";
window.KC3Node = function(sortie_id, id, UTCTime){
this.sortie = (sortie_id || 0);
this.id = (id || 0);
this.type = "";
this.stime = UTCTime;
this.isPvP = false;
};
// static function. predicts battle rank,
// arguments are beginHPs, endHPs in following structure:
// { ally: [array of hps]
// , enemy: [array of hps]
// }
// arrays are all begins at 0
KC3Node.predictRank = function(beginHPs, endHPs, battleName) {
console.assert(
beginHPs.ally.length === endHPs.ally.length,
"ally data length mismatched");
console.assert(
beginHPs.enemy.length === endHPs.enemy.length,
"enemy data length mismatched");
// removes "-1"s in begin HPs
// also removes data from same position
// in end HPs
// in addition, negative end HP values are set to 0
function normalizeHP(begins, ends) {
var nBegins = [];
var nEnds = [];
for (var i=0; i<begins.length; ++i) {
if (begins[i] !== -1) {
console.assert(
begins[i] > 0,
"wrong begin HP");
nBegins.push(begins[i]);
nEnds.push( ends[i]<0 ? 0 : ends[i] );
}
}
return [nBegins,nEnds];
}
// perform normalization
var result1, result2;
result1 = normalizeHP(beginHPs.ally, endHPs.ally);
result2 = normalizeHP(beginHPs.enemy, endHPs.enemy);
// create new objs leaving old data intact
beginHPs = {
ally: result1[0],
enemy: result2[0]
};
endHPs = {
ally: result1[1],
enemy: result2[1]
};
var allySunkCount = endHPs.ally.filter(function(x){return x===0;}).length;
var allyCount = endHPs.ally.length;
var enemySunkCount = endHPs.enemy.filter(function(x){return x===0;}).length;
var enemyCount = endHPs.enemy.length;
var requiredSunk = enemyCount === 6 ? 4 : Math.ceil( enemyCount / 2);
var i;
// damage taken by ally
var allyGauge = 0;
var allyBeginHP = 0;
for (i=0; i<allyCount; ++i) {
allyGauge += beginHPs.ally[i] - endHPs.ally[i];
allyBeginHP += beginHPs.ally[i];
}
var enemyGauge = 0;
var enemyBeginHP = 0;
for (i=0; i<enemyCount; ++i) {
enemyGauge += beginHPs.enemy[i] - endHPs.enemy[i];
enemyBeginHP += beginHPs.enemy[i];
}
// related comments:
// - https://github.com/KC3Kai/KC3Kai/issues/728#issuecomment-139681987
// - https://github.com/KC3Kai/KC3Kai/issues/1766#issuecomment-275883784
// - Regular battle rules: https://github.com/andanteyk/ElectronicObserver/blob/master/ElectronicObserver/Other/Information/kcmemo.md#%E6%88%A6%E9%97%98%E5%8B%9D%E5%88%A9%E5%88%A4%E5%AE%9A
// the flooring behavior is intended and important.
// please do not change it unless it's proved to be more accurate than
// the formula referred to by the comments above.
var allyGaugeRate = Math.floor(allyGauge / allyBeginHP * 100);
var enemyGaugeRate = Math.floor(enemyGauge / enemyBeginHP * 100);
var equalOrMore = enemyGaugeRate > (0.9 * allyGaugeRate);
var superior = enemyGaugeRate > 0 && enemyGaugeRate > (2.5 * allyGaugeRate);
// For long distance air raid
if ( (battleName||"").indexOf("ld_airbattle") >-1 ) {
// reference:
// - http://kancolle.wikia.com/wiki/Events/Mechanics (as of 2017-01-28)
// - http://nga.178.com/read.php?tid=8989155
// - Long distance air raid rules: https://github.com/andanteyk/ElectronicObserver/blob/master/ElectronicObserver/Other/Information/kcmemo.md#%E9%95%B7%E8%B7%9D%E9%9B%A2%E7%A9%BA%E8%A5%B2%E6%88%A6%E3%81%A7%E3%81%AE%E5%8B%9D%E5%88%A9%E5%88%A4%E5%AE%9A
return (allyGauge === 0) ? "SS"
: (allyGaugeRate < 10) ? "A"
: (allyGaugeRate < 20) ? "B"
: (allyGaugeRate < 50) ? "C"
: (allyGaugeRate < 80) ? "D"
: /* otherwise */ "E";
}
if (allySunkCount === 0) {
if (enemySunkCount === enemyCount) {
return allyGauge === 0 ? "SS" : "S";
}
if (enemySunkCount >= requiredSunk)
return "A";
if (endHPs.enemy[0] === 0)
return "B";
if (superior)
return "B";
} else {
if (enemySunkCount === enemyCount)
return "B";
if (endHPs.enemy[0] === 0 && allySunkCount < enemySunkCount)
return "B";
if (superior)
return "B";
if (endHPs.enemy[0] === 0)
return "C";
}
if (enemyGauge > 0 && equalOrMore)
return "C";
if (allySunkCount > 0 && allyCount === 1)
return "E";
return "D";
};
KC3Node.prototype.defineAsBattle = function( nodeData ){
this.type = "battle";
this.startNight = false;
// If passed initial values
if(typeof nodeData != "undefined"){
// If passed raw data from compass
//"api_event_id":4,"api_event_kind":1
if(typeof nodeData.api_event_kind != "undefined"){
this.eships = [];
this.eventKind = nodeData.api_event_kind;
this.eventId = nodeData.api_event_id;
this.gaugeDamage = 0; // calculate this on result screen. make it fair :D
}
// If passed formatted enemy list from PVP
if(typeof nodeData.pvp_opponents != "undefined"){
this.eships = nodeData.pvp_opponents;
this.gaugeDamage = -1;
}
}
this.enemySunk = [false, false, false, false, false, false];
this.enemyHP = [0,0,0,0,0,0];
this.originalHPs = [0,0,0,0,0,0,0,0,0,0,0,0,0];
this.allyNoDamage = true;
this.nodalXP = 0;
this.lostShips = [[],[]];
this.mvps = [];
this.dameConConsumed = [];
this.dameConConsumedEscort = [];
return this;
};
// Building up resource / item gain / loss descriptions
KC3Node.prototype.buildItemNodeDesc = function(itemInfoArray) {
var resourceNameMap = {
"1": 31, "2": 32, "3": 33, "4": 34, // Fuel, Ammo, Steel, Bauxite
"5": 2 , "6": 1 , "7": 3 // Blowtorch, Bucket, DevMat, Compass
};
var resourceDescs = [];
itemInfoArray.forEach(function(item) {
var rescKeyDesc = KC3Meta.useItemName(
resourceNameMap[item.api_icon_id] || item.api_icon_id
);
if (!rescKeyDesc)
return;
if (typeof item.api_getcount !== "undefined")
resourceDescs.push( rescKeyDesc + ": " + item.api_getcount );
else if (typeof item.api_count !== "undefined")
resourceDescs.push( rescKeyDesc + ": -" + item.api_count );
});
return resourceDescs.join("\n");
};
KC3Node.prototype.defineAsResource = function( nodeData ){
var self = this;
this.type = "resource";
this.item = [];
this.icon = [];
this.amount = [];
if (typeof nodeData.api_itemget == "object" && typeof nodeData.api_itemget.api_id != "undefined") {
nodeData.api_itemget = [nodeData.api_itemget];
}
this.nodeDesc = this.buildItemNodeDesc( nodeData.api_itemget );
nodeData.api_itemget.forEach(function(itemget){
var icon_id = itemget.api_icon_id;
var getcount = itemget.api_getcount;
self.item.push(icon_id);
self.icon.push(function(folder){
return folder+(
["fuel","ammo","steel","bauxite","ibuild","bucket","devmat","compass","","box1","box2","box3"]
[icon_id - 1]
)+".png";
});
self.amount.push(getcount);
if(icon_id < 8)
KC3SortieManager.materialGain[icon_id-1] += getcount;
});
return this;
};
KC3Node.prototype.defineAsBounty = function( nodeData ){
var
self = this,
maps = JSON.parse(localStorage.maps),
ckey = ["m",KC3SortieManager.map_world,KC3SortieManager.map_num].join("");
this.type = "bounty";
this.item = nodeData.api_itemget_eo_comment.api_id;
this.icon = function(folder){
return folder+(
["fuel","ammo","steel","bauxite","ibuild","bucket","devmat","compass"]
[self.item-1]
)+".png";
};
this.nodeDesc = this.buildItemNodeDesc([
{ api_icon_id: nodeData.api_itemget_eo_comment.api_id,
api_getcount: nodeData.api_itemget_eo_comment.api_getcount
}
]);
this.amount = nodeData.api_itemget_eo_comment.api_getcount;
KC3SortieManager.materialGain[this.item-1] += this.amount;
maps[ckey].clear |= (++maps[ckey].kills) >= KC3Meta.gauge(ckey.replace("m",""));
localStorage.maps = JSON.stringify(maps);
return this;
};
KC3Node.prototype.defineAsMaelstrom = function( nodeData ){
this.type = "maelstrom";
this.item = nodeData.api_happening.api_icon_id;
this.icon = function(folder){
return folder+(
["fuel","ammo","steel","bauxite","ibuild","bucket","devmat","compass"]
[nodeData.api_happening.api_icon_id-1]
)+".png";
};
this.nodeDesc = this.buildItemNodeDesc( [nodeData.api_happening] );
this.amount = nodeData.api_happening.api_count;
return this;
};
KC3Node.prototype.defineAsSelector = function( nodeData ){
console.log("defining as selector", nodeData);
this.type = "select";
this.choices = [
KC3Meta.nodeLetter(
KC3SortieManager.map_world,
KC3SortieManager.map_num,
nodeData.api_select_route.api_select_cells[0] ),
KC3Meta.nodeLetter(
KC3SortieManager.map_world,
KC3SortieManager.map_num,
nodeData.api_select_route.api_select_cells[1] )
];
console.log("choices", this.choices);
return this;
};
KC3Node.prototype.defineAsTransport = function( nodeData ){
this.type = "transport";
this.amount = Math.floor(KC3SortieManager.getSortieFleet().map(function(fleetId){
return PlayerManager.fleets[fleetId].ship().map(function(ship){
return ship.obtainTP();
}).reduce(function(pre,cur){ return pre.add(cur); },KC3Meta.tpObtained());
}).reduce(function(pre,cur){ return pre.add(cur); },KC3Meta.tpObtained())
.value);
return this;
};
KC3Node.prototype.defineAsDud = function( nodeData ){
this.type = "";
return this;
};
/* BATTLE FUNCTIONS
---------------------------------------------*/
KC3Node.prototype.engage = function( battleData, fleetSent ){
this.battleDay = battleData;
//console.log("battleData", battleData);
var enemyships = battleData.api_ship_ke;
if(enemyships[0]==-1){ enemyships.splice(0,1); }
var isEnemyCombined = (typeof battleData.api_ship_ke_combined !== "undefined");
var enemyEscortList = battleData.api_ship_ke_combined;
if (typeof enemyEscortList != "undefined") {
if(enemyEscortList[0]==-1){ enemyEscortList.splice(0,1); }
enemyships = enemyships.concat(enemyEscortList);
}
this.eships = enemyships;
// Reserved for combined enemy ships if eships re-assigned on night battle
this.ecships = undefined;
this.eformation = battleData.api_formation[1];
this.eParam = battleData.api_eParam;
if (typeof battleData.api_eParam_combined != "undefined") {
this.eParam = this.eParam.concat(battleData.api_eParam_combined);
}
this.eKyouka = battleData.api_eKyouka || [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1];
this.eSlot = battleData.api_eSlot;
if (typeof battleData.api_eSlot_combined != "undefined") {
this.eSlot = this.eSlot.concat(battleData.api_eSlot_combined);
}
this.supportFlag = (battleData.api_support_flag>0);
if(this.supportFlag){
this.supportInfo = battleData.api_support_info;
this.supportInfo.api_support_flag = battleData.api_support_flag;
}
this.yasenFlag = (battleData.api_midnight_flag>0);
this.originalHPs = battleData.api_nowhps;
this.maxHPs = {
ally: battleData.api_maxhps.slice(1,7),
enemy: battleData.api_maxhps.slice(7,13)
};
if (typeof battleData.api_maxhps_combined != "undefined") {
this.maxHPs.ally = this.maxHPs.ally.concat(battleData.api_maxhps_combined.slice(1,7));
this.maxHPs.enemy = this.maxHPs.enemy.concat(battleData.api_maxhps_combined.slice(7,13));
}
var beginHPs = {
ally: battleData.api_nowhps.slice(1,7),
enemy: battleData.api_nowhps.slice(7,13)
};
if (typeof battleData.api_nowhps_combined != "undefined") {
beginHPs.ally = beginHPs.ally.concat(battleData.api_nowhps_combined.slice(1,7));
beginHPs.enemy = beginHPs.enemy.concat(battleData.api_nowhps_combined.slice(7,13));
}
this.dayBeginHPs = beginHPs;
this.detection = KC3Meta.detection( battleData.api_search[0] );
this.engagement = KC3Meta.engagement( battleData.api_formation[2] );
// LBAS attack phase, including jet plane assault
this.lbasFlag = typeof battleData.api_air_base_attack != "undefined";
if(this.lbasFlag){
// Array of engaged land bases
this.airBaseAttack = battleData.api_air_base_attack;
// No plane from, just injecting from far away air base :)
this.airBaseJetInjection = battleData.api_air_base_injection;
}
// Air phases
var
planePhase = battleData.api_kouku.api_stage1 || {
api_touch_plane:[-1,-1],
api_f_count :0,
api_f_lostcount:0,
api_e_count :0,
api_e_lostcount:0,
},
attackPhase = battleData.api_kouku.api_stage2;
this.fcontactId = planePhase.api_touch_plane[0];
this.fcontact = this.fcontactId > 0 ? KC3Meta.term("BattleContactYes") : KC3Meta.term("BattleContactNo");
this.econtactId = planePhase.api_touch_plane[1];
this.econtact = this.econtactId > 0 ? KC3Meta.term("BattleContactYes") : KC3Meta.term("BattleContactNo");
this.airbattle = KC3Meta.airbattle( planePhase.api_disp_seiku );
if(!!attackPhase && !!attackPhase.api_air_fire){
this.antiAirFire = [ attackPhase.api_air_fire ];
}
// Fighter phase 1
this.planeFighters = {
player:[
planePhase.api_f_count,
planePhase.api_f_lostcount
],
abyssal:[
planePhase.api_e_count,
planePhase.api_e_lostcount
]
};
if(
this.planeFighters.player[0]===0
&& this.planeFighters.abyssal[0]===0
&& attackPhase===null
){
this.airbattle = KC3Meta.airbattle(5);
}
// Bombing phase 1
this.planeBombers = { player:[0,0], abyssal:[0,0] };
if(attackPhase !== null){
this.planeBombers.player[0] = attackPhase.api_f_count;
this.planeBombers.player[1] = attackPhase.api_f_lostcount;
this.planeBombers.abyssal[0] = attackPhase.api_e_count;
this.planeBombers.abyssal[1] = attackPhase.api_e_lostcount;
}
// Fighter phase 2
if(typeof battleData.api_kouku2 != "undefined"){
this.planeFighters.player[1] += battleData.api_kouku2.api_stage1.api_f_lostcount;
this.planeFighters.abyssal[1] += battleData.api_kouku2.api_stage1.api_e_lostcount;
// Bombine phase 2
if(battleData.api_kouku2.api_stage2 !== null){
this.planeBombers.player[1] += battleData.api_kouku2.api_stage2.api_f_lostcount;
this.planeBombers.abyssal[1] += battleData.api_kouku2.api_stage2.api_e_lostcount;
if(!!battleData.api_kouku2.api_stage2.api_air_fire){
if(!this.antiAirFire || this.antiAirFire.length<1){
this.antiAirFire = [null];
}
this.antiAirFire[1] = battleData.api_kouku2.api_stage2.api_air_fire;
}
}
}
// Jet plane phase, happen before fighter attack phase
if(typeof battleData.api_injection_kouku != "undefined"){
var jetPlanePhase = battleData.api_injection_kouku;
this.planeJetFighters = { player:[0,0], abyssal:[0,0] };
this.planeJetBombers = { player:[0,0], abyssal:[0,0] };
this.planeJetFighters.player[0] = jetPlanePhase.api_stage1.api_f_count;
this.planeJetFighters.player[1] = jetPlanePhase.api_stage1.api_f_lostcount;
this.planeJetFighters.abyssal[0] = jetPlanePhase.api_stage1.api_e_count;
this.planeJetFighters.abyssal[1] = jetPlanePhase.api_stage1.api_e_lostcount;
if(!!jetPlanePhase.api_stage2){
this.planeJetBombers.player[0] = jetPlanePhase.api_stage2.api_f_count;
this.planeJetBombers.player[1] = jetPlanePhase.api_stage2.api_f_lostcount;
this.planeJetBombers.abyssal[0] = jetPlanePhase.api_stage2.api_e_count;
this.planeJetBombers.abyssal[1] = jetPlanePhase.api_stage2.api_e_lostcount;
}
// Jet planes consume steels each battle based on:
// pendingConsumingSteel = floor(jetMaster.api_cost * ship.slots[jetIdx] * 0.2)
if(this.planeJetFighters.player[0] > 0
&& (KC3SortieManager.onSortie > 0 || KC3SortieManager.isPvP())){
var consumedSteel = PlayerManager.fleets[
(parseInt(fleetSent) || KC3SortieManager.fleetSent) - 1
].calcJetsSteelCost(KC3SortieManager.sortieName(2));
console.log("Jets consumed steel:", consumedSteel);
}
}
// Boss Debuffed
this.debuffed = typeof battleData.api_boss_damaged != "undefined" ?
(battleData.api_boss_damaged == 1) ? true : false
: false;
var i = 0;
// Battle analysis only if on sortie or PvP, not applied to sortielogs
if(KC3SortieManager.onSortie > 0 || KC3SortieManager.isPvP()){
var PS = window.PS;
var DA = PS["KanColle.DamageAnalysis.FFI"];
var result = null;
var fleet;
var dameConCode;
var shipNum;
var ship;
var fleetId = parseInt(fleetSent) || KC3SortieManager.fleetSent;
var enemyMain, enemyEscort, mainFleet, escortFleet;
// PLAYER SINGLE FLEET
if ((typeof PlayerManager.combinedFleet === "undefined") || (PlayerManager.combinedFleet === 0) || fleetId>1){
// single fleet: not combined, or sent fleet is not first fleet
// Update our fleet
fleet = PlayerManager.fleets[fleetId - 1];
// damecon ignored for PvP
dameConCode = KC3SortieManager.isPvP()
? [0,0,0,0,0,0]
: fleet.getDameConCodes();
var endHPs = {
ally: beginHPs.ally.slice(),
enemy: beginHPs.enemy.slice()
};
// ONLY ENEMY IS COMBINED
if (isEnemyCombined) {
this.ecships = this.eships;
result = DA.analyzeAbyssalCTFBattleJS(dameConCode, battleData);
console.log("only enemy is combined", result);
// Update enemy ships
for (i = 7; i < 13; i++) {
this.enemyHP[i-7] = result.enemyMain[i-7];
endHPs.enemy[i-7] = result.enemyMain[i-7] ? result.enemyMain[i-7].hp : -1;
this.enemySunk[i-7] = result.enemyMain[i-7] ? result.enemyMain[i-7].sunk : true;
}
for (i = 13; i < 19; i++) {
this.enemyHP[i-7] = result.enemyEscort[i-13];
endHPs.enemy[i-7] = result.enemyEscort[i-13] ? result.enemyEscort[i-13].hp : -1;
this.enemySunk[i-7] = result.enemyEscort[i-13] ? result.enemyEscort[i-13].sunk : true;
}
// BOTH SINGLE FLEET
} else {
// regular day-battle
result = DA.analyzeBattleJS(dameConCode, battleData);
console.log("both single fleet", result);
// Update enemy ships
for (i = 7; i < 13; i++) {
this.enemyHP[i-7] = result.enemy[i-7];
endHPs.enemy[i-7] = result.enemy[i-7] ? result.enemy[i-7].hp : -1;
this.enemySunk[i-7] = result.enemy[i-7] ? result.enemy[i-7].sunk : true;
}
}
// update player ships
shipNum = fleet.countShips();
for(i = 0; i < shipNum; i++) {
ship = fleet.ship(i);
ship.afterHp[0] = result.main[i].hp;
this.allyNoDamage &= ship.hp[0]==ship.afterHp[0];
ship.afterHp[1] = ship.hp[1];
endHPs.ally[i] = result.main[i].hp;
// Check if damecon consumed, if yes, get item consumed
if (result.main[i].dameConConsumed){
this.dameConConsumed[i] = ship.findDameCon();
} else {
this.dameConConsumed[i] = false;
}
}
if(ConfigManager.info_btrank
// long distance aerial battle not accurate for now, see #1333
// but go for aerial battle (eventKind:4) possible Yasen
//&& [6].indexOf(this.eventKind)<0
){
this.predictedRank = KC3Node.predictRank( beginHPs, endHPs, battleData.api_name );
// console.debug("Rank Predict:", this.predictedRank);
}
// PLAYER COMBINED FLEET
} else {
dameConCode = PlayerManager.fleets[0].getDameConCodes()
.concat( PlayerManager.fleets[1].getDameConCodes() );
console.assert(dameConCode.length === 12, "dameConCode length should be 12 for combined fleets");
// BOTH COMBINED FLEET
if (isEnemyCombined) {
this.ecships = this.eships;
if (PlayerManager.combinedFleet === 1 || PlayerManager.combinedFleet === 3) {
// Carrier Task Force or Transport Escort
result = DA.analyzeBothCombinedCTFBattleJS(dameConCode,battleData);
console.log("CTF both combined", result);
} else if (PlayerManager.combinedFleet === 2) {
// Surface Task Force
result = DA.analyzeBothCombinedSTFBattleJS(dameConCode,battleData);
console.log("STF both combined", result);
} else {
console.error( "Unknown combined fleet code: " + PlayerManager.combinedFleet );
}
// Update enemy
for(i = 1; i <= 6; i++) {
enemyMain = result.enemyMain[i-1];
if (enemyMain !== null) {
this.enemyHP[i-1] = enemyMain;
this.enemySunk[i-1] = enemyMain.sunk;
}
}
for(i = 1; i <= 6; i++) {
enemyEscort = result.enemyEscort[i-1];
if (enemyEscort !== null) {
this.enemyHP[i+5] = enemyEscort;
this.enemySunk[i+5] = enemyEscort.sunk;
}
}
// Update main fleet
fleet = PlayerManager.fleets[0];
shipNum = fleet.countShips();
mainFleet = result.allyMain;
for(i = 0; i < shipNum; i++) {
ship = fleet.ship(i);
ship.afterHp[0] = mainFleet[i].hp;
this.allyNoDamage &= ship.hp[0]==ship.afterHp[0];
ship.afterHp[1] = ship.hp[1];
// Check if damecon consumed, if yes, get item consumed
if (mainFleet[i].dameConConsumed){
this.dameConConsumed[i] = ship.findDameCon();
} else {
this.dameConConsumed[i] = false;
}
}
// Update escort fleet
fleet = PlayerManager.fleets[1];
shipNum = fleet.countShips();
escortFleet = result.allyEscort;
for(i = 0; i < shipNum; i++) {
ship = fleet.ship(i);
ship.afterHp[0] = escortFleet[i].hp;
this.allyNoDamage &= ship.hp[0]==ship.afterHp[0];
ship.afterHp[1] = ship.hp[1];
// Check if damecon consumed, if yes, get item consumed
if (escortFleet[i].dameConConsumed){
this.dameConConsumedEscort[i] = ship.findDameCon();
} else {
this.dameConConsumedEscort[i] = false;
}
}
// ONLY PLAYER IS COMBINED
} else {
if (PlayerManager.combinedFleet === 1) {
// Carrier Task Force
result = DA.analyzeCTFBattleJS(dameConCode,battleData);
console.log("CTF only player is combined", result);
} else if (PlayerManager.combinedFleet === 2) {
// Surface Task Force
result = DA.analyzeSTFBattleJS(dameConCode,battleData);
console.log("STF only player is combined", result);
} else if (PlayerManager.combinedFleet === 3) {
// Transport Escort
result = DA.analyzeTECFBattleJS(dameConCode,battleData);
console.log("TECF only player is combined", result);
} else {
console.error( "Unknown combined fleet code: " + PlayerManager.combinedFleet );
}
// Update enemy
for(i = 1; i <= 6; i++) {
enemyMain = result.enemy[i-1];
if (enemyMain !== null) {
this.enemyHP[i-1] = enemyMain;
this.enemySunk[i-1] = enemyMain.sunk;
}
}
// Update main fleet
fleet = PlayerManager.fleets[0];
shipNum = fleet.countShips();
mainFleet = result.main;
for(i = 0; i < shipNum; i++) {
ship = fleet.ship(i);
ship.afterHp[0] = mainFleet[i].hp;
this.allyNoDamage &= ship.hp[0]==ship.afterHp[0];
ship.afterHp[1] = ship.hp[1];
// Check if damecon consumed, if yes, get item consumed
if (mainFleet[i].dameConConsumed){
this.dameConConsumed[i] = ship.findDameCon();
} else {
this.dameConConsumed[i] = false;
}
}
// Update escort fleet
fleet = PlayerManager.fleets[1];
shipNum = fleet.countShips();
escortFleet = result.escort;
for(i = 0; i < shipNum; i++) {
ship = fleet.ship(i);
ship.afterHp[0] = escortFleet[i].hp;
this.allyNoDamage &= ship.hp[0]==ship.afterHp[0];
ship.afterHp[1] = ship.hp[1];
// Check if damecon consumed, if yes, get item consumed
if (escortFleet[i].dameConConsumed){
this.dameConConsumedEscort[i] = ship.findDameCon();
} else {
this.dameConConsumedEscort[i] = false;
}
}
}
}
}
if(this.gaugeDamage > -1) {
this.gaugeDamage = Math.min(this.originalHPs[7],this.originalHPs[7] - this.enemyHP[0].hp);
(function(sortieData){
var
maps = localStorage.getObject('maps'),
desg = ['m',sortieData.map_world,sortieData.map_num].join('');
if(this.isBoss() && maps[desg].kind == 'gauge-hp') {
maps[desg].baseHp = maps[desg].baseHp || this.originalHPs[7];
}
localStorage.setObject('maps',maps);
}).call(this,KC3SortieManager);
}
// Record encoutners only if on sortie
if(KC3SortieManager.onSortie > 0) {
this.saveEnemyEncounterInfo(this.battleDay);
}
};
KC3Node.prototype.engageNight = function( nightData, fleetSent, setAsOriginalHP ){
if(typeof setAsOriginalHP == "undefined"){ setAsOriginalHP = true; }
this.battleNight = nightData;
this.startNight = !!fleetSent;
var enemyships = nightData.api_ship_ke;
if(enemyships[0]==-1){ enemyships.splice(0,1); }
var isEnemyCombined = (typeof nightData.api_ship_ke_combined !== "undefined");
this.eships = enemyships;
this.eformation = this.eformation || nightData.api_formation[1];
this.eParam = nightData.api_eParam;
this.eKyouka = nightData.api_eKyouka || [-1,-1,-1,-1,-1,-1];
this.eSlot = nightData.api_eSlot;
this.maxHPs = {
ally: nightData.api_maxhps.slice(1,7),
enemy: nightData.api_maxhps.slice(7,13)
};
if (typeof nightData.api_maxhps_combined != "undefined") {
this.maxHPs.ally = this.maxHPs.ally.concat(nightData.api_maxhps_combined.slice(1,7));
this.maxHPs.enemy = this.maxHPs.enemy.concat(nightData.api_maxhps_combined.slice(7,13));
}
// if we did not started at night, at this point dayBeginHPs should be available
var beginHPs = {
ally: [],
enemy: []
};
if (this.dayBeginHPs) {
beginHPs = this.dayBeginHPs;
} else {
beginHPs.ally = nightData.api_nowhps.slice(1,7);
beginHPs.enemy = nightData.api_nowhps.slice(7,13);
}
if(setAsOriginalHP){
this.originalHPs = nightData.api_nowhps;
}
this.engagement = this.engagement || KC3Meta.engagement( nightData.api_formation[2] );
this.fcontactId = nightData.api_touch_plane[0]; // masterId of slotitem, starts from 1
this.fcontact = this.fcontactId > 0 ? KC3Meta.term("BattleContactYes") : KC3Meta.term("BattleContactNo");
this.econtactId = nightData.api_touch_plane[1];
this.econtact = this.econtactId > 0 ? KC3Meta.term("BattleContactYes") : KC3Meta.term("BattleContactNo");
this.flarePos = nightData.api_flare_pos[0]; // Star shell user pos 1-6
this.eFlarePos = nightData.api_flare_pos[1]; // PvP opponent only, abyss star shell not existed yet
var PS = window.PS;
var DA = PS["KanColle.DamageAnalysis.FFI"];
var result = null;
var i = 0;
var fleet;
var dameConCode;
var shipNum;
var ship;
var fleetId = parseInt(fleetSent) || KC3SortieManager.fleetSent;
var endHPs = {
ally: beginHPs.ally.slice(),
enemy: beginHPs.enemy.slice()
};
// PLAYER COMBINED FLEET
if (PlayerManager.combinedFleet && (fleetId <= 1)) {
// player combined fleet yasen, escort always fleet #2
fleet = PlayerManager.fleets[1];
dameConCode = fleet.getDameConCodes();
// BOTH COMBINED FLEET
if (isEnemyCombined) {
// still needs 12-element array for dameConCode
if (dameConCode.length < 7) {
dameConCode = dameConCode.concat([0,0,0,0,0,0]);
}
console.log("dameConCode", dameConCode);
result = DA.analyzeBothCombinedNightBattleJS(dameConCode, nightData);
console.log("player combined", "enemy combined", result);
// enemy info, enemy main fleet in yasen
if (nightData.api_active_deck[1] == 1) {
console.log("enemy main fleet in yasen", result.enemyMain);
for (i = 7; i < 13; i++) {
this.enemyHP[i-7] = result.enemyMain[i-7];
endHPs.enemy[i-7] = result.enemyMain[i-7] ? result.enemyMain[i-7].hp : -1;
this.enemySunk[i-7] = result.enemyMain[i-7] ? result.enemyMain[i-7].sunk : true;
}
// enemy info, enemy escort fleet in yasen
} else {
console.log("enemy escort fleet in yasen", result.enemyEscort);
enemyships = nightData.api_ship_ke_combined;
if(enemyships[0]==-1){ enemyships.splice(0,1); }
this.eships = enemyships;
this.eParam = nightData.api_eParam_combined;
this.eSlot = nightData.api_eSlot_combined;
for (i = 7; i < 13; i++) {
this.enemyHP[i-7] = result.enemyEscort[i-7];
endHPs.enemy[i-7] = result.enemyEscort[i-7] ? result.enemyEscort[i-7].hp : -1;
this.enemySunk[i-7] = result.enemyEscort[i-7] ? result.enemyEscort[i-7].sunk : true;
}
}
// player fleet
shipNum = fleet.countShips();
for(i = 0; i < shipNum; i++) {
ship = fleet.ship(i);
ship.hp = [ship.afterHp[0], ship.afterHp[1]];
ship.morale = Math.max(0,Math.min(100,ship.morale+(fleetSent ? 1 : -3 )));
ship.afterHp[0] = result.allyEscort[i].hp;
this.allyNoDamage &= ship.hp[0]==ship.afterHp[0];
ship.afterHp[1] = ship.hp[1];
endHPs.ally[i] = result.allyEscort[i].hp;
}
// ONLY PLAYER IS COMBINED
} else {
// only player is combined fleet
result = DA.analyzeCombinedNightBattleJS(dameConCode, nightData);
console.log("player combined", "enemy single", result);
// update enemy info
for (i = 7; i < 13; i++) {
this.enemyHP[i-7] = result.enemy[i-7];
endHPs.enemy[i-7] = result.enemy[i-7] ? result.enemy[i-7].hp : -1;
this.enemySunk[i-7] = result.enemy[i-7] ? result.enemy[i-7].sunk : true;
}
// player fleet
shipNum = fleet.countShips();
for(i = 0; i < shipNum; i++) {
ship = fleet.ship(i);
ship.hp = [ship.afterHp[0], ship.afterHp[1]];
ship.morale = Math.max(0,Math.min(100,ship.morale+(fleetSent ? 1 : -3 )));
ship.afterHp[0] = result.main[i].hp;
this.allyNoDamage &= ship.hp[0]==ship.afterHp[0];
ship.afterHp[1] = ship.hp[1];
endHPs.ally[i] = result.main[i].hp;
}
}
// PLAYER SINGLE FLEET
} else {
fleet = PlayerManager.fleets[fleetId - 1];
// damecon ignored for PvP
dameConCode = KC3SortieManager.isPvP() ? [0,0,0, 0,0,0] : fleet.getDameConCodes();
// ONLY ENEMY IS COMBINED
if (isEnemyCombined) {
// enemy combined fleet
result = DA.analyzeAbyssalCTFNightBattleJS(dameConCode, nightData);
console.log("player single", "enemy combined", result);
// enemy info, enemy main fleet in yasen
if (nightData.api_active_deck[1] == 1) {
console.log("enemy main fleet in yasen", result.enemyMain);
for (i = 7; i < 13; i++) {
this.enemyHP[i-7] = result.enemyMain[i-7];
endHPs.enemy[i-7] = result.enemyMain[i-7] ? result.enemyMain[i-7].hp : -1;
this.enemySunk[i-7] = result.enemyMain[i-7] ? result.enemyMain[i-7].sunk : true;
}
// enemy info, enemy escort fleet in yasen
} else {
console.log("enemy escort fleet in yasen", result.enemyEscort);
enemyships = nightData.api_ship_ke_combined;
if(enemyships[0]==-1){ enemyships.splice(0,1); }
this.eships = enemyships;
this.eParam = nightData.api_eParam_combined;
this.eSlot = nightData.api_eSlot_combined;
for (i = 7; i < 13; i++) {
this.enemyHP[i-7] = result.enemyEscort[i-7];
endHPs.enemy[i-7] = result.enemyEscort[i-7] ? result.enemyEscort[i-7].hp : -1;
this.enemySunk[i-7] = result.enemyEscort[i-7] ? result.enemyEscort[i-7].sunk : true;
}
}
// BOTH SINGLE FLEET
} else {
// regular yasen
result = DA.analyzeNightBattleJS(dameConCode, nightData);
console.log("player single", "enemy single", result);
// regular yasen enemy info
for (i = 7; i < 13; i++) {
this.enemyHP[i-7] = result.enemy[i-7];
endHPs.enemy[i-7] = result.enemy[i-7] ? result.enemy[i-7].hp : -1;
this.enemySunk[i-7] = result.enemy[i-7] ? result.enemy[i-7].sunk : true;
}
}
// regular yasen fleet info
shipNum = fleet.countShips();
for(i = 0; i < shipNum; i++) {
ship = fleet.ship(i);
ship.hp = [ship.afterHp[0], ship.afterHp[1]];
ship.morale = Math.max(0,Math.min(100,ship.morale+(fleetSent ? 1 : -3 )));
ship.afterHp[0] = result.main[i].hp;
this.allyNoDamage &= ship.hp[0]==ship.afterHp[0];
ship.afterHp[1] = ship.hp[1];
endHPs.ally[i] = result.main[i].hp;
}
}
console.log("enemyHP", this.enemyHP);
console.log("enemySunk", this.enemySunk);
if(ConfigManager.info_btrank){
this.predictedRankNight = KC3Node.predictRank( beginHPs, endHPs );
// console.debug("Rank Predict (Night):", this.predictedRankNight);
}
if(this.gaugeDamage > -1
&& (!isEnemyCombined || nightData.api_active_deck[1] == 1) ){
this.gaugeDamage = this.gaugeDamage +
Math.min(nightData.api_nowhps[7],nightData.api_nowhps[7] - this.enemyHP[0].hp);
}
// Record encoutners only if on sortie and starts from night
if(this.startNight && KC3SortieManager.onSortie > 0) {
this.saveEnemyEncounterInfo(this.battleNight);
}
};
KC3Node.prototype.night = function( nightData ){
this.engageNight(nightData, null, false);
};
KC3Node.prototype.results = function( resultData ){
try {
this.rating = resultData.api_win_rank;
this.nodalXP = resultData.api_get_base_exp;
if(this.allyNoDamage && this.rating === "S")
this.rating = "SS";
console.log("This battle, the ally fleet has no damage:",this.allyNoDamage);
if(this.isBoss()) {
var
maps = localStorage.getObject('maps'),
ckey = ["m",KC3SortieManager.map_world,KC3SortieManager.map_num].join(""),
stat = maps[ckey].stat,
srid = KC3SortieManager.onSortie;
/* DESPAIR STATISTICS ==> */
if(stat) {
var
fs = [this.gaugeDamage,this.originalHPs[7]],
pt = 'dummy',
sb = stat.onBoss,
oc = 0;
fs.push(fs[0]/fs[1]);
fs.push(fs[1]-fs[0]);
switch(true){
case (fs[0] === 0): pt = 'fresh'; break;
case (fs[2] < 0.25): pt = 'graze'; break;
case (fs[2] < 0.50): pt = 'light'; break;
case (fs[2] < 0.75): pt = 'modrt'; break;
case (fs[3] > 9): pt = 'heavy'; break;
case (fs[3] > 1): pt = 'despe'; break;
case (fs[3] == 1): pt = 'endur'; break;
case (fs[3] < 1): pt = 'destr'; break;
}
sb[pt].push(srid);
oc = sb[pt].length;
console.info('Current sortie recorded as',pt);
console.info('You\'ve done this',oc,'time'+(oc != 1 ? 's' : '')+'.','Good luck, see you next time!');
}
/* ==> DESPAIR STATISTICS */
/* FLAGSHIP ATTACKING ==> */
console.log("Damaged Flagship",this.gaugeDamage,"/",maps[ckey].curhp || 0,"pts");
switch(maps[ckey].kind) {
case 'single': /* Single Victory */
break;
case 'multiple': /* Kill-based */
if((KC3Meta.gauge(ckey.replace("m","")) - (maps[ckey].kills || 0)) > 0)
maps[ckey].kills += resultData.api_destsf;
break;
case 'gauge-hp': /* HP-Gauge */
if((this.gaugeDamage >= 0) && (maps[ckey].curhp || 0) > 0) {
maps[ckey].curhp -= this.gaugeDamage;
if(maps[ckey].curhp <= 0) // if last kill -- check whether flagship is killed or not -- flagship killed = map clear
maps[ckey].curhp = 1-(maps[ckey].clear = resultData.api_destsf);
}
break;
case 'gauge-tp': /* TP-Gauge */
/* TP Gauge */
if (typeof resultData.api_landing_hp != "undefined") {
var TPdata = resultData.api_landing_hp;
this.gaugeDamage = Math.min(TPdata.api_now_hp,TPdata.api_sub_value);
maps[ckey].curhp = TPdata.api_now_hp - this.gaugeDamage;
maps[ckey].maxhp = TPdata.api_max_hp - 0;
} else {
maps[ckey].curhp = 0;
}
console.log("Landing get",this.gaugeDamage,"->",maps[ckey].curhp,"/",maps[ckey].maxhp,"TP");
break;
default: /* Undefined */
break;
}
maps[ckey].clear |= resultData.api_first_clear; // obtaining clear once
if(stat) {
stat.onBoss.hpdat[srid] = [maps[ckey].curhp,maps[ckey].maxhp];
if(resultData.api_first_clear)
stat.onClear = srid; // retrieve sortie ID for first clear mark
}
/* ==> FLAGSHIP ATTACKING */
localStorage.setObject('maps',maps);
}
var
ship_get = [];
if(typeof resultData.api_get_ship != "undefined"){
this.drop = resultData.api_get_ship.api_ship_id;
KC3ShipManager.pendingShipNum += 1;
KC3GearManager.pendingGearNum += KC3Meta.defaultEquip(this.drop);
console.log("Drop " + resultData.api_get_ship.api_ship_name + " (" + this.drop + ") Equip " + KC3Meta.defaultEquip(this.drop));
ship_get.push(this.drop);
}else{
this.drop = 0;
}
/*
api_get_eventitem :海域攻略報酬 イベント海域突破時のみ存在
api_type :報酬種別 1=アイテム, 2=艦娘, 3=装備
api_id :ID
api_value :個数?
*/
(function(resultEventItems){
console.log("event result",resultEventItems);
(resultEventItems || []).forEach(function(eventItem){
switch(eventItem.api_type){
case 1: // Item
if(eventItem.api_id.inside(1,4)) {
KC3SortieManager.materialGain[eventItem.api_id+3] += eventItem.api_value;
}
break;
case 2: // Ship
ship_get.push(eventItem.api_id);
break;
case 3: // Equip
break;
default:
console.log("unknown type",eventItem);
break;
}
});
}).call(this,resultData.api_get_eventitem);
ConfigManager.loadIfNecessary();
ship_get.forEach(function(newShipId){
var wish_kind = ["salt","wish"];
wish_kind.some(function(wishType){
var
wish_key = [wishType,'list'].join('_'),
wish_id = ConfigManager[wish_key].indexOf(newShipId)+1;
if(wish_id){
ConfigManager[wish_key].splice(wish_id-1,1);
console.warn("Removed",KC3Meta.shipName(KC3Master.ship(newShipId).api_name),"from",wishType,"list");
ConfigManager.lock_prep.push(newShipId);
return true;
} else {
return false;
}
});
});
ConfigManager.save();
this.mvps = [resultData.api_mvp || 0,resultData.api_mvp_combined || 0].filter(function(x){return !!x;});
var
lostCheck = (resultData.api_lost_flag) ?
[resultData.api_lost_flag,null] : /* if api_lost_flag is explicitly specified */
[resultData.api_get_ship_exp,resultData.api_get_ship_exp_combined].map(function(expData,fleetId){
return expData ? expData.slice(1) : []; // filter out first dummy element, be aware for undefined item
}).map(function(expData,fleetId){
/* Example data:
"api_get_ship_exp":[-1,420,140,140,140,-1,-1],
"api_get_exp_lvup":[[177,300,600],[236,300,600],[118,300],[118,300]],
"api_get_ship_exp_combined":[-1,420,140,140,-1,-1,-1],
"api_get_exp_lvup_combined":[[177,300,600],[236,300,600],[118,300],[118,300]]
Logic :
- for ship_exp indices, start from 1.
- compare ship_exp data, check it if -1
- (fail condition) ignore, set as non-sink and skip to next one
- compare the current index with the neighboring array (exp_lvup),
check if an array exists on that index
- if it exists, mark as sunk
Source: https://gitter.im/KC3Kai/Public?at=5662e448c15bca7e3c96376f
*/
return expData.map(function(data,slotId){
return (data == -1) && !!resultData[['api_get','exp_lvup','combined'].slice(0,fleetId+2).join('_')][slotId];
});
}),
fleetDesg = [KC3SortieManager.fleetSent - 1,1]; // designated fleet (fleet mapping)
this.lostShips = lostCheck.map(function(lostFlags,fleetNum){
console.log("lostFlags",fleetNum, lostFlags);
return (lostFlags || []).filter(function(x){return x>=0;}).map(function(checkSunk,rosterPos){
if(!!checkSunk) {
var rtv = PlayerManager.fleets[fleetDesg[fleetNum]].ships[rosterPos];
if(KC3ShipManager.get(rtv).didFlee) return 0;
console.log("このクソ提督、深海に%c%s%cが沈んだ (ID:%d)",
'color:red,font-weight:bold',
KC3ShipManager.get(rtv).master().api_name,
'color:initial,font-weight:initial',
rtv
);
return rtv;
} else {
return 0;
}
}).filter(function(shipId){return shipId;});
});
//var enemyCVL = [510, 523, 560];
//var enemyCV = [512, 525, 528, 565, 579];
//var enemySS = [530, 532, 534, 531, 533, 535, 570, 571, 572];
//var enemyAP = [513, 526, 558];
var eshipCnt = (this.ecships || []).length || 6;
for(var i = 0; i < eshipCnt; i++) {
if (this.enemySunk[i]) {
var enemyShip = KC3Master.ship( (this.ecships || this.eships)[i] );
if (!enemyShip) {
console.log("Cannot find enemy " + this.eships[i]);
} else if (this.eships[i] < 500) {
console.log("Enemy ship is not Abyssal!");
} else {
switch(enemyShip.api_stype) {
case 7: // 7 = CVL
case 11: // 11 = CV
console.log("You sunk a CV"+((enemyShip.api_stype==7)?"L":""));
KC3QuestManager.get(217).increment();
KC3QuestManager.get(211).increment();
KC3QuestManager.get(220).increment();
break;
case 13: // 13 = SS
console.log("You sunk a SS");
KC3QuestManager.get(230).increment();
KC3QuestManager.get(228).increment();
break;
case 15: // 15 = AP
console.log("You sunk a AP");
KC3QuestManager.get(218).increment();
KC3QuestManager.get(212).increment();
KC3QuestManager.get(213).increment();
KC3QuestManager.get(221).increment();
break;
}
}
}
}
// Save enemy deck name for encounter
var name = resultData.api_enemy_info.api_deck_name;
if(KC3SortieManager.onSortie > 0 && !!name){
this.saveEnemyEncounterInfo(null, name);
}
} catch (e) {
console.error("Captured an exception ==>", e,"\n==> proceeds safely");
} finally {
this.saveBattleOnDB(resultData);
}
};
KC3Node.prototype.resultsPvP = function( resultData ){
try {
this.rating = resultData.api_win_rank;
this.nodalXP = resultData.api_get_base_exp;
if(this.allyNoDamage && this.rating === "S")
this.rating = "SS";
this.mvps = [resultData.api_mvp || 0];
} catch (e) {
console.error("Captured an exception ==>", e,"\n==> proceeds safely");
} finally {
this.savePvPOnDB(resultData);
}
};
/**
* Builds a complex long message for results of Exped/LBAS support attack,
* Used as a tooltip by devtools panel or SRoom Maps History for now.
* return a empty string if no any support triggered.
*/
KC3Node.prototype.buildSupportAttackMessage = function(){
var thisNode = this;
var supportTips = "";
if(thisNode.supportFlag && !!thisNode.supportInfo){
var fleetId = "", supportDamage = 0;
var attackType = thisNode.supportInfo.api_support_flag;
if(attackType === 1){
var airatack = thisNode.supportInfo.api_support_airatack;
fleetId = airatack.api_deck_id;
supportDamage = !airatack.api_stage3 ? 0 :
Math.floor(airatack.api_stage3.api_edam.slice(1).reduce(function(a,b){return a+b;},0));
// Support air attack has the same structure with kouku/LBAS
// So disp_seiku, plane xxx_count are also possible to be displayed
// Should break BattleSupportTips into another type for air attack
} else if([2,3].indexOf(attackType) > -1){
var hourai = thisNode.supportInfo.api_support_hourai;
fleetId = hourai.api_deck_id;
supportDamage = !hourai.api_damage ? 0 :
Math.floor(hourai.api_damage.slice(1).reduce(function(a,b){return a+b;},0));
}
supportTips = KC3Meta.term("BattleSupportTips").format(fleetId, KC3Meta.support(attackType), supportDamage);
}
var lbasTips = "";
if(thisNode.lbasFlag && !!thisNode.airBaseAttack){
if(!!thisNode.airBaseJetInjection){
var jet = thisNode.airBaseJetInjection;
var jetStage2 = jet.api_stage2 || {};
var jetPlanes = jet.api_stage1.api_f_count;
var jetShotdown = jet.api_stage1.api_e_lostcount + (jetStage2.api_e_lostcount || 0);
var jetDamage = !jet.api_stage3 ? 0 :
Math.floor(jet.api_stage3.api_edam.slice(1).reduce(function(a,b){return a+b;},0));
jetDamage += !jet.api_stage3_combined ? 0 :
Math.floor(jet.api_stage3_combined.api_edam.slice(1).reduce(function(a,b){return a+b;},0));
var jetLost = jet.api_stage1.api_f_lostcount + (jetStage2.api_f_lostcount || 0);
var jetEnemyPlanes = jet.api_stage1.api_e_count;
if(jetEnemyPlanes > 0) {
jetShotdown = "{0:eLostCount} / {1:eTotalCount}".format(jetShotdown, jetEnemyPlanes);
}
lbasTips += KC3Meta.term("BattleLbasJetSupportTips").format(jetPlanes, jetShotdown, jetDamage, jetLost);
}
$.each(thisNode.airBaseAttack, function(i, ab){
var baseId = ab.api_base_id;
var stage2 = ab.api_stage2 || {};
var airBattle = KC3Meta.airbattle(ab.api_stage1.api_disp_seiku)[2];
airBattle += ab.api_stage1.api_touch_plane[0] > 0 ? "+" + KC3Meta.term("BattleContact") : "";
var planes = ab.api_stage1.api_f_count;
var shotdown = ab.api_stage1.api_e_lostcount + (stage2.api_e_lostcount || 0);
var damage = !ab.api_stage3 ? 0 :
Math.floor(ab.api_stage3.api_edam.slice(1).reduce(function(a,b){return a+b;},0));
damage += !ab.api_stage3_combined ? 0 :
Math.floor(ab.api_stage3_combined.api_edam.slice(1).reduce(function(a,b){return a+b;},0));
var lost = ab.api_stage1.api_f_lostcount + (stage2.api_f_lostcount || 0);
var enemyPlanes = ab.api_stage1.api_e_count;
if(enemyPlanes > 0) {
shotdown = "{0:eLostCount} / {1:eTotalCount}".format(shotdown, enemyPlanes);
}
if(!!lbasTips) { lbasTips += "\n"; }
lbasTips += KC3Meta.term("BattleLbasSupportTips").format(planes, baseId, shotdown, damage, lost, airBattle);
});
if(!!supportTips && !!lbasTips) { supportTips += "\n"; }
}
return supportTips + lbasTips;
};
/**
* Builds a complex long message for results of AACI fire,
* Used as a tooltip by devtools panel or SRoom Maps History for now.
* return a empty string if no any AACI triggered.
*/
KC3Node.prototype.buildAntiAirCutinMessage = function(){
var thisNode = this;
var aaciTips = "";
if(!!thisNode.antiAirFire && thisNode.antiAirFire.length > 0){
thisNode.antiAirFire.forEach(function(fire){
if(!!fire){
var fireShipPos = fire.api_idx; // starts from 0
// fireShipPos = [0,5]: in normal fleet or main fleet
// fireShipPos = [6,11]: in escort fleet
if(fireShipPos >= 0 && fireShipPos < 12){
var sentFleet = PlayerManager.fleets[fireShipPos >= 6 ? 1 : KC3SortieManager.fleetSent-1];
var shipName = KC3ShipManager.get(sentFleet.ships[fireShipPos % 6]).name();
aaciTips += (!!aaciTips ? "\n" : "") + shipName;
var aaciType = AntiAir.AACITable[fire.api_kind];
if(!!aaciType){
aaciTips += "\n[{0}] +{1} (x{2})"
.format(aaciType.id, aaciType.fixed, aaciType.modifier);
}
}
var itemList = fire.api_use_items;
if(!!itemList && itemList.length > 0){
for(var itemIdx = 0; itemIdx < Math.min(itemList.length,4); itemIdx++) {
if(itemList[itemIdx] > -1) aaciTips += "\n" +
KC3Meta.gearName(KC3Master.slotitem(itemList[itemIdx]).api_name);
}
}
}
});
}
return aaciTips;
};
/**
* Not real battle on this node in fact. Enemy raid just randomly occurs before entering node.
* See: http://kancolle.wikia.com/wiki/Land-Base_Aerial_Support#Enemy_Raid
*/
KC3Node.prototype.airBaseRaid = function( battleData ){
this.battleDestruction = battleData;
console.log("AirBaseRaidBattle", battleData);
this.lostKind = battleData.api_lost_kind;
this.eships = battleData.api_ship_ke.slice(1);
this.eformation = battleData.api_formation[1];
this.eSlot = battleData.api_eSlot;
this.engagement = KC3Meta.engagement(battleData.api_formation[2]);
var planePhase = battleData.api_air_base_attack.api_stage1 || {
api_touch_plane:[-1,-1],
api_f_count :0,
api_f_lostcount:0,
api_e_count :0,
api_e_lostcount:0,
},
attackPhase = battleData.api_air_base_attack.api_stage2,
bomberPhase = battleData.api_air_base_attack.api_stage3;
this.fplaneFrom = battleData.api_air_base_attack.api_plane_from[0];
this.fcontactId = planePhase.api_touch_plane[0];
this.fcontact = this.fcontactId > 0 ? KC3Meta.term("BattleContactYes") : KC3Meta.term("BattleContactNo");
this.eplaneFrom = battleData.api_air_base_attack.api_plane_from[1];
this.econtactId = planePhase.api_touch_plane[1];
this.econtact = this.econtactId > 0 ? KC3Meta.term("BattleContactYes") : KC3Meta.term("BattleContactNo");
this.airbattle = KC3Meta.airbattle(planePhase.api_disp_seiku);
this.planeFighters = {
player:[
planePhase.api_f_count,
planePhase.api_f_lostcount
],
abyssal:[
planePhase.api_e_count,
planePhase.api_e_lostcount
]
};
if(
this.planeFighters.player[0]===0
&& this.planeFighters.abyssal[0]===0
&& attackPhase===null
){
this.airbattle = KC3Meta.airbattle(5);
}
this.planeBombers = { player:[0,0], abyssal:[0,0] };
if(attackPhase !== null){
this.planeBombers.player[0] = attackPhase.api_f_count;
this.planeBombers.player[1] = attackPhase.api_f_lostcount;
this.planeBombers.abyssal[0] = attackPhase.api_e_count;
this.planeBombers.abyssal[1] = attackPhase.api_e_lostcount;
}
this.baseDamage = bomberPhase && bomberPhase.api_fdam ? Math.floor(
bomberPhase.api_fdam.slice(1).reduce(function(a,b){return a+b;},0)
) : 0;
};
KC3Node.prototype.isBoss = function(){
// Normal BOSS node starts from day battle
return (this.eventKind === 1 && this.eventId === 5)
// Combined BOSS node, see advanceNode()@SortieManager.js
|| (this.eventKind === 5 && this.eventId === 5);
};
KC3Node.prototype.saveEnemyEncounterInfo = function(battleData, updatedName){
// Update name only if new name offered
if(!battleData && !!updatedName){
if(!!this.enemyEncounter){
this.enemyEncounter.name = updatedName;
KC3Database.Encounter(this.enemyEncounter, false);
return true;
}
return false;
}
// Validate map values
if(KC3SortieManager.map_world < 1){ return false; }
if(KC3SortieManager.map_num < 1){ return false; }
// Save the enemy encounter
var ed = {
world: KC3SortieManager.map_world,
map: KC3SortieManager.map_num,
diff: KC3SortieManager.map_difficulty,
node: this.id,
form: this.eformation,
ke: JSON.stringify(this.eships)
};
ed.uniqid = [ed.world,ed.map,ed.diff,ed.node,ed.form,ed.ke]
.filter(function(v){return !!v;}).join("/");
KC3Database.Encounter(ed, true);
this.enemyEncounter = ed;
var i, enemyId;
// Save enemy info
for(i = 0; i < 6; i++) {
enemyId = this.eships[i] || -1;
// Only record ships with ID more than 500 coz abyss only
if (enemyId > 500) {
KC3Database.Enemy({
id: enemyId,
hp: battleData.api_maxhps[i+7],
fp: battleData.api_eParam[i][0],
tp: battleData.api_eParam[i][1],
aa: battleData.api_eParam[i][2],
ar: battleData.api_eParam[i][3],
eq1: battleData.api_eSlot[i][0],
eq2: battleData.api_eSlot[i][1],
eq3: battleData.api_eSlot[i][2],
eq4: battleData.api_eSlot[i][3]
});
}
}
// Save combined enemy info
if(this.eships.length > 6) {
for(i = 6; i < 13; i++) {
enemyId = this.eships[i] || -1;
if (enemyId > 500) {
KC3Database.Enemy({
id: enemyId,
hp: battleData.api_maxhps_combined[i+1],
fp: battleData.api_eParam_combined[i-6][0],
tp: battleData.api_eParam_combined[i-6][1],
aa: battleData.api_eParam_combined[i-6][2],
ar: battleData.api_eParam_combined[i-6][3],
eq1: battleData.api_eSlot_combined[i-6][0],
eq2: battleData.api_eSlot_combined[i-6][1],
eq3: battleData.api_eSlot_combined[i-6][2],
eq4: battleData.api_eSlot_combined[i-6][3]
});
}
}
}
return true;
};
KC3Node.prototype.saveBattleOnDB = function( resultData ){
KC3Database.Battle({
sortie_id: (this.sortie || KC3SortieManager.onSortie || 0),
node: this.id,
enemyId: (this.epattern || 0),
data: (this.battleDay || {}),
yasen: (this.battleNight || {}),
airRaid: (this.battleDestruction || {}),
rating: this.rating,
drop: this.drop,
time: this.stime,
baseEXP: this.nodalXP,
hqEXP: resultData.api_get_exp || 0,
shizunde: this.lostShips.map(function(fleetLost){
return fleetLost.map(function(shipSunk){
return KC3ShipManager.get(shipSunk).masterId;
});
}),
mvp: this.mvps
});
};
KC3Node.prototype.savePvPOnDB = function( resultData ){
console.log("savePvPOnDB", KC3SortieManager);
KC3Database.PvP({
fleet: PlayerManager.fleets[KC3SortieManager.fleetSent-1].sortieJson(),
enemy: [],
data: (this.battleDay || {}),
yasen: (this.battleNight || {}),
rating: this.rating,
baseEXP: this.nodalXP,
mvp: this.mvps,
time: KC3SortieManager.sortieTime
});
};
})();
| Refine comments & docs
| src/library/objects/Node.js | Refine comments & docs | <ide><path>rc/library/objects/Node.js
<ide> this.isPvP = false;
<ide> };
<ide>
<del> // static function. predicts battle rank,
<del> // arguments are beginHPs, endHPs in following structure:
<del> // { ally: [array of hps]
<del> // , enemy: [array of hps]
<del> // }
<del> // arrays are all begins at 0
<del>
<add> /**
<add> // Return predicted battle rank letter. Static function.
<add> // @param beginHPs, endHPs in following structure:
<add> // { ally: [array of hps],
<add> // enemy: [array of hps]
<add> // }
<add> // arrays are all begins at 0.
<add> // @param battleName - optional, the API call name invoked currently
<add> */
<ide> KC3Node.predictRank = function(beginHPs, endHPs, battleName) {
<ide> console.assert(
<ide> beginHPs.ally.length === endHPs.ally.length,
<ide> beginHPs.enemy.length === endHPs.enemy.length,
<ide> "enemy data length mismatched");
<ide>
<del> // removes "-1"s in begin HPs
<add> // Removes "-1"s in begin HPs
<ide> // also removes data from same position
<ide> // in end HPs
<ide> // in addition, negative end HP values are set to 0
<ide> enemyBeginHP += beginHPs.enemy[i];
<ide> }
<ide>
<del> // related comments:
<add> // Related comments:
<ide> // - https://github.com/KC3Kai/KC3Kai/issues/728#issuecomment-139681987
<ide> // - https://github.com/KC3Kai/KC3Kai/issues/1766#issuecomment-275883784
<del> // - Regular battle rules: https://github.com/andanteyk/ElectronicObserver/blob/master/ElectronicObserver/Other/Information/kcmemo.md#%E6%88%A6%E9%97%98%E5%8B%9D%E5%88%A9%E5%88%A4%E5%AE%9A
<del> // the flooring behavior is intended and important.
<del> // please do not change it unless it's proved to be more accurate than
<add> // - https://github.com/andanteyk/ElectronicObserver/blob/master/ElectronicObserver/Other/Information/kcmemo.md#%E6%88%A6%E9%97%98%E5%8B%9D%E5%88%A9%E5%88%A4%E5%AE%9A
<add> // The flooring behavior is intended and important.
<add> // Please do not change it unless it's proved to be more accurate than
<ide> // the formula referred to by the comments above.
<ide> var allyGaugeRate = Math.floor(allyGauge / allyBeginHP * 100);
<ide> var enemyGaugeRate = Math.floor(enemyGauge / enemyBeginHP * 100);
<ide>
<ide> // For long distance air raid
<ide> if ( (battleName||"").indexOf("ld_airbattle") >-1 ) {
<del> // reference:
<add> // Based on long distance air raid rules from:
<add> // https://github.com/andanteyk/ElectronicObserver/blob/master/ElectronicObserver/Other/Information/kcmemo.md#%E9%95%B7%E8%B7%9D%E9%9B%A2%E7%A9%BA%E8%A5%B2%E6%88%A6%E3%81%A7%E3%81%AE%E5%8B%9D%E5%88%A9%E5%88%A4%E5%AE%9A
<add> // Also referenced:
<ide> // - http://kancolle.wikia.com/wiki/Events/Mechanics (as of 2017-01-28)
<ide> // - http://nga.178.com/read.php?tid=8989155
<del> // - Long distance air raid rules: https://github.com/andanteyk/ElectronicObserver/blob/master/ElectronicObserver/Other/Information/kcmemo.md#%E9%95%B7%E8%B7%9D%E9%9B%A2%E7%A9%BA%E8%A5%B2%E6%88%A6%E3%81%A7%E3%81%AE%E5%8B%9D%E5%88%A9%E5%88%A4%E5%AE%9A
<ide> return (allyGauge === 0) ? "SS"
<ide> : (allyGaugeRate < 10) ? "A"
<ide> : (allyGaugeRate < 20) ? "B" |
|
JavaScript | lgpl-2.1 | fccce4f4b987b269f6b6b25230aa05bac95b3311 | 0 | kernelci/kernelci-frontend,kernelci/kernelci-frontend,kernelci/kernelci-frontend,kernelci/kernelci-frontend | function emptyTableOnError (tableId, colspan) {
'use strict';
var localId = tableId;
if (tableId[0] !== '#') {
localId = '#' + tableId;
}
$(localId).empty().append(
'<tr><td colspan="' + colspan +
'" align="center" valign="middle">' +
'<h4>Error loading data.</h4></td></tr>'
);
}
$(document).ready(function () {
'use strict';
$('#li-home').addClass('active');
$('body').tooltip({
'selector': '[rel=tooltip]',
'placement': 'auto'
});
$('.clickable-table tbody').on("click", "tr", function () {
var url = $(this).data('url');
if (url) {
window.location = url;
}
});
});
$(document).ready(function () {
'use strict';
var errorReason = '',
ajaxDeferredCall = null;
function countFailCallback () {
$('.fail-badge').each(function () {
$(this).empty().append('∞');
});
}
function countDoneCallback(data) {
var localData = data.result,
len = localData.length,
i = 0,
batchResult = null;
if (len > 0) {
if (len === 1) {
$('#fail-count0').empty().append(localData[0].count);
} else {
for (i; i < len; i++) {
batchResult = localData[i].result[0];
$(localData[i].operation_id).empty().append(
batchResult.count
);
}
}
} else {
countFailCallback();
}
}
function countFailedDefconfigs(data) {
var localData = data.result,
i = 0,
len = localData.length,
deferredCall = null,
batchQueries = new Array(len);
if (len > 0) {
if (len === 1) {
errorReason = 'Defconfig data call failed.';
// Peform normal GET.
deferredCall = $.ajax({
'url': '/_ajax/count/defconfig',
'traditional': true,
'cache': true,
'dataType': 'json',
'data': {
'status': 'FAIL',
'job': localData[0].job,
'kernel': localData[0].kernel
},
'beforeSend': function(jqXHR) {
setXhrHeader(jqXHR);
},
'error': function() {
countFailCallback();
},
'timeout': 6000,
'statusCode': {
403: function() {
setErrorAlert('batch-403-error', 403, errorReason);
},
404: function () {
setErrorAlert('batch-404-error', 404, errorReason);
},
408: function () {
errorReason = 'Defconfing data call failed: timeout.';
setErrorAlert('batch-408-error', 408, errorReason);
},
500: function () {
setErrorAlert('batch-500-error', 500, errorReason);
}
}
});
} else {
// Perform POST on batch API.
for (i; i < len; i++) {
batchQueries[i] = {
'method': 'GET',
'operation_id': '#fail-count' + i,
'collection': 'count',
'document_id': 'defconfig',
'query': 'status=FAIL&job=' + localData[i].job +
'&kernel=' + localData[i].kernel
};
}
errorReason = 'Batch count failed.';
deferredCall = $.ajax({
'url': '/_ajax/batch',
'type': 'POST',
'traditional': true,
'dataType': 'json',
'headers': {
'Content-Type': 'application/json'
},
'beforeSend': function(jqXHR) {
setXhrHeader(jqXHR);
},
'data': JSON.stringify({
'batch': batchQueries
}),
'error': function() {
countFailCallback();
},
'timeout': 10000,
'statusCode': {
403: function() {
setErrorAlert('batch-403-error', 403, errorReason);
},
404: function () {
setErrorAlert('batch-404-error', 404, errorReason);
},
408: function () {
errorReason = 'Batch count failed: timeout.';
setErrorAlert('batch-408-error', 408, errorReason);
},
500: function () {
setErrorAlert('batch-500-error', 500, errorReason);
}
}
});
}
$.when(deferredCall).then(countDoneCallback, countFailCallback);
}
}
function populateFailedDefconfigTable(data) {
var localData = data.result,
row = '',
job,
created,
col1,
col2,
col3,
col4,
col5,
href,
kernel,
git_branch,
i = 0,
len = localData.length;
if (len === 0) {
row = '<tr><td colspan="5" align="center" valign="middle"><h4>' +
'No failed builds.</h4></td></tr>';
$('#failed-builds-body').empty().append(row);
} else {
for (i; i < len; i++) {
job = localData[i].job;
kernel = localData[i].kernel;
git_branch = localData[i].metadata.git_branch;
created = new Date(localData[i].created_on['$date']);
href = '/build/' + job + '/kernel/' + kernel + '/';
col1 = '<td><a class="table-link" href="/job/' + job + '/">' + job + ' ‐ <small>' +
git_branch + '</small></td>';
col2 = '<td>' + kernel + '</a></td>';
col3 = '<td class="pull-center">' +
'<span class="badge alert-danger">' +
'<span id="fail-count' + i + '" ' +
'class="fail-badge">' +
'<i class="fa fa-cog fa-spin"></i></span></span>' +
'</td>';
col4 = '<td class="pull-center">' +
created.getCustomISODate() + '</td>';
col5 = '<td class="pull-center">' +
'<span rel="tooltip" data-toggle="tooltip" ' +
'title="Details for job ' + job +
' ‐ ' + kernel + '">' +
'<a href="' + href + '">' +
'<i class="fa fa-search"></i></a>' +
'</span></td>';
row += '<tr data-url="' + href + '">' +
col1 + col2 + col3 + col4 + col5 + '</tr>';
}
$('#failed-builds-body').empty().append(row);
}
}
errorReason = 'Defconfig data call failed.';
ajaxDeferredCall = $.ajax({
'url': '/_ajax/defconf',
'traditional': true,
'cache': true,
'dataType': 'json',
'data': {
'aggregate': 'kernel',
'status': 'FAIL',
'sort': 'created_on',
'sort_order': -1,
'limit': 25,
'date_range': $('#date-range').val(),
'field': ['job', 'kernel', 'metadata', 'created_on']
},
'beforeSend': function(jqXHR) {
setXhrHeader(jqXHR);
},
'error': function() {
emptyTableOnError('#failed-builds-body', 5);
},
'timeout': 6000,
'statusCode': {
403: function () {
setErrorAlert('defconfs-403-error', 403, errorReason);
},
404: function () {
setErrorAlert('defconfs-404-error', 404, errorReason);
},
408: function () {
errorReason = 'Defconfing data call failed: timeout.';
setErrorAlert('defconfs-408-error', 408, errorReason);
},
500: function () {
setErrorAlert('defconfs-500-error', 500, errorReason);
}
}
}).done(populateFailedDefconfigTable);
$.when(ajaxDeferredCall).then(countFailedDefconfigs, countFailCallback);
});
$(document).ready(function () {
'use strict';
var errorReason = 'Job data call failed.',
ajaxCall;
function populateJobsTalbe(data) {
var localData = data.result,
row = '',
created, col1, col2, col3, href,
job, git_branch,
i = 0,
len = localData.length;
if (len === 0) {
row = '<tr><td colspan="4" align="center" valign="middle"><h4>' +
'No failed jobs.</h4></td></tr>';
$('#failed-jobs-body').empty().append(row);
} else {
for (i; i < len; i++) {
created = new Date(localData[i].created_on['$date']);
job = localData[i].job;
git_branch = localData[i].metadata.git_branch;
href = '/job/' + job + '/';
col1 = '<td><a class="table-link" href="' + href + '">' +
job + ' ‐ <small>' +
git_branch + '</small>' + '</a></td>';
col2 = '<td class="pull-center">' +
created.getCustomISODate() + '</td>';
col3 = '<td class="pull-center">' +
'<span rel="tooltip" data-toggle="tooltip" ' +
'title="Details for job ' + job + '">' +
'<a href="' + href + '">' +
'<i class="fa fa-search"></i></a>' +
'</span></td>';
row = '<tr data-url="' + href + '">' +
col1 + col2 + col3 + '</tr>';
}
$('#failed-jobs-body').empty().append(row);
}
}
ajaxCall = $.ajax({
'url': '/_ajax/job',
'dataType': 'json',
'traditional': true,
'cache': true,
'data': {
'status': 'FAIL',
'sort': 'created_on',
'sort_order': -1,
'limit': 25,
'date_range': $('#date-range').val(),
'field': ['job', 'created_on', 'metadata']
},
'beforeSend': function(jqXHR) {
setXhrHeader(jqXHR);
},
'error': function(jqXHR, textStatus, errorThrown) {
console.log("ERROR RUNNING AJAX JOB CALL");
emptyTableOnError('#failed-jobs-body', 3);
},
'timeout': 6000,
'statusCode': {
403: function () {
setErrorAlert('jobs-403-error', 403, errorReason);
},
404: function () {
setErrorAlert('jobs-404-error', 404, errorReason);
},
408: function () {
errorReason = 'Job data call failed: timeout.';
setErrorAlert('jobs-408-error', 408, errorReason);
},
500: function () {
setErrorAlert('jobs-500-error', 500, errorReason);
}
}
});
$.when(ajaxCall).then(populateJobsTalbe);
});
$(document).ready(function () {
'use strict';
var errorReason = 'Boot data call failed.',
colSpan = 7;
$.ajax({
'url': '/_ajax/boot',
'traditional': true,
'cache': true,
'dataType': 'json',
'context': $('#failed-boots-body'),
'data': {
'status': 'FAIL',
'sort_order': -1,
'sort': 'created_on',
'limit': 25,
'date_range': $('#date-range').val(),
'field': ['board', 'job', 'kernel', 'defconfig', 'created_on', 'metadata']
},
'beforeSend': function(jqXHR) {
setXhrHeader(jqXHR);
},
'error': function() {
emptyTableOnError('#failed-boots-body', colSpan);
},
'timeout': 6000,
'statusCode': {
403: function () {
setErrorAlert('boots-403-error', 403, errorReason);
},
404: function () {
setErrorAlert('boots-404-error', 404, errorReason);
},
408: function () {
errorReason = 'Boot data call failed: timeout.';
setErrorAlert('boots-408-error', 408, errorReason);
},
500: function () {
setErrorAlert('boots-500-error', 500, errorReason);
}
}
}).done(function (data) {
var localData = data.result,
row = '',
created,
board,
job,
kernel,
defconfig,
col1,
col2,
col3,
col4,
col5,
col6,
col7,
href,
len = localData.length,
col5Content,
failureReason = null,
i = 0;
if (len === 0) {
row = '<tr><td colspan="' + colSpan +
'" align="center" valign="middle"><h4>' +
'No failed boot reports.</h4></td></tr>';
$(this).empty().append(row);
} else {
for (i; i < len; i++) {
if (localData[i].boot_result_description !== undefined) {
failureReason = localData[i].boot_result_description;
} else if (localData[i].metadata !== undefined) {
if (localData[i].metadata.hasOwnProperty('boot_result_description')) {
failureReason = localData[i].metadata.boot_result_description;
}
}
if (failureReason === null) {
col5Content = '<td class="pull-center">' +
'<span rel="tooltip" data-toggle="tooltip"' +
'title="Not available"><i class="fa fa-ban"></i>' +
'</span></td>';
} else {
col5Content = '<td class="pull-center">' +
'<span rel="tooltip" data-toggle="tooltip"' +
'title="' + failureReason + '">' +
'<i class="fa fa-question-circle"></i>' +
'</span></td>';
}
created = new Date(localData[i].created_on['$date']);
job = localData[i].job;
kernel = localData[i].kernel;
board = localData[i].board;
defconfig = localData[i].defconfig;
href = '/boot/' + board + '/job/' + job + '/kernel/' +
kernel + '/defconfig/' + defconfig + '/';
col1 = '<td><a class="table-link" href="/job/' + job + '/">' +
job + '</a></td>';
col2 = '<td>' + kernel + '</td>';
col3 = '<td>' + board + '</td>';
col4 = '<td>' + defconfig + '</td>';
col5 = col5Content;
col6 = '<td class="pull-center">' +
created.getCustomISODate() + '</td>';
col7 = '<td class="pull-center">' +
'<span rel="tooltip" data-toggle="tooltip" ' +
'title="Details for board ' + board + '">' +
'<a href="' + href + '">' +
'<i class="fa fa-search"></i></a>' +
'</span></td>';
row += '<tr data-url="' + href + '">' +
col1 + col2 + col3 + col4 + col5 + col6 + col7 + '</tr>';
}
$(this).empty().append(row);
}
});
});
| app/dashboard/static/js/linaro-index-1.2.8.js | function emptyTableOnError (tableId, colspan) {
'use strict';
var localId = tableId;
if (tableId[0] !== '#') {
localId = '#' + tableId;
}
$(localId).empty().append(
'<tr><td colspan="' + colspan +
'" align="center" valign="middle">' +
'<h4>Error loading data.</h4></td></tr>'
);
}
$(document).ready(function () {
'use strict';
$('#li-home').addClass('active');
$('body').tooltip({
'selector': '[rel=tooltip]',
'placement': 'auto'
});
$('.clickable-table tbody').on("click", "tr", function () {
var url = $(this).data('url');
if (url) {
window.location = url;
}
});
});
$(document).ready(function () {
'use strict';
var errorReason = '',
ajaxDeferredCall = null;
function countFailCallback () {
$('.fail-badge').each(function () {
$(this).empty().append('∞');
});
}
function countDoneCallback(data) {
var localData = data.result,
len = localData.length,
i = 0,
batchResult = null;
if (len > 0) {
if (len === 1) {
$('#fail-count0').empty().append(localData[0].count);
} else {
for (i; i < len; i++) {
batchResult = localData[i].result[0];
$(localData[i].operation_id).empty().append(
batchResult.count
);
}
}
} else {
countFailCallback();
}
}
function countFailedDefconfigs(data) {
var localData = data.result,
i = 0,
len = localData.length,
deferredCall = null,
batchQueries = new Array(len);
if (len > 0) {
if (len === 1) {
errorReason = 'Defconfig data call failed.';
// Peform normal GET.
deferredCall = $.ajax({
'url': '/_ajax/count/defconfig',
'traditional': true,
'cache': true,
'dataType': 'json',
'data': {
'status': 'FAIL',
'job': localData[0].job,
'kernel': localData[0].kernel
},
'beforeSend': function(jqXHR) {
setXhrHeader(jqXHR);
},
'error': function() {
countFailCallback();
},
'timeout': 6000,
'statusCode': {
403: function() {
setErrorAlert('batch-403-error', 403, errorReason);
},
404: function () {
setErrorAlert('batch-404-error', 404, errorReason);
},
408: function () {
errorReason = 'Defconfing data call failed: timeout.';
setErrorAlert('batch-408-error', 408, errorReason);
},
500: function () {
setErrorAlert('batch-500-error', 500, errorReason);
}
}
});
} else {
// Perform POST on batch API.
for (i; i < len; i++) {
batchQueries[i] = {
'method': 'GET',
'operation_id': '#fail-count' + i,
'collection': 'count',
'document_id': 'defconfig',
'query': 'status=FAIL&job=' + localData[i].job +
'&kernel=' + localData[i].kernel
};
}
errorReason = 'Batch count failed.';
deferredCall = $.ajax({
'url': '/_ajax/batch',
'type': 'POST',
'traditional': true,
'dataType': 'json',
'headers': {
'Content-Type': 'application/json'
},
'beforeSend': function(jqXHR) {
setXhrHeader(jqXHR);
},
'data': JSON.stringify({
'batch': batchQueries
}),
'error': function() {
countFailCallback();
},
'timeout': 10000,
'statusCode': {
403: function() {
setErrorAlert('batch-403-error', 403, errorReason);
},
404: function () {
setErrorAlert('batch-404-error', 404, errorReason);
},
408: function () {
errorReason = 'Batch count failed: timeout.';
setErrorAlert('batch-408-error', 408, errorReason);
},
500: function () {
setErrorAlert('batch-500-error', 500, errorReason);
}
}
});
}
$.when(deferredCall).then(countDoneCallback, countFailCallback);
}
}
function populateFailedDefconfigTable(data) {
var localData = data.result,
row = '',
job,
created,
col1,
col2,
col3,
col4,
col5,
href,
kernel,
git_branch,
i = 0,
len = localData.length;
if (len === 0) {
row = '<tr><td colspan="5" align="center" valign="middle"><h4>' +
'No failed builds.</h4></td></tr>';
$('#failed-builds-body').empty().append(row);
} else {
for (i; i < len; i++) {
job = localData[i].job;
kernel = localData[i].kernel;
git_branch = localData[i].metadata.git_branch;
created = new Date(localData[i].created_on['$date']);
href = '/build/' + job + '/kernel/' + kernel + '/';
col1 = '<td><a class="table-link" href="/job/' + job + '/">' + job + ' ‐ <small>' +
git_branch + '</small></td>';
col2 = '<td>' + kernel + '</a></td>';
col3 = '<td class="pull-center">' +
'<span class="badge alert-danger">' +
'<span id="fail-count' + i + '" ' +
'class="fail-badge">' +
'<i class="fa fa-cog fa-spin"></i></span></span>' +
'</td>';
col4 = '<td class="pull-center">' +
created.getCustomISODate() + '</td>';
col5 = '<td class="pull-center">' +
'<span rel="tooltip" data-toggle="tooltip" ' +
'title="Details for job ' + job +
' ‐ ' + kernel + '">' +
'<a href="' + href + '">' +
'<i class="fa fa-search"></i></a>' +
'</span></td>';
row += '<tr data-url="' + href + '">' +
col1 + col2 + col3 + col4 + col5 + '</tr>';
}
$('#failed-builds-body').empty().append(row);
}
}
errorReason = 'Defconfig data call failed.';
ajaxDeferredCall = $.ajax({
'url': '/_ajax/defconf',
'traditional': true,
'cache': true,
'dataType': 'json',
'data': {
'aggregate': 'kernel',
'status': 'FAIL',
'sort': 'created_on',
'sort_order': -1,
'limit': 25,
'date_range': $('#date-range').val(),
'field': ['job', 'kernel', 'metadata', 'created_on']
},
'beforeSend': function(jqXHR) {
setXhrHeader(jqXHR);
},
'error': function() {
emptyTableOnError('#failed-builds-body', 5);
},
'timeout': 6000,
'statusCode': {
403: function () {
setErrorAlert('defconfs-403-error', 403, errorReason);
},
404: function () {
setErrorAlert('defconfs-404-error', 404, errorReason);
},
408: function () {
errorReason = 'Defconfing data call failed: timeout.';
setErrorAlert('defconfs-408-error', 408, errorReason);
},
500: function () {
setErrorAlert('defconfs-500-error', 500, errorReason);
}
}
}).done(populateFailedDefconfigTable);
$.when(ajaxDeferredCall).then(countFailedDefconfigs, countFailCallback);
});
$(document).ready(function () {
"use strict";
var errorReason = 'Job data call failed.';
$.ajax({
'url': '/_ajax/job',
'dataType': 'json',
'traditional': true,
'cache': true,
'context': $('#failed-jobs-body'),
'data': {
'status': 'FAIL',
'sort': 'created_on',
'sort_order': -1,
'limit': 25,
'date_range': $('#date-range').val(),
'field': ['job', 'created_on', 'metadata']
},
'beforeSend': function(jqXHR) {
setXhrHeader(jqXHR);
},
'error': function() {
emptyTableOnError('#failed-jobs-body', 3);
},
'timeout': 6000,
'statusCode': {
403: function () {
setErrorAlert('jobs-403-error', 403, errorReason);
},
404: function () {
setErrorAlert('jobs-404-error', 404, errorReason);
},
408: function () {
errorReason = 'Job data call failed: timeout.';
setErrorAlert('jobs-408-error', 408, errorReason);
},
500: function () {
setErrorAlert('jobs-500-error', 500, errorReason);
}
}
}).done(function (data) {
var localData = data.result,
row = '',
created, col1, col2, col3, href,
job, git_branch,
i = 0,
len = localData.length;
if (len === 0) {
row = '<tr><td colspan="4" align="center" valign="middle"><h4>' +
'No failed jobs.</h4></td></tr>';
$(this).empty().append(row);
} else {
for (i; i < len; i++) {
created = new Date(localData[i].created_on['$date']);
job = localData[i].job;
git_branch = localData[i].metadata.git_branch;
href = '/job/' + job + '/';
col1 = '<td><a class="table-link" href="' + href + '">' +
job + ' ‐ <small>' +
git_branch + '</small>' + '</a></td>';
col2 = '<td class="pull-center">' +
created.getCustomISODate() + '</td>';
col3 = '<td class="pull-center">' +
'<span rel="tooltip" data-toggle="tooltip" ' +
'title="Details for job ' + job + '">' +
'<a href="' + href + '">' +
'<i class="fa fa-search"></i></a>' +
'</span></td>';
row = '<tr data-url="' + href + '">' +
col1 + col2 + col3 + '</tr>';
}
$(this).empty().append(row);
}
});
});
$(document).ready(function () {
'use strict';
var errorReason = 'Boot data call failed.',
colSpan = 7;
$.ajax({
'url': '/_ajax/boot',
'traditional': true,
'cache': true,
'dataType': 'json',
'context': $('#failed-boots-body'),
'data': {
'status': 'FAIL',
'sort_order': -1,
'sort': 'created_on',
'limit': 25,
'date_range': $('#date-range').val(),
'field': ['board', 'job', 'kernel', 'defconfig', 'created_on', 'metadata']
},
'beforeSend': function(jqXHR) {
setXhrHeader(jqXHR);
},
'error': function() {
emptyTableOnError('#failed-boots-body', colSpan);
},
'timeout': 6000,
'statusCode': {
403: function () {
setErrorAlert('boots-403-error', 403, errorReason);
},
404: function () {
setErrorAlert('boots-404-error', 404, errorReason);
},
408: function () {
errorReason = 'Boot data call failed: timeout.';
setErrorAlert('boots-408-error', 408, errorReason);
},
500: function () {
setErrorAlert('boots-500-error', 500, errorReason);
}
}
}).done(function (data) {
var localData = data.result,
row = '',
created,
board,
job,
kernel,
defconfig,
col1,
col2,
col3,
col4,
col5,
col6,
col7,
href,
len = localData.length,
col5Content,
failureReason = null,
i = 0;
if (len === 0) {
row = '<tr><td colspan="' + colSpan +
'" align="center" valign="middle"><h4>' +
'No failed boot reports.</h4></td></tr>';
$(this).empty().append(row);
} else {
for (i; i < len; i++) {
if (localData[i].boot_result_description !== undefined) {
failureReason = localData[i].boot_result_description;
} else if (localData[i].metadata !== undefined) {
if (localData[i].metadata.hasOwnProperty('boot_result_description')) {
failureReason = localData[i].metadata.boot_result_description;
}
}
if (failureReason === null) {
col5Content = '<td class="pull-center">' +
'<span rel="tooltip" data-toggle="tooltip"' +
'title="Not available"><i class="fa fa-ban"></i>' +
'</span></td>';
} else {
col5Content = '<td class="pull-center">' +
'<span rel="tooltip" data-toggle="tooltip"' +
'title="' + failureReason + '">' +
'<i class="fa fa-question-circle"></i>' +
'</span></td>';
}
created = new Date(localData[i].created_on['$date']);
job = localData[i].job;
kernel = localData[i].kernel;
board = localData[i].board;
defconfig = localData[i].defconfig;
href = '/boot/' + board + '/job/' + job + '/kernel/' +
kernel + '/defconfig/' + defconfig + '/';
col1 = '<td><a class="table-link" href="/job/' + job + '/">' +
job + '</a></td>';
col2 = '<td>' + kernel + '</td>';
col3 = '<td>' + board + '</td>';
col4 = '<td>' + defconfig + '</td>';
col5 = col5Content;
col6 = '<td class="pull-center">' +
created.getCustomISODate() + '</td>';
col7 = '<td class="pull-center">' +
'<span rel="tooltip" data-toggle="tooltip" ' +
'title="Details for board ' + board + '">' +
'<a href="' + href + '">' +
'<i class="fa fa-search"></i></a>' +
'</span></td>';
row += '<tr data-url="' + href + '">' +
col1 + col2 + col3 + col4 + col5 + col6 + col7 + '</tr>';
}
$(this).empty().append(row);
}
});
});
| index: Use jquery $.when.
Change-Id: I9e6c6be162be5ae58c14a76515e29b54ffb56a67
| app/dashboard/static/js/linaro-index-1.2.8.js | index: Use jquery $.when. | <ide><path>pp/dashboard/static/js/linaro-index-1.2.8.js
<ide> });
<ide>
<ide> $(document).ready(function () {
<del> "use strict";
<del>
<del> var errorReason = 'Job data call failed.';
<del>
<del> $.ajax({
<del> 'url': '/_ajax/job',
<del> 'dataType': 'json',
<del> 'traditional': true,
<del> 'cache': true,
<del> 'context': $('#failed-jobs-body'),
<del> 'data': {
<del> 'status': 'FAIL',
<del> 'sort': 'created_on',
<del> 'sort_order': -1,
<del> 'limit': 25,
<del> 'date_range': $('#date-range').val(),
<del> 'field': ['job', 'created_on', 'metadata']
<del> },
<del> 'beforeSend': function(jqXHR) {
<del> setXhrHeader(jqXHR);
<del> },
<del> 'error': function() {
<del> emptyTableOnError('#failed-jobs-body', 3);
<del> },
<del> 'timeout': 6000,
<del> 'statusCode': {
<del> 403: function () {
<del> setErrorAlert('jobs-403-error', 403, errorReason);
<del> },
<del> 404: function () {
<del> setErrorAlert('jobs-404-error', 404, errorReason);
<del> },
<del> 408: function () {
<del> errorReason = 'Job data call failed: timeout.';
<del> setErrorAlert('jobs-408-error', 408, errorReason);
<del> },
<del> 500: function () {
<del> setErrorAlert('jobs-500-error', 500, errorReason);
<del> }
<del> }
<del> }).done(function (data) {
<add> 'use strict';
<add>
<add> var errorReason = 'Job data call failed.',
<add> ajaxCall;
<add>
<add> function populateJobsTalbe(data) {
<ide> var localData = data.result,
<ide> row = '',
<ide> created, col1, col2, col3, href,
<ide> if (len === 0) {
<ide> row = '<tr><td colspan="4" align="center" valign="middle"><h4>' +
<ide> 'No failed jobs.</h4></td></tr>';
<del> $(this).empty().append(row);
<add> $('#failed-jobs-body').empty().append(row);
<ide> } else {
<ide> for (i; i < len; i++) {
<ide> created = new Date(localData[i].created_on['$date']);
<ide> col1 + col2 + col3 + '</tr>';
<ide> }
<ide>
<del> $(this).empty().append(row);
<add> $('#failed-jobs-body').empty().append(row);
<add> }
<add> }
<add>
<add> ajaxCall = $.ajax({
<add> 'url': '/_ajax/job',
<add> 'dataType': 'json',
<add> 'traditional': true,
<add> 'cache': true,
<add> 'data': {
<add> 'status': 'FAIL',
<add> 'sort': 'created_on',
<add> 'sort_order': -1,
<add> 'limit': 25,
<add> 'date_range': $('#date-range').val(),
<add> 'field': ['job', 'created_on', 'metadata']
<add> },
<add> 'beforeSend': function(jqXHR) {
<add> setXhrHeader(jqXHR);
<add> },
<add> 'error': function(jqXHR, textStatus, errorThrown) {
<add> console.log("ERROR RUNNING AJAX JOB CALL");
<add> emptyTableOnError('#failed-jobs-body', 3);
<add> },
<add> 'timeout': 6000,
<add> 'statusCode': {
<add> 403: function () {
<add> setErrorAlert('jobs-403-error', 403, errorReason);
<add> },
<add> 404: function () {
<add> setErrorAlert('jobs-404-error', 404, errorReason);
<add> },
<add> 408: function () {
<add> errorReason = 'Job data call failed: timeout.';
<add> setErrorAlert('jobs-408-error', 408, errorReason);
<add> },
<add> 500: function () {
<add> setErrorAlert('jobs-500-error', 500, errorReason);
<add> }
<ide> }
<ide> });
<add>
<add> $.when(ajaxCall).then(populateJobsTalbe);
<ide> });
<ide>
<ide> $(document).ready(function () { |
|
Java | apache-2.0 | 1ade9d7e390f9736c3e0024bf033bcd16d526498 | 0 | davidsoergel/dsutils | /* $Id$ */
/*
* Copyright (c) 2001-2007 David Soergel
* 418 Richmond St., El Cerrito, CA 94530
* [email protected]
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the author nor the names of any 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 com.davidsoergel.dsutils;
import org.apache.log4j.Logger;
/**
* @author lorax
* @version 1.0
*/
public class MathUtils
{
// ------------------------------ FIELDS ------------------------------
// private static double[] logTableBelowOne;
// private static double[] logTableAboveOne;
// public static int logbins;
//public static double logResolution;
// public static double maxLogArg;
//public static int logLevels;
public static int logMinOrderOfMagnitude;
public static int logMaxOrderOfMagnitude;
public static int logOrdersOfMagnitudePerLevel;
public static int logBinsPerLevel;
public static int logLevels;
public static double[] logBinIncrement;
public static double[] logBinLimit;
private static Logger logger = Logger.getLogger(MathUtils.class);
private static final int FACTORIAL_LIMIT = 100;
private static double[] factorials = new double[FACTORIAL_LIMIT + 1];
// log(x+y) = log(x) + log [1 + exp[log(y) - log(x)]]
// for x >= y
/* double logsum(double x, double y)
{
double largest = Math.max(x, y);
double smallest = Math.min(x, y);
return largest + Math.log(1.0 + Math.exp(smallest - largest));
}
*/
// Still stuck on how to implement this:
// need to know which is bigger, exp(x) or exp(y)+exp(z)
static double MAX_EXPONENT = Math.log(Double.MAX_VALUE);
static double LOG_TWO_PI = Math.log(2.0 * Math.PI);
private static double[][] logTable;
// -------------------------- STATIC METHODS --------------------------
public static double minmax(double min, double b, double max)
{
return Math.max(Math.min(b, max), min);
}
public static long choose(int n, int m)
{
if (m == 0)
{
return 1;
}
double result = 1;
// this was supposed to be faster than doing the multiplication explicitly, but it has all kinds of Infinity issues etc.
//result = factorial(n) / (factorial(m) * factorial(n - m));
for (int i = n; i > n - m; i--)
{
result *= i;
}
result /= factorial(m);
return (long) result;
}
public static double factorial(int n) throws ArithmeticException
{
if (n > FACTORIAL_LIMIT)
{
return stirlingFactorial(n);
}
if (factorials[n] == 0)
{
factorials[n] = n * factorial(n - 1);
}
return factorials[n];
}
public static double stirlingFactorial(int n)
{
if (n >= 144)
{
throw new ArithmeticException("Factorials greater than 144 don't fit in Double.");
}
double result = Math.sqrt(2.0 * Math.PI * n) * Math.pow(n, n) * Math.pow(Math.E, -n);
return result;
}
static
{
factorials[0] = 1;
factorials[1] = 1;
}
/**
* log(n!) =~ n * log(n) - n
*
* @param d
* @return
*/
public static double stirlingLogFactorial(double d)
{
// double d = n;// just to be sure
// use the real log here, not the approximate one
return ((d + 0.5) * Math.log(d)) - d + (0.5 * LOG_TWO_PI);
}
public static double approximateLog(double x)
{
if (x <= logBinIncrement[0])
{
// x is too small
return Math.log(x);
}
// ** Is there a faster way to decide which bin to use? e.g. binary tree instead of linear?
for (int level = 0; level < logLevels; level++)
{
if (x < logBinLimit[level])
{
return logTable[level][(int) (x / logBinIncrement[level])];
}
}
// x is too big
return Math.log(x);
}
/**
* log(sum(exp(args)))
*
* @param x
* @param y
*/
public static double logsum(double x, double y)
{
// scale all the log probabilities up to avoid underflow.
double B = MAX_EXPONENT - Math.log(3) - Math.max(x, y);
double result = Math.log(Math.exp(x + B) + Math.exp(y + B)) - B;
// logger.debug("Log sum: " + x + " + " + y + " = " + result + " (Scale factor: " + B + ")");
return result;
}
/**
* log(sum(exp(args)))
*
* @param x
* @param y
* @param z
*/
public static double logsum(double x, double y, double z)
{
// scale all the log probabilities up to avoid underflow.
double B = MAX_EXPONENT - Math.log(3) - Math.max(x, Math.max(y, z));
double result = Math.log(Math.exp(x + B) + Math.exp(y + B) + Math.exp(z + B)) - B;
if (Double.isNaN(result))
{
result = Double.NEGATIVE_INFINITY;
//xklogger.info("Log sum produced NaN: " + x + " + " + y + " + " + z + " = " + result + " (Scale factor: " + B + ")", new Exception());
//logger.debug("Log sum produced NaN!");
// try
// {
// throw new Exception("bogus");
// }
// catch(Exception e) { e.printStackTrace(); }
}
// logger.debug("Log sum: " + x + " + " + y + " + " + z + " = " + result + " (Scale factor: " + B + ")");
// if (result > 0)
// {
// throw new Error("Positive log probability not allowed!");
// }
return result;
}
public static void initApproximateLog(int minOrderOfMagnitude, int maxOrderOfMagnitude,
int ordersOfMagnitudePerLevel, int binsPerLevel)
{
minOrderOfMagnitude += ordersOfMagnitudePerLevel;// since we use the order to define the top of the bin
logMinOrderOfMagnitude = minOrderOfMagnitude;
logMaxOrderOfMagnitude = maxOrderOfMagnitude;
logOrdersOfMagnitudePerLevel = ordersOfMagnitudePerLevel;
logBinsPerLevel = binsPerLevel;
logLevels = ((maxOrderOfMagnitude - minOrderOfMagnitude) / ordersOfMagnitudePerLevel) + 1;
logTable = new double[logLevels][binsPerLevel];
logBinIncrement = new double[logLevels];
logBinLimit = new double[logLevels];
int level = 0;
for (int order = minOrderOfMagnitude; order <= maxOrderOfMagnitude; order += ordersOfMagnitudePerLevel)
{
//logTable[level] = new double[binsPerLevel];
logBinLimit[level] = Math.pow(10, order);
logBinIncrement[level] = logBinLimit[level] / binsPerLevel;
for (int i = 0; i < binsPerLevel; i++)
{
logTable[level][i] = Math.log((double) (i * Math.pow(10, order)) / (double) binsPerLevel);
}
level++;
}
logLevels = level;
}
public static boolean equalWithinFPError(double a, double b)
{
if (a == b)
{
return true;
}// covers Infinity cases
double nearlyZero = a - b;
// these errors are generally in the vicinity of 1e-15
// let's be extra permissive, 1e-10 is good enough anyway
return -1e-10 < nearlyZero && nearlyZero < 1e-10;
}
/**
* Greatest Common Denominator.
*
* @param x
* @param y
* @return
*/
public static long GCD(long x, long y)
{
return extendedGCD(x, y)[2];
}
/**
* Extended GCD algorithm; solves the linear Diophantine equation ax + by = c. This clever implementation comes from
* http://www.cs.utsa.edu/~wagner/laws/fav_alg.html, who in turn adapted it from D. Knuth.
*
* @param x
* @param y
* @return an array of long containing {a, b, c}
* @throws ArithmeticException if either argument is negative or zero
*/
public static long[] extendedGCD(long x, long y) throws ArithmeticException
{
/*
if (x <= 0 || y <= 0)
{
throw new ArithmeticException("Can take GCD only of positive numbers");
}
*/
long[] u = {
1,
0,
x
}, v = {
0,
1,
y
}, t = new long[3];
while (v[2] != 0)
{
long q = u[2] / v[2];
logger.debug("" + x + "(" + u[0] + ") + " + y + "(" + u[1] + ") = " + u[2] + " [" + q + "]");
for (int i = 0; i < 3; i++)
{
t[i] = u[i] - v[i] * q;
u[i] = v[i];
v[i] = t[i];
}
}
logger.debug("" + x + "(" + u[0] + ") + " + y + "(" + u[1] + ") = " + u[2] + " [DONE]");
/*
* The result is inverted if necessary to guarantee that the GCD (c) is non-negative.
*
* If one of the arguments is 0, the other argument is returned (0 can't have a common divisor with anything except itself).
*/
/*if (u[2] < 0)
{
u[0] = -u[0];
u[1] = -u[1];
u[2] = -u[2];
}*/
return u;
}
/**
* Extended GCD algorithm; solves the linear Diophantine equation ax + by = c with the constraints that a and c must be
* positive. To achieve this, we first apply the standard GCD algorithm, and then adjust as needed by replacing a with
* (a+ny) and b with (b-nx), since (a+ny)x + (b-nx)y = c
*
* @param x
* @param y
* @return an array of long containing {a, b, c}
* @throws ArithmeticException if either argument is negative or zero
*/
public static long[] extendedGCDPositive(long x, long y) throws ArithmeticException
{
long[] u = extendedGCD(x, y);
if (u[2] < 0)
{
u[0] *= -1;
u[1] *= -1;
u[2] *= -1;
}
if (u[0] > 0)
{
return u;
}
long n = -u[0] / y;
// long division gives floor for positive, ceil for negative
// but we want the reverse
// so if y was positive, we got the floor, so we need to increment it, and vice versa
if (y > 0)
{
n++;
}
else
{
n--;
}
u[0] += n * y;
u[1] -= n * x;
// brute force variant
/*while(u[0] < 0)
{
u[0] += y;
u[1] -= x;
}
*/
return u;
}
}
| src/main/java/com/davidsoergel/dsutils/MathUtils.java | /* $Id$ */
/*
* Copyright (c) 2001-2007 David Soergel
* 418 Richmond St., El Cerrito, CA 94530
* [email protected]
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the author nor the names of any 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 com.davidsoergel.dsutils;
import org.apache.log4j.Logger;
/**
* @author lorax
* @version 1.0
*/
public class MathUtils
{
// ------------------------------ FIELDS ------------------------------
// private static double[] logTableBelowOne;
// private static double[] logTableAboveOne;
// public static int logbins;
//public static double logResolution;
// public static double maxLogArg;
//public static int logLevels;
public static int logMinOrderOfMagnitude;
public static int logMaxOrderOfMagnitude;
public static int logOrdersOfMagnitudePerLevel;
public static int logBinsPerLevel;
public static int logLevels;
public static double[] logBinIncrement;
public static double[] logBinLimit;
private static Logger logger = Logger.getLogger(MathUtils.class);
private static final int FACTORIAL_LIMIT = 100;
private static double[] factorials = new double[FACTORIAL_LIMIT + 1];
// log(x+y) = log(x) + log [1 + exp[log(y) - log(x)]]
// for x >= y
/* double logsum(double x, double y)
{
double largest = Math.max(x, y);
double smallest = Math.min(x, y);
return largest + Math.log(1.0 + Math.exp(smallest - largest));
}
*/
// Still stuck on how to implement this:
// need to know which is bigger, exp(x) or exp(y)+exp(z)
static double MAX_EXPONENT = Math.log(Double.MAX_VALUE);
private static double[][] logTable;
// -------------------------- STATIC METHODS --------------------------
public static double minmax(double min, double b, double max)
{
return Math.max(Math.min(b, max), min);
}
public static long choose(int n, int m)
{
if (m == 0)
{
return 1;
}
double result = 1;
// this was supposed to be faster than doing the multiplication explicitly, but it has all kinds of Infinity issues etc.
//result = factorial(n) / (factorial(m) * factorial(n - m));
for (int i = n; i > n - m; i--)
{
result *= i;
}
result /= factorial(m);
return (long) result;
}
public static double factorial(int n) throws ArithmeticException
{
if (n > FACTORIAL_LIMIT)
{
return stirlingFactorial(n);
}
if (factorials[n] == 0)
{
factorials[n] = n * factorial(n - 1);
}
return factorials[n];
}
public static double stirlingFactorial(int n)
{
if (n >= 144)
{
throw new ArithmeticException("Factorials greater than 144 don't fit in Double.");
}
double result = Math.sqrt(2.0 * Math.PI * n) * Math.pow(n, n) * Math.pow(Math.E, -n);
return result;
}
static
{
factorials[0] = 1;
factorials[1] = 1;
}
/**
* log(n!) =~ n * log(n) - n
*
* @param d
* @return
*/
public static double stirlingLogFactorial(double d)
{
// double d = n;// just to be sure
return ((d * approximateLog(d)) - d);
}
public static double approximateLog(double x)
{
if (x <= logBinIncrement[0])
{
// x is too small
return Math.log(x);
}
// ** Is there a faster way to decide which bin to use? e.g. binary tree instead of linear?
for (int level = 0; level < logLevels; level++)
{
if (x < logBinLimit[level])
{
return logTable[level][(int) (x / logBinIncrement[level])];
}
}
// x is too big
return Math.log(x);
}
/**
* log(sum(exp(args)))
*
* @param x
* @param y
*/
public static double logsum(double x, double y)
{
// scale all the log probabilities up to avoid underflow.
double B = MAX_EXPONENT - Math.log(3) - Math.max(x, y);
double result = Math.log(Math.exp(x + B) + Math.exp(y + B)) - B;
// logger.debug("Log sum: " + x + " + " + y + " = " + result + " (Scale factor: " + B + ")");
return result;
}
/**
* log(sum(exp(args)))
*
* @param x
* @param y
* @param z
*/
public static double logsum(double x, double y, double z)
{
// scale all the log probabilities up to avoid underflow.
double B = MAX_EXPONENT - Math.log(3) - Math.max(x, Math.max(y, z));
double result = Math.log(Math.exp(x + B) + Math.exp(y + B) + Math.exp(z + B)) - B;
if (Double.isNaN(result))
{
result = Double.NEGATIVE_INFINITY;
//xklogger.info("Log sum produced NaN: " + x + " + " + y + " + " + z + " = " + result + " (Scale factor: " + B + ")", new Exception());
//logger.debug("Log sum produced NaN!");
// try
// {
// throw new Exception("bogus");
// }
// catch(Exception e) { e.printStackTrace(); }
}
// logger.debug("Log sum: " + x + " + " + y + " + " + z + " = " + result + " (Scale factor: " + B + ")");
// if (result > 0)
// {
// throw new Error("Positive log probability not allowed!");
// }
return result;
}
public static void initApproximateLog(int minOrderOfMagnitude, int maxOrderOfMagnitude,
int ordersOfMagnitudePerLevel, int binsPerLevel)
{
minOrderOfMagnitude += ordersOfMagnitudePerLevel;// since we use the order to define the top of the bin
logMinOrderOfMagnitude = minOrderOfMagnitude;
logMaxOrderOfMagnitude = maxOrderOfMagnitude;
logOrdersOfMagnitudePerLevel = ordersOfMagnitudePerLevel;
logBinsPerLevel = binsPerLevel;
logLevels = ((maxOrderOfMagnitude - minOrderOfMagnitude) / ordersOfMagnitudePerLevel) + 1;
logTable = new double[logLevels][binsPerLevel];
logBinIncrement = new double[logLevels];
logBinLimit = new double[logLevels];
int level = 0;
for (int order = minOrderOfMagnitude; order <= maxOrderOfMagnitude; order += ordersOfMagnitudePerLevel)
{
//logTable[level] = new double[binsPerLevel];
logBinLimit[level] = Math.pow(10, order);
logBinIncrement[level] = logBinLimit[level] / binsPerLevel;
for (int i = 0; i < binsPerLevel; i++)
{
logTable[level][i] = Math.log((double) (i * Math.pow(10, order)) / (double) binsPerLevel);
}
level++;
}
logLevels = level;
}
public static boolean equalWithinFPError(double a, double b)
{
if (a == b)
{
return true;
}// covers Infinity cases
double nearlyZero = a - b;
// these errors are generally in the vicinity of 1e-15
// let's be extra permissive, 1e-10 is good enough anyway
return -1e-10 < nearlyZero && nearlyZero < 1e-10;
}
/**
* Greatest Common Denominator.
*
* @param x
* @param y
* @return
*/
public static long GCD(long x, long y)
{
return extendedGCD(x, y)[2];
}
/**
* Extended GCD algorithm; solves the linear Diophantine equation ax + by = c. This clever implementation comes from
* http://www.cs.utsa.edu/~wagner/laws/fav_alg.html, who in turn adapted it from D. Knuth.
*
* @param x
* @param y
* @return an array of long containing {a, b, c}
* @throws ArithmeticException if either argument is negative or zero
*/
public static long[] extendedGCD(long x, long y) throws ArithmeticException
{
/*
if (x <= 0 || y <= 0)
{
throw new ArithmeticException("Can take GCD only of positive numbers");
}
*/
long[] u = {1, 0, x}, v = {0, 1, y}, t = new long[3];
while (v[2] != 0)
{
long q = u[2] / v[2];
logger.debug("" + x + "(" + u[0] + ") + " + y + "(" + u[1] + ") = " + u[2] + " [" + q + "]");
for (int i = 0; i < 3; i++)
{
t[i] = u[i] - v[i] * q;
u[i] = v[i];
v[i] = t[i];
}
}
logger.debug("" + x + "(" + u[0] + ") + " + y + "(" + u[1] + ") = " + u[2] + " [DONE]");
/*
* The result is inverted if necessary to guarantee that the GCD (c) is non-negative.
*
* If one of the arguments is 0, the other argument is returned (0 can't have a common divisor with anything except itself).
*/
/*if (u[2] < 0)
{
u[0] = -u[0];
u[1] = -u[1];
u[2] = -u[2];
}*/
return u;
}
/**
* Extended GCD algorithm; solves the linear Diophantine equation ax + by = c with the constraints that a and c must
* be positive. To achieve this, we first apply the standard GCD algorithm, and then adjust as needed by replacing a
* with (a+ny) and b with (b-nx), since (a+ny)x + (b-nx)y = c
*
* @param x
* @param y
* @return an array of long containing {a, b, c}
* @throws ArithmeticException if either argument is negative or zero
*/
public static long[] extendedGCDPositive(long x, long y) throws ArithmeticException
{
long[] u = extendedGCD(x, y);
if (u[2] < 0)
{
u[0] *= -1;
u[1] *= -1;
u[2] *= -1;
}
if (u[0] > 0)
{
return u;
}
long n = -u[0] / y;
// long division gives floor for positive, ceil for negative
// but we want the reverse
// so if y was positive, we got the floor, so we need to increment it, and vice versa
if (y > 0)
{
n++;
}
else
{
n--;
}
u[0] += n * y;
u[1] -= n * x;
// brute force variant
/*while(u[0] < 0)
{
u[0] += y;
u[1] -= x;
}
*/
return u;
}
}
| Fixed precision of Stirling Log Factorial
| src/main/java/com/davidsoergel/dsutils/MathUtils.java | Fixed precision of Stirling Log Factorial | <ide><path>rc/main/java/com/davidsoergel/dsutils/MathUtils.java
<ide> // need to know which is bigger, exp(x) or exp(y)+exp(z)
<ide>
<ide> static double MAX_EXPONENT = Math.log(Double.MAX_VALUE);
<add> static double LOG_TWO_PI = Math.log(2.0 * Math.PI);
<ide>
<ide> private static double[][] logTable;
<ide>
<ide> public static double stirlingLogFactorial(double d)
<ide> {
<ide> // double d = n;// just to be sure
<del> return ((d * approximateLog(d)) - d);
<add> // use the real log here, not the approximate one
<add> return ((d + 0.5) * Math.log(d)) - d + (0.5 * LOG_TWO_PI);
<ide> }
<ide>
<ide> public static double approximateLog(double x)
<ide> }
<ide> */
<ide>
<del> long[] u = {1, 0, x}, v = {0, 1, y}, t = new long[3];
<add> long[] u = {
<add> 1,
<add> 0,
<add> x
<add> }, v = {
<add> 0,
<add> 1,
<add> y
<add> }, t = new long[3];
<ide> while (v[2] != 0)
<ide> {
<ide> long q = u[2] / v[2];
<ide> }
<ide>
<ide> /**
<del> * Extended GCD algorithm; solves the linear Diophantine equation ax + by = c with the constraints that a and c must
<del> * be positive. To achieve this, we first apply the standard GCD algorithm, and then adjust as needed by replacing a
<del> * with (a+ny) and b with (b-nx), since (a+ny)x + (b-nx)y = c
<add> * Extended GCD algorithm; solves the linear Diophantine equation ax + by = c with the constraints that a and c must be
<add> * positive. To achieve this, we first apply the standard GCD algorithm, and then adjust as needed by replacing a with
<add> * (a+ny) and b with (b-nx), since (a+ny)x + (b-nx)y = c
<ide> *
<ide> * @param x
<ide> * @param y |
|
Java | apache-2.0 | 2b87f75dea7f1851645cc0c7e82c5c6b4e0bf661 | 0 | antoinesd/weld-core,weld/core,manovotn/core,antoinesd/weld-core,weld/core,manovotn/core,antoinesd/weld-core,manovotn/core | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.weld.tests.annotatedType;
import javax.enterprise.inject.spi.Annotated;
import javax.enterprise.inject.spi.AnnotatedConstructor;
import javax.enterprise.inject.spi.AnnotatedField;
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.AnnotatedParameter;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.BeanManager;
import javax.inject.Inject;
import org.jboss.arquillian.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.BeanArchive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
*
* @author <a href="[email protected]">Kabir Khan</a>
* @version $Revision: 1.1 $
*/
@RunWith(Arquillian.class)
public class ExampleTest
{
@Deployment
public static Archive<?> deploy()
{
return ShrinkWrap.create("test.jar", BeanArchive.class)
.addPackage(ExampleTest.class.getPackage());
}
@Inject
private BeanManager beanManager;
@Test
public void testAnnotatedCallableGetParameters() throws Exception
{
AnnotatedType<Bean> type = beanManager.createAnnotatedType(Bean.class);
assertNoAnnotations(type);
Assert.assertEquals(1, type.getConstructors().size());
for (AnnotatedConstructor<Bean> ctor : type.getConstructors())
{
assertNoAnnotations(ctor);
for (AnnotatedParameter<Bean> param : ctor.getParameters())
{
assertNoAnnotations(param);
}
}
Assert.assertEquals(1, type.getMethods().size());
for (AnnotatedMethod<? super Bean> method : type.getMethods())
{
assertNoAnnotations(method);
for (AnnotatedParameter<? super Bean> param : method.getParameters())
{
assertNoAnnotations(param);
}
}
Assert.assertEquals(1, type.getFields().size());
for (AnnotatedField<? super Bean> field : type.getFields())
{
assertNoAnnotations(field);
}
}
private void assertNoAnnotations(Annotated annotated)
{
Assert.assertEquals(0, annotated.getAnnotations().size());
}
}
| tests-arquillian/src/test/java/org/jboss/weld/tests/annotatedType/ExampleTest.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.weld.tests.annotatedType;
import javax.enterprise.inject.spi.Annotated;
import javax.enterprise.inject.spi.AnnotatedConstructor;
import javax.enterprise.inject.spi.AnnotatedField;
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.AnnotatedParameter;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.BeanManager;
import javax.inject.Inject;
import org.jboss.arquillian.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.BeanArchive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
*
* @author <a href="[email protected]">Kabir Khan</a>
* @version $Revision: 1.1 $
*/
@RunWith(Arquillian.class)
public class ExampleTest
{
@Deployment
public static Archive<?> deploy()
{
return ShrinkWrap.create("test.jar", BeanArchive.class)
.addPackage(ExampleTest.class.getPackage())
.as(JavaArchive.class);
}
@Inject
private BeanManager beanManager;
@Test
public void testAnnotatedCallableGetParameters() throws Exception
{
AnnotatedType<Bean> type = beanManager.createAnnotatedType(Bean.class);
assertNoAnnotations(type);
Assert.assertEquals(1, type.getConstructors().size());
for (AnnotatedConstructor<Bean> ctor : type.getConstructors())
{
assertNoAnnotations(ctor);
for (AnnotatedParameter<Bean> param : ctor.getParameters())
{
assertNoAnnotations(param);
}
}
Assert.assertEquals(1, type.getMethods().size());
for (AnnotatedMethod<? super Bean> method : type.getMethods())
{
assertNoAnnotations(method);
for (AnnotatedParameter<? super Bean> param : method.getParameters())
{
assertNoAnnotations(param);
}
}
Assert.assertEquals(1, type.getFields().size());
for (AnnotatedField<? super Bean> field : type.getFields())
{
assertNoAnnotations(field);
}
}
private void assertNoAnnotations(Annotated annotated)
{
Assert.assertEquals(0, annotated.getAnnotations().size());
}
}
| minor
| tests-arquillian/src/test/java/org/jboss/weld/tests/annotatedType/ExampleTest.java | minor | <ide><path>ests-arquillian/src/test/java/org/jboss/weld/tests/annotatedType/ExampleTest.java
<ide> import org.jboss.shrinkwrap.api.Archive;
<ide> import org.jboss.shrinkwrap.api.BeanArchive;
<ide> import org.jboss.shrinkwrap.api.ShrinkWrap;
<del>import org.jboss.shrinkwrap.api.spec.JavaArchive;
<ide> import org.junit.Assert;
<ide> import org.junit.Test;
<ide> import org.junit.runner.RunWith;
<ide> public static Archive<?> deploy()
<ide> {
<ide> return ShrinkWrap.create("test.jar", BeanArchive.class)
<del> .addPackage(ExampleTest.class.getPackage())
<del> .as(JavaArchive.class);
<add> .addPackage(ExampleTest.class.getPackage());
<ide> }
<ide>
<ide> @Inject |
|
JavaScript | mit | 99f71db03b827ea5fa466fa4841321c944696a0e | 0 | datalocale/dataviz-finances-gironde,datalocale/dataviz-finances-gironde | import {Record, OrderedSet as ImmutableSet} from 'immutable';
import {isRF, isDF, isRI, isDI} from './rowFilters';
/*
This file's very French and even Gironde-specific.
It describes, documents and encodes the rules that allows to get from
an "M52 budget" to a "budget agrégé"
*/
export const rules = Object.freeze({
/**
* Recettes de fonctionnement
*/
'RF-1-1' : {
label: 'Taxe Foncière sur les propriétés bâties+rôles supplémentaires',
filter(m52Row){
const article = m52Row['Nature'];
return isRF(m52Row) &&
['73111', '7318'].includes(article);
}
}
,
'RF-1-2' : {
label: "Cotisation sur la valeur ajoutée des entreprises (CVAE)",
filter(m52Row){
return isRF(m52Row) && ['7311', '73112'].includes(m52Row['Nature']);
}
},
'RF-1-3': {
label: "Imposition forfaitaire pour les entreprises de réseaux (IFER)",
filter(m52Row){
return isRF(m52Row) && m52Row['Nature'] === '73114';
}
},
'RF-1-4': { // should be 0 before 2016 and >0 in 2017
label: 'Reversement CVAE Région',
filter(m52Row){
return isRF(m52Row) && m52Row['Nature'] === '73123';
}
},
'RF-2-1': {
label: "Taxe Intérieure de Consommation sur les Produits Energétiques (TICPE)",
filter(m52Row){
return isRF(m52Row) && '7352' === m52Row['Nature'];
}
},
'RF-2-2': {
label: "Taxe Sur les Contrats d’Assurance (TSCA)",
filter(m52Row){
return isRF(m52Row) && m52Row['Nature'] === '7342';
}
},
'RF-3': {
label: "Droits de mutation à titre onéreux (DMTO)",
filter(m52Row){
return isRF(m52Row) && ['7321', '7322', '7482'].includes(m52Row['Nature']);
}
},
'RF-4-1': {
label: "Taxe d'aménagement (incluant les anciennes Taxe Départementale Espaces Naturels Sensibles (TDENS) et financement CAUE)",
filter(m52Row){
return isRF(m52Row) && ['7323', '7324', '7327'].includes(m52Row['Nature']);
}
},
'RF-4-2': {
label: "Taxe sur l’électricité",
filter(m52Row){
return isRF(m52Row) && m52Row['Nature'] === '7351';
}
},
'RF-4-3': {
label: "Redevance des mines",
filter(m52Row){
return isRF(m52Row) && m52Row['Nature'] === '7353';
}
},
'RF-4-4': {
label: "autres fiscalités",
filter(m52Row){
return isRF(m52Row) && ['7362', '7388', '738'].includes(m52Row['Nature']);
}
},
'RF-5-1': {
label: "Dotation Globale de Fonctionnement (DGF)",
filter(m52Row){
return isRF(m52Row) && ['7411', '74122', '74123'].includes(m52Row['Nature']);
}
},
'RF-5-2': {
label: "Dotation Globale de Décentralisation (DGD)",
filter(m52Row){
return isRF(m52Row) && '7461' === m52Row['Nature'];
}
},
'RF-5-3': {
label: "Compensations fiscales",
filter(m52Row){
return isRF(m52Row) && ['74833', '74834', '74835'].includes(m52Row['Nature']);
}
},
'RF-5-4': {
label: "Dotation de compensation de la réforme de la taxe professionnelle (DCRTP)",
filter(m52Row){
return isRF(m52Row) && '74832' === m52Row['Nature'];
}
},
'RF-5-5': {
label: "Fonds National de Garantie Individuelle de Ressources (FNGIR)",
filter(m52Row){
return isRF(m52Row) && '73121' === m52Row['Nature'];
}
},
'RF-5-6': {
label: "Autres dotations",
filter(m52Row){
return isRF(m52Row) && '744' === m52Row['Nature'];
}
},
'RF-6-1': {
label: "Indus RSA",
filter(m52Row){
// modifié pour le CA 2017
return isRF(m52Row) && ['75342', '75343', '7531'].includes(m52Row['Nature']);
}
},
'RF-6-2': {
label: "Contributions de la Caisse nationale de solidarité pour l'autonomie (CNSA)",
filter(m52Row){
return isRF(m52Row) && ['747811', '747812'].includes(m52Row['Nature']);
}
},
'RF-6-3': {
label: "Recouvrements sur bénéficiaires",
filter(m52Row){
return isRF(m52Row) && m52Row['Nature'] === '7513';
}
},
'RF-6-4': {
// This didn't exist in 2015
// It was new in 2016 and put in R53*A74788
// Since 2017, it'll be as A7478141+A7478142
label: "Conférence des financeurs",
filter(m52Row){
const fonction = m52Row['Fonction'];
return isRF(m52Row) && (
['7478141', '7478142'].includes(m52Row['Nature']) ||
(m52Row['Exercice'] === 2016 && m52Row['Nature'] === '74788' && fonction === '53')
)
}
},
'RF-6-5': {
label: "Autres",
filter(m52Row){
const fonction = m52Row['Fonction'];
const f1 = fonction.slice(0, 1);
const otherRecetteSocialeIds = Object.keys(rules)
.filter(id => id !== 'RF-6-5' && id.startsWith('RF-6-'));
return isRF(m52Row) &&
m52Row['Nature'] !== '74783' &&
m52Row['Nature'] !== '775' &&
(f1 === '4' || f1 === '5') &&
otherRecetteSocialeIds.every(
id => !rules[id].filter(m52Row)
)
}
},
'RF-7-1': {
label: "Fonds de Mobilisation Départementale pour l'Insertion (FMDI)",
filter(m52Row){
return isRF(m52Row) && m52Row['Nature'] === '74783';
}
},
'RF-7-2': {
label: "Dotation de compensation peréquée DCP",
filter(m52Row){
return isRF(m52Row) && m52Row['Nature'] === '73125';
}
},
'RF-7-3': {
label: "Fonds d'appui d'aide à domicile (CNSA AAD)",
status: 'TEMPORARY',
filter(m52Row){
//return isRF(m52Row) && m52Row['Nature'] === 'A74788';
}
},
'RF-7-4': {
label: "Fonds d'appui aux politiques d'insertion",
status: 'TEMPORARY',
filter(m52Row){
//return isRF(m52Row) && m52Row['Nature'] === 'A74718';
}
},
'RF-8-1': {
label: "Fonds de Péréquation DMTO et Fonds de solidarité",
filter(m52Row){
return isRF(m52Row) && ['7326', '73261', '73262'].includes(m52Row['Nature']);
}
},
'RF-8-2': {
label: "Fonds exceptionnel pour les départements en difficulté",
status: 'TEMPORARY',
filter(m52Row){
//return isRF(m52Row) && m52Row['Nature'] === 'A74718';
}
},
'RF-9-1': {
label: "Produits des domaines (ventes)",
filter(m52Row){
return isRF(m52Row) && m52Row['Nature'] === '752';
}
},
'RF-9-2': {
label: "Produits exceptionnels",
filter(m52Row){
const fonction = m52Row['Fonction'];
const f1 = fonction.slice(0, 1);
return isRF(m52Row) && f1!=='4' && f1!=='5' && [
'7817', '7711', '7714', '7718',
'773', '7788', '7875', '7816', '7866'
// ajout de l'article 7866 pour le CA 2017
].includes(m52Row['Nature']);
}
},
'RF-9-3': {
label: "Dotations et participations (dont fonds européens)",
filter(m52Row){
const fonction = m52Row['Fonction'];
const f1 = fonction.slice(0, 1);
return isRF(m52Row) && f1!=='4' && f1!=='5' && [
'7475', '7476', '74771', '74772', '74778',
'74788', '74888', '74718', '7474', '7472',
'7473', '7478228'
].includes(m52Row['Nature']);
}
},
'RF-9-4': {
label: "Restauration collège",
filter(m52Row){
return isRF(m52Row) && m52Row['Nature'] === '74881';
}
},
'RF-9-5': {
label: "Produits des services",
filter(m52Row){
const fonction = m52Row['Fonction'];
const f1 = fonction.slice(0, 1);
return isRF(m52Row) && f1 !== '4' && f1 !== '5' && m52Row['Nature'].startsWith('70');
}
},
'RF-9-6': {
label: "Remboursement charges de personnels",
filter(m52Row){
const fonction = m52Row['Fonction'];
const f1 = fonction.slice(0, 1);
return isRF(m52Row) && f1 !== '4' && f1 !=='5' && ['6419', '6459', '6479'].includes(m52Row['Nature']);
}
},
'RF-9-7': {
label: "Autres produits de gestions courants",
filter(m52Row){
const fonction = m52Row['Fonction'];
const article = m52Row['Nature'];
const f1 = fonction.slice(0, 1);
return isRF(m52Row) &&
f1 !== '4' && f1 !== '5' &&
article.startsWith('75') &&
article !== '752' &&
article !== '7513' &&
article !== '75342' &&
article !== '75343' &&
// article exclus pour le CA 2017
article !== '7511' &&
article !== '7535' &&
article !== '7533' &&
article !== '7512' &&
article !== '7531';
}
},
'RF-9-8': {
label: "Produits financiers",
filter(m52Row){
return isRF(m52Row) && m52Row['Nature'].startsWith('76');
}
},
/**
* Dépenses de fonctionnement
*/
'DF-1-1-1': {
label: "Pour les personnes handicapées",
filter(m52Row){
return isDF(m52Row) && ['652221', '65242'].includes(m52Row['Nature']);
}
},
'DF-1-1-2': {
label: "Frais d’hébergement - Pour les personnes âgées",
filter(m52Row){
return isDF(m52Row) && ['652224', '65243'].includes(m52Row['Nature']);
}
},
'DF-1-1-3': {
label: "Liés à l’enfance",
// Also contains R51 A65111 from a correction
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
return isDF(m52Row) &&
(
fonction.slice(0, 2) === '51' &&
(
[
"6132", "6135", "6184",
"6234", "6245",
"65221", "652222", "65223", "65228",
"6523", "652411", "652412", "652415", "652418",
"65821", "6718", "6336"
].includes(article) ||
article.startsWith('64')
)
||
(fonction === '50' && article === '64121') ||
(fonction === '50' && article === '64126')
);
}
},
'DF-1-2': {
label: "Revenu de Solidarité Active (RSA)",
filter(m52Row){
return isDF(m52Row) && ['6515', '65171', '65172'].includes(m52Row['Nature']);
}
},
'DF-1-3': {
label: "Prestation Compensatoire du Handicap (PCH) + Allocation Compensatrice aux Tierces Personnes (ACTP)",
filter(m52Row){
return isDF(m52Row) && ['6511211', '6511212', '651128', '651122'].includes(m52Row['Nature']);
}
},
'DF-1-4': {
label: "Allocation Personnalisée d’Autonomie (APA)",
filter(m52Row){
return isDF(m52Row) && ['651141', '651142', '651143', '651144', '651148'].includes(m52Row['Nature']);
}
},
'DF-1-5': {
label: "Préventions enfants",
// Also contains R51 A65111 from a correction
filter(m52Row){
const fonction = m52Row['Fonction'];
return isDF(m52Row) &&
fonction.slice(0, 2) === '51' &&
['652416', '6514'].includes(m52Row['Nature']);
}
},
'DF-1-6': {
label: "Subventions sociales",
filter(m52Row){
const fonction = m52Row['Fonction'];
const art = m52Row['Nature'];
const f1 = fonction.slice(0, 1);
return isDF(m52Row) &&
(f1 === '4' || f1 === '5') &&
art.startsWith('657') &&
fonction !== '51';
}
},
'DF-1-7-1': {
label: "Autres divers enfants",
filter(m52Row){
const fonction = m52Row['Fonction'];
return isDF(m52Row) &&
fonction.slice(0, 2) === '51' &&
[
"6068", "6188", "616", "62268", "6227",
"62878", "654", "6541", "6542", "6568",
"65734", "65737", "6574", "673", "6745"
].includes(m52Row['Nature']);
}
},
'DF-1-7-2': {
label: "Divers social - Autres",
filter(m52Row){
const fonction = m52Row['Fonction'];
const art = m52Row['Nature'];
const f1 = fonction.slice(0, 1);
const parPrestationRuleIds = Object.keys(rules).filter(id => id.startsWith('DF-1-') && id !== 'DF-1-7-2');
return isDF(m52Row) &&
(f1 === '4' || f1 === '5') &&
(
art.startsWith('60') || art.startsWith('61') || art.startsWith('62') ||
art.startsWith('63') || art.startsWith('65') || art.startsWith('67')
) &&
parPrestationRuleIds.every(
id => !rules[id].filter(m52Row)
) &&
!(art === '6556' && fonction === '58') &&
!(art === '6568' && fonction === '52') &&
!(art === '6526' && fonction === '51') &&
!(art === '6513' && fonction === '52') &&
!(art === '6336') &&
!(art === '6218') &&
!(art === '6245' && fonction === '568') &&
!(art === '6245' && fonction === '52') &&
!(art === '65111' && fonction === '51') &&
!((art === '65113' || art === '6568') && fonction.startsWith('53'));
}
},
'DF-1-8': {
label: "Conférence des financeurs",
filter(m52Row){
const fonction = m52Row['Fonction'];
return isDF(m52Row) &&
fonction.startsWith('53') &&
[
"61113", "6568"
].includes(m52Row['Nature']);
}
},
'DF-2-1': {
label: "Personnes en difficultés",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f2 = fonction.slice(0, 2);
return isDF(m52Row) && (f2 === '54' || f2 === '56') &&
article !== '6568' &&
article !== '6513' &&
!article.startsWith('64') &&
article !== '6336' &&
article !== '6245';
}
},
'DF-2-2': {
label: "Personnes handicapées",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f2 = fonction.slice(0, 2);
return isDF(m52Row) && f2 === '52' &&
article !== '6568' &&
article !== '6513' &&
!article.startsWith('64') &&
article !== '6336' &&
article !== '6245';
}
},
'DF-2-3': {
label: "Personnes âgées",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f2 = fonction.slice(0, 2);
return isDF(m52Row) && (f2 === '55' || f2 === '53') &&
article !== '6513' &&
!article.startsWith('64') &&
article !== '6336' &&
article !== '6245';
}
},
'DF-2-4': {
label: "Enfance",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f2 = fonction.slice(0, 2);
return isDF(m52Row) &&
(
(f2 === '51' && article !== '6526') ||
(f2 === '50' && article === '64121') ||
(f2 === '50' && article === '64126')
)
}
},
'DF-2-5': {
label: "Autres",
filter(m52Row){
const fonction = m52Row['Fonction'];
const article = m52Row['Nature'];
const f2 = fonction.slice(0, 2);
return isDF(m52Row) &&
['58', '50', '40', '41', '42', '48'].includes(f2) &&
!(article === '6556' && fonction === '58')
&& !article.startsWith('64')
&& article !== '6336' &&
article !== '6218';
}
},
'DF-3-1': {
label: "Service Départemental d'Incendie et de Secours (SDIS)",
filter(m52Row){
return isDF(m52Row) && m52Row['Nature'] === '6553';
}
},
'DF-3-2': {
label: "Transports",
filter(m52Row){
const f = m52Row['Fonction'];
const f1 = f.slice(0, 1);
const article = m52Row['Nature']
return isDF(m52Row) && (
(f1 === '8' && !article.startsWith('64') && article !== '6336') ||
(
f === '568' &&
(
article === '6245' ||
article === '6336' ||
article === '6218'
)
)
)
}
},
'DF-3-3': {
label: "Transports des étudiants et des élèves handicapés",
filter(m52Row){
const fonction = m52Row['Fonction'];
const f2 = fonction.slice(0, 2);
return isDF(m52Row) &&
f2 === '52' &&
['6245', '6513', '6568'].includes(m52Row['Nature']);
}
},
'DF-3-4': {
label: "Prévention spécialisée",
filter(m52Row){
const f = m52Row['Fonction'];
return isDF(m52Row) && ['6526', '6563'].includes(m52Row['Nature']) && f === '51';
}
},
'DF-3-5': {
label: "Dotation de fonctionnement des collèges",
filter(m52Row){
return isDF(m52Row) && ['65511', '65512'].includes(m52Row['Nature']);
}
},
'DF-3-6': {
label: "Subventions de fonctionnement",
filter(m52Row){
const art = m52Row['Nature'];
const f1 = m52Row['Fonction'].slice(0, 1);
return isDF(m52Row) &&
[
"65731", "65732", "65733", "65734", "65735",
"65736", "65737", "65738", "6574"
].includes(art) &&
!( art.startsWith('657') && (f1 === '4' || f1 === '5' || f1 === '8'));
}
},
'DF-3-7-1': {
label: "Fond social logement FSL",
filter(m52Row){
const f2 = m52Row['Fonction'].slice(0, 2);
return isDF(m52Row) &&
(f2 === '72') &&
('6556' === m52Row['Nature'] ||
'65561' === m52Row['Nature']);
}
},
'DF-3-7-2': {
label: "Bourses départementales",
filter(m52Row){
const f2 = m52Row['Fonction'].slice(0, 2);
return isDF(m52Row) && m52Row['Nature'] === '6513' &&
f2 !== '52' && f2 !== '81';
}
},
'DF-3-7-3': {
label: "Participation diverses",
filter(m52Row){
const f1 = m52Row['Fonction'].slice(0, 1);
const f2 = m52Row['Fonction'].slice(0, 2);
return isDF(m52Row) &&
(
f1 !== '4' && f1 !== '5' && f1 !== '8' &&
['6512', '65568'].includes(m52Row['Nature'])
) ||
(
m52Row['Nature'] === '6556' && m52Row['Fonction'] === '58'
) ||
(
f1 !== '4' && f1 !== '5' && f1 !== '8' && f2 !== '91' &&
['6561', '6568'].includes(m52Row['Nature'])
);
/*
D 91 6561 (600 000,00 €) utilisé dans DF-3-7-3, DF-6-4
D 91 6568 (151 221,00 €) utilisé dans DF-3-7-3, DF-6-4
*/
}
},
'DF-4': {
label: "Frais de personnel",
filter(m52Row){
const chap = m52Row['Chapitre'];
const art = m52Row['Nature'];
const f = m52Row['Fonction'];
const f2 = f.slice(0, 2);
return isDF(m52Row) &&
(
chap === '012' ||
(
(art.startsWith('64') || art === '6218' || art === '6336') &&
(chap === '015' || chap === '016' || chap === '017')
)
) &&
!((art.startsWith('64') || art === '6336') && f2 === '51') &&
!(art === '6336' && f === '568') &&
!((art === '64126' || art === '64121') && f2 === '50');
}
},
'DF-5': {
label: "Péréquation verticale",
filter(m52Row){
const art = m52Row['Nature'];
return isDF(m52Row) &&
['73913', '73914', '73926', '739261', '739262'].includes(art);
}
},
'DF-6-1-1': {
label: "Achats et fournitures",
filter(m52Row){
const f3 = m52Row['Fonction'].slice(0, 3);
const f1 = m52Row['Fonction'].slice(0, 1);
const art = m52Row['Nature'];
return isDF(m52Row) && art.startsWith('60') &&
!(['4', '5', '8'].includes(f1)) &&
!(f3 === '621');
}
},
'DF-6-1-2': {
label: "Prestations de services (entretien et réparation, assurances, locations, frais divers, formation, colloques…)",
filter(m52Row){
const f3 = m52Row['Fonction'].slice(0, 3);
const f1 = m52Row['Fonction'].slice(0, 1);
const art = m52Row['Nature'];
return isDF(m52Row) &&
art.startsWith('61') &&
!(['4', '5', '8'].includes(f1)) &&
!(f3 === '621');
}
},
'DF-6-1-3': {
label: "Frais divers (honoraires, conseils, reception, frais télécom, affranchissement, services bancaires…)",
filter(m52Row){
const f3 = m52Row['Fonction'].slice(0, 3);
const f1 = m52Row['Fonction'].slice(0, 1);
const art = m52Row['Nature'];
return isDF(m52Row) &&
art.startsWith('62') &&
!(['4', '5', '8'].includes(f1)) &&
!(f3 === '621') &&
art !== '6218';
}
},
'DF-6-1-4': {
label: "Autres impôts et taxes",
filter(m52Row){
const f3 = m52Row['Fonction'].slice(0, 3);
const f1 = m52Row['Fonction'].slice(0, 1);
const art = m52Row['Nature'];
return isDF(m52Row) &&
art.startsWith('63') &&
!(['4', '5', '8'].includes(f1)) &&
!(f3 === '621') &&
art !== '6336';
}
},
'DF-6-2': {
label: "Dépenses de voirie",
filter(m52Row){
const art = m52Row['Nature'];
const f3 = m52Row['Fonction'].slice(0, 3);
return isDF(m52Row) &&
f3 === '621' &&
(art.startsWith('60') || art.startsWith('61') || art.startsWith('62') || art.startsWith('63')) &&
art !== '6336' &&
art !== '6215';
}
},
'DF-6-3-1': {
label: "Questure/indemnités des élus",
filter(m52Row){
return isDF(m52Row) &&
[
"65861", "65862", "6531", "6532", "6533",
"6534", "65372", '6535'
].includes(m52Row['Nature']);
}
},
'DF-6-3-2': {
label: "Charges exceptionnelles et provisions",
filter(m52Row){
const f1 = m52Row['Fonction'].slice(0, 1);
const art = m52Row['Nature'];
return isDF(m52Row) &&
(art.startsWith('67') || art.startsWith('68')) &&
!(['4', '5', '8'].includes(f1));
}
},
'DF-6-3-3': {
label: "Autres",
filter(m52Row){
const f1 = m52Row['Fonction'].slice(0, 1);
const art = m52Row['Nature'];
return isDF(m52Row) &&
(
(art.startsWith('73') &&
!['73913', '73914', '73926', '739261', '739262'].includes(art)
) ||
['654', '6541', '6542', '6581', '65821', '65888', '65661'].includes(art)
) &&
!(['4', '5', '8'].includes(f1));
}
},
'DF-6-4': {
label: "Dotations transferts",
filter(m52Row){
const art = m52Row['Nature'];
const f2 = m52Row['Fonction'].slice(0, 2);
return isDF(m52Row) &&
(
f2 === '91' &&
['6561', '6568'].includes(art)
) ||
['65542'].includes(m52Row['Nature']);
}
},
'DF-7': {
label: "Intérêts des emprunts",
filter(m52Row){
return isDF(m52Row) && m52Row['Nature'].startsWith('66');
}
},
/**
* Recettes d’investissement
*/
'RI-1':{
label: "Fonds de Compensation de la Taxe sur la Valeur Ajoutée (FCTVA)",
filter(m52Row){
return isRI(m52Row) && m52Row['Nature'] === '10222';
}
},
'RI-2':{
label: "Dotation Décentralisée pour l’Equipement des collèges (DDEC)",
filter(m52Row){
return isRI(m52Row) && m52Row['Nature'] === '1332';
}
},
'RI-3':{
label: "Dotation Globale d’Equipement (DGE)",
filter(m52Row){
return isRI(m52Row) && (m52Row['Nature'] === '1341' || m52Row['Nature'] === '10221');
}
},
'RI-4': {
label: "Subventions",
filter(m52Row){
const art = m52Row['Nature'];
return isRI(m52Row) &&
art !== '1332' && art !== '1341' && art !== '1335' && art !== '1345' &&
(art.startsWith('13') || art.startsWith('204'))
}
},
'RI-5': {
label: "Divers",
filter(m52Row){
const article = m52Row['Nature'];
return isRI(m52Row) &&
article !== '204' &&
(
["165", "1676", "454121", "454421", "454428", "45821", '1335', '1345'].includes(article) ||
['20', '21', '22', '23', '26', '27'].includes(m52Row['Chapitre'])
)
}
},
'RI-6': {
label: "Cessions",
filter(m52Row){
// The choice of picking from "Recette de Fonctionnement" (RF) and not RI is deliberate
return isRF(m52Row) && m52Row['Nature'] === '775';
}
},
'RI-EM-1': {
label: "Emprunt nouveau",
filter(m52Row){
return isRI(m52Row) && ["1641", "16311", "167", "168","1631","16811"].includes(m52Row['Nature']);
}
},
'RI-EM-2': {
label: "OCLT",
filter(m52Row){
return isRI(m52Row) && ["16441"].includes(m52Row['Nature']);
}
},
/**
* Dépenses d’investissement
*/
'DI-1-1': {
label: "Collèges",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f3 = fonction.slice(0, 3);
return isDI(m52Row) &&
(
article.startsWith('20') ||
article.startsWith('21') ||
article.startsWith('23')
) &&
!article.startsWith('204') &&
f3 === '221';
}
},
'DI-1-2': {
label: "Routes",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f3 = fonction.slice(0, 3);
return isDI(m52Row) &&
(
article.startsWith('20') ||
article.startsWith('21') ||
article.startsWith('23') ||
// ajout des investissements effectués pour le compte de tiers articles 1321/1324 fonction 621
article.startsWith('13')
) &&
!article.startsWith('204') &&
['621', '622', '628'].includes(f3);
}
},
'DI-1-3': {
label: "Bâtiments",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f3 = fonction.slice(0, 3);
return isDI(m52Row) &&
(
(
article.startsWith('20') ||
article.startsWith('21') ||
article.startsWith('23')
) &&
!article.startsWith('204') &&
!['221', '621', '622', '628', '738'].includes(f3) ||
article === '1322'
);
}
},
'DI-1-4': {
label: "Aménagement",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f3 = fonction.slice(0, 3);
return isDI(m52Row) &&
(
([
"1311", "2031", "2111", "2157",
"2182", "21848", "2312", "231351", "2314",
"23152", "23153"
].includes(article) &&
f3 === '738' ) ||
article === '45441'
);
}
},
'DI-1-5': {
label: "Autres",
filter(m52Row){
const article = m52Row['Nature'];
//const otherEquipementPropreRuleIds = Object.keys(rules).filter(id => id.startsWith('DI-1') && id !== 'DI-1-4');
return isDI(m52Row) && article === '1675';
/* &&
otherEquipementPropreRuleIds.every(
id => !rules[id].filter(m52Row)
);*/
}
},
'DI-2-1': {
label: "subventions aux communes",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f2 = fonction.slice(0, 2);
return isDI(m52Row) &&
f2 !== '72' &&
['20414', '204141', '204142'].includes(article);
}
},
'DI-2-2': {
label: "logement",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f2 = fonction.slice(0, 2);
return isDI(m52Row) &&
['204142', '204182', '20422'].includes(article) &&
f2 === '72';
}
},
'DI-2-3': {
label: "sdis",
filter(m52Row){
const article = m52Row['Nature'];
return isDI(m52Row) && article === '2041781';
}
},
'DI-2-4': {
label: "subventions tiers (hors sdis)",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
return isDI(m52Row) &&
[
"204112", "204113", "204122", "204131", "204132",
"204151", "204152", "204162", "2041721", "2041722",
"2041782", "204181", "204182", "204182", "20421",
"20422", "20431", '2761', '261', '20421', '204183',
'204113', '1321','2748','1328','13278'
].includes(article) &&
fonction !== '72' &&
!(article === '204152' && fonction === '93') &&
!(article === '1321' && fonction === '621') &&
!(article === '204182' && fonction === '68');
}
},
'DI-2-5': {
label: "LGV",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f2 = fonction.slice(0, 2);
return isDI(m52Row) &&
"204182" === article &&
f2 === '68';
}
},
'DI-2-6': {
label: "Gironde Numérique",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f2 = fonction.slice(0, 2);
return isDI(m52Row) &&
"204152" === article &&
f2 === '93';
}
},
'DI-EM-1': {
label: "Amortissement emprunt",
filter(m52Row){
const article = m52Row['Nature'];
return isDI(m52Row) && ["1641", "16311", "167", "168", '16811'].includes(article);
}
},
'DI-EM-2': {
label: "Amortissement OCLT",
filter(m52Row){
const article = m52Row['Nature'];
return isDI(m52Row) && ["16441"].includes(article);
}
},
'DI-EM-3': {
label: "Divers emprunts",
filter(m52Row){
const article = m52Row['Nature'];
return isDI(m52Row) && ['1672', '165', '275'].includes(article);
}
},
// 2 lignes en DI et RI qui s'annulent
'REAM-OCLT-1': {
label: "Refinancement dette",
filter(m52Row){
const article = m52Row['Nature'];
return (isDI(m52Row) || isRI(m52Row)) && article === '166';
}
},
// 2 lignes en DI et RI qui s'annulent
'REAM-OCLT-2': {
label: "Opération tirage ligne de trésorerie",
filter(m52Row){
const article = m52Row['Nature'];
return (isDI(m52Row) || isRI(m52Row)) && article === '16449';
}
},
'EXC': {
label: "Excédents",
filter(m52Row){
const article = m52Row['Nature'];
return isRI(m52Row) && article === '1068';
}
}
});
const AggregatedInstructionRowRecord = Record({
"id": undefined,
"Libellé": undefined,
"Statut": undefined,
"M52Rows": undefined,
"Montant": 0
});
function makeAggregatedInstructionRowRecord(id, rows, corrections){
const rule = rules[id];
let relevantDocBudgRows = rows.filter(rule.filter).union(corrections);
return AggregatedInstructionRowRecord({
id,
"Libellé": rule.label,
"Statut": rule.status,
"M52Rows": relevantDocBudgRows,
"Montant": relevantDocBudgRows.reduce(((acc, r) => {
return acc + r["MtReal"];
}), 0)
})
}
export default function convert(docBudg, corrections = []){
const yearCorrections = corrections.filter(c => c['Exer'] === docBudg['Exer']);
return ImmutableSet(
Object.keys(rules)
.map(id => makeAggregatedInstructionRowRecord(
id,
docBudg.rows,
yearCorrections.filter(c => c['splitFor'] === id)
))
)
}
| src/shared/js/finance/m52ToAggregated.js | import {Record, OrderedSet as ImmutableSet} from 'immutable';
import {isRF, isDF, isRI, isDI} from './rowFilters';
/*
This file's very French and even Gironde-specific.
It describes, documents and encodes the rules that allows to get from
an "M52 budget" to a "budget agrégé"
*/
export const rules = Object.freeze({
/**
* Recettes de fonctionnement
*/
'RF-1-1' : {
label: 'Taxe Foncière sur les propriétés bâties+rôles supplémentaires',
filter(m52Row){
const article = m52Row['Nature'];
return isRF(m52Row) &&
['73111', '7318'].includes(article);
}
}
,
'RF-1-2' : {
label: "Cotisation sur la valeur ajoutée des entreprises (CVAE)",
filter(m52Row){
return isRF(m52Row) && ['7311', '73112'].includes(m52Row['Nature']);
}
},
'RF-1-3': {
label: "Imposition forfaitaire pour les entreprises de réseaux (IFER)",
filter(m52Row){
return isRF(m52Row) && m52Row['Nature'] === '73114';
}
},
'RF-1-4': { // should be 0 before 2016 and >0 in 2017
label: 'Reversement CVAE Région',
filter(m52Row){
return isRF(m52Row) && m52Row['Nature'] === '73123';
}
},
'RF-2-1': {
label: "Taxe Intérieure de Consommation sur les Produits Energétiques (TICPE)",
filter(m52Row){
return isRF(m52Row) && '7352' === m52Row['Nature'];
}
},
'RF-2-2': {
label: "Taxe Sur les Contrats d’Assurance (TSCA)",
filter(m52Row){
return isRF(m52Row) && m52Row['Nature'] === '7342';
}
},
'RF-3': {
label: "Droits de mutation à titre onéreux (DMTO)",
filter(m52Row){
return isRF(m52Row) && ['7321', '7322', '7482'].includes(m52Row['Nature']);
}
},
'RF-4-1': {
label: "Taxe d'aménagement (incluant les anciennes Taxe Départementale Espaces Naturels Sensibles (TDENS) et financement CAUE)",
filter(m52Row){
return isRF(m52Row) && ['7323', '7324', '7327'].includes(m52Row['Nature']);
}
},
'RF-4-2': {
label: "Taxe sur l’électricité",
filter(m52Row){
return isRF(m52Row) && m52Row['Nature'] === '7351';
}
},
'RF-4-3': {
label: "Redevance des mines",
filter(m52Row){
return isRF(m52Row) && m52Row['Nature'] === '7353';
}
},
'RF-4-4': {
label: "autres fiscalités",
filter(m52Row){
return isRF(m52Row) && ['7362', '7388', '738'].includes(m52Row['Nature']);
}
},
'RF-5-1': {
label: "Dotation Globale de Fonctionnement (DGF)",
filter(m52Row){
return isRF(m52Row) && ['7411', '74122', '74123'].includes(m52Row['Nature']);
}
},
'RF-5-2': {
label: "Dotation Globale de Décentralisation (DGD)",
filter(m52Row){
return isRF(m52Row) && '7461' === m52Row['Nature'];
}
},
'RF-5-3': {
label: "Compensations fiscales",
filter(m52Row){
return isRF(m52Row) && ['74833', '74834', '74835'].includes(m52Row['Nature']);
}
},
'RF-5-4': {
label: "Dotation de compensation de la réforme de la taxe professionnelle (DCRTP)",
filter(m52Row){
return isRF(m52Row) && '74832' === m52Row['Nature'];
}
},
'RF-5-5': {
label: "Fonds National de Garantie Individuelle de Ressources (FNGIR)",
filter(m52Row){
return isRF(m52Row) && '73121' === m52Row['Nature'];
}
},
'RF-5-6': {
label: "Autres dotations",
filter(m52Row){
return isRF(m52Row) && '744' === m52Row['Nature'];
}
},
'RF-6-1': {
label: "Indus RSA",
filter(m52Row){
// modifié pour le CA 2017
return isRF(m52Row) && ['75342', '75343', '7531'].includes(m52Row['Nature']);
}
},
'RF-6-2': {
label: "Contributions de la Caisse nationale de solidarité pour l'autonomie (CNSA)",
filter(m52Row){
return isRF(m52Row) && ['747811', '747812'].includes(m52Row['Nature']);
}
},
'RF-6-3': {
label: "Recouvrements sur bénéficiaires",
filter(m52Row){
return isRF(m52Row) && m52Row['Nature'] === '7513';
}
},
'RF-6-4': {
// This didn't exist in 2015
// It was new in 2016 and put in R53*A74788
// Since 2017, it'll be as A7478141+A7478142
label: "Conférence des financeurs",
filter(m52Row){
const fonction = m52Row['Fonction'];
return isRF(m52Row) && (
['7478141', '7478142'].includes(m52Row['Nature']) ||
(m52Row['Exercice'] === 2016 && m52Row['Nature'] === '74788' && fonction === '53')
)
}
},
'RF-6-5': {
label: "Autres",
filter(m52Row){
const fonction = m52Row['Fonction'];
const f1 = fonction.slice(0, 1);
const otherRecetteSocialeIds = Object.keys(rules)
.filter(id => id !== 'RF-6-5' && id.startsWith('RF-6-'));
return isRF(m52Row) &&
m52Row['Nature'] !== '74783' &&
m52Row['Nature'] !== '775' &&
(f1 === '4' || f1 === '5') &&
otherRecetteSocialeIds.every(
id => !rules[id].filter(m52Row)
)
}
},
'RF-7-1': {
label: "Fonds de Mobilisation Départementale pour l'Insertion (FMDI)",
filter(m52Row){
return isRF(m52Row) && m52Row['Nature'] === '74783';
}
},
'RF-7-2': {
label: "Dotation de compensation peréquée DCP",
filter(m52Row){
return isRF(m52Row) && m52Row['Nature'] === '73125';
}
},
'RF-7-3': {
label: "Fonds d'appui d'aide à domicile (CNSA AAD)",
status: 'TEMPORARY',
filter(m52Row){
//return isRF(m52Row) && m52Row['Nature'] === 'A74788';
}
},
'RF-7-4': {
label: "Fonds d'appui aux politiques d'insertion",
status: 'TEMPORARY',
filter(m52Row){
//return isRF(m52Row) && m52Row['Nature'] === 'A74718';
}
},
'RF-8-1': {
label: "Fonds de Péréquation DMTO et Fonds de solidarité",
filter(m52Row){
return isRF(m52Row) && ['7326', '73261', '73262'].includes(m52Row['Nature']);
}
},
'RF-8-2': {
label: "Fonds exceptionnel pour les départements en difficulté",
status: 'TEMPORARY',
filter(m52Row){
//return isRF(m52Row) && m52Row['Nature'] === 'A74718';
}
},
'RF-9-1': {
label: "Produits des domaines (ventes)",
filter(m52Row){
return isRF(m52Row) && m52Row['Nature'] === '752';
}
},
'RF-9-2': {
label: "Produits exceptionnels",
filter(m52Row){
const fonction = m52Row['Fonction'];
const f1 = fonction.slice(0, 1);
return isRF(m52Row) && f1!=='4' && f1!=='5' && [
'7817', '7711', '7714', '7718',
'773', '7788', '7875', '7816', '7866'
// ajout de l'article 7866 pour le CA 2017
].includes(m52Row['Nature']);
}
},
'RF-9-3': {
label: "Dotations et participations (dont fonds européens)",
filter(m52Row){
const fonction = m52Row['Fonction'];
const f1 = fonction.slice(0, 1);
return isRF(m52Row) && f1!=='4' && f1!=='5' && [
'7475', '7476', '74771', '74772', '74778',
'74788', '74888', '74718', '7474', '7472',
'7473', '7478228'
].includes(m52Row['Nature']);
}
},
'RF-9-4': {
label: "Restauration collège",
filter(m52Row){
return isRF(m52Row) && m52Row['Nature'] === '74881';
}
},
'RF-9-5': {
label: "Produits des services",
filter(m52Row){
const fonction = m52Row['Fonction'];
const f1 = fonction.slice(0, 1);
return isRF(m52Row) && f1 !== '4' && f1 !== '5' && m52Row['Nature'].startsWith('70');
}
},
'RF-9-6': {
label: "Remboursement charges de personnels",
filter(m52Row){
const fonction = m52Row['Fonction'];
const f1 = fonction.slice(0, 1);
return isRF(m52Row) && f1 !== '4' && f1 !=='5' && ['6419', '6459', '6479'].includes(m52Row['Nature']);
}
},
'RF-9-7': {
label: "Autres produits de gestions courants",
filter(m52Row){
const fonction = m52Row['Fonction'];
const article = m52Row['Nature'];
const f1 = fonction.slice(0, 1);
return isRF(m52Row) &&
f1 !== '4' && f1 !== '5' &&
article.startsWith('75') &&
article !== '752' &&
article !== '7513' &&
article !== '75342' &&
article !== '75343' &&
// article exclus pour le CA 2017
article !== '7511' &&
article !== '7535' &&
article !== '7533' &&
article !== '7512' &&
article !== '7531';
}
},
'RF-9-8': {
label: "Produits financiers",
filter(m52Row){
return isRF(m52Row) && m52Row['Nature'].startsWith('76');
}
},
/**
* Dépenses de fonctionnement
*/
'DF-1-1-1': {
label: "Pour les personnes handicapées",
filter(m52Row){
return isDF(m52Row) && ['652221', '65242'].includes(m52Row['Nature']);
}
},
'DF-1-1-2': {
label: "Frais d’hébergement - Pour les personnes âgées",
filter(m52Row){
return isDF(m52Row) && ['652224', '65243'].includes(m52Row['Nature']);
}
},
'DF-1-1-3': {
label: "Liés à l’enfance",
// Also contains R51 A65111 from a correction
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
return isDF(m52Row) &&
(
fonction.slice(0, 2) === '51' &&
(
[
"6132", "6135", "6184",
"6234", "6245",
"65221", "652222", "65223", "65228",
"6523", "652411", "652412", "652415", "652418",
"65821", "6718", "6336"
].includes(article) ||
article.startsWith('64')
)
||
(fonction === '50' && article === '64121') ||
(fonction === '50' && article === '64126')
);
}
},
'DF-1-2': {
label: "Revenu de Solidarité Active (RSA)",
filter(m52Row){
return isDF(m52Row) && ['6515', '65171', '65172'].includes(m52Row['Nature']);
}
},
'DF-1-3': {
label: "Prestation Compensatoire du Handicap (PCH) + Allocation Compensatrice aux Tierces Personnes (ACTP)",
filter(m52Row){
return isDF(m52Row) && ['6511211', '6511212', '651128', '651122'].includes(m52Row['Nature']);
}
},
'DF-1-4': {
label: "Allocation Personnalisée d’Autonomie (APA)",
filter(m52Row){
return isDF(m52Row) && ['651141', '651142', '651143', '651144', '651148'].includes(m52Row['Nature']);
}
},
'DF-1-5': {
label: "Préventions enfants",
// Also contains R51 A65111 from a correction
filter(m52Row){
const fonction = m52Row['Fonction'];
return isDF(m52Row) &&
fonction.slice(0, 2) === '51' &&
['652416', '6514'].includes(m52Row['Nature']);
}
},
'DF-1-6': {
label: "Subventions sociales",
filter(m52Row){
const fonction = m52Row['Fonction'];
const art = m52Row['Nature'];
const f1 = fonction.slice(0, 1);
return isDF(m52Row) &&
(f1 === '4' || f1 === '5') &&
art.startsWith('657') &&
fonction !== '51';
}
},
'DF-1-7-1': {
label: "Autres divers enfants",
filter(m52Row){
const fonction = m52Row['Fonction'];
return isDF(m52Row) &&
fonction.slice(0, 2) === '51' &&
[
"6068", "6188", "616", "62268", "6227",
"62878", "654", "6541", "6542", "6568",
"65734", "65737", "6574", "673", "6745"
].includes(m52Row['Nature']);
}
},
'DF-1-7-2': {
label: "Divers social - Autres",
filter(m52Row){
const fonction = m52Row['Fonction'];
const art = m52Row['Nature'];
const f1 = fonction.slice(0, 1);
const parPrestationRuleIds = Object.keys(rules).filter(id => id.startsWith('DF-1-') && id !== 'DF-1-7-2');
return isDF(m52Row) &&
(f1 === '4' || f1 === '5') &&
(
art.startsWith('60') || art.startsWith('61') || art.startsWith('62') ||
art.startsWith('63') || art.startsWith('65') || art.startsWith('67')
) &&
parPrestationRuleIds.every(
id => !rules[id].filter(m52Row)
) &&
!(art === '6556' && fonction === '58') &&
!(art === '6568' && fonction === '52') &&
!(art === '6526' && fonction === '51') &&
!(art === '6513' && fonction === '52') &&
!(art === '6336') &&
!(art === '6218') &&
!(art === '6245' && fonction === '568') &&
!(art === '6245' && fonction === '52') &&
!(art === '65111' && fonction === '51');
}
},
'DF-2-1': {
label: "Personnes en difficultés",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f2 = fonction.slice(0, 2);
return isDF(m52Row) && (f2 === '54' || f2 === '56') &&
article !== '6568' &&
article !== '6513' &&
!article.startsWith('64') &&
article !== '6336' &&
article !== '6245';
}
},
'DF-2-2': {
label: "Personnes handicapées",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f2 = fonction.slice(0, 2);
return isDF(m52Row) && f2 === '52' &&
article !== '6568' &&
article !== '6513' &&
!article.startsWith('64') &&
article !== '6336' &&
article !== '6245';
}
},
'DF-2-3': {
label: "Personnes âgées",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f2 = fonction.slice(0, 2);
return isDF(m52Row) && (f2 === '55' || f2 === '53') &&
article !== '6513' &&
!article.startsWith('64') &&
article !== '6336' &&
article !== '6245';
}
},
'DF-2-4': {
label: "Enfance",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f2 = fonction.slice(0, 2);
return isDF(m52Row) &&
(
(f2 === '51' && article !== '6526') ||
(f2 === '50' && article === '64121') ||
(f2 === '50' && article === '64126')
)
}
},
'DF-2-5': {
label: "Autres",
filter(m52Row){
const fonction = m52Row['Fonction'];
const article = m52Row['Nature'];
const f2 = fonction.slice(0, 2);
return isDF(m52Row) &&
['58', '50', '40', '41', '42', '48'].includes(f2) &&
!(article === '6556' && fonction === '58')
&& !article.startsWith('64')
&& article !== '6336' &&
article !== '6218';
}
},
'DF-3-1': {
label: "Service Départemental d'Incendie et de Secours (SDIS)",
filter(m52Row){
return isDF(m52Row) && m52Row['Nature'] === '6553';
}
},
'DF-3-2': {
label: "Transports",
filter(m52Row){
const f = m52Row['Fonction'];
const f1 = f.slice(0, 1);
const article = m52Row['Nature']
return isDF(m52Row) && (
(f1 === '8' && !article.startsWith('64') && article !== '6336') ||
(
f === '568' &&
(
article === '6245' ||
article === '6336' ||
article === '6218'
)
)
)
}
},
'DF-3-3': {
label: "Transports des étudiants et des élèves handicapés",
filter(m52Row){
const fonction = m52Row['Fonction'];
const f2 = fonction.slice(0, 2);
return isDF(m52Row) &&
f2 === '52' &&
['6245', '6513', '6568'].includes(m52Row['Nature']);
}
},
'DF-3-4': {
label: "Prévention spécialisée",
filter(m52Row){
const f = m52Row['Fonction'];
return isDF(m52Row) && ['6526', '6563'].includes(m52Row['Nature']) && f === '51';
}
},
'DF-3-5': {
label: "Dotation de fonctionnement des collèges",
filter(m52Row){
return isDF(m52Row) && ['65511', '65512'].includes(m52Row['Nature']);
}
},
'DF-3-6': {
label: "Subventions de fonctionnement",
filter(m52Row){
const art = m52Row['Nature'];
const f1 = m52Row['Fonction'].slice(0, 1);
return isDF(m52Row) &&
[
"65731", "65732", "65733", "65734", "65735",
"65736", "65737", "65738", "6574"
].includes(art) &&
!( art.startsWith('657') && (f1 === '4' || f1 === '5' || f1 === '8'));
}
},
'DF-3-7-1': {
label: "Fond social logement FSL",
filter(m52Row){
const f2 = m52Row['Fonction'].slice(0, 2);
return isDF(m52Row) &&
(f2 === '72') &&
('6556' === m52Row['Nature'] ||
'65561' === m52Row['Nature']);
}
},
'DF-3-7-2': {
label: "Bourses départementales",
filter(m52Row){
const f2 = m52Row['Fonction'].slice(0, 2);
return isDF(m52Row) && m52Row['Nature'] === '6513' &&
f2 !== '52' && f2 !== '81';
}
},
'DF-3-7-3': {
label: "Participation diverses",
filter(m52Row){
const f1 = m52Row['Fonction'].slice(0, 1);
const f2 = m52Row['Fonction'].slice(0, 2);
return isDF(m52Row) &&
(
f1 !== '4' && f1 !== '5' && f1 !== '8' &&
['6512', '65568'].includes(m52Row['Nature'])
) ||
(
m52Row['Nature'] === '6556' && m52Row['Fonction'] === '58'
) ||
(
f1 !== '4' && f1 !== '5' && f1 !== '8' && f2 !== '91' &&
['6561', '6568'].includes(m52Row['Nature'])
);
/*
D 91 6561 (600 000,00 €) utilisé dans DF-3-7-3, DF-6-4
D 91 6568 (151 221,00 €) utilisé dans DF-3-7-3, DF-6-4
*/
}
},
'DF-4': {
label: "Frais de personnel",
filter(m52Row){
const chap = m52Row['Chapitre'];
const art = m52Row['Nature'];
const f = m52Row['Fonction'];
const f2 = f.slice(0, 2);
return isDF(m52Row) &&
(
chap === '012' ||
(
(art.startsWith('64') || art === '6218' || art === '6336') &&
(chap === '015' || chap === '016' || chap === '017')
)
) &&
!((art.startsWith('64') || art === '6336') && f2 === '51') &&
!(art === '6336' && f === '568') &&
!((art === '64126' || art === '64121') && f2 === '50');
}
},
'DF-5': {
label: "Péréquation verticale",
filter(m52Row){
const art = m52Row['Nature'];
return isDF(m52Row) &&
['73913', '73914', '73926', '739261', '739262'].includes(art);
}
},
'DF-6-1-1': {
label: "Achats et fournitures",
filter(m52Row){
const f3 = m52Row['Fonction'].slice(0, 3);
const f1 = m52Row['Fonction'].slice(0, 1);
const art = m52Row['Nature'];
return isDF(m52Row) && art.startsWith('60') &&
!(['4', '5', '8'].includes(f1)) &&
!(f3 === '621');
}
},
'DF-6-1-2': {
label: "Prestations de services (entretien et réparation, assurances, locations, frais divers, formation, colloques…)",
filter(m52Row){
const f3 = m52Row['Fonction'].slice(0, 3);
const f1 = m52Row['Fonction'].slice(0, 1);
const art = m52Row['Nature'];
return isDF(m52Row) &&
art.startsWith('61') &&
!(['4', '5', '8'].includes(f1)) &&
!(f3 === '621');
}
},
'DF-6-1-3': {
label: "Frais divers (honoraires, conseils, reception, frais télécom, affranchissement, services bancaires…)",
filter(m52Row){
const f3 = m52Row['Fonction'].slice(0, 3);
const f1 = m52Row['Fonction'].slice(0, 1);
const art = m52Row['Nature'];
return isDF(m52Row) &&
art.startsWith('62') &&
!(['4', '5', '8'].includes(f1)) &&
!(f3 === '621') &&
art !== '6218';
}
},
'DF-6-1-4': {
label: "Autres impôts et taxes",
filter(m52Row){
const f3 = m52Row['Fonction'].slice(0, 3);
const f1 = m52Row['Fonction'].slice(0, 1);
const art = m52Row['Nature'];
return isDF(m52Row) &&
art.startsWith('63') &&
!(['4', '5', '8'].includes(f1)) &&
!(f3 === '621') &&
art !== '6336';
}
},
'DF-6-2': {
label: "Dépenses de voirie",
filter(m52Row){
const art = m52Row['Nature'];
const f3 = m52Row['Fonction'].slice(0, 3);
return isDF(m52Row) &&
f3 === '621' &&
(art.startsWith('60') || art.startsWith('61') || art.startsWith('62') || art.startsWith('63')) &&
art !== '6336' &&
art !== '6215';
}
},
'DF-6-3-1': {
label: "Questure/indemnités des élus",
filter(m52Row){
return isDF(m52Row) &&
[
"65861", "65862", "6531", "6532", "6533",
"6534", "65372", '6535'
].includes(m52Row['Nature']);
}
},
'DF-6-3-2': {
label: "Charges exceptionnelles et provisions",
filter(m52Row){
const f1 = m52Row['Fonction'].slice(0, 1);
const art = m52Row['Nature'];
return isDF(m52Row) &&
(art.startsWith('67') || art.startsWith('68')) &&
!(['4', '5', '8'].includes(f1));
}
},
'DF-6-3-3': {
label: "Autres",
filter(m52Row){
const f1 = m52Row['Fonction'].slice(0, 1);
const art = m52Row['Nature'];
return isDF(m52Row) &&
(
(art.startsWith('73') &&
!['73913', '73914', '73926', '739261', '739262'].includes(art)
) ||
['654', '6541', '6542', '6581', '65821', '65888', '65661'].includes(art)
) &&
!(['4', '5', '8'].includes(f1));
}
},
'DF-6-4': {
label: "Dotations transferts",
filter(m52Row){
const art = m52Row['Nature'];
const f2 = m52Row['Fonction'].slice(0, 2);
return isDF(m52Row) &&
(
f2 === '91' &&
['6561', '6568'].includes(art)
) ||
['65542'].includes(m52Row['Nature']);
}
},
'DF-7': {
label: "Intérêts des emprunts",
filter(m52Row){
return isDF(m52Row) && m52Row['Nature'].startsWith('66');
}
},
/**
* Recettes d’investissement
*/
'RI-1':{
label: "Fonds de Compensation de la Taxe sur la Valeur Ajoutée (FCTVA)",
filter(m52Row){
return isRI(m52Row) && m52Row['Nature'] === '10222';
}
},
'RI-2':{
label: "Dotation Décentralisée pour l’Equipement des collèges (DDEC)",
filter(m52Row){
return isRI(m52Row) && m52Row['Nature'] === '1332';
}
},
'RI-3':{
label: "Dotation Globale d’Equipement (DGE)",
filter(m52Row){
return isRI(m52Row) && (m52Row['Nature'] === '1341' || m52Row['Nature'] === '10221');
}
},
'RI-4': {
label: "Subventions",
filter(m52Row){
const art = m52Row['Nature'];
return isRI(m52Row) &&
art !== '1332' && art !== '1341' && art !== '1335' && art !== '1345' &&
(art.startsWith('13') || art.startsWith('204'))
}
},
'RI-5': {
label: "Divers",
filter(m52Row){
const article = m52Row['Nature'];
return isRI(m52Row) &&
article !== '204' &&
(
["165", "1676", "454121", "454421", "454428", "45821", '1335', '1345'].includes(article) ||
['20', '21', '22', '23', '26', '27'].includes(m52Row['Chapitre'])
)
}
},
'RI-6': {
label: "Cessions",
filter(m52Row){
// The choice of picking from "Recette de Fonctionnement" (RF) and not RI is deliberate
return isRF(m52Row) && m52Row['Nature'] === '775';
}
},
'RI-EM-1': {
label: "Emprunt nouveau",
filter(m52Row){
return isRI(m52Row) && ["1641", "16311", "167", "168","1631","16811"].includes(m52Row['Nature']);
}
},
'RI-EM-2': {
label: "OCLT",
filter(m52Row){
return isRI(m52Row) && ["16441"].includes(m52Row['Nature']);
}
},
/**
* Dépenses d’investissement
*/
'DI-1-1': {
label: "Collèges",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f3 = fonction.slice(0, 3);
return isDI(m52Row) &&
(
article.startsWith('20') ||
article.startsWith('21') ||
article.startsWith('23')
) &&
!article.startsWith('204') &&
f3 === '221';
}
},
'DI-1-2': {
label: "Routes",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f3 = fonction.slice(0, 3);
return isDI(m52Row) &&
(
article.startsWith('20') ||
article.startsWith('21') ||
article.startsWith('23') ||
// ajout des investissements effectués pour le compte de tiers articles 1321/1324 fonction 621
article.startsWith('13')
) &&
!article.startsWith('204') &&
['621', '622', '628'].includes(f3);
}
},
'DI-1-3': {
label: "Bâtiments",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f3 = fonction.slice(0, 3);
return isDI(m52Row) &&
(
(
article.startsWith('20') ||
article.startsWith('21') ||
article.startsWith('23')
) &&
!article.startsWith('204') &&
!['221', '621', '622', '628', '738'].includes(f3) ||
article === '1322'
);
}
},
'DI-1-4': {
label: "Aménagement",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f3 = fonction.slice(0, 3);
return isDI(m52Row) &&
(
([
"1311", "2031", "2111", "2157",
"2182", "21848", "2312", "231351", "2314",
"23152", "23153"
].includes(article) &&
f3 === '738' ) ||
article === '45441'
);
}
},
'DI-1-5': {
label: "Autres",
filter(m52Row){
const article = m52Row['Nature'];
//const otherEquipementPropreRuleIds = Object.keys(rules).filter(id => id.startsWith('DI-1') && id !== 'DI-1-4');
return isDI(m52Row) && article === '1675';
/* &&
otherEquipementPropreRuleIds.every(
id => !rules[id].filter(m52Row)
);*/
}
},
'DI-2-1': {
label: "subventions aux communes",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f2 = fonction.slice(0, 2);
return isDI(m52Row) &&
f2 !== '72' &&
['20414', '204141', '204142'].includes(article);
}
},
'DI-2-2': {
label: "logement",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f2 = fonction.slice(0, 2);
return isDI(m52Row) &&
['204142', '204182', '20422'].includes(article) &&
f2 === '72';
}
},
'DI-2-3': {
label: "sdis",
filter(m52Row){
const article = m52Row['Nature'];
return isDI(m52Row) && article === '2041781';
}
},
'DI-2-4': {
label: "subventions tiers (hors sdis)",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
return isDI(m52Row) &&
[
"204112", "204113", "204122", "204131", "204132",
"204151", "204152", "204162", "2041721", "2041722",
"2041782", "204181", "204182", "204182", "20421",
"20422", "20431", '2761', '261', '20421', '204183',
'204113', '1321','2748','1328','13278'
].includes(article) &&
fonction !== '72' &&
!(article === '204152' && fonction === '93') &&
!(article === '1321' && fonction === '621') &&
!(article === '204182' && fonction === '68');
}
},
'DI-2-5': {
label: "LGV",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f2 = fonction.slice(0, 2);
return isDI(m52Row) &&
"204182" === article &&
f2 === '68';
}
},
'DI-2-6': {
label: "Gironde Numérique",
filter(m52Row){
const article = m52Row['Nature'];
const fonction = m52Row['Fonction'];
const f2 = fonction.slice(0, 2);
return isDI(m52Row) &&
"204152" === article &&
f2 === '93';
}
},
'DI-EM-1': {
label: "Amortissement emprunt",
filter(m52Row){
const article = m52Row['Nature'];
return isDI(m52Row) && ["1641", "16311", "167", "168", '16811'].includes(article);
}
},
'DI-EM-2': {
label: "Amortissement OCLT",
filter(m52Row){
const article = m52Row['Nature'];
return isDI(m52Row) && ["16441"].includes(article);
}
},
'DI-EM-3': {
label: "Divers emprunts",
filter(m52Row){
const article = m52Row['Nature'];
return isDI(m52Row) && ['1672', '165', '275'].includes(article);
}
},
// 2 lignes en DI et RI qui s'annulent
'REAM-OCLT-1': {
label: "Refinancement dette",
filter(m52Row){
const article = m52Row['Nature'];
return (isDI(m52Row) || isRI(m52Row)) && article === '166';
}
},
// 2 lignes en DI et RI qui s'annulent
'REAM-OCLT-2': {
label: "Opération tirage ligne de trésorerie",
filter(m52Row){
const article = m52Row['Nature'];
return (isDI(m52Row) || isRI(m52Row)) && article === '16449';
}
},
'EXC': {
label: "Excédents",
filter(m52Row){
const article = m52Row['Nature'];
return isRI(m52Row) && article === '1068';
}
}
});
const AggregatedInstructionRowRecord = Record({
"id": undefined,
"Libellé": undefined,
"Statut": undefined,
"M52Rows": undefined,
"Montant": 0
});
function makeAggregatedInstructionRowRecord(id, rows, corrections){
const rule = rules[id];
let relevantDocBudgRows = rows.filter(rule.filter).union(corrections);
return AggregatedInstructionRowRecord({
id,
"Libellé": rule.label,
"Statut": rule.status,
"M52Rows": relevantDocBudgRows,
"Montant": relevantDocBudgRows.reduce(((acc, r) => {
return acc + r["MtReal"];
}), 0)
})
}
export default function convert(docBudg, corrections = []){
const yearCorrections = corrections.filter(c => c['Exer'] === docBudg['Exer']);
return ImmutableSet(
Object.keys(rules)
.map(id => makeAggregatedInstructionRowRecord(
id,
docBudg.rows,
yearCorrections.filter(c => c['splitFor'] === id)
))
)
}
| ajout d'un article suite à une modification d'imputation comptable DF-1-8
| src/shared/js/finance/m52ToAggregated.js | ajout d'un article suite à une modification d'imputation comptable DF-1-8 | <ide><path>rc/shared/js/finance/m52ToAggregated.js
<ide> !(art === '6218') &&
<ide> !(art === '6245' && fonction === '568') &&
<ide> !(art === '6245' && fonction === '52') &&
<del> !(art === '65111' && fonction === '51');
<del> }
<del> },
<del>
<add> !(art === '65111' && fonction === '51') &&
<add> !((art === '65113' || art === '6568') && fonction.startsWith('53'));
<add> }
<add> },
<add> 'DF-1-8': {
<add> label: "Conférence des financeurs",
<add> filter(m52Row){
<add> const fonction = m52Row['Fonction'];
<add>
<add> return isDF(m52Row) &&
<add> fonction.startsWith('53') &&
<add> [
<add> "61113", "6568"
<add> ].includes(m52Row['Nature']);
<add> }
<add> },
<ide> 'DF-2-1': {
<ide> label: "Personnes en difficultés",
<ide> filter(m52Row){ |
|
Java | apache-2.0 | 2b77eb4885666fd682f5b10f63873875cc86ca95 | 0 | GerHobbelt/closure-compiler,GerHobbelt/closure-compiler,GerHobbelt/closure-compiler,GerHobbelt/closure-compiler | /*
* Copyright 2009 The Closure Compiler 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 com.google.javascript.jscomp;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Ascii;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.primitives.Chars;
import com.google.javascript.jscomp.deps.ModuleLoader;
import com.google.javascript.jscomp.parsing.Config;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.SourcePosition;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Properties;
import javax.annotation.Nullable;
/**
* Compiler options
*
* @author [email protected] (Nick Santos)
*/
public class CompilerOptions implements Serializable {
// The number of characters after which we insert a line break in the code
static final int DEFAULT_LINE_LENGTH_THRESHOLD = 500;
static final char[] POLYMER_PROPERTY_RESERVED_FIRST_CHARS =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ$".toCharArray();
static final char[] POLYMER_PROPERTY_RESERVED_NON_FIRST_CHARS = "_$".toCharArray();
static final char[] ANGULAR_PROPERTY_RESERVED_FIRST_CHARS = {'$'};
/**
* A common enum for compiler passes that can run either globally or locally.
*/
public enum Reach {
ALL,
LOCAL_ONLY,
NONE
}
// TODO(nicksantos): All public properties of this class should be made
// package-private, and have a public setter.
/**
* Should the compiled output start with "'use strict';"?
*
* <p>Ignored for non-strict output language modes.
*/
private boolean emitUseStrict = true;
/**
* The JavaScript language version accepted.
*/
private LanguageMode languageIn;
/**
* The JavaScript language version that should be produced.
*/
private LanguageMode languageOut;
/**
* The builtin set of externs to be used
*/
private Environment environment;
/**
* If true, don't transpile ES6 to ES3.
* WARNING: Enabling this option will likely cause the compiler to crash
* or produce incorrect output.
*/
boolean skipTranspilationAndCrash = false;
/**
* Allow disabling ES6 to ES3 transpilation.
*/
public void setSkipTranspilationAndCrash(boolean value) {
skipTranspilationAndCrash = value;
}
/**
* Sets the input sourcemap files, indexed by the JS files they refer to.
*
* @param inputSourceMaps the collection of input sourcemap files
*/
public void setInputSourceMaps(final ImmutableMap<String, SourceMapInput> inputSourceMaps) {
this.inputSourceMaps = inputSourceMaps;
}
/**
* Whether to infer consts. This should not be configurable by
* external clients. This is a transitional flag for a new type
* of const analysis.
*
* TODO(nicksantos): Remove this option.
*/
boolean inferConsts = true;
// TODO(tbreisacher): Remove this method after ctemplate issues are solved.
public void setInferConst(boolean value) {
inferConsts = value;
}
/**
* Whether the compiler should assume that a function's "this" value
* never needs coercion (for example in non-strict "null" or "undefined" will
* be coerced to the global "this" and primitives to objects).
*/
private boolean assumeStrictThis;
private boolean allowHotswapReplaceScript = false;
private boolean preserveDetailedSourceInfo = false;
private boolean continueAfterErrors = false;
public enum IncrementalCheckMode {
/** Normal mode */
OFF,
/**
* The compiler should generate an output file that represents the type-only interface
* of the code being compiled. This is useful for incremental type checking.
*/
GENERATE_IJS,
/**
* The compiler should check type-only interface definitions generated above.
*/
CHECK_IJS,
}
private IncrementalCheckMode incrementalCheckMode = IncrementalCheckMode.OFF;
public void setIncrementalChecks(IncrementalCheckMode value) {
incrementalCheckMode = value;
switch (value) {
case OFF:
break;
case GENERATE_IJS:
setPreserveTypeAnnotations(true);
setOutputJs(OutputJs.NORMAL);
break;
case CHECK_IJS:
setChecksOnly(true);
setOutputJs(OutputJs.SENTINEL);
break;
}
}
public boolean shouldGenerateTypedExterns() {
return incrementalCheckMode == IncrementalCheckMode.GENERATE_IJS;
}
public boolean allowIjsInputs() {
return incrementalCheckMode != IncrementalCheckMode.OFF;
}
public boolean allowUnfulfilledForwardDeclarations() {
return incrementalCheckMode == IncrementalCheckMode.OFF;
}
private Config.JsDocParsing parseJsDocDocumentation = Config.JsDocParsing.TYPES_ONLY;
/**
* Even if checkTypes is disabled, clients such as IDEs might want to still infer types.
*/
boolean inferTypes;
private boolean useNewTypeInference;
/**
* Relevant only when {@link #useNewTypeInference} is true, where we normally disable OTI errors.
* If you want both NTI and OTI errors in this case, set to true.
* E.g. if using using a warnings guard to filter NTI or OTI warnings in new or legacy code,
* respectively.
* This will be removed when NTI entirely replaces OTI.
*/
boolean reportOTIErrorsUnderNTI = false;
/**
* Configures the compiler to skip as many passes as possible.
* If transpilation is requested, it will be run, but all others passes will be skipped.
*/
boolean skipNonTranspilationPasses;
/**
* Configures the compiler to run expensive sanity checks after
* every pass. Only intended for internal development.
*/
DevMode devMode;
/**
* Configures the compiler to log a hash code of the AST after
* every pass. Only intended for internal development.
*/
private boolean checkDeterminism;
//--------------------------------
// Input Options
//--------------------------------
DependencyOptions dependencyOptions = new DependencyOptions();
// TODO(tbreisacher): When this is false, report an error if there's a goog.provide
// in an externs file.
boolean allowGoogProvideInExterns() {
return allowIjsInputs();
}
/** Returns localized replacement for MSG_* variables */
public MessageBundle messageBundle = null;
//--------------------------------
// Checks
//--------------------------------
/** Checks that all symbols are defined */
// TODO(tbreisacher): Remove this and deprecate the corresponding setter.
public boolean checkSymbols;
/** Checks for suspicious statements that have no effect */
public boolean checkSuspiciousCode;
/** Checks types on expressions */
public boolean checkTypes;
public CheckLevel checkGlobalNamesLevel;
/**
* Checks the integrity of references to qualified global names.
* (e.g. "a.b")
*/
public void setCheckGlobalNamesLevel(CheckLevel level) {
checkGlobalNamesLevel = level;
}
@Deprecated
public CheckLevel brokenClosureRequiresLevel;
/**
* Sets the check level for bad Closure require calls.
* Do not use; this should always be an error.
*/
@Deprecated
public void setBrokenClosureRequiresLevel(CheckLevel level) {
brokenClosureRequiresLevel = level;
}
public CheckLevel checkGlobalThisLevel;
/**
* Checks for certain uses of the {@code this} keyword that are considered
* unsafe because they are likely to reference the global {@code this}
* object unintentionally.
*
* If this is off, but collapseProperties is on, then the compiler will
* usually ignore you and run this check anyways.
*/
public void setCheckGlobalThisLevel(CheckLevel level) {
this.checkGlobalThisLevel = level;
}
public CheckLevel checkMissingGetCssNameLevel;
/**
* Checks that certain string literals only appear in strings used as
* goog.getCssName arguments.
*/
public void setCheckMissingGetCssNameLevel(CheckLevel level) {
this.checkMissingGetCssNameLevel = level;
}
/**
* Regex of string literals that may only appear in goog.getCssName arguments.
*/
public String checkMissingGetCssNameBlacklist;
/**
* A set of extra annotation names which are accepted and silently ignored
* when encountered in a source file. Defaults to null which has the same
* effect as specifying an empty set.
*/
Set<String> extraAnnotationNames;
/**
* Policies to determine the disposal checking level.
*/
public enum DisposalCheckingPolicy {
/**
* Don't check any disposal.
*/
OFF,
/**
* Default/conservative disposal checking.
*/
ON,
/**
* Aggressive disposal checking.
*/
AGGRESSIVE,
}
/**
* Check for patterns that are known to cause memory leaks.
*/
DisposalCheckingPolicy checkEventfulObjectDisposalPolicy;
public void setCheckEventfulObjectDisposalPolicy(DisposalCheckingPolicy policy) {
this.checkEventfulObjectDisposalPolicy = policy;
// The CheckEventfulObjectDisposal pass requires types so enable inferring types if
// this pass is enabled.
if (policy != DisposalCheckingPolicy.OFF) {
this.inferTypes = true;
}
}
public DisposalCheckingPolicy getCheckEventfulObjectDisposalPolicy() {
return checkEventfulObjectDisposalPolicy;
}
/**
* Used for projects that are not well maintained, but are still used.
* Does not allow promoting warnings to errors, and disables some potentially
* risky optimizations.
*/
boolean legacyCodeCompile = false;
public boolean getLegacyCodeCompile() {
return this.legacyCodeCompile;
}
public void setLegacyCodeCompile(boolean legacy) {
this.legacyCodeCompile = legacy;
}
// TODO(bradfordcsmith): Investigate how can we use multi-threads as default.
int numParallelThreads = 1;
/**
* Sets the level of parallelism for compilation passes that can exploit multi-threading.
*
* <p>Some compiler passes may take advantage of multi-threading, for example, parsing inputs.
* This sets the level of parallelism. The compiler will not start more than this number of
* threads.
*
* @param parallelism up to this number of parallel threads may be created.
*/
public void setNumParallelThreads(int parallelism) {
numParallelThreads = parallelism;
}
//--------------------------------
// Optimizations
//--------------------------------
/** Prefer commas over semicolons when doing statement fusion */
boolean aggressiveFusion;
/** Folds constants (e.g. (2 + 3) to 5) */
public boolean foldConstants;
/** Remove assignments to values that can not be referenced */
public boolean deadAssignmentElimination;
/** Inlines constants (symbols that are all CAPS) */
public boolean inlineConstantVars;
/** Inlines global functions */
public boolean inlineFunctions;
/**
* For projects that want to avoid the creation of giant functions after
* inlining.
*/
int maxFunctionSizeAfterInlining;
static final int UNLIMITED_FUN_SIZE_AFTER_INLINING = -1;
/** Inlines functions defined in local scopes */
public boolean inlineLocalFunctions;
/** More aggressive function inlining */
boolean assumeClosuresOnlyCaptureReferences;
/** Inlines properties */
private boolean inlineProperties;
/** Move code to a deeper module */
public boolean crossModuleCodeMotion;
/**
* Don't generate stub functions when moving methods deeper.
*
* Note, switching on this option may break existing code that depends on
* enumerating prototype methods for mixin behavior, such as goog.mixin or
* goog.object.extend, since the prototype assignments will be removed from
* the parent module and moved to a later module.
**/
boolean crossModuleCodeMotionNoStubMethods;
/**
* Whether when module B depends on module A and module B declares a symbol,
* this symbol can be seen in A after B has been loaded. This is often true,
* but may not be true when loading code using nested eval.
*/
boolean parentModuleCanSeeSymbolsDeclaredInChildren;
/** Merge two variables together as one. */
public boolean coalesceVariableNames;
/** Move methods to a deeper module */
public boolean crossModuleMethodMotion;
/** Inlines trivial getters */
boolean inlineGetters;
/** Inlines variables */
public boolean inlineVariables;
/** Inlines variables */
boolean inlineLocalVariables;
// TODO(user): This is temporary. Once flow sensitive inlining is stable
// Remove this.
public boolean flowSensitiveInlineVariables;
/** Removes code associated with unused global names */
public boolean smartNameRemoval;
/** Removes code associated with unused global names */
boolean extraSmartNameRemoval;
/** Removes code that will never execute */
public boolean removeDeadCode;
public enum ExtractPrototypeMemberDeclarationsMode {
OFF,
USE_GLOBAL_TEMP,
USE_IIFE
}
/** Extracts common prototype member declarations */
ExtractPrototypeMemberDeclarationsMode extractPrototypeMemberDeclarations;
/** Removes unused member prototypes */
public boolean removeUnusedPrototypeProperties;
/** Tells AnalyzePrototypeProperties it can remove externed props. */
public boolean removeUnusedPrototypePropertiesInExterns;
/** Removes unused member properties */
public boolean removeUnusedClassProperties;
/** Removes unused constructor properties */
boolean removeUnusedConstructorProperties;
/** Removes unused variables */
public boolean removeUnusedVars;
/** Removes unused variables in local scope. */
public boolean removeUnusedLocalVars;
/** Collapses multiple variable declarations into one */
public boolean collapseVariableDeclarations;
/**
* Collapses anonymous function declarations into named function
* declarations
*/
public boolean collapseAnonymousFunctions;
/**
* If set to a non-empty set, those strings literals will be aliased to a
* single global instance per string, to avoid creating more objects than
* necessary.
*/
public Set<String> aliasableStrings;
/**
* A blacklist in the form of a regular expression to block strings that
* contains certain words from being aliased.
* If the value is the empty string, no words are blacklisted.
*/
public String aliasStringsBlacklist;
/**
* Aliases all string literals to global instances, to avoid creating more
* objects than necessary (if true, overrides any set of strings passed in
* to aliasableStrings)
*/
public boolean aliasAllStrings;
/** Print string usage as part of the compilation log. */
boolean outputJsStringUsage;
/** Converts quoted property accesses to dot syntax (a['b'] → a.b) */
public boolean convertToDottedProperties;
/** Reduces the size of common function expressions. */
public boolean rewriteFunctionExpressions;
/**
* Remove unused and constant parameters.
*/
public boolean optimizeParameters;
/**
* Remove unused return values.
*/
public boolean optimizeReturns;
/**
* Remove unused parameters from call sites.
*/
public boolean optimizeCalls;
/**
* Provide formal names for elements of arguments array.
*/
public boolean optimizeArgumentsArray;
/** Chains calls to functions that return this. */
boolean chainCalls;
/** Use type information to enable additional optimization opportunities. */
boolean useTypesForLocalOptimization;
boolean useSizeHeuristicToStopOptimizationLoop = true;
//--------------------------------
// Renaming
//--------------------------------
/** Controls which variables get renamed. */
public VariableRenamingPolicy variableRenaming;
/** Controls which properties get renamed. */
PropertyRenamingPolicy propertyRenaming;
/** Controls label renaming. */
public boolean labelRenaming;
/** Reserve property names on the global this object. */
public boolean reserveRawExports;
/** Should shadow variable names in outer scope. */
boolean shadowVariables;
/**
* Use a renaming heuristic with better stability across source
* changes. With this option each symbol is more likely to receive
* the same name between builds. The cost may be a slight increase
* in code size.
*/
boolean preferStableNames;
/**
* Generate pseudo names for variables and properties for debugging purposes.
*/
public boolean generatePseudoNames;
/** Specifies a prefix for all globals */
public String renamePrefix;
/**
* Specifies the name of an object that will be used to store all non-extern
* globals.
*/
public String renamePrefixNamespace;
/**
* Used by tests of the RescopeGlobalSymbols pass to avoid having declare 2
* modules in simple cases.
*/
boolean renamePrefixNamespaceAssumeCrossModuleNames = false;
void setRenamePrefixNamespaceAssumeCrossModuleNames(boolean assume) {
renamePrefixNamespaceAssumeCrossModuleNames = assume;
}
/** Flattens multi-level property names (e.g. a$b = x) */
public boolean collapseProperties;
/** Split object literals into individual variables when possible. */
boolean collapseObjectLiterals;
public void setCollapseObjectLiterals(boolean enabled) {
collapseObjectLiterals = enabled;
}
/**
* Devirtualize prototype method by rewriting them to be static calls that
* take the this pointer as their first argument
*/
public boolean devirtualizePrototypeMethods;
/**
* Use @nosideeffects annotations, function bodies and name graph
* to determine if calls have side effects. Requires --check_types.
*/
public boolean computeFunctionSideEffects;
/**
* Where to save debug report for compute function side effects.
*/
String debugFunctionSideEffectsPath;
/**
* Rename private properties to disambiguate between unrelated fields based on
* the coding convention.
*/
boolean disambiguatePrivateProperties;
/**
* Rename properties to disambiguate between unrelated fields based on
* type information.
*/
private boolean disambiguateProperties;
/** Rename unrelated properties to the same name to reduce code size. */
private boolean ambiguateProperties;
/** Input sourcemap files, indexed by the JS files they refer to */
ImmutableMap<String, SourceMapInput> inputSourceMaps;
/** Give anonymous functions names for easier debugging */
public AnonymousFunctionNamingPolicy anonymousFunctionNaming;
/** Input anonymous function renaming map. */
VariableMap inputAnonymousFunctionNamingMap;
/**
* Input variable renaming map.
* <p>During renaming, the compiler uses this map and the inputPropertyMap to
* try to preserve renaming mappings from a previous compilation.
* The application is delta encoding: keeping the diff between consecutive
* versions of one's code small.
* The compiler does NOT guarantee to respect these maps; projects should not
* use these maps to prevent renaming or to select particular names.
* Point questioners to this post:
* http://closuretools.blogspot.com/2011/01/property-by-any-other-name-part-3.html
*/
VariableMap inputVariableMap;
/** Input property renaming map. */
VariableMap inputPropertyMap;
/** List of individually configured compiler options. WARNING: experimental; these override the three compiler optimization levels! */
Properties inputCompilerOptions;
/** Whether to export test functions. */
public boolean exportTestFunctions;
/** Whether to declare globals declared in externs as properties on window */
boolean declaredGlobalExternsOnWindow;
/** Shared name generator */
NameGenerator nameGenerator;
public void setNameGenerator(NameGenerator nameGenerator) {
this.nameGenerator = nameGenerator;
}
//--------------------------------
// Special-purpose alterations
//--------------------------------
/**
* Replace UI strings with chrome.i18n.getMessage calls.
* Used by Chrome extensions/apps.
*/
boolean replaceMessagesWithChromeI18n;
String tcProjectId;
public void setReplaceMessagesWithChromeI18n(
boolean replaceMessagesWithChromeI18n,
String tcProjectId) {
if (replaceMessagesWithChromeI18n
&& messageBundle != null
&& !(messageBundle instanceof EmptyMessageBundle)) {
throw new RuntimeException("When replacing messages with"
+ " chrome.i18n.getMessage, a message bundle should not be specified.");
}
this.replaceMessagesWithChromeI18n = replaceMessagesWithChromeI18n;
this.tcProjectId = tcProjectId;
}
/** Inserts run-time type assertions for debugging. */
boolean runtimeTypeCheck;
/**
* A JS function to be used for logging run-time type assertion
* failures. It will be passed the warning as a string and the
* faulty expression as arguments.
*/
String runtimeTypeCheckLogFunction;
/** A CodingConvention to use during the compile. */
private CodingConvention codingConvention;
@Nullable
public String syntheticBlockStartMarker;
@Nullable
public String syntheticBlockEndMarker;
/** Compiling locale */
public String locale;
/** Sets the special "COMPILED" value to true */
public boolean markAsCompiled;
/** Processes goog.provide() and goog.require() calls */
public boolean closurePass;
/** Do not strip goog.provide()/goog.require() calls from the code. */
private boolean preserveGoogProvidesAndRequires;
/** Processes AngularJS-specific annotations */
boolean angularPass;
/** If non-null, processes Polymer code */
@Nullable
Integer polymerVersion;
/** Processes cr.* functions */
boolean chromePass;
/** Processes the output of the Dart Dev Compiler */
boolean dartPass;
/** Processes the output of J2CL */
J2clPassMode j2clPassMode;
/** Remove goog.abstractMethod assignments and @abstract methods. */
boolean removeAbstractMethods;
/** Remove methods that only make a super call without changing the arguments. */
boolean removeSuperMethods;
/** Remove goog.asserts calls. */
boolean removeClosureAsserts;
/** Gather CSS names (requires closurePass) */
public boolean gatherCssNames;
/** Names of types to strip */
public Set<String> stripTypes;
/** Name suffixes that determine which variables and properties to strip */
public Set<String> stripNameSuffixes;
/** Name prefixes that determine which variables and properties to strip */
public Set<String> stripNamePrefixes;
/** Qualified type name prefixes that determine which types to strip */
public Set<String> stripTypePrefixes;
/** Custom passes */
protected transient
Multimap<CustomPassExecutionTime, CompilerPass> customPasses;
/** Mark no side effect calls */
public boolean markNoSideEffectCalls;
/** Replacements for @defines. Will be Boolean, Numbers, or Strings */
private Map<String, Object> defineReplacements;
/** What kind of processing to do for goog.tweak functions. */
private TweakProcessing tweakProcessing;
/** Replacements for tweaks. Will be Boolean, Numbers, or Strings */
private Map<String, Object> tweakReplacements;
/** Move top-level function declarations to the top */
public boolean moveFunctionDeclarations;
/** Instrumentation template to use with #recordFunctionInformation */
public Instrumentation instrumentationTemplate;
String appNameStr;
/**
* App identifier string for use by the instrumentation template's
* app_name_setter. @see #instrumentationTemplate
*/
public void setAppNameStr(String appNameStr) {
this.appNameStr = appNameStr;
}
/** Record function information */
public boolean recordFunctionInformation;
boolean checksOnly;
static enum OutputJs {
// Don't output anything.
NONE,
// Output a "sentinel" file containing just a comment.
SENTINEL,
// Output the compiled JS.
NORMAL,
}
OutputJs outputJs;
public boolean generateExports;
// TODO(dimvar): generate-exports should always run after typechecking.
// If it runs before, it adds a bunch of properties to Object, which masks
// many type warnings. Cleanup all clients and remove this.
boolean generateExportsAfterTypeChecking;
boolean exportLocalPropertyDefinitions;
/** Map used in the renaming of CSS class names. */
public CssRenamingMap cssRenamingMap;
/** Whitelist used in the renaming of CSS class names. */
Set<String> cssRenamingWhitelist;
/** Process instances of goog.testing.ObjectPropertyString. */
boolean processObjectPropertyString;
/** Replace id generators */
boolean replaceIdGenerators = true; // true by default for legacy reasons.
/** Id generators to replace. */
ImmutableMap<String, RenamingMap> idGenerators;
/** Hash function to use for xid generation. */
Xid.HashFunction xidHashFunction;
/**
* A previous map of ids (serialized to a string by a previous compile).
* This will be used as a hint during the ReplaceIdGenerators pass, which
* will attempt to reuse the same ids.
*/
String idGeneratorsMapSerialized;
/** Configuration strings */
List<String> replaceStringsFunctionDescriptions;
String replaceStringsPlaceholderToken;
// A list of strings that should not be used as replacements
Set<String> replaceStringsReservedStrings;
// A previous map of replacements to strings.
VariableMap replaceStringsInputMap;
/** List of properties that we report invalidation errors for. */
Map<String, CheckLevel> propertyInvalidationErrors;
/** Transform AMD to CommonJS modules. */
boolean transformAMDToCJSModules = false;
/** Rewrite CommonJS modules so that they can be concatenated together. */
boolean processCommonJSModules = false;
/** CommonJS module prefix. */
List<String> moduleRoots = ImmutableList.of(ModuleLoader.DEFAULT_FILENAME_PREFIX);
/** Rewrite polyfills. */
boolean rewritePolyfills = false;
/** Runtime libraries to always inject. */
List<String> forceLibraryInjection = ImmutableList.of();
/** Runtime libraries to never inject. */
boolean preventLibraryInjection = false;
boolean assumeForwardDeclaredForMissingTypes = false;
/**
* If {@code true}, considers all missing types to be forward declared (useful for partial
* compilation).
*/
public void setAssumeForwardDeclaredForMissingTypes(
boolean assumeForwardDeclaredForMissingTypes) {
this.assumeForwardDeclaredForMissingTypes = assumeForwardDeclaredForMissingTypes;
}
//--------------------------------
// Output options
//--------------------------------
/** Do not strip closure-style type annotations from code. */
public boolean preserveTypeAnnotations;
/** Output in pretty indented format */
private boolean prettyPrint;
/** Line break the output a bit more aggressively */
public boolean lineBreak;
/** Prefer line breaks at end of file */
public boolean preferLineBreakAtEndOfFile;
/** Prints a separator comment before each JS script */
public boolean printInputDelimiter;
/** The string to use as the separator for printInputDelimiter */
public String inputDelimiter = "// Input %num%";
/** Whether to write keyword properties as foo['class'] instead of foo.class; needed for IE8. */
boolean quoteKeywordProperties;
boolean preferSingleQuotes;
/**
* Normally, when there are an equal number of single and double quotes
* in a string, the compiler will use double quotes. Set this to true
* to prefer single quotes.
*/
public void setPreferSingleQuotes(boolean enabled) {
this.preferSingleQuotes = enabled;
}
boolean trustedStrings;
/**
* Some people want to put arbitrary user input into strings, which are then
* run through the compiler. These scripts are then put into HTML.
* By default, we assume strings are untrusted. If the compiler is run
* from the command-line, we assume that strings are trusted.
*/
public void setTrustedStrings(boolean yes) {
trustedStrings = yes;
}
// Should only be used when debugging compiler bugs.
boolean printSourceAfterEachPass;
// Used to narrow down the printed source when overall input size is large. If this is empty,
// the entire source is printed.
List<String> filesToPrintAfterEachPass = ImmutableList.of();
public void setPrintSourceAfterEachPass(boolean printSource) {
this.printSourceAfterEachPass = printSource;
}
public void setFilesToPrintAfterEachPass(List<String> filenames) {
this.filesToPrintAfterEachPass = filenames;
}
String reportPath;
/** Where to save a report of global name usage */
public void setReportPath(String reportPath) {
this.reportPath = reportPath;
}
private TracerMode tracer;
public TracerMode getTracerMode() {
return tracer;
}
public void setTracerMode(TracerMode mode) {
this.tracer = mode;
}
private boolean colorizeErrorOutput;
public ErrorFormat errorFormat;
private ComposeWarningsGuard warningsGuard = new ComposeWarningsGuard();
int summaryDetailLevel = 1;
int lineLengthThreshold = DEFAULT_LINE_LENGTH_THRESHOLD;
/**
* Whether to use the original names of nodes in the code output. This option is only really
* useful when using the compiler to print code meant to check in to source.
*/
boolean useOriginalNamesInOutput = false;
//--------------------------------
// Special Output Options
//--------------------------------
/**
* Whether the exports should be made available via {@link Result} after
* compilation. This is implicitly true if {@link #externExportsPath} is set.
*/
private boolean externExports;
/** The output path for the created externs file. */
String externExportsPath;
//--------------------------------
// Debugging Options
//--------------------------------
/** The output path for the source map. */
public String sourceMapOutputPath;
/** The detail level for the generated source map. */
public SourceMap.DetailLevel sourceMapDetailLevel =
SourceMap.DetailLevel.ALL;
/** The source map file format */
public SourceMap.Format sourceMapFormat =
SourceMap.Format.DEFAULT;
/**
* Whether to parse inline source maps.
*/
boolean parseInlineSourceMaps = true;
/**
* Whether to apply input source maps to the output, i.e. map back to original inputs from
* input files that have source maps applied to them.
*/
boolean applyInputSourceMaps = false;
public List<SourceMap.LocationMapping> sourceMapLocationMappings =
Collections.emptyList();
/**
* Whether to include full file contents in the source map.
*/
boolean sourceMapIncludeSourcesContent = false;
/**
* Whether to return strings logged with AbstractCompiler#addToDebugLog
* in the compiler's Result.
*/
boolean useDebugLog;
/**
* Charset to use when generating code. If null, then output ASCII.
*/
Charset outputCharset;
/**
* Transitional option.
*/
boolean enforceAccessControlCodingConventions;
/**
* When set, assume that apparently side-effect free code is meaningful.
*/
private boolean protectHiddenSideEffects;
/**
* When enabled, assume that apparently side-effect free code is meaningful.
*/
public void setProtectHiddenSideEffects(boolean enable) {
this.protectHiddenSideEffects = enable;
}
/**
* Whether or not the compiler should wrap apparently side-effect free code
* to prevent it from being removed
*/
public boolean shouldProtectHiddenSideEffects() {
return protectHiddenSideEffects && !checksOnly && !allowHotswapReplaceScript;
}
/**
* Data holder Alias Transformation information accumulated during a compile.
*/
private transient AliasTransformationHandler aliasHandler;
/**
* Handler for compiler warnings and errors.
*/
transient ErrorHandler errorHandler;
/**
* Instrument code for the purpose of collecting coverage data.
*/
public boolean instrumentForCoverage;
/** Instrument branch coverage data - valid only if instrumentForCoverage is True */
public boolean instrumentBranchCoverage;
String instrumentationTemplateFile;
/** List of conformance configs to use in CheckConformance */
private ImmutableList<ConformanceConfig> conformanceConfigs = ImmutableList.of();
/**
* For use in {@link CompilationLevel#WHITESPACE_ONLY} mode, when using goog.module.
*/
boolean wrapGoogModulesForWhitespaceOnly = true;
public void setWrapGoogModulesForWhitespaceOnly(boolean enable) {
this.wrapGoogModulesForWhitespaceOnly = enable;
}
/**
* Print all configuration options to stderr after the compiler is initialized.
*/
boolean printConfig = false;
/**
* Are the input files written for strict mode?
*
* <p>Ignored for language modes that do not support strict mode.
*/
private boolean isStrictModeInput = true;
/** Which algorithm to use for locating ES6 and CommonJS modules */
ModuleLoader.ResolutionMode moduleResolutionMode;
/**
* Should the compiler print its configuration options to stderr when they are initialized?
*
* <p>Default {@code false}.
*/
public void setPrintConfig(boolean printConfig) {
this.printConfig = printConfig;
}
/**
* Initializes compiler options. All options are disabled by default.
*
* Command-line frontends to the compiler should set these properties
* like a builder.
*/
public CompilerOptions() {
// Accepted language
languageIn = LanguageMode.ECMASCRIPT3;
languageOut = LanguageMode.NO_TRANSPILE;
// Which environment to use
environment = Environment.BROWSER;
// Modules
moduleResolutionMode = ModuleLoader.ResolutionMode.LEGACY;
// Checks
skipNonTranspilationPasses = false;
devMode = DevMode.OFF;
checkDeterminism = false;
checkSymbols = false;
checkSuspiciousCode = false;
checkTypes = false;
checkGlobalNamesLevel = CheckLevel.OFF;
brokenClosureRequiresLevel = CheckLevel.ERROR;
checkGlobalThisLevel = CheckLevel.OFF;
checkMissingGetCssNameLevel = CheckLevel.OFF;
checkMissingGetCssNameBlacklist = null;
computeFunctionSideEffects = false;
chainCalls = false;
extraAnnotationNames = null;
checkEventfulObjectDisposalPolicy = DisposalCheckingPolicy.OFF;
// Optimizations
foldConstants = false;
coalesceVariableNames = false;
deadAssignmentElimination = false;
inlineConstantVars = false;
inlineFunctions = false;
maxFunctionSizeAfterInlining = UNLIMITED_FUN_SIZE_AFTER_INLINING;
inlineLocalFunctions = false;
assumeStrictThis = false;
assumeClosuresOnlyCaptureReferences = false;
inlineProperties = false;
crossModuleCodeMotion = false;
parentModuleCanSeeSymbolsDeclaredInChildren = false;
crossModuleMethodMotion = false;
inlineGetters = false;
inlineVariables = false;
inlineLocalVariables = false;
smartNameRemoval = false;
extraSmartNameRemoval = false;
removeDeadCode = false;
extractPrototypeMemberDeclarations =
ExtractPrototypeMemberDeclarationsMode.OFF;
removeUnusedPrototypeProperties = false;
removeUnusedPrototypePropertiesInExterns = false;
removeUnusedClassProperties = false;
removeUnusedConstructorProperties = false;
removeUnusedVars = false;
removeUnusedLocalVars = false;
collapseVariableDeclarations = false;
collapseAnonymousFunctions = false;
aliasableStrings = Collections.emptySet();
aliasStringsBlacklist = "";
aliasAllStrings = false;
outputJsStringUsage = false;
convertToDottedProperties = false;
rewriteFunctionExpressions = false;
optimizeParameters = false;
optimizeReturns = false;
// Renaming
variableRenaming = VariableRenamingPolicy.OFF;
propertyRenaming = PropertyRenamingPolicy.OFF;
labelRenaming = false;
generatePseudoNames = false;
shadowVariables = false;
preferStableNames = false;
renamePrefix = null;
collapseProperties = false;
collapseObjectLiterals = false;
devirtualizePrototypeMethods = false;
disambiguateProperties = false;
ambiguateProperties = false;
anonymousFunctionNaming = AnonymousFunctionNamingPolicy.OFF;
exportTestFunctions = false;
declaredGlobalExternsOnWindow = true;
nameGenerator = new DefaultNameGenerator();
// Alterations
runtimeTypeCheck = false;
runtimeTypeCheckLogFunction = null;
syntheticBlockStartMarker = null;
syntheticBlockEndMarker = null;
locale = null;
markAsCompiled = false;
closurePass = false;
preserveGoogProvidesAndRequires = false;
angularPass = false;
polymerVersion = null;
dartPass = false;
j2clPassMode = J2clPassMode.OFF;
removeAbstractMethods = false;
removeSuperMethods = false;
removeClosureAsserts = false;
stripTypes = Collections.emptySet();
stripNameSuffixes = Collections.emptySet();
stripNamePrefixes = Collections.emptySet();
stripTypePrefixes = Collections.emptySet();
customPasses = null;
markNoSideEffectCalls = false;
defineReplacements = new HashMap<>();
tweakProcessing = TweakProcessing.OFF;
tweakReplacements = new HashMap<>();
moveFunctionDeclarations = false;
appNameStr = "";
recordFunctionInformation = false;
checksOnly = false;
outputJs = OutputJs.NORMAL;
generateExports = false;
generateExportsAfterTypeChecking = true;
exportLocalPropertyDefinitions = false;
cssRenamingMap = null;
cssRenamingWhitelist = null;
processObjectPropertyString = false;
idGenerators = ImmutableMap.of();
replaceStringsFunctionDescriptions = Collections.emptyList();
replaceStringsPlaceholderToken = "";
replaceStringsReservedStrings = Collections.emptySet();
propertyInvalidationErrors = new HashMap<>();
inputSourceMaps = ImmutableMap.of();
// Instrumentation
instrumentationTemplate = null; // instrument functions
instrumentForCoverage = false; // instrument lines
instrumentBranchCoverage = false; // instrument branches
instrumentationTemplateFile = "";
// Output
preserveTypeAnnotations = false;
printInputDelimiter = false;
prettyPrint = false;
lineBreak = false;
preferLineBreakAtEndOfFile = false;
reportPath = null;
tracer = TracerMode.OFF;
colorizeErrorOutput = false;
errorFormat = ErrorFormat.SINGLELINE;
debugFunctionSideEffectsPath = null;
externExports = false;
// Debugging
aliasHandler = NULL_ALIAS_TRANSFORMATION_HANDLER;
errorHandler = null;
printSourceAfterEachPass = false;
useDebugLog = false;
}
/**
* @return Whether to attempt to remove unused class properties
*/
public boolean isRemoveUnusedClassProperties() {
return removeUnusedClassProperties;
}
/**
* @param removeUnusedClassProperties Whether to attempt to remove
* unused class properties
*/
public void setRemoveUnusedClassProperties(boolean removeUnusedClassProperties) {
this.removeUnusedClassProperties = removeUnusedClassProperties;
}
/**
* @return Whether to attempt to remove unused constructor properties
*/
public boolean isRemoveUnusedConstructorProperties() {
return removeUnusedConstructorProperties;
}
/**
* @param removeUnused Whether to attempt to remove
* unused constructor properties
*/
public void setRemoveUnusedConstructorProperties(boolean removeUnused) {
this.removeUnusedConstructorProperties = removeUnused;
}
/**
* Returns the map of define replacements.
*/
public Map<String, Node> getDefineReplacements() {
return getReplacementsHelper(defineReplacements);
}
/**
* Returns the map of tweak replacements.
*/
public Map<String, Node> getTweakReplacements() {
return getReplacementsHelper(tweakReplacements);
}
/**
* Creates a map of String->Node from a map of String->Number/String/Boolean.
*/
private static Map<String, Node> getReplacementsHelper(
Map<String, Object> source) {
ImmutableMap.Builder<String, Node> map = ImmutableMap.builder();
for (Map.Entry<String, Object> entry : source.entrySet()) {
String name = entry.getKey();
Object value = entry.getValue();
if (value instanceof Boolean) {
map.put(name, NodeUtil.booleanNode(((Boolean) value).booleanValue()));
} else if (value instanceof Integer) {
map.put(name, IR.number(((Integer) value).intValue()));
} else if (value instanceof Double) {
map.put(name, IR.number(((Double) value).doubleValue()));
} else {
Preconditions.checkState(value instanceof String);
map.put(name, IR.string((String) value));
}
}
return map.build();
}
/**
* Sets the value of the {@code @define} variable in JS
* to a boolean literal.
*/
public void setDefineToBooleanLiteral(String defineName, boolean value) {
defineReplacements.put(defineName, value);
}
/**
* Sets the value of the {@code @define} variable in JS to a
* String literal.
*/
public void setDefineToStringLiteral(String defineName, String value) {
defineReplacements.put(defineName, value);
}
/**
* Sets the value of the {@code @define} variable in JS to a
* number literal.
*/
public void setDefineToNumberLiteral(String defineName, int value) {
defineReplacements.put(defineName, value);
}
/**
* Sets the value of the {@code @define} variable in JS to a
* number literal.
*/
public void setDefineToDoubleLiteral(String defineName, double value) {
defineReplacements.put(defineName, value);
}
/**
* Sets the value of the tweak in JS
* to a boolean literal.
*/
public void setTweakToBooleanLiteral(String tweakId, boolean value) {
tweakReplacements.put(tweakId, value);
}
/**
* Sets the value of the tweak in JS to a
* String literal.
*/
public void setTweakToStringLiteral(String tweakId, String value) {
tweakReplacements.put(tweakId, value);
}
/**
* Sets the value of the tweak in JS to a
* number literal.
*/
public void setTweakToNumberLiteral(String tweakId, int value) {
tweakReplacements.put(tweakId, value);
}
/**
* Sets the value of the tweak in JS to a
* number literal.
*/
public void setTweakToDoubleLiteral(String tweakId, double value) {
tweakReplacements.put(tweakId, value);
}
/**
* Skip all possible passes, to make the compiler as fast as possible.
*/
public void skipAllCompilerPasses() {
skipNonTranspilationPasses = true;
}
/**
* Whether the warnings guard in this Options object enables the given
* group of warnings.
*/
boolean enables(DiagnosticGroup type) {
return this.warningsGuard.enables(type);
}
/**
* Whether the warnings guard in this Options object disables the given
* group of warnings.
*/
boolean disables(DiagnosticGroup type) {
return this.warningsGuard.disables(type);
}
/**
* Configure the given type of warning to the given level.
*/
public void setWarningLevel(DiagnosticGroup type, CheckLevel level) {
addWarningsGuard(new DiagnosticGroupWarningsGuard(type, level));
}
WarningsGuard getWarningsGuard() {
return this.warningsGuard;
}
/**
* Reset the warnings guard.
*/
public void resetWarningsGuard() {
this.warningsGuard = new ComposeWarningsGuard();
}
/**
* The emergency fail safe removes all strict and ERROR-escalating
* warnings guards.
*/
void useEmergencyFailSafe() {
this.warningsGuard = this.warningsGuard.makeEmergencyFailSafeGuard();
}
void useNonStrictWarningsGuard() {
this.warningsGuard = this.warningsGuard.makeNonStrict();
}
/**
* Add a guard to the set of warnings guards.
*/
public void addWarningsGuard(WarningsGuard guard) {
this.warningsGuard.addGuard(guard);
}
/**
* Sets the variable and property renaming policies for the compiler,
* in a way that clears warnings about the renaming policy being
* uninitialized from flags.
*/
public void setRenamingPolicy(VariableRenamingPolicy newVariablePolicy,
PropertyRenamingPolicy newPropertyPolicy) {
this.variableRenaming = newVariablePolicy;
this.propertyRenaming = newPropertyPolicy;
}
/** Should shadow outer scope variable name during renaming. */
public void setShadowVariables(boolean shadow) {
this.shadowVariables = shadow;
}
/**
* If true, process goog.testing.ObjectPropertyString instances.
*/
public void setProcessObjectPropertyString(boolean process) {
processObjectPropertyString = process;
}
/**
* @param replaceIdGenerators the replaceIdGenerators to set
*/
public void setReplaceIdGenerators(boolean replaceIdGenerators) {
this.replaceIdGenerators = replaceIdGenerators;
}
/**
* Sets the id generators to replace.
*/
public void setIdGenerators(Set<String> idGenerators) {
RenamingMap gen = new UniqueRenamingToken();
ImmutableMap.Builder<String, RenamingMap> builder = ImmutableMap.builder();
for (String name : idGenerators) {
builder.put(name, gen);
}
this.idGenerators = builder.build();
}
/**
* Sets the hash function to use for Xid
*/
public void setXidHashFunction(Xid.HashFunction xidHashFunction) {
this.xidHashFunction = xidHashFunction;
}
/**
* Sets the id generators to replace.
*/
public void setIdGenerators(Map<String, RenamingMap> idGenerators) {
this.idGenerators = ImmutableMap.copyOf(idGenerators);
}
/**
* A previous map of ids (serialized to a string by a previous compile).
* This will be used as a hint during the ReplaceIdGenerators pass, which
* will attempt to reuse the same ids.
*/
public void setIdGeneratorsMap(String previousMappings) {
this.idGeneratorsMapSerialized = previousMappings;
}
/**
* Set the function inlining policy for the compiler.
*/
public void setInlineFunctions(Reach reach) {
switch (reach) {
case ALL:
this.inlineFunctions = true;
this.inlineLocalFunctions = true;
break;
case LOCAL_ONLY:
this.inlineFunctions = false;
this.inlineLocalFunctions = true;
break;
case NONE:
this.inlineFunctions = false;
this.inlineLocalFunctions = false;
break;
default:
throw new IllegalStateException("unexpected");
}
}
public void setMaxFunctionSizeAfterInlining(int funAstSize) {
Preconditions.checkArgument(funAstSize > 0);
this.maxFunctionSizeAfterInlining = funAstSize;
}
/**
* Set the variable inlining policy for the compiler.
*/
public void setInlineVariables(Reach reach) {
switch (reach) {
case ALL:
this.inlineVariables = true;
this.inlineLocalVariables = true;
break;
case LOCAL_ONLY:
this.inlineVariables = false;
this.inlineLocalVariables = true;
break;
case NONE:
this.inlineVariables = false;
this.inlineLocalVariables = false;
break;
default:
throw new IllegalStateException("unexpected");
}
}
/**
* Set the function inlining policy for the compiler.
*/
public void setInlineProperties(boolean enable) {
inlineProperties = enable;
}
boolean shouldInlineProperties() {
return inlineProperties;
}
/**
* Set the variable removal policy for the compiler.
*/
public void setRemoveUnusedVariables(Reach reach) {
switch (reach) {
case ALL:
this.removeUnusedVars = true;
this.removeUnusedLocalVars = true;
break;
case LOCAL_ONLY:
this.removeUnusedVars = false;
this.removeUnusedLocalVars = true;
break;
case NONE:
this.removeUnusedVars = false;
this.removeUnusedLocalVars = false;
break;
default:
throw new IllegalStateException("unexpected");
}
}
/**
* Sets the functions whose debug strings to replace.
*/
public void setReplaceStringsConfiguration(
String placeholderToken, List<String> functionDescriptors) {
this.replaceStringsPlaceholderToken = placeholderToken;
this.replaceStringsFunctionDescriptions =
new ArrayList<>(functionDescriptors);
}
public void setRemoveAbstractMethods(boolean remove) {
this.removeAbstractMethods = remove;
}
public void setRemoveSuperMethods(boolean remove) {
this.removeSuperMethods = remove;
}
public void setRemoveClosureAsserts(boolean remove) {
this.removeClosureAsserts = remove;
}
public void setColorizeErrorOutput(boolean colorizeErrorOutput) {
this.colorizeErrorOutput = colorizeErrorOutput;
}
public boolean shouldColorizeErrorOutput() {
return colorizeErrorOutput;
}
/**
* If true, chain calls to functions that return this.
*/
public void setChainCalls(boolean value) {
this.chainCalls = value;
}
/**
* Enable run-time type checking, which adds JS type assertions for debugging.
*
* @param logFunction A JS function to be used for logging run-time type
* assertion failures.
*/
public void enableRuntimeTypeCheck(String logFunction) {
this.runtimeTypeCheck = true;
this.runtimeTypeCheckLogFunction = logFunction;
}
public void disableRuntimeTypeCheck() {
this.runtimeTypeCheck = false;
}
public void setChecksOnly(boolean checksOnly) {
this.checksOnly = checksOnly;
}
void setOutputJs(OutputJs outputJs) {
this.outputJs = outputJs;
}
public void setGenerateExports(boolean generateExports) {
this.generateExports = generateExports;
}
public void setExportLocalPropertyDefinitions(boolean export) {
this.exportLocalPropertyDefinitions = export;
}
public void setAngularPass(boolean angularPass) {
this.angularPass = angularPass;
}
public void setPolymerVersion(Integer polymerVersion) {
checkArgument(polymerVersion == null || polymerVersion == 1 || polymerVersion == 2,
"Invalid Polymer version:", polymerVersion);
this.polymerVersion = polymerVersion;
}
public void setDartPass(boolean dartPass) {
this.dartPass = dartPass;
}
@Deprecated
public void setJ2clPass(boolean flag) {
setJ2clPass(flag ? J2clPassMode.ON : J2clPassMode.OFF);
}
public void setJ2clPass(J2clPassMode j2clPassMode) {
this.j2clPassMode = j2clPassMode;
if (j2clPassMode.isExplicitlyOn()) {
setWarningLevel(DiagnosticGroup.forType(SourceFile.DUPLICATE_ZIP_CONTENTS), CheckLevel.OFF);
}
}
public void setCodingConvention(CodingConvention codingConvention) {
this.codingConvention = codingConvention;
}
public CodingConvention getCodingConvention() {
return codingConvention;
}
/**
* Sets dependency options. See the DependencyOptions class for more info.
* This supersedes manageClosureDependencies.
*/
public void setDependencyOptions(DependencyOptions options) {
this.dependencyOptions = options;
}
public DependencyOptions getDependencyOptions() {
return dependencyOptions;
}
/**
* Sort inputs by their goog.provide/goog.require calls, and prune inputs
* whose symbols are not required.
*/
public void setManageClosureDependencies(boolean newVal) {
dependencyOptions.setDependencySorting(
newVal || dependencyOptions.shouldSortDependencies());
dependencyOptions.setDependencyPruning(
newVal || dependencyOptions.shouldPruneDependencies());
dependencyOptions.setMoocherDropping(false);
}
/**
* Sort inputs by their goog.provide/goog.require calls.
*
* @param entryPoints Entry points to the program. Must be goog.provide'd
* symbols. Any goog.provide'd symbols that are not a transitive
* dependency of the entry points will be deleted.
* Files without goog.provides, and their dependencies,
* will always be left in.
*/
public void setManageClosureDependencies(List<String> entryPoints) {
Preconditions.checkNotNull(entryPoints);
setManageClosureDependencies(true);
List<ModuleIdentifier> normalizedEntryPoints = new ArrayList<>();
for (String entryPoint : entryPoints) {
normalizedEntryPoints.add(ModuleIdentifier.forClosure(entryPoint));
}
dependencyOptions.setEntryPoints(normalizedEntryPoints);
}
/**
* Controls how detailed the compilation summary is. Values:
* 0 (never print summary), 1 (print summary only if there are
* errors or warnings), 2 (print summary if type checking is on,
* see --check_types), 3 (always print summary). The default level
* is 1
*/
public void setSummaryDetailLevel(int summaryDetailLevel) {
this.summaryDetailLevel = summaryDetailLevel;
}
/**
* @deprecated replaced by {@link #setExternExports}
*/
@Deprecated
public void enableExternExports(boolean enabled) {
this.externExports = enabled;
}
public void setExtraAnnotationNames(Iterable<String> extraAnnotationNames) {
this.extraAnnotationNames = ImmutableSet.copyOf(extraAnnotationNames);
}
public boolean isExternExportsEnabled() {
return externExports;
}
/**
* Sets the output charset.
*/
public void setOutputCharset(Charset charsetName) {
this.outputCharset = charsetName;
}
/**
* Gets the output charset.
*/
Charset getOutputCharset() {
return outputCharset;
}
/**
* Sets how goog.tweak calls are processed.
*/
public void setTweakProcessing(TweakProcessing tweakProcessing) {
this.tweakProcessing = tweakProcessing;
}
public TweakProcessing getTweakProcessing() {
return tweakProcessing;
}
/**
* Sets ECMAScript version to use.
*/
public void setLanguage(LanguageMode language) {
Preconditions.checkState(language != LanguageMode.NO_TRANSPILE);
this.languageIn = language;
this.languageOut = language;
}
/**
* Sets ECMAScript version to use for the input. If you are not
* transpiling from one version to another, use #setLanguage instead.
*/
public void setLanguageIn(LanguageMode languageIn) {
Preconditions.checkState(languageIn != LanguageMode.NO_TRANSPILE);
this.languageIn = languageIn;
}
public LanguageMode getLanguageIn() {
return languageIn;
}
/**
* Sets ECMAScript version to use for the output. If you are not
* transpiling from one version to another, use #setLanguage instead.
*/
public void setLanguageOut(LanguageMode languageOut) {
this.languageOut = languageOut;
if (languageOut == LanguageMode.ECMASCRIPT3) {
this.quoteKeywordProperties = true;
}
}
public LanguageMode getLanguageOut() {
if (languageOut == LanguageMode.NO_TRANSPILE) {
return languageIn;
}
return languageOut;
}
/**
* Set which set of builtin externs to use.
*/
public void setEnvironment(Environment environment) {
this.environment = environment;
}
public Environment getEnvironment() {
return environment;
}
/**
* @return whether we are currently transpiling from ES6 to a lower version.
*/
boolean lowerFromEs6() {
return languageOut != LanguageMode.NO_TRANSPILE
&& languageIn.isEs6OrHigher()
&& !languageOut.isEs6OrHigher();
}
/**
* @return whether we are currently transpiling to ES6_TYPED
*/
boolean raiseToEs6Typed() {
return languageOut != LanguageMode.NO_TRANSPILE
&& !languageIn.isEs6OrHigher()
&& languageOut == LanguageMode.ECMASCRIPT6_TYPED;
}
public void setAliasTransformationHandler(
AliasTransformationHandler changes) {
this.aliasHandler = changes;
}
public AliasTransformationHandler getAliasTransformationHandler() {
return this.aliasHandler;
}
/**
* Set a custom handler for warnings and errors.
*
* This is mostly used for piping the warnings and errors to
* a file behind the scenes.
*
* If you want to filter warnings and errors, you should use a WarningsGuard.
*
* If you want to change how warnings and errors are reported to the user,
* you should set a ErrorManager on the Compiler. An ErrorManager is
* intended to summarize the errors for a single compile job.
*/
public void setErrorHandler(ErrorHandler handler) {
this.errorHandler = handler;
}
/**
* If true, enables type inference. If checkTypes is enabled, this flag has
* no effect.
*/
public void setInferTypes(boolean enable) {
inferTypes = enable;
}
/**
* Gets the inferTypes flag. Note that if checkTypes is enabled, this flag
* is ignored when configuring the compiler.
*/
public boolean getInferTypes() {
return inferTypes;
}
public boolean getNewTypeInference() {
return this.useNewTypeInference;
}
public void setNewTypeInference(boolean enable) {
this.useNewTypeInference = enable;
}
// Not dead code; used by the open-source users of the compiler.
public void setReportOTIErrorsUnderNTI(boolean enable) {
this.reportOTIErrorsUnderNTI = enable;
}
/**
* @return Whether assumeStrictThis is set.
*/
public boolean assumeStrictThis() {
return assumeStrictThis;
}
/**
* If true, enables enables additional optimizations.
*/
public void setAssumeStrictThis(boolean enable) {
this.assumeStrictThis = enable;
}
/**
* @return Whether assumeClosuresOnlyCaptureReferences is set.
*/
public boolean assumeClosuresOnlyCaptureReferences() {
return assumeClosuresOnlyCaptureReferences;
}
/**
* Whether to assume closures capture only what they reference. This allows
* more aggressive function inlining.
*/
public void setAssumeClosuresOnlyCaptureReferences(boolean enable) {
this.assumeClosuresOnlyCaptureReferences = enable;
}
/**
* Sets the list of properties that we report property invalidation errors
* for.
*/
public void setPropertyInvalidationErrors(
Map<String, CheckLevel> propertyInvalidationErrors) {
this.propertyInvalidationErrors =
ImmutableMap.copyOf(propertyInvalidationErrors);
}
/**
* Configures the compiler for use as an IDE backend. In this mode:
* <ul>
* <li>No optimization passes will run.</li>
* <li>The last time custom passes are invoked is
* {@link CustomPassExecutionTime#BEFORE_OPTIMIZATIONS}</li>
* <li>The compiler will always try to process all inputs fully, even
* if it encounters errors.</li>
* <li>The compiler may record more information than is strictly
* needed for codegen.</li>
* </ul>
*
* @deprecated Some "IDE" clients will need some of these options but not
* others. Consider calling setChecksOnly, setAllowRecompilation, etc,
* explicitly, instead of calling this method which does a variety of
* different things.
*/
@Deprecated
public void setIdeMode(boolean ideMode) {
setChecksOnly(ideMode);
setContinueAfterErrors(ideMode);
setAllowHotswapReplaceScript(ideMode);
setPreserveDetailedSourceInfo(ideMode);
setParseJsDocDocumentation(
ideMode
? Config.JsDocParsing.INCLUDE_DESCRIPTIONS_NO_WHITESPACE
: Config.JsDocParsing.TYPES_ONLY);
}
public void setAllowHotswapReplaceScript(boolean allowRecompilation) {
this.allowHotswapReplaceScript = allowRecompilation;
}
boolean allowsHotswapReplaceScript() {
return allowHotswapReplaceScript;
}
public void setPreserveDetailedSourceInfo(boolean preserveDetailedSourceInfo) {
this.preserveDetailedSourceInfo = preserveDetailedSourceInfo;
}
boolean preservesDetailedSourceInfo() {
return preserveDetailedSourceInfo;
}
public void setContinueAfterErrors(boolean continueAfterErrors) {
this.continueAfterErrors = continueAfterErrors;
}
boolean canContinueAfterErrors() {
return continueAfterErrors;
}
/**
* Enables or disables the parsing of JSDoc documentation, and optionally also
* the preservation of all whitespace and formatting within a JSDoc comment.
* By default, whitespace is collapsed for all comments except {@literal @license} and
* {@literal @preserve} blocks,
*
*/
public void setParseJsDocDocumentation(Config.JsDocParsing parseJsDocDocumentation) {
this.parseJsDocDocumentation = parseJsDocDocumentation;
}
/**
* Checks JSDoc documentation will be parsed.
*
* @return True when JSDoc documentation will be parsed, false if not.
*/
public Config.JsDocParsing isParseJsDocDocumentation() {
return this.parseJsDocDocumentation;
}
/**
* Skip all passes (other than transpilation, if requested). Don't inject any
* runtime libraries (unless explicitly requested) or do any checks/optimizations
* (this is useful for per-file transpilation).
*/
public void setSkipNonTranspilationPasses(boolean skipNonTranspilationPasses) {
this.skipNonTranspilationPasses = skipNonTranspilationPasses;
}
public void setDevMode(DevMode devMode) {
this.devMode = devMode;
}
public void setCheckDeterminism(boolean checkDeterminism) {
this.checkDeterminism = checkDeterminism;
if (checkDeterminism) {
this.useDebugLog = true;
}
}
public boolean getCheckDeterminism() {
return checkDeterminism;
}
public void setMessageBundle(MessageBundle messageBundle) {
this.messageBundle = messageBundle;
}
public void setCheckSymbols(boolean checkSymbols) {
this.checkSymbols = checkSymbols;
}
public void setCheckSuspiciousCode(boolean checkSuspiciousCode) {
this.checkSuspiciousCode = checkSuspiciousCode;
}
public void setCheckTypes(boolean checkTypes) {
this.checkTypes = checkTypes;
}
public void setCheckMissingGetCssNameBlacklist(String blackList) {
this.checkMissingGetCssNameBlacklist = blackList;
}
public void setFoldConstants(boolean foldConstants) {
this.foldConstants = foldConstants;
}
public void setDeadAssignmentElimination(boolean deadAssignmentElimination) {
this.deadAssignmentElimination = deadAssignmentElimination;
}
public void setInlineConstantVars(boolean inlineConstantVars) {
this.inlineConstantVars = inlineConstantVars;
}
public void setInlineFunctions(boolean inlineFunctions) {
this.inlineFunctions = inlineFunctions;
}
public void setInlineLocalFunctions(boolean inlineLocalFunctions) {
this.inlineLocalFunctions = inlineLocalFunctions;
}
public void setCrossModuleCodeMotion(boolean crossModuleCodeMotion) {
this.crossModuleCodeMotion = crossModuleCodeMotion;
}
public void setCrossModuleCodeMotionNoStubMethods(boolean
crossModuleCodeMotionNoStubMethods) {
this.crossModuleCodeMotionNoStubMethods = crossModuleCodeMotionNoStubMethods;
}
public void setParentModuleCanSeeSymbolsDeclaredInChildren(
boolean parentModuleCanSeeSymbolsDeclaredInChildren) {
this.parentModuleCanSeeSymbolsDeclaredInChildren =
parentModuleCanSeeSymbolsDeclaredInChildren;
}
public void setCoalesceVariableNames(boolean coalesceVariableNames) {
this.coalesceVariableNames = coalesceVariableNames;
}
public void setCrossModuleMethodMotion(boolean crossModuleMethodMotion) {
this.crossModuleMethodMotion = crossModuleMethodMotion;
}
public void setInlineVariables(boolean inlineVariables) {
this.inlineVariables = inlineVariables;
}
public void setInlineLocalVariables(boolean inlineLocalVariables) {
this.inlineLocalVariables = inlineLocalVariables;
}
public void setFlowSensitiveInlineVariables(boolean enabled) {
this.flowSensitiveInlineVariables = enabled;
}
public void setSmartNameRemoval(boolean smartNameRemoval) {
this.smartNameRemoval = smartNameRemoval;
}
public void setExtraSmartNameRemoval(boolean smartNameRemoval) {
this.extraSmartNameRemoval = smartNameRemoval;
}
public void setRemoveDeadCode(boolean removeDeadCode) {
this.removeDeadCode = removeDeadCode;
}
public void setExtractPrototypeMemberDeclarations(boolean enabled) {
this.extractPrototypeMemberDeclarations =
enabled ? ExtractPrototypeMemberDeclarationsMode.USE_GLOBAL_TEMP
: ExtractPrototypeMemberDeclarationsMode.OFF;
}
// USE_IIFE is currently unused. Consider removing support for it and
// deleting this setter.
public void setExtractPrototypeMemberDeclarations(ExtractPrototypeMemberDeclarationsMode mode) {
this.extractPrototypeMemberDeclarations = mode;
}
public void setRemoveUnusedPrototypeProperties(boolean enabled) {
this.removeUnusedPrototypeProperties = enabled;
// InlineSimpleMethods makes similar assumptions to
// RemoveUnusedPrototypeProperties, so they are enabled together.
this.inlineGetters = enabled;
}
public void setRemoveUnusedPrototypePropertiesInExterns(boolean enabled) {
this.removeUnusedPrototypePropertiesInExterns = enabled;
}
public void setCollapseVariableDeclarations(boolean enabled) {
this.collapseVariableDeclarations = enabled;
}
public void setCollapseAnonymousFunctions(boolean enabled) {
this.collapseAnonymousFunctions = enabled;
}
public void setAliasableStrings(Set<String> aliasableStrings) {
this.aliasableStrings = aliasableStrings;
}
public void setAliasStringsBlacklist(String aliasStringsBlacklist) {
this.aliasStringsBlacklist = aliasStringsBlacklist;
}
public void setAliasAllStrings(boolean aliasAllStrings) {
this.aliasAllStrings = aliasAllStrings;
}
public void setOutputJsStringUsage(boolean outputJsStringUsage) {
this.outputJsStringUsage = outputJsStringUsage;
}
public void setConvertToDottedProperties(boolean convertToDottedProperties) {
this.convertToDottedProperties = convertToDottedProperties;
}
public void setUseTypesForLocalOptimization(boolean useTypesForLocalOptimization) {
this.useTypesForLocalOptimization = useTypesForLocalOptimization;
}
public void setUseSizeHeuristicToStopOptimizationLoop(boolean mayStopEarly) {
this.useSizeHeuristicToStopOptimizationLoop = mayStopEarly;
}
@Deprecated
public void setUseTypesForOptimization(boolean useTypesForOptimization) {
if (useTypesForOptimization) {
this.disambiguateProperties = useTypesForOptimization;
this.ambiguateProperties = useTypesForOptimization;
this.inlineProperties = useTypesForOptimization;
this.useTypesForLocalOptimization = useTypesForOptimization;
}
}
public void setRewriteFunctionExpressions(boolean rewriteFunctionExpressions) {
this.rewriteFunctionExpressions = rewriteFunctionExpressions;
}
public void setOptimizeParameters(boolean optimizeParameters) {
this.optimizeParameters = optimizeParameters;
}
public void setOptimizeReturns(boolean optimizeReturns) {
this.optimizeReturns = optimizeReturns;
}
public void setOptimizeCalls(boolean optimizeCalls) {
this.optimizeCalls = optimizeCalls;
}
public void setOptimizeArgumentsArray(boolean optimizeArgumentsArray) {
this.optimizeArgumentsArray = optimizeArgumentsArray;
}
public void setVariableRenaming(VariableRenamingPolicy variableRenaming) {
this.variableRenaming = variableRenaming;
}
public void setPropertyRenaming(PropertyRenamingPolicy propertyRenaming) {
this.propertyRenaming = propertyRenaming;
}
public void setLabelRenaming(boolean labelRenaming) {
this.labelRenaming = labelRenaming;
}
public void setReserveRawExports(boolean reserveRawExports) {
this.reserveRawExports = reserveRawExports;
}
public void setPreferStableNames(boolean preferStableNames) {
this.preferStableNames = preferStableNames;
}
public void setGeneratePseudoNames(boolean generatePseudoNames) {
this.generatePseudoNames = generatePseudoNames;
}
public void setRenamePrefix(String renamePrefix) {
this.renamePrefix = renamePrefix;
}
public String getRenamePrefixNamespace() {
return this.renamePrefixNamespace;
}
public void setRenamePrefixNamespace(String renamePrefixNamespace) {
this.renamePrefixNamespace = renamePrefixNamespace;
}
public void setCollapseProperties(boolean collapseProperties) {
this.collapseProperties = collapseProperties;
}
public void setDevirtualizePrototypeMethods(boolean devirtualizePrototypeMethods) {
this.devirtualizePrototypeMethods = devirtualizePrototypeMethods;
}
public void setComputeFunctionSideEffects(boolean computeFunctionSideEffects) {
this.computeFunctionSideEffects = computeFunctionSideEffects;
}
public void setDebugFunctionSideEffectsPath(String debugFunctionSideEffectsPath) {
this.debugFunctionSideEffectsPath = debugFunctionSideEffectsPath;
}
/**
* @return Whether disambiguate private properties is enabled.
*/
public boolean isDisambiguatePrivateProperties() {
return disambiguatePrivateProperties;
}
/**
* @param value Whether to enable private property disambiguation based on
* the coding convention.
*/
public void setDisambiguatePrivateProperties(boolean value) {
this.disambiguatePrivateProperties = value;
}
public void setDisambiguateProperties(boolean disambiguateProperties) {
this.disambiguateProperties = disambiguateProperties;
}
boolean shouldDisambiguateProperties() {
return this.disambiguateProperties;
}
public void setAmbiguateProperties(boolean ambiguateProperties) {
this.ambiguateProperties = ambiguateProperties;
}
boolean shouldAmbiguateProperties() {
return this.ambiguateProperties;
}
public void setAnonymousFunctionNaming(
AnonymousFunctionNamingPolicy anonymousFunctionNaming) {
this.anonymousFunctionNaming = anonymousFunctionNaming;
}
public void setInputAnonymousFunctionNamingMap(VariableMap inputMap) {
this.inputAnonymousFunctionNamingMap = inputMap;
}
public void setInputVariableMap(VariableMap inputVariableMap) {
this.inputVariableMap = inputVariableMap;
}
public void setInputCompilerOptions(Properties inputCompilerOptions) {
this.inputCompilerOptions = inputCompilerOptions;
}
public void setInputPropertyMap(VariableMap inputPropertyMap) {
this.inputPropertyMap = inputPropertyMap;
}
public void setExportTestFunctions(boolean exportTestFunctions) {
this.exportTestFunctions = exportTestFunctions;
}
public void setRuntimeTypeCheck(boolean runtimeTypeCheck) {
this.runtimeTypeCheck = runtimeTypeCheck;
}
public void setRuntimeTypeCheckLogFunction(String runtimeTypeCheckLogFunction) {
this.runtimeTypeCheckLogFunction = runtimeTypeCheckLogFunction;
}
public void setSyntheticBlockStartMarker(String syntheticBlockStartMarker) {
this.syntheticBlockStartMarker = syntheticBlockStartMarker;
}
public void setSyntheticBlockEndMarker(String syntheticBlockEndMarker) {
this.syntheticBlockEndMarker = syntheticBlockEndMarker;
}
public void setLocale(String locale) {
this.locale = locale;
}
public void setMarkAsCompiled(boolean markAsCompiled) {
this.markAsCompiled = markAsCompiled;
}
public void setClosurePass(boolean closurePass) {
this.closurePass = closurePass;
}
public void setPreserveGoogProvidesAndRequires(boolean preserveGoogProvidesAndRequires) {
this.preserveGoogProvidesAndRequires = preserveGoogProvidesAndRequires;
}
public boolean shouldPreservesGoogProvidesAndRequires() {
return this.preserveGoogProvidesAndRequires || this.shouldGenerateTypedExterns();
}
public void setPreserveTypeAnnotations(boolean preserveTypeAnnotations) {
this.preserveTypeAnnotations = preserveTypeAnnotations;
}
public void setGatherCssNames(boolean gatherCssNames) {
this.gatherCssNames = gatherCssNames;
}
public void setStripTypes(Set<String> stripTypes) {
this.stripTypes = stripTypes;
}
public void setStripNameSuffixes(Set<String> stripNameSuffixes) {
this.stripNameSuffixes = stripNameSuffixes;
}
public void setStripNamePrefixes(Set<String> stripNamePrefixes) {
this.stripNamePrefixes = stripNamePrefixes;
}
public void setStripTypePrefixes(Set<String> stripTypePrefixes) {
this.stripTypePrefixes = stripTypePrefixes;
}
public void addCustomPass(CustomPassExecutionTime time, CompilerPass customPass) {
if (customPasses == null) {
customPasses = LinkedHashMultimap.<CustomPassExecutionTime, CompilerPass>create();
}
customPasses.put(time, customPass);
}
public void setMarkNoSideEffectCalls(boolean markNoSideEffectCalls) {
this.markNoSideEffectCalls = markNoSideEffectCalls;
}
public void setDefineReplacements(Map<String, Object> defineReplacements) {
this.defineReplacements = defineReplacements;
}
public void setTweakReplacements(Map<String, Object> tweakReplacements) {
this.tweakReplacements = tweakReplacements;
}
public void setMoveFunctionDeclarations(boolean moveFunctionDeclarations) {
this.moveFunctionDeclarations = moveFunctionDeclarations;
}
public void setInstrumentationTemplate(Instrumentation instrumentationTemplate) {
this.instrumentationTemplate = instrumentationTemplate;
}
public void setInstrumentationTemplateFile(String filename){
this.instrumentationTemplateFile = filename;
}
public void setRecordFunctionInformation(boolean recordFunctionInformation) {
this.recordFunctionInformation = recordFunctionInformation;
}
public void setCssRenamingMap(CssRenamingMap cssRenamingMap) {
this.cssRenamingMap = cssRenamingMap;
}
public void setCssRenamingWhitelist(Set<String> whitelist) {
this.cssRenamingWhitelist = whitelist;
}
public void setReplaceStringsFunctionDescriptions(
List<String> replaceStringsFunctionDescriptions) {
this.replaceStringsFunctionDescriptions =
replaceStringsFunctionDescriptions;
}
public void setReplaceStringsPlaceholderToken(
String replaceStringsPlaceholderToken) {
this.replaceStringsPlaceholderToken =
replaceStringsPlaceholderToken;
}
public void setReplaceStringsReservedStrings(
Set<String> replaceStringsReservedStrings) {
this.replaceStringsReservedStrings =
replaceStringsReservedStrings;
}
public void setReplaceStringsInputMap(VariableMap serializedMap) {
this.replaceStringsInputMap = serializedMap;
}
public void setPrettyPrint(boolean prettyPrint) {
this.prettyPrint = prettyPrint;
}
public boolean isPrettyPrint() {
return this.prettyPrint;
}
public void setLineBreak(boolean lineBreak) {
this.lineBreak = lineBreak;
}
public boolean getPreferLineBreakAtEndOfFile() {
return this.preferLineBreakAtEndOfFile;
}
public void setPreferLineBreakAtEndOfFile(boolean lineBreakAtEnd) {
this.preferLineBreakAtEndOfFile = lineBreakAtEnd;
}
public void setPrintInputDelimiter(boolean printInputDelimiter) {
this.printInputDelimiter = printInputDelimiter;
}
public void setInputDelimiter(String inputDelimiter) {
this.inputDelimiter = inputDelimiter;
}
public void setQuoteKeywordProperties(boolean quoteKeywordProperties) {
this.quoteKeywordProperties = quoteKeywordProperties;
}
public void setErrorFormat(ErrorFormat errorFormat) {
this.errorFormat = errorFormat;
}
public ErrorFormat getErrorFormat() {
return this.errorFormat;
}
public void setWarningsGuard(ComposeWarningsGuard warningsGuard) {
this.warningsGuard = warningsGuard;
}
public void setLineLengthThreshold(int lineLengthThreshold) {
this.lineLengthThreshold = lineLengthThreshold;
}
public int getLineLengthThreshold() {
return this.lineLengthThreshold;
}
public void setUseOriginalNamesInOutput(boolean useOriginalNamesInOutput) {
this.useOriginalNamesInOutput = useOriginalNamesInOutput;
}
public boolean getUseOriginalNamesInOutput() {
return this.useOriginalNamesInOutput;
}
public void setExternExports(boolean externExports) {
this.externExports = externExports;
}
public void setExternExportsPath(String externExportsPath) {
this.externExportsPath = externExportsPath;
}
public void setSourceMapOutputPath(String sourceMapOutputPath) {
this.sourceMapOutputPath = sourceMapOutputPath;
}
public void setApplyInputSourceMaps(boolean applyInputSourceMaps) {
this.applyInputSourceMaps = applyInputSourceMaps;
}
public void setSourceMapIncludeSourcesContent(boolean sourceMapIncludeSourcesContent) {
this.sourceMapIncludeSourcesContent = sourceMapIncludeSourcesContent;
}
public void setSourceMapDetailLevel(SourceMap.DetailLevel sourceMapDetailLevel) {
this.sourceMapDetailLevel = sourceMapDetailLevel;
}
public void setSourceMapFormat(SourceMap.Format sourceMapFormat) {
this.sourceMapFormat = sourceMapFormat;
}
public void setSourceMapLocationMappings(
List<SourceMap.LocationMapping> sourceMapLocationMappings) {
this.sourceMapLocationMappings = sourceMapLocationMappings;
}
/**
* Activates transformation of AMD to CommonJS modules.
*/
public void setTransformAMDToCJSModules(boolean transformAMDToCJSModules) {
this.transformAMDToCJSModules = transformAMDToCJSModules;
}
/**
* Rewrites CommonJS modules so that modules can be concatenated together,
* by renaming all globals to avoid conflicting with other modules.
*/
public void setProcessCommonJSModules(boolean processCommonJSModules) {
this.processCommonJSModules = processCommonJSModules;
}
/**
* Sets a path prefix for CommonJS modules (maps to {@link #setModuleRoots(List)}).
*/
public void setCommonJSModulePathPrefix(String commonJSModulePathPrefix) {
setModuleRoots(ImmutableList.of(commonJSModulePathPrefix));
}
/**
* Sets the module roots.
*/
public void setModuleRoots(List<String> moduleRoots) {
this.moduleRoots = moduleRoots;
}
/**
* Sets whether to rewrite polyfills.
*/
public void setRewritePolyfills(boolean rewritePolyfills) {
this.rewritePolyfills = rewritePolyfills;
}
public boolean getRewritePolyfills() {
return this.rewritePolyfills;
}
/**
* Sets list of libraries to always inject, even if not needed.
*/
public void setForceLibraryInjection(Iterable<String> libraries) {
this.forceLibraryInjection = ImmutableList.copyOf(libraries);
}
/**
* Sets the set of libraries to never inject, even if required.
*/
public void setPreventLibraryInjection(boolean preventLibraryInjection) {
this.preventLibraryInjection = preventLibraryInjection;
}
/**
* Set whether or not code should be modified to provide coverage
* information.
*/
public void setInstrumentForCoverage(boolean instrumentForCoverage) {
this.instrumentForCoverage = instrumentForCoverage;
}
/** Set whether to instrument to collect branch coverage */
public void setInstrumentBranchCoverage(boolean instrumentBranchCoverage) {
if (instrumentForCoverage || !instrumentBranchCoverage) {
this.instrumentBranchCoverage = instrumentBranchCoverage;
} else {
throw new RuntimeException("The option instrumentForCoverage must be set to true for "
+ "instrumentBranchCoverage to be set to true.");
}
}
public List<ConformanceConfig> getConformanceConfigs() {
return conformanceConfigs;
}
/**
* Both enable and configure conformance checks, if non-null.
*/
@GwtIncompatible("Conformance")
public void setConformanceConfig(ConformanceConfig conformanceConfig) {
this.conformanceConfigs = ImmutableList.of(conformanceConfig);
}
/**
* Both enable and configure conformance checks, if non-null.
*/
@GwtIncompatible("Conformance")
public void setConformanceConfigs(List<ConformanceConfig> configs) {
this.conformanceConfigs = ImmutableList.copyOf(configs);
}
public boolean isEmitUseStrict() {
return emitUseStrict;
}
public CompilerOptions setEmitUseStrict(boolean emitUseStrict) {
this.emitUseStrict = emitUseStrict;
return this;
}
public ModuleLoader.ResolutionMode getModuleResolutionMode() {
return this.moduleResolutionMode;
}
public void setModuleResolutionMode(ModuleLoader.ResolutionMode mode) {
this.moduleResolutionMode = mode;
}
/** Serializes compiler options to a stream. */
@GwtIncompatible("ObjectOutputStream")
public void serialize(OutputStream objectOutputStream) throws IOException {
new java.io.ObjectOutputStream(objectOutputStream).writeObject(this);
}
/** Deserializes compiler options from a stream. */
@GwtIncompatible("ObjectInputStream")
public static CompilerOptions deserialize(InputStream objectInputStream)
throws IOException, ClassNotFoundException {
return (CompilerOptions) new java.io.ObjectInputStream(objectInputStream).readObject();
}
@Override
public String toString() {
String strValue =
MoreObjects.toStringHelper(this)
.omitNullValues()
.add("aggressiveFusion", aggressiveFusion)
.add("aliasableStrings", aliasableStrings)
.add("aliasAllStrings", aliasAllStrings)
.add("aliasHandler", getAliasTransformationHandler())
.add("aliasStringsBlacklist", aliasStringsBlacklist)
.add("allowHotswapReplaceScript", allowsHotswapReplaceScript())
.add("ambiguateProperties", ambiguateProperties)
.add("angularPass", angularPass)
.add("anonymousFunctionNaming", anonymousFunctionNaming)
.add("appNameStr", appNameStr)
.add("assumeClosuresOnlyCaptureReferences", assumeClosuresOnlyCaptureReferences)
.add("assumeStrictThis", assumeStrictThis())
.add("brokenClosureRequiresLevel", brokenClosureRequiresLevel)
.add("chainCalls", chainCalls)
.add("checkDeterminism", getCheckDeterminism())
.add("checkEventfulObjectDisposalPolicy", checkEventfulObjectDisposalPolicy)
.add("checkGlobalNamesLevel", checkGlobalNamesLevel)
.add("checkGlobalThisLevel", checkGlobalThisLevel)
.add("checkMissingGetCssNameBlacklist", checkMissingGetCssNameBlacklist)
.add("checkMissingGetCssNameLevel", checkMissingGetCssNameLevel)
.add("checksOnly", checksOnly)
.add("checkSuspiciousCode", checkSuspiciousCode)
.add("checkSymbols", checkSymbols)
.add("checkTypes", checkTypes)
.add("closurePass", closurePass)
.add("coalesceVariableNames", coalesceVariableNames)
.add("codingConvention", getCodingConvention())
.add("collapseAnonymousFunctions", collapseAnonymousFunctions)
.add("collapseObjectLiterals", collapseObjectLiterals)
.add("collapseProperties", collapseProperties)
.add("collapseVariableDeclarations", collapseVariableDeclarations)
.add("colorizeErrorOutput", shouldColorizeErrorOutput())
.add("computeFunctionSideEffects", computeFunctionSideEffects)
.add("conformanceConfigs", getConformanceConfigs())
.add("continueAfterErrors", canContinueAfterErrors())
.add("convertToDottedProperties", convertToDottedProperties)
.add("crossModuleCodeMotion", crossModuleCodeMotion)
.add("crossModuleCodeMotionNoStubMethods", crossModuleCodeMotionNoStubMethods)
.add("crossModuleMethodMotion", crossModuleMethodMotion)
.add("cssRenamingMap", cssRenamingMap)
.add("cssRenamingWhitelist", cssRenamingWhitelist)
.add("customPasses", customPasses)
.add("dartPass", dartPass)
.add("deadAssignmentElimination", deadAssignmentElimination)
.add("debugFunctionSideEffectsPath", debugFunctionSideEffectsPath)
.add("declaredGlobalExternsOnWindow", declaredGlobalExternsOnWindow)
.add("defineReplacements", getDefineReplacements())
.add("dependencyOptions", dependencyOptions)
.add("devirtualizePrototypeMethods", devirtualizePrototypeMethods)
.add("devMode", devMode)
.add("disambiguatePrivateProperties", disambiguatePrivateProperties)
.add("disambiguateProperties", disambiguateProperties)
.add("enforceAccessControlCodingConventions", enforceAccessControlCodingConventions)
.add("environment", getEnvironment())
.add("errorFormat", errorFormat)
.add("errorHandler", errorHandler)
.add("exportLocalPropertyDefinitions", exportLocalPropertyDefinitions)
.add("exportTestFunctions", exportTestFunctions)
.add("externExports", isExternExportsEnabled())
.add("externExportsPath", externExportsPath)
.add("extraAnnotationNames", extraAnnotationNames)
.add("extractPrototypeMemberDeclarations", extractPrototypeMemberDeclarations)
.add("extraSmartNameRemoval", extraSmartNameRemoval)
.add("flowSensitiveInlineVariables", flowSensitiveInlineVariables)
.add("foldConstants", foldConstants)
.add("forceLibraryInjection", forceLibraryInjection)
.add("gatherCssNames", gatherCssNames)
.add("generateExportsAfterTypeChecking", generateExportsAfterTypeChecking)
.add("generateExports", generateExports)
.add("generatePseudoNames", generatePseudoNames)
.add("generateTypedExterns", shouldGenerateTypedExterns())
.add("idGenerators", idGenerators)
.add("idGeneratorsMapSerialized", idGeneratorsMapSerialized)
.add("inferConsts", inferConsts)
.add("inferTypes", inferTypes)
.add("inlineConstantVars", inlineConstantVars)
.add("inlineFunctions", inlineFunctions)
.add("inlineGetters", inlineGetters)
.add("inlineLocalFunctions", inlineLocalFunctions)
.add("inlineLocalVariables", inlineLocalVariables)
.add("inlineProperties", inlineProperties)
.add("inlineVariables", inlineVariables)
.add("inputAnonymousFunctionNamingMap", inputAnonymousFunctionNamingMap)
.add("inputDelimiter", inputDelimiter)
.add("inputPropertyMap", inputPropertyMap)
.add("inputSourceMaps", inputSourceMaps)
.add("inputVariableMap", inputVariableMap)
.add("instrumentationTemplateFile", instrumentationTemplateFile)
.add("instrumentationTemplate", instrumentationTemplate)
.add("instrumentForCoverage", instrumentForCoverage)
.add("instrumentBranchCoverage", instrumentBranchCoverage)
.add("j2clPassMode", j2clPassMode)
.add("labelRenaming", labelRenaming)
.add("languageIn", getLanguageIn())
.add("languageOut", getLanguageOut())
.add("legacyCodeCompile", legacyCodeCompile)
.add("lineBreak", lineBreak)
.add("lineLengthThreshold", lineLengthThreshold)
.add("locale", locale)
.add("markAsCompiled", markAsCompiled)
.add("markNoSideEffectCalls", markNoSideEffectCalls)
.add("maxFunctionSizeAfterInlining", maxFunctionSizeAfterInlining)
.add("messageBundle", messageBundle)
.add("moduleRoots", moduleRoots)
.add("moveFunctionDeclarations", moveFunctionDeclarations)
.add("nameGenerator", nameGenerator)
.add("optimizeArgumentsArray", optimizeArgumentsArray)
.add("optimizeCalls", optimizeCalls)
.add("optimizeParameters", optimizeParameters)
.add("optimizeReturns", optimizeReturns)
.add("outputCharset", outputCharset)
.add("outputJs", outputJs)
.add("outputJsStringUsage", outputJsStringUsage)
.add(
"parentModuleCanSeeSymbolsDeclaredInChildren",
parentModuleCanSeeSymbolsDeclaredInChildren)
.add("parseJsDocDocumentation", isParseJsDocDocumentation())
.add("polymerVersion", polymerVersion)
.add("preferLineBreakAtEndOfFile", preferLineBreakAtEndOfFile)
.add("preferSingleQuotes", preferSingleQuotes)
.add("preferStableNames", preferStableNames)
.add("preserveDetailedSourceInfo", preservesDetailedSourceInfo())
.add("preserveGoogProvidesAndRequires", preserveGoogProvidesAndRequires)
.add("preserveTypeAnnotations", preserveTypeAnnotations)
.add("prettyPrint", prettyPrint)
.add("preventLibraryInjection", preventLibraryInjection)
.add("printConfig", printConfig)
.add("printInputDelimiter", printInputDelimiter)
.add("printSourceAfterEachPass", printSourceAfterEachPass)
.add("processCommonJSModules", processCommonJSModules)
.add("processObjectPropertyString", processObjectPropertyString)
.add("propertyInvalidationErrors", propertyInvalidationErrors)
.add("propertyRenaming", propertyRenaming)
.add("protectHiddenSideEffects", protectHiddenSideEffects)
.add("quoteKeywordProperties", quoteKeywordProperties)
.add("recordFunctionInformation", recordFunctionInformation)
.add("removeAbstractMethods", removeAbstractMethods)
.add("removeSuperMethods", removeSuperMethods)
.add("removeClosureAsserts", removeClosureAsserts)
.add("removeDeadCode", removeDeadCode)
.add("removeUnusedClassProperties", removeUnusedClassProperties)
.add("removeUnusedConstructorProperties", removeUnusedConstructorProperties)
.add("removeUnusedLocalVars", removeUnusedLocalVars)
.add(
"removeUnusedPrototypePropertiesInExterns",
removeUnusedPrototypePropertiesInExterns)
.add("removeUnusedPrototypeProperties", removeUnusedPrototypeProperties)
.add("removeUnusedVars", removeUnusedVars)
.add(
"renamePrefixNamespaceAssumeCrossModuleNames",
renamePrefixNamespaceAssumeCrossModuleNames)
.add("renamePrefixNamespace", renamePrefixNamespace)
.add("renamePrefix", renamePrefix)
.add("replaceIdGenerators", replaceIdGenerators)
.add("replaceMessagesWithChromeI18n", replaceMessagesWithChromeI18n)
.add("replaceStringsFunctionDescriptions", replaceStringsFunctionDescriptions)
.add("replaceStringsInputMap", replaceStringsInputMap)
.add("replaceStringsPlaceholderToken", replaceStringsPlaceholderToken)
.add("replaceStringsReservedStrings", replaceStringsReservedStrings)
.add("reportOTIErrorsUnderNTI", reportOTIErrorsUnderNTI)
.add("reportPath", reportPath)
.add("reserveRawExports", reserveRawExports)
.add("rewriteFunctionExpressions", rewriteFunctionExpressions)
.add("rewritePolyfills", rewritePolyfills)
.add("runtimeTypeCheckLogFunction", runtimeTypeCheckLogFunction)
.add("runtimeTypeCheck", runtimeTypeCheck)
.add("shadowVariables", shadowVariables)
.add("skipNonTranspilationPasses", skipNonTranspilationPasses)
.add("skipTranspilationAndCrash", skipTranspilationAndCrash)
.add("smartNameRemoval", smartNameRemoval)
.add("sourceMapDetailLevel", sourceMapDetailLevel)
.add("sourceMapFormat", sourceMapFormat)
.add("sourceMapLocationMappings", sourceMapLocationMappings)
.add("sourceMapOutputPath", sourceMapOutputPath)
.add("stripNamePrefixes", stripNamePrefixes)
.add("stripNameSuffixes", stripNameSuffixes)
.add("stripTypePrefixes", stripTypePrefixes)
.add("stripTypes", stripTypes)
.add("summaryDetailLevel", summaryDetailLevel)
.add("syntheticBlockEndMarker", syntheticBlockEndMarker)
.add("syntheticBlockStartMarker", syntheticBlockStartMarker)
.add("tcProjectId", tcProjectId)
.add("tracer", tracer)
.add("transformAMDToCJSModules", transformAMDToCJSModules)
.add("trustedStrings", trustedStrings)
.add("tweakProcessing", getTweakProcessing())
.add("tweakReplacements", getTweakReplacements())
.add("useDebugLog", useDebugLog)
.add("useNewTypeInference", getNewTypeInference())
.add("emitUseStrict", emitUseStrict)
.add("useTypesForLocalOptimization", useTypesForLocalOptimization)
.add("variableRenaming", variableRenaming)
.add("warningsGuard", getWarningsGuard())
.add("wrapGoogModulesForWhitespaceOnly", wrapGoogModulesForWhitespaceOnly)
.toString();
return strValue;
}
//////////////////////////////////////////////////////////////////////////////
// Enums
/**
* A language mode applies to the whole compilation job.
* As a result, the compiler does not support mixed strict and non-strict in
* the same compilation job. Therefore, the 'use strict' directive is ignored
* when the language mode is not strict.
*/
public static enum LanguageMode {
/**
* 90's JavaScript
*/
ECMASCRIPT3,
/**
* Traditional JavaScript
*/
ECMASCRIPT5,
/**
* Nitpicky, traditional JavaScript
*/
ECMASCRIPT5_STRICT,
/**
* Shiny new JavaScript
* @deprecated Use ECMASCRIPT_2015 with {@code isStrictModeInput == false}.
*/
@Deprecated
ECMASCRIPT6,
/**
* Nitpicky, shiny new JavaScript
* @deprecated Use ECMASCRIPT_2015 with {@code isStrictModeInput == true}.
*/
@Deprecated
ECMASCRIPT6_STRICT,
/** ECMAScript standard approved in 2015. */
ECMASCRIPT_2015,
/**
* A superset of ES6 which adds Typescript-style type declarations. Always strict.
*/
ECMASCRIPT6_TYPED,
/**
* @deprecated Use ECMASCRIPT_2016.
*/
@Deprecated
ECMASCRIPT7,
/**
* ECMAScript standard approved in 2016.
* Adds the exponent operator (**).
*/
ECMASCRIPT_2016,
/** @deprecated Use {@code ECMASCRIPT_NEXT} */
@Deprecated
ECMASCRIPT8,
/**
* ECMAScript latest draft standard.
*/
ECMASCRIPT_NEXT,
/**
* For languageOut only. The same language mode as the input.
*/
NO_TRANSPILE;
/** Whether this is ECMAScript 5 or higher. */
public boolean isEs5OrHigher() {
Preconditions.checkState(this != NO_TRANSPILE);
return this != LanguageMode.ECMASCRIPT3;
}
/** Whether this is ECMAScript 6 or higher. */
public boolean isEs6OrHigher() {
Preconditions.checkState(this != NO_TRANSPILE);
switch (this) {
case ECMASCRIPT3:
case ECMASCRIPT5:
case ECMASCRIPT5_STRICT:
return false;
default:
return true;
}
}
public static LanguageMode fromString(String value) {
if (value == null) {
return null;
}
// Trim spaces, disregard case, and allow abbreviation of ECMASCRIPT for convenience.
String canonicalizedName = Ascii.toUpperCase(value.trim()).replaceFirst("^ES", "ECMASCRIPT");
try {
return LanguageMode.valueOf(canonicalizedName);
} catch (IllegalArgumentException e) {
return null; // unknown name.
}
}
}
/** When to do the extra sanity checks */
static enum DevMode {
/**
* Don't do any extra sanity checks.
*/
OFF,
/**
* After the initial parse
*/
START,
/**
* At the start and at the end of all optimizations.
*/
START_AND_END,
/**
* After every pass
*/
EVERY_PASS
}
/** How much tracing we want to do */
public static enum TracerMode {
ALL, // Collect all timing and size metrics. Very slow.
RAW_SIZE, // Collect all timing and size metrics, except gzipped size. Slow.
AST_SIZE, // For size data, don't serialize the AST, just count the number of nodes.
TIMING_ONLY, // Collect timing metrics only.
OFF; // Collect no timing and size metrics.
boolean isOn() {
return this != OFF;
}
}
/** Option for the ProcessTweaks pass */
public static enum TweakProcessing {
OFF, // Do not run the ProcessTweaks pass.
CHECK, // Run the pass, but do not strip out the calls.
STRIP; // Strip out all calls to goog.tweak.*.
public boolean isOn() {
return this != OFF;
}
public boolean shouldStrip() {
return this == STRIP;
}
}
/** What kind of isolation is going to be used */
public static enum IsolationMode {
NONE, // output does not include additional isolation.
IIFE; // The output should be wrapped in an IIFE to isolate global variables.
}
/**
* A Role Specific Interface for JS Compiler that represents a data holder
* object which is used to store goog.scope alias code changes to code made
* during a compile. There is no guarantee that individual alias changes are
* invoked in the order they occur during compilation, so implementations
* should not assume any relevance to the order changes arrive.
* <p>
* Calls to the mutators are expected to resolve very quickly, so
* implementations should not perform expensive operations in the mutator
* methods.
*
* @author [email protected] (Tyler Goodwin)
*/
public interface AliasTransformationHandler {
/**
* Builds an AliasTransformation implementation and returns it to the
* caller.
* <p>
* Callers are allowed to request multiple AliasTransformation instances for
* the same file, though it is expected that the first and last char values
* for multiple instances will not overlap.
* <p>
* This method is expected to have a side-effect of storing off the created
* AliasTransformation, which guarantees that invokers of this interface
* cannot leak AliasTransformation to this implementation that the
* implementor did not create
*
* @param sourceFile the source file the aliases re contained in.
* @param position the region of the source file associated with the
* goog.scope call. The item of the SourcePosition is the returned
* AliasTransformation
*/
public AliasTransformation logAliasTransformation(
String sourceFile, SourcePosition<AliasTransformation> position);
}
/**
* A Role Specific Interface for the JS Compiler to report aliases used to
* change the code during a compile.
* <p>
* While aliases defined by goog.scope are expected to by only 1 per file, and
* the only top-level structure in the file, this is not enforced.
*/
public interface AliasTransformation {
/**
* Adds an alias definition to the AliasTransformation instance.
* <p>
* Last definition for a given alias is kept if an alias is inserted
* multiple times (since this is generally the behavior in JavaScript code).
*
* @param alias the name of the alias.
* @param definition the definition of the alias.
*/
void addAlias(String alias, String definition);
}
/**
* A Null implementation of the CodeChanges interface which performs all
* operations as a No-Op
*/
static final AliasTransformationHandler NULL_ALIAS_TRANSFORMATION_HANDLER =
new NullAliasTransformationHandler();
private static class NullAliasTransformationHandler implements AliasTransformationHandler {
private static final AliasTransformation NULL_ALIAS_TRANSFORMATION =
new NullAliasTransformation();
@Override
public AliasTransformation logAliasTransformation(
String sourceFile, SourcePosition<AliasTransformation> position) {
position.setItem(NULL_ALIAS_TRANSFORMATION);
return NULL_ALIAS_TRANSFORMATION;
}
private static class NullAliasTransformation implements AliasTransformation {
@Override
public void addAlias(String alias, String definition) {
}
}
}
/**
* An environment specifies the built-in externs that are loaded for a given
* compilation.
*/
public static enum Environment {
/**
* Hand crafted externs that have traditionally been the default externs.
*/
BROWSER,
/**
* Only language externs are loaded.
*/
CUSTOM
}
/**
* Whether standard input or standard output should be an array of
* JSON encoded files
*/
static enum JsonStreamMode {
/**
* stdin/out are both single files.
*/
NONE,
/**
* stdin is a json stream.
*/
IN,
/**
* stdout is a json stream.
*/
OUT,
/**
* stdin and stdout are both json streams.
*/
BOTH
}
/** How compiler should prune files based on the provide-require dependency graph */
public static enum DependencyMode {
/**
* All files will be included in the compilation
*/
NONE,
/**
* Files must be discoverable from specified entry points. Files
* which do not goog.provide a namespace and and are not either
* an ES6 or CommonJS module will be automatically treated as entry points.
* Module files will be included only if referenced from an entry point.
*/
LOOSE,
/**
* Files must be discoverable from specified entry points. Files which
* do not goog.provide a namespace and are neither
* an ES6 or CommonJS module will be dropped. Module files will be included
* only if referenced from an entry point.
*/
STRICT
}
/**
* A mode enum used to indicate whether J2clPass should be enabled, disabled, or enabled
* automatically if there is any J2cl source file (i.e. in the AUTO mode).
*/
public static enum J2clPassMode {
/** J2clPass is disabled. */
FALSE,
/** J2clPass is enabled. */
TRUE,
/** J2clPass is disabled. */
OFF,
/** J2clPass is enabled. */
ON,
/** It auto-detects whether there are J2cl generated file. If yes, execute J2clPass. */
AUTO;
boolean shouldAddJ2clPasses() {
return this == TRUE || this == ON || this == AUTO;
}
boolean isExplicitlyOn() {
return this == TRUE || this == ON;
}
}
public boolean isStrictModeInput() {
return isStrictModeInput;
}
public CompilerOptions setStrictModeInput(boolean isStrictModeInput) {
this.isStrictModeInput = isStrictModeInput;
return this;
}
public char[] getPropertyReservedNamingFirstChars() {
char[] reservedChars = anonymousFunctionNaming.getReservedCharacters();
if (polymerVersion != null && polymerVersion > 1) {
if (reservedChars == null) {
reservedChars = POLYMER_PROPERTY_RESERVED_FIRST_CHARS;
} else {
reservedChars = Chars.concat(reservedChars, POLYMER_PROPERTY_RESERVED_FIRST_CHARS);
}
} else if (angularPass) {
if (reservedChars == null) {
reservedChars = ANGULAR_PROPERTY_RESERVED_FIRST_CHARS;
} else {
reservedChars = Chars.concat(reservedChars, ANGULAR_PROPERTY_RESERVED_FIRST_CHARS);
}
}
return reservedChars;
}
public char[] getPropertyReservedNamingNonFirstChars() {
char[] reservedChars = anonymousFunctionNaming.getReservedCharacters();
if (polymerVersion != null && polymerVersion > 1) {
if (reservedChars == null) {
reservedChars = POLYMER_PROPERTY_RESERVED_NON_FIRST_CHARS;
} else {
reservedChars = Chars.concat(reservedChars, POLYMER_PROPERTY_RESERVED_NON_FIRST_CHARS);
}
}
return reservedChars;
}
}
| src/com/google/javascript/jscomp/CompilerOptions.java | /*
* Copyright 2009 The Closure Compiler 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 com.google.javascript.jscomp;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Ascii;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.primitives.Chars;
import com.google.javascript.jscomp.deps.ModuleLoader;
import com.google.javascript.jscomp.parsing.Config;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.SourcePosition;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Properties;
import javax.annotation.Nullable;
/**
* Compiler options
*
* @author [email protected] (Nick Santos)
*/
public class CompilerOptions implements Serializable {
// The number of characters after which we insert a line break in the code
static final int DEFAULT_LINE_LENGTH_THRESHOLD = 500;
static final char[] POLYMER_PROPERTY_RESERVED_FIRST_CHARS =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ$".toCharArray();
static final char[] POLYMER_PROPERTY_RESERVED_NON_FIRST_CHARS = "_$".toCharArray();
static final char[] ANGULAR_PROPERTY_RESERVED_FIRST_CHARS = {'$'};
/**
* A common enum for compiler passes that can run either globally or locally.
*/
public enum Reach {
ALL,
LOCAL_ONLY,
NONE
}
// TODO(nicksantos): All public properties of this class should be made
// package-private, and have a public setter.
/**
* Should the compiled output start with "'use strict';"?
*
* <p>Ignored for non-strict output language modes.
*/
private boolean emitUseStrict = true;
/**
* The JavaScript language version accepted.
*/
private LanguageMode languageIn;
/**
* The JavaScript language version that should be produced.
*/
private LanguageMode languageOut;
/**
* The builtin set of externs to be used
*/
private Environment environment;
/**
* If true, don't transpile ES6 to ES3.
* WARNING: Enabling this option will likely cause the compiler to crash
* or produce incorrect output.
*/
boolean skipTranspilationAndCrash = false;
/**
* Allow disabling ES6 to ES3 transpilation.
*/
public void setSkipTranspilationAndCrash(boolean value) {
skipTranspilationAndCrash = value;
}
/**
* Sets the input sourcemap files, indexed by the JS files they refer to.
*
* @param inputSourceMaps the collection of input sourcemap files
*/
public void setInputSourceMaps(final ImmutableMap<String, SourceMapInput> inputSourceMaps) {
this.inputSourceMaps = inputSourceMaps;
}
/**
* Sets the input sourcemap files, indexed by the JS files they refer to.
*
* @param inputSourceMaps the collection of input sourcemap files
*/
public void setInputSourceMaps(final ImmutableMap<String, SourceMapInput> inputSourceMaps) {
this.inputSourceMaps = inputSourceMaps;
}
/**
* Whether to infer consts. This should not be configurable by
* external clients. This is a transitional flag for a new type
* of const analysis.
*
* TODO(nicksantos): Remove this option.
*/
boolean inferConsts = true;
// TODO(tbreisacher): Remove this method after ctemplate issues are solved.
public void setInferConst(boolean value) {
inferConsts = value;
}
/**
* Whether the compiler should assume that a function's "this" value
* never needs coercion (for example in non-strict "null" or "undefined" will
* be coerced to the global "this" and primitives to objects).
*/
private boolean assumeStrictThis;
private boolean allowHotswapReplaceScript = false;
private boolean preserveDetailedSourceInfo = false;
private boolean continueAfterErrors = false;
public enum IncrementalCheckMode {
/** Normal mode */
OFF,
/**
* The compiler should generate an output file that represents the type-only interface
* of the code being compiled. This is useful for incremental type checking.
*/
GENERATE_IJS,
/**
* The compiler should check type-only interface definitions generated above.
*/
CHECK_IJS,
}
private IncrementalCheckMode incrementalCheckMode = IncrementalCheckMode.OFF;
public void setIncrementalChecks(IncrementalCheckMode value) {
incrementalCheckMode = value;
switch (value) {
case OFF:
break;
case GENERATE_IJS:
setPreserveTypeAnnotations(true);
setOutputJs(OutputJs.NORMAL);
break;
case CHECK_IJS:
setChecksOnly(true);
setOutputJs(OutputJs.SENTINEL);
break;
}
}
public boolean shouldGenerateTypedExterns() {
return incrementalCheckMode == IncrementalCheckMode.GENERATE_IJS;
}
public boolean allowIjsInputs() {
return incrementalCheckMode != IncrementalCheckMode.OFF;
}
public boolean allowUnfulfilledForwardDeclarations() {
return incrementalCheckMode == IncrementalCheckMode.OFF;
}
private Config.JsDocParsing parseJsDocDocumentation = Config.JsDocParsing.TYPES_ONLY;
/**
* Even if checkTypes is disabled, clients such as IDEs might want to still infer types.
*/
boolean inferTypes;
private boolean useNewTypeInference;
/**
* Relevant only when {@link #useNewTypeInference} is true, where we normally disable OTI errors.
* If you want both NTI and OTI errors in this case, set to true.
* E.g. if using using a warnings guard to filter NTI or OTI warnings in new or legacy code,
* respectively.
* This will be removed when NTI entirely replaces OTI.
*/
boolean reportOTIErrorsUnderNTI = false;
/**
* Configures the compiler to skip as many passes as possible.
* If transpilation is requested, it will be run, but all others passes will be skipped.
*/
boolean skipNonTranspilationPasses;
/**
* Configures the compiler to run expensive sanity checks after
* every pass. Only intended for internal development.
*/
DevMode devMode;
/**
* Configures the compiler to log a hash code of the AST after
* every pass. Only intended for internal development.
*/
private boolean checkDeterminism;
//--------------------------------
// Input Options
//--------------------------------
DependencyOptions dependencyOptions = new DependencyOptions();
// TODO(tbreisacher): When this is false, report an error if there's a goog.provide
// in an externs file.
boolean allowGoogProvideInExterns() {
return allowIjsInputs();
}
/** Returns localized replacement for MSG_* variables */
public MessageBundle messageBundle = null;
//--------------------------------
// Checks
//--------------------------------
/** Checks that all symbols are defined */
// TODO(tbreisacher): Remove this and deprecate the corresponding setter.
public boolean checkSymbols;
/** Checks for suspicious statements that have no effect */
public boolean checkSuspiciousCode;
/** Checks types on expressions */
public boolean checkTypes;
public CheckLevel checkGlobalNamesLevel;
/**
* Checks the integrity of references to qualified global names.
* (e.g. "a.b")
*/
public void setCheckGlobalNamesLevel(CheckLevel level) {
checkGlobalNamesLevel = level;
}
@Deprecated
public CheckLevel brokenClosureRequiresLevel;
/**
* Sets the check level for bad Closure require calls.
* Do not use; this should always be an error.
*/
@Deprecated
public void setBrokenClosureRequiresLevel(CheckLevel level) {
brokenClosureRequiresLevel = level;
}
public CheckLevel checkGlobalThisLevel;
/**
* Checks for certain uses of the {@code this} keyword that are considered
* unsafe because they are likely to reference the global {@code this}
* object unintentionally.
*
* If this is off, but collapseProperties is on, then the compiler will
* usually ignore you and run this check anyways.
*/
public void setCheckGlobalThisLevel(CheckLevel level) {
this.checkGlobalThisLevel = level;
}
public CheckLevel checkMissingGetCssNameLevel;
/**
* Checks that certain string literals only appear in strings used as
* goog.getCssName arguments.
*/
public void setCheckMissingGetCssNameLevel(CheckLevel level) {
this.checkMissingGetCssNameLevel = level;
}
/**
* Regex of string literals that may only appear in goog.getCssName arguments.
*/
public String checkMissingGetCssNameBlacklist;
/**
* A set of extra annotation names which are accepted and silently ignored
* when encountered in a source file. Defaults to null which has the same
* effect as specifying an empty set.
*/
Set<String> extraAnnotationNames;
/**
* Policies to determine the disposal checking level.
*/
public enum DisposalCheckingPolicy {
/**
* Don't check any disposal.
*/
OFF,
/**
* Default/conservative disposal checking.
*/
ON,
/**
* Aggressive disposal checking.
*/
AGGRESSIVE,
}
/**
* Check for patterns that are known to cause memory leaks.
*/
DisposalCheckingPolicy checkEventfulObjectDisposalPolicy;
public void setCheckEventfulObjectDisposalPolicy(DisposalCheckingPolicy policy) {
this.checkEventfulObjectDisposalPolicy = policy;
// The CheckEventfulObjectDisposal pass requires types so enable inferring types if
// this pass is enabled.
if (policy != DisposalCheckingPolicy.OFF) {
this.inferTypes = true;
}
}
public DisposalCheckingPolicy getCheckEventfulObjectDisposalPolicy() {
return checkEventfulObjectDisposalPolicy;
}
/**
* Used for projects that are not well maintained, but are still used.
* Does not allow promoting warnings to errors, and disables some potentially
* risky optimizations.
*/
boolean legacyCodeCompile = false;
public boolean getLegacyCodeCompile() {
return this.legacyCodeCompile;
}
public void setLegacyCodeCompile(boolean legacy) {
this.legacyCodeCompile = legacy;
}
// TODO(bradfordcsmith): Investigate how can we use multi-threads as default.
int numParallelThreads = 1;
/**
* Sets the level of parallelism for compilation passes that can exploit multi-threading.
*
* <p>Some compiler passes may take advantage of multi-threading, for example, parsing inputs.
* This sets the level of parallelism. The compiler will not start more than this number of
* threads.
*
* @param parallelism up to this number of parallel threads may be created.
*/
public void setNumParallelThreads(int parallelism) {
numParallelThreads = parallelism;
}
//--------------------------------
// Optimizations
//--------------------------------
/** Prefer commas over semicolons when doing statement fusion */
boolean aggressiveFusion;
/** Folds constants (e.g. (2 + 3) to 5) */
public boolean foldConstants;
/** Remove assignments to values that can not be referenced */
public boolean deadAssignmentElimination;
/** Inlines constants (symbols that are all CAPS) */
public boolean inlineConstantVars;
/** Inlines global functions */
public boolean inlineFunctions;
/**
* For projects that want to avoid the creation of giant functions after
* inlining.
*/
int maxFunctionSizeAfterInlining;
static final int UNLIMITED_FUN_SIZE_AFTER_INLINING = -1;
/** Inlines functions defined in local scopes */
public boolean inlineLocalFunctions;
/** More aggressive function inlining */
boolean assumeClosuresOnlyCaptureReferences;
/** Inlines properties */
private boolean inlineProperties;
/** Move code to a deeper module */
public boolean crossModuleCodeMotion;
/**
* Don't generate stub functions when moving methods deeper.
*
* Note, switching on this option may break existing code that depends on
* enumerating prototype methods for mixin behavior, such as goog.mixin or
* goog.object.extend, since the prototype assignments will be removed from
* the parent module and moved to a later module.
**/
boolean crossModuleCodeMotionNoStubMethods;
/**
* Whether when module B depends on module A and module B declares a symbol,
* this symbol can be seen in A after B has been loaded. This is often true,
* but may not be true when loading code using nested eval.
*/
boolean parentModuleCanSeeSymbolsDeclaredInChildren;
/** Merge two variables together as one. */
public boolean coalesceVariableNames;
/** Move methods to a deeper module */
public boolean crossModuleMethodMotion;
/** Inlines trivial getters */
boolean inlineGetters;
/** Inlines variables */
public boolean inlineVariables;
/** Inlines variables */
boolean inlineLocalVariables;
// TODO(user): This is temporary. Once flow sensitive inlining is stable
// Remove this.
public boolean flowSensitiveInlineVariables;
/** Removes code associated with unused global names */
public boolean smartNameRemoval;
/** Removes code associated with unused global names */
boolean extraSmartNameRemoval;
/** Removes code that will never execute */
public boolean removeDeadCode;
public enum ExtractPrototypeMemberDeclarationsMode {
OFF,
USE_GLOBAL_TEMP,
USE_IIFE
}
/** Extracts common prototype member declarations */
ExtractPrototypeMemberDeclarationsMode extractPrototypeMemberDeclarations;
/** Removes unused member prototypes */
public boolean removeUnusedPrototypeProperties;
/** Tells AnalyzePrototypeProperties it can remove externed props. */
public boolean removeUnusedPrototypePropertiesInExterns;
/** Removes unused member properties */
public boolean removeUnusedClassProperties;
/** Removes unused constructor properties */
boolean removeUnusedConstructorProperties;
/** Removes unused variables */
public boolean removeUnusedVars;
/** Removes unused variables in local scope. */
public boolean removeUnusedLocalVars;
/** Collapses multiple variable declarations into one */
public boolean collapseVariableDeclarations;
/**
* Collapses anonymous function declarations into named function
* declarations
*/
public boolean collapseAnonymousFunctions;
/**
* If set to a non-empty set, those strings literals will be aliased to a
* single global instance per string, to avoid creating more objects than
* necessary.
*/
public Set<String> aliasableStrings;
/**
* A blacklist in the form of a regular expression to block strings that
* contains certain words from being aliased.
* If the value is the empty string, no words are blacklisted.
*/
public String aliasStringsBlacklist;
/**
* Aliases all string literals to global instances, to avoid creating more
* objects than necessary (if true, overrides any set of strings passed in
* to aliasableStrings)
*/
public boolean aliasAllStrings;
/** Print string usage as part of the compilation log. */
boolean outputJsStringUsage;
/** Converts quoted property accesses to dot syntax (a['b'] → a.b) */
public boolean convertToDottedProperties;
/** Reduces the size of common function expressions. */
public boolean rewriteFunctionExpressions;
/**
* Remove unused and constant parameters.
*/
public boolean optimizeParameters;
/**
* Remove unused return values.
*/
public boolean optimizeReturns;
/**
* Remove unused parameters from call sites.
*/
public boolean optimizeCalls;
/**
* Provide formal names for elements of arguments array.
*/
public boolean optimizeArgumentsArray;
/** Chains calls to functions that return this. */
boolean chainCalls;
/** Use type information to enable additional optimization opportunities. */
boolean useTypesForLocalOptimization;
boolean useSizeHeuristicToStopOptimizationLoop = true;
//--------------------------------
// Renaming
//--------------------------------
/** Controls which variables get renamed. */
public VariableRenamingPolicy variableRenaming;
/** Controls which properties get renamed. */
PropertyRenamingPolicy propertyRenaming;
/** Controls label renaming. */
public boolean labelRenaming;
/** Reserve property names on the global this object. */
public boolean reserveRawExports;
/** Should shadow variable names in outer scope. */
boolean shadowVariables;
/**
* Use a renaming heuristic with better stability across source
* changes. With this option each symbol is more likely to receive
* the same name between builds. The cost may be a slight increase
* in code size.
*/
boolean preferStableNames;
/**
* Generate pseudo names for variables and properties for debugging purposes.
*/
public boolean generatePseudoNames;
/** Specifies a prefix for all globals */
public String renamePrefix;
/**
* Specifies the name of an object that will be used to store all non-extern
* globals.
*/
public String renamePrefixNamespace;
/**
* Used by tests of the RescopeGlobalSymbols pass to avoid having declare 2
* modules in simple cases.
*/
boolean renamePrefixNamespaceAssumeCrossModuleNames = false;
void setRenamePrefixNamespaceAssumeCrossModuleNames(boolean assume) {
renamePrefixNamespaceAssumeCrossModuleNames = assume;
}
/** Flattens multi-level property names (e.g. a$b = x) */
public boolean collapseProperties;
/** Split object literals into individual variables when possible. */
boolean collapseObjectLiterals;
public void setCollapseObjectLiterals(boolean enabled) {
collapseObjectLiterals = enabled;
}
/**
* Devirtualize prototype method by rewriting them to be static calls that
* take the this pointer as their first argument
*/
public boolean devirtualizePrototypeMethods;
/**
* Use @nosideeffects annotations, function bodies and name graph
* to determine if calls have side effects. Requires --check_types.
*/
public boolean computeFunctionSideEffects;
/**
* Where to save debug report for compute function side effects.
*/
String debugFunctionSideEffectsPath;
/**
* Rename private properties to disambiguate between unrelated fields based on
* the coding convention.
*/
boolean disambiguatePrivateProperties;
/**
* Rename properties to disambiguate between unrelated fields based on
* type information.
*/
private boolean disambiguateProperties;
/** Rename unrelated properties to the same name to reduce code size. */
private boolean ambiguateProperties;
/** Input sourcemap files, indexed by the JS files they refer to */
ImmutableMap<String, SourceMapInput> inputSourceMaps;
/** Give anonymous functions names for easier debugging */
public AnonymousFunctionNamingPolicy anonymousFunctionNaming;
/** Input anonymous function renaming map. */
VariableMap inputAnonymousFunctionNamingMap;
/**
* Input variable renaming map.
* <p>During renaming, the compiler uses this map and the inputPropertyMap to
* try to preserve renaming mappings from a previous compilation.
* The application is delta encoding: keeping the diff between consecutive
* versions of one's code small.
* The compiler does NOT guarantee to respect these maps; projects should not
* use these maps to prevent renaming or to select particular names.
* Point questioners to this post:
* http://closuretools.blogspot.com/2011/01/property-by-any-other-name-part-3.html
*/
VariableMap inputVariableMap;
/** Input property renaming map. */
VariableMap inputPropertyMap;
/** List of individually configured compiler options. WARNING: experimental; these override the three compiler optimization levels! */
Properties inputCompilerOptions;
/** Whether to export test functions. */
public boolean exportTestFunctions;
/** Whether to declare globals declared in externs as properties on window */
boolean declaredGlobalExternsOnWindow;
/** Shared name generator */
NameGenerator nameGenerator;
public void setNameGenerator(NameGenerator nameGenerator) {
this.nameGenerator = nameGenerator;
}
//--------------------------------
// Special-purpose alterations
//--------------------------------
/**
* Replace UI strings with chrome.i18n.getMessage calls.
* Used by Chrome extensions/apps.
*/
boolean replaceMessagesWithChromeI18n;
String tcProjectId;
public void setReplaceMessagesWithChromeI18n(
boolean replaceMessagesWithChromeI18n,
String tcProjectId) {
if (replaceMessagesWithChromeI18n
&& messageBundle != null
&& !(messageBundle instanceof EmptyMessageBundle)) {
throw new RuntimeException("When replacing messages with"
+ " chrome.i18n.getMessage, a message bundle should not be specified.");
}
this.replaceMessagesWithChromeI18n = replaceMessagesWithChromeI18n;
this.tcProjectId = tcProjectId;
}
/** Inserts run-time type assertions for debugging. */
boolean runtimeTypeCheck;
/**
* A JS function to be used for logging run-time type assertion
* failures. It will be passed the warning as a string and the
* faulty expression as arguments.
*/
String runtimeTypeCheckLogFunction;
/** A CodingConvention to use during the compile. */
private CodingConvention codingConvention;
@Nullable
public String syntheticBlockStartMarker;
@Nullable
public String syntheticBlockEndMarker;
/** Compiling locale */
public String locale;
/** Sets the special "COMPILED" value to true */
public boolean markAsCompiled;
/** Processes goog.provide() and goog.require() calls */
public boolean closurePass;
/** Do not strip goog.provide()/goog.require() calls from the code. */
private boolean preserveGoogProvidesAndRequires;
/** Processes AngularJS-specific annotations */
boolean angularPass;
/** If non-null, processes Polymer code */
@Nullable
Integer polymerVersion;
/** Processes cr.* functions */
boolean chromePass;
/** Processes the output of the Dart Dev Compiler */
boolean dartPass;
/** Processes the output of J2CL */
J2clPassMode j2clPassMode;
/** Remove goog.abstractMethod assignments and @abstract methods. */
boolean removeAbstractMethods;
/** Remove methods that only make a super call without changing the arguments. */
boolean removeSuperMethods;
/** Remove goog.asserts calls. */
boolean removeClosureAsserts;
/** Gather CSS names (requires closurePass) */
public boolean gatherCssNames;
/** Names of types to strip */
public Set<String> stripTypes;
/** Name suffixes that determine which variables and properties to strip */
public Set<String> stripNameSuffixes;
/** Name prefixes that determine which variables and properties to strip */
public Set<String> stripNamePrefixes;
/** Qualified type name prefixes that determine which types to strip */
public Set<String> stripTypePrefixes;
/** Custom passes */
protected transient
Multimap<CustomPassExecutionTime, CompilerPass> customPasses;
/** Mark no side effect calls */
public boolean markNoSideEffectCalls;
/** Replacements for @defines. Will be Boolean, Numbers, or Strings */
private Map<String, Object> defineReplacements;
/** What kind of processing to do for goog.tweak functions. */
private TweakProcessing tweakProcessing;
/** Replacements for tweaks. Will be Boolean, Numbers, or Strings */
private Map<String, Object> tweakReplacements;
/** Move top-level function declarations to the top */
public boolean moveFunctionDeclarations;
/** Instrumentation template to use with #recordFunctionInformation */
public Instrumentation instrumentationTemplate;
String appNameStr;
/**
* App identifier string for use by the instrumentation template's
* app_name_setter. @see #instrumentationTemplate
*/
public void setAppNameStr(String appNameStr) {
this.appNameStr = appNameStr;
}
/** Record function information */
public boolean recordFunctionInformation;
boolean checksOnly;
static enum OutputJs {
// Don't output anything.
NONE,
// Output a "sentinel" file containing just a comment.
SENTINEL,
// Output the compiled JS.
NORMAL,
}
OutputJs outputJs;
public boolean generateExports;
// TODO(dimvar): generate-exports should always run after typechecking.
// If it runs before, it adds a bunch of properties to Object, which masks
// many type warnings. Cleanup all clients and remove this.
boolean generateExportsAfterTypeChecking;
boolean exportLocalPropertyDefinitions;
/** Map used in the renaming of CSS class names. */
public CssRenamingMap cssRenamingMap;
/** Whitelist used in the renaming of CSS class names. */
Set<String> cssRenamingWhitelist;
/** Process instances of goog.testing.ObjectPropertyString. */
boolean processObjectPropertyString;
/** Replace id generators */
boolean replaceIdGenerators = true; // true by default for legacy reasons.
/** Id generators to replace. */
ImmutableMap<String, RenamingMap> idGenerators;
/** Hash function to use for xid generation. */
Xid.HashFunction xidHashFunction;
/**
* A previous map of ids (serialized to a string by a previous compile).
* This will be used as a hint during the ReplaceIdGenerators pass, which
* will attempt to reuse the same ids.
*/
String idGeneratorsMapSerialized;
/** Configuration strings */
List<String> replaceStringsFunctionDescriptions;
String replaceStringsPlaceholderToken;
// A list of strings that should not be used as replacements
Set<String> replaceStringsReservedStrings;
// A previous map of replacements to strings.
VariableMap replaceStringsInputMap;
/** List of properties that we report invalidation errors for. */
Map<String, CheckLevel> propertyInvalidationErrors;
/** Transform AMD to CommonJS modules. */
boolean transformAMDToCJSModules = false;
/** Rewrite CommonJS modules so that they can be concatenated together. */
boolean processCommonJSModules = false;
/** CommonJS module prefix. */
List<String> moduleRoots = ImmutableList.of(ModuleLoader.DEFAULT_FILENAME_PREFIX);
/** Rewrite polyfills. */
boolean rewritePolyfills = false;
/** Runtime libraries to always inject. */
List<String> forceLibraryInjection = ImmutableList.of();
/** Runtime libraries to never inject. */
boolean preventLibraryInjection = false;
boolean assumeForwardDeclaredForMissingTypes = false;
/**
* If {@code true}, considers all missing types to be forward declared (useful for partial
* compilation).
*/
public void setAssumeForwardDeclaredForMissingTypes(
boolean assumeForwardDeclaredForMissingTypes) {
this.assumeForwardDeclaredForMissingTypes = assumeForwardDeclaredForMissingTypes;
}
//--------------------------------
// Output options
//--------------------------------
/** Do not strip closure-style type annotations from code. */
public boolean preserveTypeAnnotations;
/** Output in pretty indented format */
private boolean prettyPrint;
/** Line break the output a bit more aggressively */
public boolean lineBreak;
/** Prefer line breaks at end of file */
public boolean preferLineBreakAtEndOfFile;
/** Prints a separator comment before each JS script */
public boolean printInputDelimiter;
/** The string to use as the separator for printInputDelimiter */
public String inputDelimiter = "// Input %num%";
/** Whether to write keyword properties as foo['class'] instead of foo.class; needed for IE8. */
boolean quoteKeywordProperties;
boolean preferSingleQuotes;
/**
* Normally, when there are an equal number of single and double quotes
* in a string, the compiler will use double quotes. Set this to true
* to prefer single quotes.
*/
public void setPreferSingleQuotes(boolean enabled) {
this.preferSingleQuotes = enabled;
}
boolean trustedStrings;
/**
* Some people want to put arbitrary user input into strings, which are then
* run through the compiler. These scripts are then put into HTML.
* By default, we assume strings are untrusted. If the compiler is run
* from the command-line, we assume that strings are trusted.
*/
public void setTrustedStrings(boolean yes) {
trustedStrings = yes;
}
// Should only be used when debugging compiler bugs.
boolean printSourceAfterEachPass;
// Used to narrow down the printed source when overall input size is large. If this is empty,
// the entire source is printed.
List<String> filesToPrintAfterEachPass = ImmutableList.of();
public void setPrintSourceAfterEachPass(boolean printSource) {
this.printSourceAfterEachPass = printSource;
}
public void setFilesToPrintAfterEachPass(List<String> filenames) {
this.filesToPrintAfterEachPass = filenames;
}
String reportPath;
/** Where to save a report of global name usage */
public void setReportPath(String reportPath) {
this.reportPath = reportPath;
}
private TracerMode tracer;
public TracerMode getTracerMode() {
return tracer;
}
public void setTracerMode(TracerMode mode) {
this.tracer = mode;
}
private boolean colorizeErrorOutput;
public ErrorFormat errorFormat;
private ComposeWarningsGuard warningsGuard = new ComposeWarningsGuard();
int summaryDetailLevel = 1;
int lineLengthThreshold = DEFAULT_LINE_LENGTH_THRESHOLD;
/**
* Whether to use the original names of nodes in the code output. This option is only really
* useful when using the compiler to print code meant to check in to source.
*/
boolean useOriginalNamesInOutput = false;
//--------------------------------
// Special Output Options
//--------------------------------
/**
* Whether the exports should be made available via {@link Result} after
* compilation. This is implicitly true if {@link #externExportsPath} is set.
*/
private boolean externExports;
/** The output path for the created externs file. */
String externExportsPath;
//--------------------------------
// Debugging Options
//--------------------------------
/** The output path for the source map. */
public String sourceMapOutputPath;
/** The detail level for the generated source map. */
public SourceMap.DetailLevel sourceMapDetailLevel =
SourceMap.DetailLevel.ALL;
/** The source map file format */
public SourceMap.Format sourceMapFormat =
SourceMap.Format.DEFAULT;
/**
* Whether to parse inline source maps.
*/
boolean parseInlineSourceMaps = true;
/**
* Whether to apply input source maps to the output, i.e. map back to original inputs from
* input files that have source maps applied to them.
*/
boolean applyInputSourceMaps = false;
public List<SourceMap.LocationMapping> sourceMapLocationMappings =
Collections.emptyList();
/**
* Whether to include full file contents in the source map.
*/
boolean sourceMapIncludeSourcesContent = false;
/**
* Whether to return strings logged with AbstractCompiler#addToDebugLog
* in the compiler's Result.
*/
boolean useDebugLog;
/**
* Charset to use when generating code. If null, then output ASCII.
*/
Charset outputCharset;
/**
* Transitional option.
*/
boolean enforceAccessControlCodingConventions;
/**
* When set, assume that apparently side-effect free code is meaningful.
*/
private boolean protectHiddenSideEffects;
/**
* When enabled, assume that apparently side-effect free code is meaningful.
*/
public void setProtectHiddenSideEffects(boolean enable) {
this.protectHiddenSideEffects = enable;
}
/**
* Whether or not the compiler should wrap apparently side-effect free code
* to prevent it from being removed
*/
public boolean shouldProtectHiddenSideEffects() {
return protectHiddenSideEffects && !checksOnly && !allowHotswapReplaceScript;
}
/**
* Data holder Alias Transformation information accumulated during a compile.
*/
private transient AliasTransformationHandler aliasHandler;
/**
* Handler for compiler warnings and errors.
*/
transient ErrorHandler errorHandler;
/**
* Instrument code for the purpose of collecting coverage data.
*/
public boolean instrumentForCoverage;
/** Instrument branch coverage data - valid only if instrumentForCoverage is True */
public boolean instrumentBranchCoverage;
String instrumentationTemplateFile;
/** List of conformance configs to use in CheckConformance */
private ImmutableList<ConformanceConfig> conformanceConfigs = ImmutableList.of();
/**
* For use in {@link CompilationLevel#WHITESPACE_ONLY} mode, when using goog.module.
*/
boolean wrapGoogModulesForWhitespaceOnly = true;
public void setWrapGoogModulesForWhitespaceOnly(boolean enable) {
this.wrapGoogModulesForWhitespaceOnly = enable;
}
/**
* Print all configuration options to stderr after the compiler is initialized.
*/
boolean printConfig = false;
/**
* Are the input files written for strict mode?
*
* <p>Ignored for language modes that do not support strict mode.
*/
private boolean isStrictModeInput = true;
/** Which algorithm to use for locating ES6 and CommonJS modules */
ModuleLoader.ResolutionMode moduleResolutionMode;
/**
* Should the compiler print its configuration options to stderr when they are initialized?
*
* <p>Default {@code false}.
*/
public void setPrintConfig(boolean printConfig) {
this.printConfig = printConfig;
}
/**
* Initializes compiler options. All options are disabled by default.
*
* Command-line frontends to the compiler should set these properties
* like a builder.
*/
public CompilerOptions() {
// Accepted language
languageIn = LanguageMode.ECMASCRIPT3;
languageOut = LanguageMode.NO_TRANSPILE;
// Which environment to use
environment = Environment.BROWSER;
// Modules
moduleResolutionMode = ModuleLoader.ResolutionMode.LEGACY;
// Checks
skipNonTranspilationPasses = false;
devMode = DevMode.OFF;
checkDeterminism = false;
checkSymbols = false;
checkSuspiciousCode = false;
checkTypes = false;
checkGlobalNamesLevel = CheckLevel.OFF;
brokenClosureRequiresLevel = CheckLevel.ERROR;
checkGlobalThisLevel = CheckLevel.OFF;
checkMissingGetCssNameLevel = CheckLevel.OFF;
checkMissingGetCssNameBlacklist = null;
computeFunctionSideEffects = false;
chainCalls = false;
extraAnnotationNames = null;
checkEventfulObjectDisposalPolicy = DisposalCheckingPolicy.OFF;
// Optimizations
foldConstants = false;
coalesceVariableNames = false;
deadAssignmentElimination = false;
inlineConstantVars = false;
inlineFunctions = false;
maxFunctionSizeAfterInlining = UNLIMITED_FUN_SIZE_AFTER_INLINING;
inlineLocalFunctions = false;
assumeStrictThis = false;
assumeClosuresOnlyCaptureReferences = false;
inlineProperties = false;
crossModuleCodeMotion = false;
parentModuleCanSeeSymbolsDeclaredInChildren = false;
crossModuleMethodMotion = false;
inlineGetters = false;
inlineVariables = false;
inlineLocalVariables = false;
smartNameRemoval = false;
extraSmartNameRemoval = false;
removeDeadCode = false;
extractPrototypeMemberDeclarations =
ExtractPrototypeMemberDeclarationsMode.OFF;
removeUnusedPrototypeProperties = false;
removeUnusedPrototypePropertiesInExterns = false;
removeUnusedClassProperties = false;
removeUnusedConstructorProperties = false;
removeUnusedVars = false;
removeUnusedLocalVars = false;
collapseVariableDeclarations = false;
collapseAnonymousFunctions = false;
aliasableStrings = Collections.emptySet();
aliasStringsBlacklist = "";
aliasAllStrings = false;
outputJsStringUsage = false;
convertToDottedProperties = false;
rewriteFunctionExpressions = false;
optimizeParameters = false;
optimizeReturns = false;
// Renaming
variableRenaming = VariableRenamingPolicy.OFF;
propertyRenaming = PropertyRenamingPolicy.OFF;
labelRenaming = false;
generatePseudoNames = false;
shadowVariables = false;
preferStableNames = false;
renamePrefix = null;
collapseProperties = false;
collapseObjectLiterals = false;
devirtualizePrototypeMethods = false;
disambiguateProperties = false;
ambiguateProperties = false;
anonymousFunctionNaming = AnonymousFunctionNamingPolicy.OFF;
exportTestFunctions = false;
declaredGlobalExternsOnWindow = true;
nameGenerator = new DefaultNameGenerator();
// Alterations
runtimeTypeCheck = false;
runtimeTypeCheckLogFunction = null;
syntheticBlockStartMarker = null;
syntheticBlockEndMarker = null;
locale = null;
markAsCompiled = false;
closurePass = false;
preserveGoogProvidesAndRequires = false;
angularPass = false;
polymerVersion = null;
dartPass = false;
j2clPassMode = J2clPassMode.OFF;
removeAbstractMethods = false;
removeSuperMethods = false;
removeClosureAsserts = false;
stripTypes = Collections.emptySet();
stripNameSuffixes = Collections.emptySet();
stripNamePrefixes = Collections.emptySet();
stripTypePrefixes = Collections.emptySet();
customPasses = null;
markNoSideEffectCalls = false;
defineReplacements = new HashMap<>();
tweakProcessing = TweakProcessing.OFF;
tweakReplacements = new HashMap<>();
moveFunctionDeclarations = false;
appNameStr = "";
recordFunctionInformation = false;
checksOnly = false;
outputJs = OutputJs.NORMAL;
generateExports = false;
generateExportsAfterTypeChecking = true;
exportLocalPropertyDefinitions = false;
cssRenamingMap = null;
cssRenamingWhitelist = null;
processObjectPropertyString = false;
idGenerators = ImmutableMap.of();
replaceStringsFunctionDescriptions = Collections.emptyList();
replaceStringsPlaceholderToken = "";
replaceStringsReservedStrings = Collections.emptySet();
propertyInvalidationErrors = new HashMap<>();
inputSourceMaps = ImmutableMap.of();
// Instrumentation
instrumentationTemplate = null; // instrument functions
instrumentForCoverage = false; // instrument lines
instrumentBranchCoverage = false; // instrument branches
instrumentationTemplateFile = "";
// Output
preserveTypeAnnotations = false;
printInputDelimiter = false;
prettyPrint = false;
lineBreak = false;
preferLineBreakAtEndOfFile = false;
reportPath = null;
tracer = TracerMode.OFF;
colorizeErrorOutput = false;
errorFormat = ErrorFormat.SINGLELINE;
debugFunctionSideEffectsPath = null;
externExports = false;
// Debugging
aliasHandler = NULL_ALIAS_TRANSFORMATION_HANDLER;
errorHandler = null;
printSourceAfterEachPass = false;
useDebugLog = false;
}
/**
* @return Whether to attempt to remove unused class properties
*/
public boolean isRemoveUnusedClassProperties() {
return removeUnusedClassProperties;
}
/**
* @param removeUnusedClassProperties Whether to attempt to remove
* unused class properties
*/
public void setRemoveUnusedClassProperties(boolean removeUnusedClassProperties) {
this.removeUnusedClassProperties = removeUnusedClassProperties;
}
/**
* @return Whether to attempt to remove unused constructor properties
*/
public boolean isRemoveUnusedConstructorProperties() {
return removeUnusedConstructorProperties;
}
/**
* @param removeUnused Whether to attempt to remove
* unused constructor properties
*/
public void setRemoveUnusedConstructorProperties(boolean removeUnused) {
this.removeUnusedConstructorProperties = removeUnused;
}
/**
* Returns the map of define replacements.
*/
public Map<String, Node> getDefineReplacements() {
return getReplacementsHelper(defineReplacements);
}
/**
* Returns the map of tweak replacements.
*/
public Map<String, Node> getTweakReplacements() {
return getReplacementsHelper(tweakReplacements);
}
/**
* Creates a map of String->Node from a map of String->Number/String/Boolean.
*/
private static Map<String, Node> getReplacementsHelper(
Map<String, Object> source) {
ImmutableMap.Builder<String, Node> map = ImmutableMap.builder();
for (Map.Entry<String, Object> entry : source.entrySet()) {
String name = entry.getKey();
Object value = entry.getValue();
if (value instanceof Boolean) {
map.put(name, NodeUtil.booleanNode(((Boolean) value).booleanValue()));
} else if (value instanceof Integer) {
map.put(name, IR.number(((Integer) value).intValue()));
} else if (value instanceof Double) {
map.put(name, IR.number(((Double) value).doubleValue()));
} else {
Preconditions.checkState(value instanceof String);
map.put(name, IR.string((String) value));
}
}
return map.build();
}
/**
* Sets the value of the {@code @define} variable in JS
* to a boolean literal.
*/
public void setDefineToBooleanLiteral(String defineName, boolean value) {
defineReplacements.put(defineName, value);
}
/**
* Sets the value of the {@code @define} variable in JS to a
* String literal.
*/
public void setDefineToStringLiteral(String defineName, String value) {
defineReplacements.put(defineName, value);
}
/**
* Sets the value of the {@code @define} variable in JS to a
* number literal.
*/
public void setDefineToNumberLiteral(String defineName, int value) {
defineReplacements.put(defineName, value);
}
/**
* Sets the value of the {@code @define} variable in JS to a
* number literal.
*/
public void setDefineToDoubleLiteral(String defineName, double value) {
defineReplacements.put(defineName, value);
}
/**
* Sets the value of the tweak in JS
* to a boolean literal.
*/
public void setTweakToBooleanLiteral(String tweakId, boolean value) {
tweakReplacements.put(tweakId, value);
}
/**
* Sets the value of the tweak in JS to a
* String literal.
*/
public void setTweakToStringLiteral(String tweakId, String value) {
tweakReplacements.put(tweakId, value);
}
/**
* Sets the value of the tweak in JS to a
* number literal.
*/
public void setTweakToNumberLiteral(String tweakId, int value) {
tweakReplacements.put(tweakId, value);
}
/**
* Sets the value of the tweak in JS to a
* number literal.
*/
public void setTweakToDoubleLiteral(String tweakId, double value) {
tweakReplacements.put(tweakId, value);
}
/**
* Skip all possible passes, to make the compiler as fast as possible.
*/
public void skipAllCompilerPasses() {
skipNonTranspilationPasses = true;
}
/**
* Whether the warnings guard in this Options object enables the given
* group of warnings.
*/
boolean enables(DiagnosticGroup type) {
return this.warningsGuard.enables(type);
}
/**
* Whether the warnings guard in this Options object disables the given
* group of warnings.
*/
boolean disables(DiagnosticGroup type) {
return this.warningsGuard.disables(type);
}
/**
* Configure the given type of warning to the given level.
*/
public void setWarningLevel(DiagnosticGroup type, CheckLevel level) {
addWarningsGuard(new DiagnosticGroupWarningsGuard(type, level));
}
WarningsGuard getWarningsGuard() {
return this.warningsGuard;
}
/**
* Reset the warnings guard.
*/
public void resetWarningsGuard() {
this.warningsGuard = new ComposeWarningsGuard();
}
/**
* The emergency fail safe removes all strict and ERROR-escalating
* warnings guards.
*/
void useEmergencyFailSafe() {
this.warningsGuard = this.warningsGuard.makeEmergencyFailSafeGuard();
}
void useNonStrictWarningsGuard() {
this.warningsGuard = this.warningsGuard.makeNonStrict();
}
/**
* Add a guard to the set of warnings guards.
*/
public void addWarningsGuard(WarningsGuard guard) {
this.warningsGuard.addGuard(guard);
}
/**
* Sets the variable and property renaming policies for the compiler,
* in a way that clears warnings about the renaming policy being
* uninitialized from flags.
*/
public void setRenamingPolicy(VariableRenamingPolicy newVariablePolicy,
PropertyRenamingPolicy newPropertyPolicy) {
this.variableRenaming = newVariablePolicy;
this.propertyRenaming = newPropertyPolicy;
}
/** Should shadow outer scope variable name during renaming. */
public void setShadowVariables(boolean shadow) {
this.shadowVariables = shadow;
}
/**
* If true, process goog.testing.ObjectPropertyString instances.
*/
public void setProcessObjectPropertyString(boolean process) {
processObjectPropertyString = process;
}
/**
* @param replaceIdGenerators the replaceIdGenerators to set
*/
public void setReplaceIdGenerators(boolean replaceIdGenerators) {
this.replaceIdGenerators = replaceIdGenerators;
}
/**
* Sets the id generators to replace.
*/
public void setIdGenerators(Set<String> idGenerators) {
RenamingMap gen = new UniqueRenamingToken();
ImmutableMap.Builder<String, RenamingMap> builder = ImmutableMap.builder();
for (String name : idGenerators) {
builder.put(name, gen);
}
this.idGenerators = builder.build();
}
/**
* Sets the hash function to use for Xid
*/
public void setXidHashFunction(Xid.HashFunction xidHashFunction) {
this.xidHashFunction = xidHashFunction;
}
/**
* Sets the id generators to replace.
*/
public void setIdGenerators(Map<String, RenamingMap> idGenerators) {
this.idGenerators = ImmutableMap.copyOf(idGenerators);
}
/**
* A previous map of ids (serialized to a string by a previous compile).
* This will be used as a hint during the ReplaceIdGenerators pass, which
* will attempt to reuse the same ids.
*/
public void setIdGeneratorsMap(String previousMappings) {
this.idGeneratorsMapSerialized = previousMappings;
}
/**
* Set the function inlining policy for the compiler.
*/
public void setInlineFunctions(Reach reach) {
switch (reach) {
case ALL:
this.inlineFunctions = true;
this.inlineLocalFunctions = true;
break;
case LOCAL_ONLY:
this.inlineFunctions = false;
this.inlineLocalFunctions = true;
break;
case NONE:
this.inlineFunctions = false;
this.inlineLocalFunctions = false;
break;
default:
throw new IllegalStateException("unexpected");
}
}
public void setMaxFunctionSizeAfterInlining(int funAstSize) {
Preconditions.checkArgument(funAstSize > 0);
this.maxFunctionSizeAfterInlining = funAstSize;
}
/**
* Set the variable inlining policy for the compiler.
*/
public void setInlineVariables(Reach reach) {
switch (reach) {
case ALL:
this.inlineVariables = true;
this.inlineLocalVariables = true;
break;
case LOCAL_ONLY:
this.inlineVariables = false;
this.inlineLocalVariables = true;
break;
case NONE:
this.inlineVariables = false;
this.inlineLocalVariables = false;
break;
default:
throw new IllegalStateException("unexpected");
}
}
/**
* Set the function inlining policy for the compiler.
*/
public void setInlineProperties(boolean enable) {
inlineProperties = enable;
}
boolean shouldInlineProperties() {
return inlineProperties;
}
/**
* Set the variable removal policy for the compiler.
*/
public void setRemoveUnusedVariables(Reach reach) {
switch (reach) {
case ALL:
this.removeUnusedVars = true;
this.removeUnusedLocalVars = true;
break;
case LOCAL_ONLY:
this.removeUnusedVars = false;
this.removeUnusedLocalVars = true;
break;
case NONE:
this.removeUnusedVars = false;
this.removeUnusedLocalVars = false;
break;
default:
throw new IllegalStateException("unexpected");
}
}
/**
* Sets the functions whose debug strings to replace.
*/
public void setReplaceStringsConfiguration(
String placeholderToken, List<String> functionDescriptors) {
this.replaceStringsPlaceholderToken = placeholderToken;
this.replaceStringsFunctionDescriptions =
new ArrayList<>(functionDescriptors);
}
public void setRemoveAbstractMethods(boolean remove) {
this.removeAbstractMethods = remove;
}
public void setRemoveSuperMethods(boolean remove) {
this.removeSuperMethods = remove;
}
public void setRemoveClosureAsserts(boolean remove) {
this.removeClosureAsserts = remove;
}
public void setColorizeErrorOutput(boolean colorizeErrorOutput) {
this.colorizeErrorOutput = colorizeErrorOutput;
}
public boolean shouldColorizeErrorOutput() {
return colorizeErrorOutput;
}
/**
* If true, chain calls to functions that return this.
*/
public void setChainCalls(boolean value) {
this.chainCalls = value;
}
/**
* Enable run-time type checking, which adds JS type assertions for debugging.
*
* @param logFunction A JS function to be used for logging run-time type
* assertion failures.
*/
public void enableRuntimeTypeCheck(String logFunction) {
this.runtimeTypeCheck = true;
this.runtimeTypeCheckLogFunction = logFunction;
}
public void disableRuntimeTypeCheck() {
this.runtimeTypeCheck = false;
}
public void setChecksOnly(boolean checksOnly) {
this.checksOnly = checksOnly;
}
void setOutputJs(OutputJs outputJs) {
this.outputJs = outputJs;
}
public void setGenerateExports(boolean generateExports) {
this.generateExports = generateExports;
}
public void setExportLocalPropertyDefinitions(boolean export) {
this.exportLocalPropertyDefinitions = export;
}
public void setAngularPass(boolean angularPass) {
this.angularPass = angularPass;
}
public void setPolymerVersion(Integer polymerVersion) {
checkArgument(polymerVersion == null || polymerVersion == 1 || polymerVersion == 2,
"Invalid Polymer version:", polymerVersion);
this.polymerVersion = polymerVersion;
}
public void setDartPass(boolean dartPass) {
this.dartPass = dartPass;
}
@Deprecated
public void setJ2clPass(boolean flag) {
setJ2clPass(flag ? J2clPassMode.ON : J2clPassMode.OFF);
}
public void setJ2clPass(J2clPassMode j2clPassMode) {
this.j2clPassMode = j2clPassMode;
if (j2clPassMode.isExplicitlyOn()) {
setWarningLevel(DiagnosticGroup.forType(SourceFile.DUPLICATE_ZIP_CONTENTS), CheckLevel.OFF);
}
}
public void setCodingConvention(CodingConvention codingConvention) {
this.codingConvention = codingConvention;
}
public CodingConvention getCodingConvention() {
return codingConvention;
}
/**
* Sets dependency options. See the DependencyOptions class for more info.
* This supersedes manageClosureDependencies.
*/
public void setDependencyOptions(DependencyOptions options) {
this.dependencyOptions = options;
}
public DependencyOptions getDependencyOptions() {
return dependencyOptions;
}
/**
* Sort inputs by their goog.provide/goog.require calls, and prune inputs
* whose symbols are not required.
*/
public void setManageClosureDependencies(boolean newVal) {
dependencyOptions.setDependencySorting(
newVal || dependencyOptions.shouldSortDependencies());
dependencyOptions.setDependencyPruning(
newVal || dependencyOptions.shouldPruneDependencies());
dependencyOptions.setMoocherDropping(false);
}
/**
* Sort inputs by their goog.provide/goog.require calls.
*
* @param entryPoints Entry points to the program. Must be goog.provide'd
* symbols. Any goog.provide'd symbols that are not a transitive
* dependency of the entry points will be deleted.
* Files without goog.provides, and their dependencies,
* will always be left in.
*/
public void setManageClosureDependencies(List<String> entryPoints) {
Preconditions.checkNotNull(entryPoints);
setManageClosureDependencies(true);
List<ModuleIdentifier> normalizedEntryPoints = new ArrayList<>();
for (String entryPoint : entryPoints) {
normalizedEntryPoints.add(ModuleIdentifier.forClosure(entryPoint));
}
dependencyOptions.setEntryPoints(normalizedEntryPoints);
}
/**
* Controls how detailed the compilation summary is. Values:
* 0 (never print summary), 1 (print summary only if there are
* errors or warnings), 2 (print summary if type checking is on,
* see --check_types), 3 (always print summary). The default level
* is 1
*/
public void setSummaryDetailLevel(int summaryDetailLevel) {
this.summaryDetailLevel = summaryDetailLevel;
}
/**
* @deprecated replaced by {@link #setExternExports}
*/
@Deprecated
public void enableExternExports(boolean enabled) {
this.externExports = enabled;
}
public void setExtraAnnotationNames(Iterable<String> extraAnnotationNames) {
this.extraAnnotationNames = ImmutableSet.copyOf(extraAnnotationNames);
}
public boolean isExternExportsEnabled() {
return externExports;
}
/**
* Sets the output charset.
*/
public void setOutputCharset(Charset charsetName) {
this.outputCharset = charsetName;
}
/**
* Gets the output charset.
*/
Charset getOutputCharset() {
return outputCharset;
}
/**
* Sets how goog.tweak calls are processed.
*/
public void setTweakProcessing(TweakProcessing tweakProcessing) {
this.tweakProcessing = tweakProcessing;
}
public TweakProcessing getTweakProcessing() {
return tweakProcessing;
}
/**
* Sets ECMAScript version to use.
*/
public void setLanguage(LanguageMode language) {
Preconditions.checkState(language != LanguageMode.NO_TRANSPILE);
this.languageIn = language;
this.languageOut = language;
}
/**
* Sets ECMAScript version to use for the input. If you are not
* transpiling from one version to another, use #setLanguage instead.
*/
public void setLanguageIn(LanguageMode languageIn) {
Preconditions.checkState(languageIn != LanguageMode.NO_TRANSPILE);
this.languageIn = languageIn;
}
public LanguageMode getLanguageIn() {
return languageIn;
}
/**
* Sets ECMAScript version to use for the output. If you are not
* transpiling from one version to another, use #setLanguage instead.
*/
public void setLanguageOut(LanguageMode languageOut) {
this.languageOut = languageOut;
if (languageOut == LanguageMode.ECMASCRIPT3) {
this.quoteKeywordProperties = true;
}
}
public LanguageMode getLanguageOut() {
if (languageOut == LanguageMode.NO_TRANSPILE) {
return languageIn;
}
return languageOut;
}
/**
* Set which set of builtin externs to use.
*/
public void setEnvironment(Environment environment) {
this.environment = environment;
}
public Environment getEnvironment() {
return environment;
}
/**
* @return whether we are currently transpiling from ES6 to a lower version.
*/
boolean lowerFromEs6() {
return languageOut != LanguageMode.NO_TRANSPILE
&& languageIn.isEs6OrHigher()
&& !languageOut.isEs6OrHigher();
}
/**
* @return whether we are currently transpiling to ES6_TYPED
*/
boolean raiseToEs6Typed() {
return languageOut != LanguageMode.NO_TRANSPILE
&& !languageIn.isEs6OrHigher()
&& languageOut == LanguageMode.ECMASCRIPT6_TYPED;
}
public void setAliasTransformationHandler(
AliasTransformationHandler changes) {
this.aliasHandler = changes;
}
public AliasTransformationHandler getAliasTransformationHandler() {
return this.aliasHandler;
}
/**
* Set a custom handler for warnings and errors.
*
* This is mostly used for piping the warnings and errors to
* a file behind the scenes.
*
* If you want to filter warnings and errors, you should use a WarningsGuard.
*
* If you want to change how warnings and errors are reported to the user,
* you should set a ErrorManager on the Compiler. An ErrorManager is
* intended to summarize the errors for a single compile job.
*/
public void setErrorHandler(ErrorHandler handler) {
this.errorHandler = handler;
}
/**
* If true, enables type inference. If checkTypes is enabled, this flag has
* no effect.
*/
public void setInferTypes(boolean enable) {
inferTypes = enable;
}
/**
* Gets the inferTypes flag. Note that if checkTypes is enabled, this flag
* is ignored when configuring the compiler.
*/
public boolean getInferTypes() {
return inferTypes;
}
public boolean getNewTypeInference() {
return this.useNewTypeInference;
}
public void setNewTypeInference(boolean enable) {
this.useNewTypeInference = enable;
}
// Not dead code; used by the open-source users of the compiler.
public void setReportOTIErrorsUnderNTI(boolean enable) {
this.reportOTIErrorsUnderNTI = enable;
}
/**
* @return Whether assumeStrictThis is set.
*/
public boolean assumeStrictThis() {
return assumeStrictThis;
}
/**
* If true, enables enables additional optimizations.
*/
public void setAssumeStrictThis(boolean enable) {
this.assumeStrictThis = enable;
}
/**
* @return Whether assumeClosuresOnlyCaptureReferences is set.
*/
public boolean assumeClosuresOnlyCaptureReferences() {
return assumeClosuresOnlyCaptureReferences;
}
/**
* Whether to assume closures capture only what they reference. This allows
* more aggressive function inlining.
*/
public void setAssumeClosuresOnlyCaptureReferences(boolean enable) {
this.assumeClosuresOnlyCaptureReferences = enable;
}
/**
* Sets the list of properties that we report property invalidation errors
* for.
*/
public void setPropertyInvalidationErrors(
Map<String, CheckLevel> propertyInvalidationErrors) {
this.propertyInvalidationErrors =
ImmutableMap.copyOf(propertyInvalidationErrors);
}
/**
* Configures the compiler for use as an IDE backend. In this mode:
* <ul>
* <li>No optimization passes will run.</li>
* <li>The last time custom passes are invoked is
* {@link CustomPassExecutionTime#BEFORE_OPTIMIZATIONS}</li>
* <li>The compiler will always try to process all inputs fully, even
* if it encounters errors.</li>
* <li>The compiler may record more information than is strictly
* needed for codegen.</li>
* </ul>
*
* @deprecated Some "IDE" clients will need some of these options but not
* others. Consider calling setChecksOnly, setAllowRecompilation, etc,
* explicitly, instead of calling this method which does a variety of
* different things.
*/
@Deprecated
public void setIdeMode(boolean ideMode) {
setChecksOnly(ideMode);
setContinueAfterErrors(ideMode);
setAllowHotswapReplaceScript(ideMode);
setPreserveDetailedSourceInfo(ideMode);
setParseJsDocDocumentation(
ideMode
? Config.JsDocParsing.INCLUDE_DESCRIPTIONS_NO_WHITESPACE
: Config.JsDocParsing.TYPES_ONLY);
}
public void setAllowHotswapReplaceScript(boolean allowRecompilation) {
this.allowHotswapReplaceScript = allowRecompilation;
}
boolean allowsHotswapReplaceScript() {
return allowHotswapReplaceScript;
}
public void setPreserveDetailedSourceInfo(boolean preserveDetailedSourceInfo) {
this.preserveDetailedSourceInfo = preserveDetailedSourceInfo;
}
boolean preservesDetailedSourceInfo() {
return preserveDetailedSourceInfo;
}
public void setContinueAfterErrors(boolean continueAfterErrors) {
this.continueAfterErrors = continueAfterErrors;
}
boolean canContinueAfterErrors() {
return continueAfterErrors;
}
/**
* Enables or disables the parsing of JSDoc documentation, and optionally also
* the preservation of all whitespace and formatting within a JSDoc comment.
* By default, whitespace is collapsed for all comments except {@literal @license} and
* {@literal @preserve} blocks,
*
*/
public void setParseJsDocDocumentation(Config.JsDocParsing parseJsDocDocumentation) {
this.parseJsDocDocumentation = parseJsDocDocumentation;
}
/**
* Checks JSDoc documentation will be parsed.
*
* @return True when JSDoc documentation will be parsed, false if not.
*/
public Config.JsDocParsing isParseJsDocDocumentation() {
return this.parseJsDocDocumentation;
}
/**
* Skip all passes (other than transpilation, if requested). Don't inject any
* runtime libraries (unless explicitly requested) or do any checks/optimizations
* (this is useful for per-file transpilation).
*/
public void setSkipNonTranspilationPasses(boolean skipNonTranspilationPasses) {
this.skipNonTranspilationPasses = skipNonTranspilationPasses;
}
public void setDevMode(DevMode devMode) {
this.devMode = devMode;
}
public void setCheckDeterminism(boolean checkDeterminism) {
this.checkDeterminism = checkDeterminism;
if (checkDeterminism) {
this.useDebugLog = true;
}
}
public boolean getCheckDeterminism() {
return checkDeterminism;
}
public void setMessageBundle(MessageBundle messageBundle) {
this.messageBundle = messageBundle;
}
public void setCheckSymbols(boolean checkSymbols) {
this.checkSymbols = checkSymbols;
}
public void setCheckSuspiciousCode(boolean checkSuspiciousCode) {
this.checkSuspiciousCode = checkSuspiciousCode;
}
public void setCheckTypes(boolean checkTypes) {
this.checkTypes = checkTypes;
}
public void setCheckMissingGetCssNameBlacklist(String blackList) {
this.checkMissingGetCssNameBlacklist = blackList;
}
public void setFoldConstants(boolean foldConstants) {
this.foldConstants = foldConstants;
}
public void setDeadAssignmentElimination(boolean deadAssignmentElimination) {
this.deadAssignmentElimination = deadAssignmentElimination;
}
public void setInlineConstantVars(boolean inlineConstantVars) {
this.inlineConstantVars = inlineConstantVars;
}
public void setInlineFunctions(boolean inlineFunctions) {
this.inlineFunctions = inlineFunctions;
}
public void setInlineLocalFunctions(boolean inlineLocalFunctions) {
this.inlineLocalFunctions = inlineLocalFunctions;
}
public void setCrossModuleCodeMotion(boolean crossModuleCodeMotion) {
this.crossModuleCodeMotion = crossModuleCodeMotion;
}
public void setCrossModuleCodeMotionNoStubMethods(boolean
crossModuleCodeMotionNoStubMethods) {
this.crossModuleCodeMotionNoStubMethods = crossModuleCodeMotionNoStubMethods;
}
public void setParentModuleCanSeeSymbolsDeclaredInChildren(
boolean parentModuleCanSeeSymbolsDeclaredInChildren) {
this.parentModuleCanSeeSymbolsDeclaredInChildren =
parentModuleCanSeeSymbolsDeclaredInChildren;
}
public void setCoalesceVariableNames(boolean coalesceVariableNames) {
this.coalesceVariableNames = coalesceVariableNames;
}
public void setCrossModuleMethodMotion(boolean crossModuleMethodMotion) {
this.crossModuleMethodMotion = crossModuleMethodMotion;
}
public void setInlineVariables(boolean inlineVariables) {
this.inlineVariables = inlineVariables;
}
public void setInlineLocalVariables(boolean inlineLocalVariables) {
this.inlineLocalVariables = inlineLocalVariables;
}
public void setFlowSensitiveInlineVariables(boolean enabled) {
this.flowSensitiveInlineVariables = enabled;
}
public void setSmartNameRemoval(boolean smartNameRemoval) {
this.smartNameRemoval = smartNameRemoval;
}
public void setExtraSmartNameRemoval(boolean smartNameRemoval) {
this.extraSmartNameRemoval = smartNameRemoval;
}
public void setRemoveDeadCode(boolean removeDeadCode) {
this.removeDeadCode = removeDeadCode;
}
public void setExtractPrototypeMemberDeclarations(boolean enabled) {
this.extractPrototypeMemberDeclarations =
enabled ? ExtractPrototypeMemberDeclarationsMode.USE_GLOBAL_TEMP
: ExtractPrototypeMemberDeclarationsMode.OFF;
}
// USE_IIFE is currently unused. Consider removing support for it and
// deleting this setter.
public void setExtractPrototypeMemberDeclarations(ExtractPrototypeMemberDeclarationsMode mode) {
this.extractPrototypeMemberDeclarations = mode;
}
public void setRemoveUnusedPrototypeProperties(boolean enabled) {
this.removeUnusedPrototypeProperties = enabled;
// InlineSimpleMethods makes similar assumptions to
// RemoveUnusedPrototypeProperties, so they are enabled together.
this.inlineGetters = enabled;
}
public void setRemoveUnusedPrototypePropertiesInExterns(boolean enabled) {
this.removeUnusedPrototypePropertiesInExterns = enabled;
}
public void setCollapseVariableDeclarations(boolean enabled) {
this.collapseVariableDeclarations = enabled;
}
public void setCollapseAnonymousFunctions(boolean enabled) {
this.collapseAnonymousFunctions = enabled;
}
public void setAliasableStrings(Set<String> aliasableStrings) {
this.aliasableStrings = aliasableStrings;
}
public void setAliasStringsBlacklist(String aliasStringsBlacklist) {
this.aliasStringsBlacklist = aliasStringsBlacklist;
}
public void setAliasAllStrings(boolean aliasAllStrings) {
this.aliasAllStrings = aliasAllStrings;
}
public void setOutputJsStringUsage(boolean outputJsStringUsage) {
this.outputJsStringUsage = outputJsStringUsage;
}
public void setConvertToDottedProperties(boolean convertToDottedProperties) {
this.convertToDottedProperties = convertToDottedProperties;
}
public void setUseTypesForLocalOptimization(boolean useTypesForLocalOptimization) {
this.useTypesForLocalOptimization = useTypesForLocalOptimization;
}
public void setUseSizeHeuristicToStopOptimizationLoop(boolean mayStopEarly) {
this.useSizeHeuristicToStopOptimizationLoop = mayStopEarly;
}
@Deprecated
public void setUseTypesForOptimization(boolean useTypesForOptimization) {
if (useTypesForOptimization) {
this.disambiguateProperties = useTypesForOptimization;
this.ambiguateProperties = useTypesForOptimization;
this.inlineProperties = useTypesForOptimization;
this.useTypesForLocalOptimization = useTypesForOptimization;
}
}
public void setRewriteFunctionExpressions(boolean rewriteFunctionExpressions) {
this.rewriteFunctionExpressions = rewriteFunctionExpressions;
}
public void setOptimizeParameters(boolean optimizeParameters) {
this.optimizeParameters = optimizeParameters;
}
public void setOptimizeReturns(boolean optimizeReturns) {
this.optimizeReturns = optimizeReturns;
}
public void setOptimizeCalls(boolean optimizeCalls) {
this.optimizeCalls = optimizeCalls;
}
public void setOptimizeArgumentsArray(boolean optimizeArgumentsArray) {
this.optimizeArgumentsArray = optimizeArgumentsArray;
}
public void setVariableRenaming(VariableRenamingPolicy variableRenaming) {
this.variableRenaming = variableRenaming;
}
public void setPropertyRenaming(PropertyRenamingPolicy propertyRenaming) {
this.propertyRenaming = propertyRenaming;
}
public void setLabelRenaming(boolean labelRenaming) {
this.labelRenaming = labelRenaming;
}
public void setReserveRawExports(boolean reserveRawExports) {
this.reserveRawExports = reserveRawExports;
}
public void setPreferStableNames(boolean preferStableNames) {
this.preferStableNames = preferStableNames;
}
public void setGeneratePseudoNames(boolean generatePseudoNames) {
this.generatePseudoNames = generatePseudoNames;
}
public void setRenamePrefix(String renamePrefix) {
this.renamePrefix = renamePrefix;
}
public String getRenamePrefixNamespace() {
return this.renamePrefixNamespace;
}
public void setRenamePrefixNamespace(String renamePrefixNamespace) {
this.renamePrefixNamespace = renamePrefixNamespace;
}
public void setCollapseProperties(boolean collapseProperties) {
this.collapseProperties = collapseProperties;
}
public void setDevirtualizePrototypeMethods(boolean devirtualizePrototypeMethods) {
this.devirtualizePrototypeMethods = devirtualizePrototypeMethods;
}
public void setComputeFunctionSideEffects(boolean computeFunctionSideEffects) {
this.computeFunctionSideEffects = computeFunctionSideEffects;
}
public void setDebugFunctionSideEffectsPath(String debugFunctionSideEffectsPath) {
this.debugFunctionSideEffectsPath = debugFunctionSideEffectsPath;
}
/**
* @return Whether disambiguate private properties is enabled.
*/
public boolean isDisambiguatePrivateProperties() {
return disambiguatePrivateProperties;
}
/**
* @param value Whether to enable private property disambiguation based on
* the coding convention.
*/
public void setDisambiguatePrivateProperties(boolean value) {
this.disambiguatePrivateProperties = value;
}
public void setDisambiguateProperties(boolean disambiguateProperties) {
this.disambiguateProperties = disambiguateProperties;
}
boolean shouldDisambiguateProperties() {
return this.disambiguateProperties;
}
public void setAmbiguateProperties(boolean ambiguateProperties) {
this.ambiguateProperties = ambiguateProperties;
}
boolean shouldAmbiguateProperties() {
return this.ambiguateProperties;
}
public void setAnonymousFunctionNaming(
AnonymousFunctionNamingPolicy anonymousFunctionNaming) {
this.anonymousFunctionNaming = anonymousFunctionNaming;
}
public void setInputAnonymousFunctionNamingMap(VariableMap inputMap) {
this.inputAnonymousFunctionNamingMap = inputMap;
}
public void setInputVariableMap(VariableMap inputVariableMap) {
this.inputVariableMap = inputVariableMap;
}
public void setInputCompilerOptions(Properties inputCompilerOptions) {
this.inputCompilerOptions = inputCompilerOptions;
}
public void setInputPropertyMap(VariableMap inputPropertyMap) {
this.inputPropertyMap = inputPropertyMap;
}
public void setExportTestFunctions(boolean exportTestFunctions) {
this.exportTestFunctions = exportTestFunctions;
}
public void setRuntimeTypeCheck(boolean runtimeTypeCheck) {
this.runtimeTypeCheck = runtimeTypeCheck;
}
public void setRuntimeTypeCheckLogFunction(String runtimeTypeCheckLogFunction) {
this.runtimeTypeCheckLogFunction = runtimeTypeCheckLogFunction;
}
public void setSyntheticBlockStartMarker(String syntheticBlockStartMarker) {
this.syntheticBlockStartMarker = syntheticBlockStartMarker;
}
public void setSyntheticBlockEndMarker(String syntheticBlockEndMarker) {
this.syntheticBlockEndMarker = syntheticBlockEndMarker;
}
public void setLocale(String locale) {
this.locale = locale;
}
public void setMarkAsCompiled(boolean markAsCompiled) {
this.markAsCompiled = markAsCompiled;
}
public void setClosurePass(boolean closurePass) {
this.closurePass = closurePass;
}
public void setPreserveGoogProvidesAndRequires(boolean preserveGoogProvidesAndRequires) {
this.preserveGoogProvidesAndRequires = preserveGoogProvidesAndRequires;
}
public boolean shouldPreservesGoogProvidesAndRequires() {
return this.preserveGoogProvidesAndRequires || this.shouldGenerateTypedExterns();
}
public void setPreserveTypeAnnotations(boolean preserveTypeAnnotations) {
this.preserveTypeAnnotations = preserveTypeAnnotations;
}
public void setGatherCssNames(boolean gatherCssNames) {
this.gatherCssNames = gatherCssNames;
}
public void setStripTypes(Set<String> stripTypes) {
this.stripTypes = stripTypes;
}
public void setStripNameSuffixes(Set<String> stripNameSuffixes) {
this.stripNameSuffixes = stripNameSuffixes;
}
public void setStripNamePrefixes(Set<String> stripNamePrefixes) {
this.stripNamePrefixes = stripNamePrefixes;
}
public void setStripTypePrefixes(Set<String> stripTypePrefixes) {
this.stripTypePrefixes = stripTypePrefixes;
}
public void addCustomPass(CustomPassExecutionTime time, CompilerPass customPass) {
if (customPasses == null) {
customPasses = LinkedHashMultimap.<CustomPassExecutionTime, CompilerPass>create();
}
customPasses.put(time, customPass);
}
public void setMarkNoSideEffectCalls(boolean markNoSideEffectCalls) {
this.markNoSideEffectCalls = markNoSideEffectCalls;
}
public void setDefineReplacements(Map<String, Object> defineReplacements) {
this.defineReplacements = defineReplacements;
}
public void setTweakReplacements(Map<String, Object> tweakReplacements) {
this.tweakReplacements = tweakReplacements;
}
public void setMoveFunctionDeclarations(boolean moveFunctionDeclarations) {
this.moveFunctionDeclarations = moveFunctionDeclarations;
}
public void setInstrumentationTemplate(Instrumentation instrumentationTemplate) {
this.instrumentationTemplate = instrumentationTemplate;
}
public void setInstrumentationTemplateFile(String filename){
this.instrumentationTemplateFile = filename;
}
public void setRecordFunctionInformation(boolean recordFunctionInformation) {
this.recordFunctionInformation = recordFunctionInformation;
}
public void setCssRenamingMap(CssRenamingMap cssRenamingMap) {
this.cssRenamingMap = cssRenamingMap;
}
public void setCssRenamingWhitelist(Set<String> whitelist) {
this.cssRenamingWhitelist = whitelist;
}
public void setReplaceStringsFunctionDescriptions(
List<String> replaceStringsFunctionDescriptions) {
this.replaceStringsFunctionDescriptions =
replaceStringsFunctionDescriptions;
}
public void setReplaceStringsPlaceholderToken(
String replaceStringsPlaceholderToken) {
this.replaceStringsPlaceholderToken =
replaceStringsPlaceholderToken;
}
public void setReplaceStringsReservedStrings(
Set<String> replaceStringsReservedStrings) {
this.replaceStringsReservedStrings =
replaceStringsReservedStrings;
}
public void setReplaceStringsInputMap(VariableMap serializedMap) {
this.replaceStringsInputMap = serializedMap;
}
public void setPrettyPrint(boolean prettyPrint) {
this.prettyPrint = prettyPrint;
}
public boolean isPrettyPrint() {
return this.prettyPrint;
}
public void setLineBreak(boolean lineBreak) {
this.lineBreak = lineBreak;
}
public boolean getPreferLineBreakAtEndOfFile() {
return this.preferLineBreakAtEndOfFile;
}
public void setPreferLineBreakAtEndOfFile(boolean lineBreakAtEnd) {
this.preferLineBreakAtEndOfFile = lineBreakAtEnd;
}
public void setPrintInputDelimiter(boolean printInputDelimiter) {
this.printInputDelimiter = printInputDelimiter;
}
public void setInputDelimiter(String inputDelimiter) {
this.inputDelimiter = inputDelimiter;
}
public void setQuoteKeywordProperties(boolean quoteKeywordProperties) {
this.quoteKeywordProperties = quoteKeywordProperties;
}
public void setErrorFormat(ErrorFormat errorFormat) {
this.errorFormat = errorFormat;
}
public ErrorFormat getErrorFormat() {
return this.errorFormat;
}
public void setWarningsGuard(ComposeWarningsGuard warningsGuard) {
this.warningsGuard = warningsGuard;
}
public void setLineLengthThreshold(int lineLengthThreshold) {
this.lineLengthThreshold = lineLengthThreshold;
}
public int getLineLengthThreshold() {
return this.lineLengthThreshold;
}
public void setUseOriginalNamesInOutput(boolean useOriginalNamesInOutput) {
this.useOriginalNamesInOutput = useOriginalNamesInOutput;
}
public boolean getUseOriginalNamesInOutput() {
return this.useOriginalNamesInOutput;
}
public void setExternExports(boolean externExports) {
this.externExports = externExports;
}
public void setExternExportsPath(String externExportsPath) {
this.externExportsPath = externExportsPath;
}
public void setSourceMapOutputPath(String sourceMapOutputPath) {
this.sourceMapOutputPath = sourceMapOutputPath;
}
public void setApplyInputSourceMaps(boolean applyInputSourceMaps) {
this.applyInputSourceMaps = applyInputSourceMaps;
}
public void setSourceMapIncludeSourcesContent(boolean sourceMapIncludeSourcesContent) {
this.sourceMapIncludeSourcesContent = sourceMapIncludeSourcesContent;
}
public void setSourceMapDetailLevel(SourceMap.DetailLevel sourceMapDetailLevel) {
this.sourceMapDetailLevel = sourceMapDetailLevel;
}
public void setSourceMapFormat(SourceMap.Format sourceMapFormat) {
this.sourceMapFormat = sourceMapFormat;
}
public void setSourceMapLocationMappings(
List<SourceMap.LocationMapping> sourceMapLocationMappings) {
this.sourceMapLocationMappings = sourceMapLocationMappings;
}
/**
* Activates transformation of AMD to CommonJS modules.
*/
public void setTransformAMDToCJSModules(boolean transformAMDToCJSModules) {
this.transformAMDToCJSModules = transformAMDToCJSModules;
}
/**
* Rewrites CommonJS modules so that modules can be concatenated together,
* by renaming all globals to avoid conflicting with other modules.
*/
public void setProcessCommonJSModules(boolean processCommonJSModules) {
this.processCommonJSModules = processCommonJSModules;
}
/**
* Sets a path prefix for CommonJS modules (maps to {@link #setModuleRoots(List)}).
*/
public void setCommonJSModulePathPrefix(String commonJSModulePathPrefix) {
setModuleRoots(ImmutableList.of(commonJSModulePathPrefix));
}
/**
* Sets the module roots.
*/
public void setModuleRoots(List<String> moduleRoots) {
this.moduleRoots = moduleRoots;
}
/**
* Sets whether to rewrite polyfills.
*/
public void setRewritePolyfills(boolean rewritePolyfills) {
this.rewritePolyfills = rewritePolyfills;
}
public boolean getRewritePolyfills() {
return this.rewritePolyfills;
}
/**
* Sets list of libraries to always inject, even if not needed.
*/
public void setForceLibraryInjection(Iterable<String> libraries) {
this.forceLibraryInjection = ImmutableList.copyOf(libraries);
}
/**
* Sets the set of libraries to never inject, even if required.
*/
public void setPreventLibraryInjection(boolean preventLibraryInjection) {
this.preventLibraryInjection = preventLibraryInjection;
}
/**
* Set whether or not code should be modified to provide coverage
* information.
*/
public void setInstrumentForCoverage(boolean instrumentForCoverage) {
this.instrumentForCoverage = instrumentForCoverage;
}
/** Set whether to instrument to collect branch coverage */
public void setInstrumentBranchCoverage(boolean instrumentBranchCoverage) {
if (instrumentForCoverage || !instrumentBranchCoverage) {
this.instrumentBranchCoverage = instrumentBranchCoverage;
} else {
throw new RuntimeException("The option instrumentForCoverage must be set to true for "
+ "instrumentBranchCoverage to be set to true.");
}
}
public List<ConformanceConfig> getConformanceConfigs() {
return conformanceConfigs;
}
/**
* Both enable and configure conformance checks, if non-null.
*/
@GwtIncompatible("Conformance")
public void setConformanceConfig(ConformanceConfig conformanceConfig) {
this.conformanceConfigs = ImmutableList.of(conformanceConfig);
}
/**
* Both enable and configure conformance checks, if non-null.
*/
@GwtIncompatible("Conformance")
public void setConformanceConfigs(List<ConformanceConfig> configs) {
this.conformanceConfigs = ImmutableList.copyOf(configs);
}
public boolean isEmitUseStrict() {
return emitUseStrict;
}
public CompilerOptions setEmitUseStrict(boolean emitUseStrict) {
this.emitUseStrict = emitUseStrict;
return this;
}
public ModuleLoader.ResolutionMode getModuleResolutionMode() {
return this.moduleResolutionMode;
}
public void setModuleResolutionMode(ModuleLoader.ResolutionMode mode) {
this.moduleResolutionMode = mode;
}
/** Serializes compiler options to a stream. */
@GwtIncompatible("ObjectOutputStream")
public void serialize(OutputStream objectOutputStream) throws IOException {
new java.io.ObjectOutputStream(objectOutputStream).writeObject(this);
}
/** Deserializes compiler options from a stream. */
@GwtIncompatible("ObjectInputStream")
public static CompilerOptions deserialize(InputStream objectInputStream)
throws IOException, ClassNotFoundException {
return (CompilerOptions) new java.io.ObjectInputStream(objectInputStream).readObject();
}
@Override
public String toString() {
String strValue =
MoreObjects.toStringHelper(this)
.omitNullValues()
.add("aggressiveFusion", aggressiveFusion)
.add("aliasableStrings", aliasableStrings)
.add("aliasAllStrings", aliasAllStrings)
.add("aliasHandler", getAliasTransformationHandler())
.add("aliasStringsBlacklist", aliasStringsBlacklist)
.add("allowHotswapReplaceScript", allowsHotswapReplaceScript())
.add("ambiguateProperties", ambiguateProperties)
.add("angularPass", angularPass)
.add("anonymousFunctionNaming", anonymousFunctionNaming)
.add("appNameStr", appNameStr)
.add("assumeClosuresOnlyCaptureReferences", assumeClosuresOnlyCaptureReferences)
.add("assumeStrictThis", assumeStrictThis())
.add("brokenClosureRequiresLevel", brokenClosureRequiresLevel)
.add("chainCalls", chainCalls)
.add("checkDeterminism", getCheckDeterminism())
.add("checkEventfulObjectDisposalPolicy", checkEventfulObjectDisposalPolicy)
.add("checkGlobalNamesLevel", checkGlobalNamesLevel)
.add("checkGlobalThisLevel", checkGlobalThisLevel)
.add("checkMissingGetCssNameBlacklist", checkMissingGetCssNameBlacklist)
.add("checkMissingGetCssNameLevel", checkMissingGetCssNameLevel)
.add("checksOnly", checksOnly)
.add("checkSuspiciousCode", checkSuspiciousCode)
.add("checkSymbols", checkSymbols)
.add("checkTypes", checkTypes)
.add("closurePass", closurePass)
.add("coalesceVariableNames", coalesceVariableNames)
.add("codingConvention", getCodingConvention())
.add("collapseAnonymousFunctions", collapseAnonymousFunctions)
.add("collapseObjectLiterals", collapseObjectLiterals)
.add("collapseProperties", collapseProperties)
.add("collapseVariableDeclarations", collapseVariableDeclarations)
.add("colorizeErrorOutput", shouldColorizeErrorOutput())
.add("computeFunctionSideEffects", computeFunctionSideEffects)
.add("conformanceConfigs", getConformanceConfigs())
.add("continueAfterErrors", canContinueAfterErrors())
.add("convertToDottedProperties", convertToDottedProperties)
.add("crossModuleCodeMotion", crossModuleCodeMotion)
.add("crossModuleCodeMotionNoStubMethods", crossModuleCodeMotionNoStubMethods)
.add("crossModuleMethodMotion", crossModuleMethodMotion)
.add("cssRenamingMap", cssRenamingMap)
.add("cssRenamingWhitelist", cssRenamingWhitelist)
.add("customPasses", customPasses)
.add("dartPass", dartPass)
.add("deadAssignmentElimination", deadAssignmentElimination)
.add("debugFunctionSideEffectsPath", debugFunctionSideEffectsPath)
.add("declaredGlobalExternsOnWindow", declaredGlobalExternsOnWindow)
.add("defineReplacements", getDefineReplacements())
.add("dependencyOptions", dependencyOptions)
.add("devirtualizePrototypeMethods", devirtualizePrototypeMethods)
.add("devMode", devMode)
.add("disambiguatePrivateProperties", disambiguatePrivateProperties)
.add("disambiguateProperties", disambiguateProperties)
.add("enforceAccessControlCodingConventions", enforceAccessControlCodingConventions)
.add("environment", getEnvironment())
.add("errorFormat", errorFormat)
.add("errorHandler", errorHandler)
.add("exportLocalPropertyDefinitions", exportLocalPropertyDefinitions)
.add("exportTestFunctions", exportTestFunctions)
.add("externExports", isExternExportsEnabled())
.add("externExportsPath", externExportsPath)
.add("extraAnnotationNames", extraAnnotationNames)
.add("extractPrototypeMemberDeclarations", extractPrototypeMemberDeclarations)
.add("extraSmartNameRemoval", extraSmartNameRemoval)
.add("flowSensitiveInlineVariables", flowSensitiveInlineVariables)
.add("foldConstants", foldConstants)
.add("forceLibraryInjection", forceLibraryInjection)
.add("gatherCssNames", gatherCssNames)
.add("generateExportsAfterTypeChecking", generateExportsAfterTypeChecking)
.add("generateExports", generateExports)
.add("generatePseudoNames", generatePseudoNames)
.add("generateTypedExterns", shouldGenerateTypedExterns())
.add("idGenerators", idGenerators)
.add("idGeneratorsMapSerialized", idGeneratorsMapSerialized)
.add("inferConsts", inferConsts)
.add("inferTypes", inferTypes)
.add("inlineConstantVars", inlineConstantVars)
.add("inlineFunctions", inlineFunctions)
.add("inlineGetters", inlineGetters)
.add("inlineLocalFunctions", inlineLocalFunctions)
.add("inlineLocalVariables", inlineLocalVariables)
.add("inlineProperties", inlineProperties)
.add("inlineVariables", inlineVariables)
.add("inputAnonymousFunctionNamingMap", inputAnonymousFunctionNamingMap)
.add("inputDelimiter", inputDelimiter)
.add("inputPropertyMap", inputPropertyMap)
.add("inputSourceMaps", inputSourceMaps)
.add("inputVariableMap", inputVariableMap)
.add("instrumentationTemplateFile", instrumentationTemplateFile)
.add("instrumentationTemplate", instrumentationTemplate)
.add("instrumentForCoverage", instrumentForCoverage)
.add("instrumentBranchCoverage", instrumentBranchCoverage)
.add("j2clPassMode", j2clPassMode)
.add("labelRenaming", labelRenaming)
.add("languageIn", getLanguageIn())
.add("languageOut", getLanguageOut())
.add("legacyCodeCompile", legacyCodeCompile)
.add("lineBreak", lineBreak)
.add("lineLengthThreshold", lineLengthThreshold)
.add("locale", locale)
.add("markAsCompiled", markAsCompiled)
.add("markNoSideEffectCalls", markNoSideEffectCalls)
.add("maxFunctionSizeAfterInlining", maxFunctionSizeAfterInlining)
.add("messageBundle", messageBundle)
.add("moduleRoots", moduleRoots)
.add("moveFunctionDeclarations", moveFunctionDeclarations)
.add("nameGenerator", nameGenerator)
.add("optimizeArgumentsArray", optimizeArgumentsArray)
.add("optimizeCalls", optimizeCalls)
.add("optimizeParameters", optimizeParameters)
.add("optimizeReturns", optimizeReturns)
.add("outputCharset", outputCharset)
.add("outputJs", outputJs)
.add("outputJsStringUsage", outputJsStringUsage)
.add(
"parentModuleCanSeeSymbolsDeclaredInChildren",
parentModuleCanSeeSymbolsDeclaredInChildren)
.add("parseJsDocDocumentation", isParseJsDocDocumentation())
.add("polymerVersion", polymerVersion)
.add("preferLineBreakAtEndOfFile", preferLineBreakAtEndOfFile)
.add("preferSingleQuotes", preferSingleQuotes)
.add("preferStableNames", preferStableNames)
.add("preserveDetailedSourceInfo", preservesDetailedSourceInfo())
.add("preserveGoogProvidesAndRequires", preserveGoogProvidesAndRequires)
.add("preserveTypeAnnotations", preserveTypeAnnotations)
.add("prettyPrint", prettyPrint)
.add("preventLibraryInjection", preventLibraryInjection)
.add("printConfig", printConfig)
.add("printInputDelimiter", printInputDelimiter)
.add("printSourceAfterEachPass", printSourceAfterEachPass)
.add("processCommonJSModules", processCommonJSModules)
.add("processObjectPropertyString", processObjectPropertyString)
.add("propertyInvalidationErrors", propertyInvalidationErrors)
.add("propertyRenaming", propertyRenaming)
.add("protectHiddenSideEffects", protectHiddenSideEffects)
.add("quoteKeywordProperties", quoteKeywordProperties)
.add("recordFunctionInformation", recordFunctionInformation)
.add("removeAbstractMethods", removeAbstractMethods)
.add("removeSuperMethods", removeSuperMethods)
.add("removeClosureAsserts", removeClosureAsserts)
.add("removeDeadCode", removeDeadCode)
.add("removeUnusedClassProperties", removeUnusedClassProperties)
.add("removeUnusedConstructorProperties", removeUnusedConstructorProperties)
.add("removeUnusedLocalVars", removeUnusedLocalVars)
.add(
"removeUnusedPrototypePropertiesInExterns",
removeUnusedPrototypePropertiesInExterns)
.add("removeUnusedPrototypeProperties", removeUnusedPrototypeProperties)
.add("removeUnusedVars", removeUnusedVars)
.add(
"renamePrefixNamespaceAssumeCrossModuleNames",
renamePrefixNamespaceAssumeCrossModuleNames)
.add("renamePrefixNamespace", renamePrefixNamespace)
.add("renamePrefix", renamePrefix)
.add("replaceIdGenerators", replaceIdGenerators)
.add("replaceMessagesWithChromeI18n", replaceMessagesWithChromeI18n)
.add("replaceStringsFunctionDescriptions", replaceStringsFunctionDescriptions)
.add("replaceStringsInputMap", replaceStringsInputMap)
.add("replaceStringsPlaceholderToken", replaceStringsPlaceholderToken)
.add("replaceStringsReservedStrings", replaceStringsReservedStrings)
.add("reportOTIErrorsUnderNTI", reportOTIErrorsUnderNTI)
.add("reportPath", reportPath)
.add("reserveRawExports", reserveRawExports)
.add("rewriteFunctionExpressions", rewriteFunctionExpressions)
.add("rewritePolyfills", rewritePolyfills)
.add("runtimeTypeCheckLogFunction", runtimeTypeCheckLogFunction)
.add("runtimeTypeCheck", runtimeTypeCheck)
.add("shadowVariables", shadowVariables)
.add("skipNonTranspilationPasses", skipNonTranspilationPasses)
.add("skipTranspilationAndCrash", skipTranspilationAndCrash)
.add("smartNameRemoval", smartNameRemoval)
.add("sourceMapDetailLevel", sourceMapDetailLevel)
.add("sourceMapFormat", sourceMapFormat)
.add("sourceMapLocationMappings", sourceMapLocationMappings)
.add("sourceMapOutputPath", sourceMapOutputPath)
.add("stripNamePrefixes", stripNamePrefixes)
.add("stripNameSuffixes", stripNameSuffixes)
.add("stripTypePrefixes", stripTypePrefixes)
.add("stripTypes", stripTypes)
.add("summaryDetailLevel", summaryDetailLevel)
.add("syntheticBlockEndMarker", syntheticBlockEndMarker)
.add("syntheticBlockStartMarker", syntheticBlockStartMarker)
.add("tcProjectId", tcProjectId)
.add("tracer", tracer)
.add("transformAMDToCJSModules", transformAMDToCJSModules)
.add("trustedStrings", trustedStrings)
.add("tweakProcessing", getTweakProcessing())
.add("tweakReplacements", getTweakReplacements())
.add("useDebugLog", useDebugLog)
.add("useNewTypeInference", getNewTypeInference())
.add("emitUseStrict", emitUseStrict)
.add("useTypesForLocalOptimization", useTypesForLocalOptimization)
.add("variableRenaming", variableRenaming)
.add("warningsGuard", getWarningsGuard())
.add("wrapGoogModulesForWhitespaceOnly", wrapGoogModulesForWhitespaceOnly)
.toString();
return strValue;
}
//////////////////////////////////////////////////////////////////////////////
// Enums
/**
* A language mode applies to the whole compilation job.
* As a result, the compiler does not support mixed strict and non-strict in
* the same compilation job. Therefore, the 'use strict' directive is ignored
* when the language mode is not strict.
*/
public static enum LanguageMode {
/**
* 90's JavaScript
*/
ECMASCRIPT3,
/**
* Traditional JavaScript
*/
ECMASCRIPT5,
/**
* Nitpicky, traditional JavaScript
*/
ECMASCRIPT5_STRICT,
/**
* Shiny new JavaScript
* @deprecated Use ECMASCRIPT_2015 with {@code isStrictModeInput == false}.
*/
@Deprecated
ECMASCRIPT6,
/**
* Nitpicky, shiny new JavaScript
* @deprecated Use ECMASCRIPT_2015 with {@code isStrictModeInput == true}.
*/
@Deprecated
ECMASCRIPT6_STRICT,
/** ECMAScript standard approved in 2015. */
ECMASCRIPT_2015,
/**
* A superset of ES6 which adds Typescript-style type declarations. Always strict.
*/
ECMASCRIPT6_TYPED,
/**
* @deprecated Use ECMASCRIPT_2016.
*/
@Deprecated
ECMASCRIPT7,
/**
* ECMAScript standard approved in 2016.
* Adds the exponent operator (**).
*/
ECMASCRIPT_2016,
/** @deprecated Use {@code ECMASCRIPT_NEXT} */
@Deprecated
ECMASCRIPT8,
/**
* ECMAScript latest draft standard.
*/
ECMASCRIPT_NEXT,
/**
* For languageOut only. The same language mode as the input.
*/
NO_TRANSPILE;
/** Whether this is ECMAScript 5 or higher. */
public boolean isEs5OrHigher() {
Preconditions.checkState(this != NO_TRANSPILE);
return this != LanguageMode.ECMASCRIPT3;
}
/** Whether this is ECMAScript 6 or higher. */
public boolean isEs6OrHigher() {
Preconditions.checkState(this != NO_TRANSPILE);
switch (this) {
case ECMASCRIPT3:
case ECMASCRIPT5:
case ECMASCRIPT5_STRICT:
return false;
default:
return true;
}
}
public static LanguageMode fromString(String value) {
if (value == null) {
return null;
}
// Trim spaces, disregard case, and allow abbreviation of ECMASCRIPT for convenience.
String canonicalizedName = Ascii.toUpperCase(value.trim()).replaceFirst("^ES", "ECMASCRIPT");
try {
return LanguageMode.valueOf(canonicalizedName);
} catch (IllegalArgumentException e) {
return null; // unknown name.
}
}
}
/** When to do the extra sanity checks */
static enum DevMode {
/**
* Don't do any extra sanity checks.
*/
OFF,
/**
* After the initial parse
*/
START,
/**
* At the start and at the end of all optimizations.
*/
START_AND_END,
/**
* After every pass
*/
EVERY_PASS
}
/** How much tracing we want to do */
public static enum TracerMode {
ALL, // Collect all timing and size metrics. Very slow.
RAW_SIZE, // Collect all timing and size metrics, except gzipped size. Slow.
AST_SIZE, // For size data, don't serialize the AST, just count the number of nodes.
TIMING_ONLY, // Collect timing metrics only.
OFF; // Collect no timing and size metrics.
boolean isOn() {
return this != OFF;
}
}
/** Option for the ProcessTweaks pass */
public static enum TweakProcessing {
OFF, // Do not run the ProcessTweaks pass.
CHECK, // Run the pass, but do not strip out the calls.
STRIP; // Strip out all calls to goog.tweak.*.
public boolean isOn() {
return this != OFF;
}
public boolean shouldStrip() {
return this == STRIP;
}
}
/** What kind of isolation is going to be used */
public static enum IsolationMode {
NONE, // output does not include additional isolation.
IIFE; // The output should be wrapped in an IIFE to isolate global variables.
}
/**
* A Role Specific Interface for JS Compiler that represents a data holder
* object which is used to store goog.scope alias code changes to code made
* during a compile. There is no guarantee that individual alias changes are
* invoked in the order they occur during compilation, so implementations
* should not assume any relevance to the order changes arrive.
* <p>
* Calls to the mutators are expected to resolve very quickly, so
* implementations should not perform expensive operations in the mutator
* methods.
*
* @author [email protected] (Tyler Goodwin)
*/
public interface AliasTransformationHandler {
/**
* Builds an AliasTransformation implementation and returns it to the
* caller.
* <p>
* Callers are allowed to request multiple AliasTransformation instances for
* the same file, though it is expected that the first and last char values
* for multiple instances will not overlap.
* <p>
* This method is expected to have a side-effect of storing off the created
* AliasTransformation, which guarantees that invokers of this interface
* cannot leak AliasTransformation to this implementation that the
* implementor did not create
*
* @param sourceFile the source file the aliases re contained in.
* @param position the region of the source file associated with the
* goog.scope call. The item of the SourcePosition is the returned
* AliasTransformation
*/
public AliasTransformation logAliasTransformation(
String sourceFile, SourcePosition<AliasTransformation> position);
}
/**
* A Role Specific Interface for the JS Compiler to report aliases used to
* change the code during a compile.
* <p>
* While aliases defined by goog.scope are expected to by only 1 per file, and
* the only top-level structure in the file, this is not enforced.
*/
public interface AliasTransformation {
/**
* Adds an alias definition to the AliasTransformation instance.
* <p>
* Last definition for a given alias is kept if an alias is inserted
* multiple times (since this is generally the behavior in JavaScript code).
*
* @param alias the name of the alias.
* @param definition the definition of the alias.
*/
void addAlias(String alias, String definition);
}
/**
* A Null implementation of the CodeChanges interface which performs all
* operations as a No-Op
*/
static final AliasTransformationHandler NULL_ALIAS_TRANSFORMATION_HANDLER =
new NullAliasTransformationHandler();
private static class NullAliasTransformationHandler implements AliasTransformationHandler {
private static final AliasTransformation NULL_ALIAS_TRANSFORMATION =
new NullAliasTransformation();
@Override
public AliasTransformation logAliasTransformation(
String sourceFile, SourcePosition<AliasTransformation> position) {
position.setItem(NULL_ALIAS_TRANSFORMATION);
return NULL_ALIAS_TRANSFORMATION;
}
private static class NullAliasTransformation implements AliasTransformation {
@Override
public void addAlias(String alias, String definition) {
}
}
}
/**
* An environment specifies the built-in externs that are loaded for a given
* compilation.
*/
public static enum Environment {
/**
* Hand crafted externs that have traditionally been the default externs.
*/
BROWSER,
/**
* Only language externs are loaded.
*/
CUSTOM
}
/**
* Whether standard input or standard output should be an array of
* JSON encoded files
*/
static enum JsonStreamMode {
/**
* stdin/out are both single files.
*/
NONE,
/**
* stdin is a json stream.
*/
IN,
/**
* stdout is a json stream.
*/
OUT,
/**
* stdin and stdout are both json streams.
*/
BOTH
}
/** How compiler should prune files based on the provide-require dependency graph */
public static enum DependencyMode {
/**
* All files will be included in the compilation
*/
NONE,
/**
* Files must be discoverable from specified entry points. Files
* which do not goog.provide a namespace and and are not either
* an ES6 or CommonJS module will be automatically treated as entry points.
* Module files will be included only if referenced from an entry point.
*/
LOOSE,
/**
* Files must be discoverable from specified entry points. Files which
* do not goog.provide a namespace and are neither
* an ES6 or CommonJS module will be dropped. Module files will be included
* only if referenced from an entry point.
*/
STRICT
}
/**
* A mode enum used to indicate whether J2clPass should be enabled, disabled, or enabled
* automatically if there is any J2cl source file (i.e. in the AUTO mode).
*/
public static enum J2clPassMode {
/** J2clPass is disabled. */
FALSE,
/** J2clPass is enabled. */
TRUE,
/** J2clPass is disabled. */
OFF,
/** J2clPass is enabled. */
ON,
/** It auto-detects whether there are J2cl generated file. If yes, execute J2clPass. */
AUTO;
boolean shouldAddJ2clPasses() {
return this == TRUE || this == ON || this == AUTO;
}
boolean isExplicitlyOn() {
return this == TRUE || this == ON;
}
}
public boolean isStrictModeInput() {
return isStrictModeInput;
}
public CompilerOptions setStrictModeInput(boolean isStrictModeInput) {
this.isStrictModeInput = isStrictModeInput;
return this;
}
public char[] getPropertyReservedNamingFirstChars() {
char[] reservedChars = anonymousFunctionNaming.getReservedCharacters();
if (polymerVersion != null && polymerVersion > 1) {
if (reservedChars == null) {
reservedChars = POLYMER_PROPERTY_RESERVED_FIRST_CHARS;
} else {
reservedChars = Chars.concat(reservedChars, POLYMER_PROPERTY_RESERVED_FIRST_CHARS);
}
} else if (angularPass) {
if (reservedChars == null) {
reservedChars = ANGULAR_PROPERTY_RESERVED_FIRST_CHARS;
} else {
reservedChars = Chars.concat(reservedChars, ANGULAR_PROPERTY_RESERVED_FIRST_CHARS);
}
}
return reservedChars;
}
public char[] getPropertyReservedNamingNonFirstChars() {
char[] reservedChars = anonymousFunctionNaming.getReservedCharacters();
if (polymerVersion != null && polymerVersion > 1) {
if (reservedChars == null) {
reservedChars = POLYMER_PROPERTY_RESERVED_NON_FIRST_CHARS;
} else {
reservedChars = Chars.concat(reservedChars, POLYMER_PROPERTY_RESERVED_NON_FIRST_CHARS);
}
}
return reservedChars;
}
}
| fix merge mistake: double-defined method
| src/com/google/javascript/jscomp/CompilerOptions.java | fix merge mistake: double-defined method | <ide><path>rc/com/google/javascript/jscomp/CompilerOptions.java
<ide> public void setInputSourceMaps(final ImmutableMap<String, SourceMapInput> inputSourceMaps) {
<ide> this.inputSourceMaps = inputSourceMaps;
<ide> }
<del>
<del> /**
<del> * Sets the input sourcemap files, indexed by the JS files they refer to.
<del> *
<del> * @param inputSourceMaps the collection of input sourcemap files
<del> */
<del> public void setInputSourceMaps(final ImmutableMap<String, SourceMapInput> inputSourceMaps) {
<del> this.inputSourceMaps = inputSourceMaps;
<del> }
<ide>
<ide> /**
<ide> * Whether to infer consts. This should not be configurable by |
|
JavaScript | mit | e5d84d62cde9eee88d0e358d494eaf280d6e42de | 0 | reuteras/RT-keyboard-shortcuts | /*
* RT Keyboard Shortcuts is an extension for RT from bestpractical.org.
* The extension is an adaptation by Peter Reuterås of Acunote Shortcuts
* from Acunote. A very good tool that was extremly easy to adopt for
* this purpose!
*
* Adds keyboard navigation for:
* ticket.sys.kth.se
* rt.reuteras.com
* rt.cpan.org
*
* Add your own installation to the @include section below and in the
* SupportedSites section. Search for the string CHANGEME and change to
* values suitable for your environment.
*
* Original message from Acunote:
*
* Acunote Shortcuts.
*
* Acunote Shortcuts is a greasemonkey script based on
* Javascript Keyboard Shortcuts library extracted from Acunote
* http://www.acunote.com/open-source/javascript-keyboard-shortcuts
*
* Shortcuts Library Copyright (c) 2007-2008 Pluron, Inc.
* Reddit, Digg and YCNews Scripts Copyright (c) 2008 Pluron, Inc.
* Other scripts are copyright of their respective authors.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*jslint browser:true */
// --------------------------------------------------------------------
//
// ==UserScript==
// @name RT Keyboard Shortcuts
// @description Adds keyboard shortcuts to RT.
// @include https://ticket.sys.kth.se/*
// @include https://rt.reuteras.com/*
// @include https://rt.cpan.org/*
// @grant none
// @downloadURL https://github.com/reuteras/RT-keyboard-shortcuts/raw/master/rtkeyboardshortcuts.user.js
// @updateURL https://github.com/reuteras/RT-keyboard-shortcuts/raw/master/rtkeyboardshortcuts.meta.js
// @version 0.1.1
// ==/UserScript==
// CHANGEME
/*
* ===========================================================
* Acunote Shortcuts: The Library
* Copyright (c) 2007-2008 Pluron, Inc.
* ===========================================================
*/
function ShortcutsSource() {
var myVersion = "Version of RT keyboard shourtcuts is 0.1.1", shortcutListener = {
listen: true,
shortcut: null,
combination: '',
lastKeypress: 0,
clearTimeout: 2000,
// Keys we don't listen to
keys: {
KEY_BACKSPACE: 8,
KEY_TAB: 9,
KEY_ENTER: 13,
KEY_SHIFT: 16,
KEY_CTRL: 17,
KEY_ALT: 18,
KEY_ESC: 27,
KEY_SPACE: 32,
KEY_LEFT: 37,
KEY_UP: 38,
KEY_RIGHT: 39,
KEY_DOWN: 40,
KEY_DELETE: 46,
KEY_HOME: 36,
KEY_END: 35,
KEY_PAGEUP: 33,
KEY_PAGEDOWN: 34
},
init: function() {
if (!window.SHORTCUTS) { return false; }
this.createStatusArea();
this.setObserver();
},
isInputTarget: function(e) {
var targetNodeName, target;
target = e.target || e.srcElement;
if (target && target.nodeName) {
targetNodeName = target.nodeName.toLowerCase();
if (targetNodeName === "textarea" || targetNodeName === "select" ||
(targetNodeName === "input" && target.type &&
(target.type.toLowerCase() === "text" ||
target.type.toLowerCase() === "password"))
) {
return true;
}
}
return false;
},
stopEvent: function(event) {
if (event.preventDefault) {
event.preventDefault();
event.stopPropagation();
} else {
event.returnValue = false;
event.cancelBubble = true;
}
},
// shortcut notification/status area
createStatusArea: function() {
var area = document.createElement('div');
area.setAttribute('id', 'shortcut_status');
area.style.display = 'none';
document.body.appendChild(area);
},
showStatus: function() {
document.getElementById('shortcut_status').style.display = '';
},
hideStatus: function() {
document.getElementById('shortcut_status').style.display = 'none';
},
showCombination: function() {
var bar = document.getElementById('shortcut_status');
bar.innerHTML = this.combination;
this.showStatus();
},
// This method creates event observer for the whole document
// This is the common way of setting event observer that works
// in all modern brwosers with "keypress" fix for
// Konqueror/Safari/KHTML borrowed from Prototype.js
setObserver: function() {
var name = 'keypress';
if (navigator.appVersion.match(/Konqueror|Safari|KHTML/) || document.detachEvent) {
name = 'keydown';
}
if (document.addEventListener) {
document.addEventListener(name, function(e) {shortcutListener.keyCollector(e); }, false);
} else if (document.attachEvent) {
document.attachEvent('on' + name, function(e) {shortcutListener.keyCollector(e); });
}
},
// Key press collector. Collects all keypresses into combination
// and checks it we have action for it
keyCollector: function(e) {
var key;
// do not listen if no shortcuts defined
if (!window.SHORTCUTS) { return false; }
// do not listen if listener was explicitly turned off
if (!shortcutListener.listen) { return false; }
// leave modifiers for browser
if (e.altKey || e.ctrlKey || e.metaKey) { return false; }
var keyCode = e.keyCode;
// do not listen for Ctrl, Alt, Tab, Space, Esc and others
for (key in this.keys) {
if (e.keyCode === this.keys[key]) { return false; }
}
// do not listen for functional keys
if (navigator.userAgent.match(/Gecko/)) {
if (e.keyCode >= 112 && e.keyCode <=123) { return false; }
}
// do not listen in input/select/textarea fields
if (this.isInputTarget(e)) { return false; }
// get letter pressed for different browsers
var code = e.which ? e.which : e.keyCode;
var letter = String.fromCharCode(code).toLowerCase();
if (e.shiftKey) { letter = letter.toUpperCase(); }
// IE hack to support "?"
if (window.ie && (code === 191) && e.shiftKey) {
letter = '?';
}
if (shortcutListener.process(letter)) { shortcutListener.stopEvent(e); }
},
// process keys
process: function(letter) {
if (!window.SHORTCUTS) { return false; }
if (!shortcutListener.listen) { return false; }
// if no combination then start from the begining
if (!shortcutListener.shortcut) { shortcutListener.shortcut = SHORTCUTS; }
// if unknown letter then say goodbye
if (!shortcutListener.shortcut[letter]) { return false; }
if (typeof(shortcutListener.shortcut[letter]) === "function") {
shortcutListener.shortcut[letter]();
shortcutListener.clearCombination();
} else {
shortcutListener.shortcut = shortcutListener.shortcut[letter];
// append combination
shortcutListener.combination = shortcutListener.combination + letter;
if (shortcutListener.combination.length > 0) {
shortcutListener.showCombination();
// save last keypress timestamp (for autoclear)
var d = new Date();
shortcutListener.lastKeypress = d.getTime();
// autoclear combination in 2 seconds
setTimeout("shortcutListener.clearCombinationOnTimeout()", shortcutListener.clearTimeout);
}
}
return true;
},
// clear combination
clearCombination: function() {
shortcutListener.shortcut = null;
shortcutListener.combination = '';
this.hideStatus();
},
clearCombinationOnTimeout: function() {
var d = new Date();
// check if last keypress was earlier than (now - clearTimeout)
// 100ms here is used just to be sure that this will work in superfast browsers :)
if ((d.getTime() - shortcutListener.lastKeypress) >= (shortcutListener.clearTimeout - 100)) {
shortcutListener.clearCombination();
}
}
};
}
/*
* ===========================================================
* RT Keyboard Support
* Copyright (c) 2010 Peter Reuterås <[email protected]>.
* ===========================================================
*/
function RTSource() {
var Cursor = {
init: function() {
shortcutListener.init();
}
};
var RThelp = function () {
var RCursorHelp =
'\n=== Ticket ===\n' +
'# - open ticket with number\n' +
'a - resolve\n' +
'b - bookmark\n' +
'c - comment\n' +
'C - comment on last\n' +
'd - display current ticket or first from a list\n' +
'e -> Edit:\n' +
' b - Basics\n' +
' d - Dates\n' +
' h - History\n' +
' j - Jumbo\n' +
' l - Links\n' +
' p - People\n' +
' r - Reminders\n' +
'f - forward current ticket\n' +
'o - open ticket\n' +
'q - open queue with name from prompt\n' +
'Q - open queue with name from prompt and show new messages\n' +
'r - reply\n' +
'R - reply on last\n' +
's - steal ticket\n' +
't - take ticket\n' +
'x - Mark as spam\n' +
'\n=== Ticket navigation ===\n' +
'F - open first ticket\n' +
'L - open last ticket\n' +
'n - open next ticket\n'+
'p - open previous ticket\n' +
'\n=== General navigation ===\n' +
'g -> \n' +
' a - Approvals\n' +
' b - Bulk update\n' +
' c - Configuration (if you have access)\n' +
' d - Developer docs (if installed)\n' +
' h - go to front page\n' +
' l - logout\n' +
' p - Preferences\n' +
' s - simple search\n' +
' S - search result page\n' +
' t -> \n' +
' i - Ticket page\n' +
' o - Tools page\n' +
'\n=== Other ===\n' +
'N - Create new ticket in default queue\n' +
'V - Show version number\n' +
'/ - Search\n' +
'? - this help\n';
alert(RCursorHelp);
return true;
};
// Submit the form named formName
function RTform_submit(formName) {
if (document.getElementById(formName)){
document.forms[formName].submit();
} else {
event.returnValue = false;
return false;
}
return true;
}
// Navigoation using the rel links in the page from RT
function RTnext_or_prev(direction) {
var links = document.getElementsByTagName("link");
var link=-1;
for ( var i = 0; i < links.length; i++) {
if (links[i].hasAttribute("rel") && links[i].rel === direction) {
link=i;
}
}
if (link === -1){
event.returnValue = false;
return false;
}
// Ugly replace, have to check if our last upgrade introduced a conf error CHANGEME
window.location = links[link].href.replace(/Ticket/,"/Ticket");
return true;
}
// Get the link for the element matchstring and follow it
function RTmatch_name(matchString) {
var link = document.getElementsByName(matchString);
if (link){
window.location = link.href;
return true;
}
event.returnValue = false;
return false;
}
// Match a part of a url and follow it
function RTmatch_link(matchString) {
var breakOn = (arguments[1]) ? arguments[1] : "" ;
var links = document.getElementsByTagName("a");
var link=-1;
for ( var i = 0; i < links.length; i++) {
if (links[i].href.match(matchString)) {
link=i;
if (breakOn === "break") { break; }
}
}
if (link === -1){
event.returnValue = false;
alert("nothing to do");
return false;
}
window.location = links[link].href;
return true;
}
// Find base url
function RTbaseurl() {
var scripts = document.getElementsByTagName("script");
var link=-1;
for ( var i = 0; i < scripts.length; i++) {
if (scripts[i].hasAttribute("src") && scripts[i].src.match("/ckeditor.js")) {
link=i;
}
}
if (link === -1){
return false;
}
var url = scripts[link].src.replace(/static\/RichText\/ckeditor.js/,"");
var base = "/" + window.location.protocol + "\/\/" + window.location.host + "/";
url.replace(base);
return url;
}
// RT home
function RThome(){
var url = RTbaseurl();
if (url) {
window.location = url + "index.html";
return true;
}
event.returnValue = false;
return false;
}
// Open ticket number given by prompt number
function RTgototicket() {
var nr = prompt("Open ticket:", "");
if (nr){
var url = RTbaseurl();
window.location = url + "Ticket/Display.html?id=" + nr;
return true;
}
event.returnValue = false;
return false;
}
// Open the first queue matched by the text from the prompt
function RTqueue() {
var queue = prompt("Open queue:", "");
if (queue){
if(arguments[0] === "new" ){
queue=queue + ".*new";
RTmatch_link(queue);
}else{
RTmatch_link(queue, "break");
}
return true;
}
event.returnValue = false;
return false;
}
var SHORTCUTS = {
'?': function() { RThelp(); },
'/': function() { RTmatch_link(/Search\/Build.html/); },
'#': function() { RTgototicket(); },
'a': function() { RTmatch_link(/Status=resolved/); },
'b': function() { RTmatch_link(/TicketBookmark/); },
'c': function() { RTmatch_link(/Action=Comment/, "break"); },
'C': function() { RTmatch_link(/Action=Comment/); },
'e': {
'b': function() { RTmatch_link(/Modify.html/); },
'd': function() { RTmatch_link(/ModifyDates.html/); },
'h': function() { RTmatch_link(/History.html/); },
'j': function() { RTmatch_link(/ModifyAll.html/); },
'l': function() { RTmatch_link(/ModifyLinks.html/); },
'p': function() { RTmatch_link(/ModifyPeople.html/); },
'r': function() { RTmatch_link(/Reminders.html/); }
},
'd': function() { RTmatch_link(/\/Display.html/, "break"); },
'f': function() { RTmatch_link(/Forward.html/); },
'F': function() { RTnext_or_prev("first"); },
'g': {
'a': function() { RTmatch_link(/Approvals/); },
'b': function() { RTmatch_link(/Bulk.html/); },
'c': function() { RTmatch_link(/Admin/); },
// If you have the documentation installed
'd': function() { RTmatch_link(/Developer\/Perldoc/); },
'h': function() { RThome(); },
'l': function() { RTmatch_link(/NoAuth\/Logout.html/); },
'p': function() { RTmatch_link(/Prefs\/Other.html/); },
'S': function() { RTmatch_link(/Results.html\?Format/); },
's': function() { RTmatch_link(/Simple.html/); },
't': {
'i': function() { RTmatch_link(/Search\/Build.html/); },
'o': function() { RTmatch_link(/Tools/); }
}
},
'L': function() { RTnext_or_prev("last"); },
'n': function() { RTnext_or_prev("next"); },
'N': function() { RTform_submit("CreateTicketInQueue"); },
'o': function() { RTmatch_link(/Status=open/); },
'p': function() { RTnext_or_prev("prev"); },
'q': function() { RTqueue(); },
'Q': function() { RTqueue("new"); },
'r': function() { RTmatch_link(/Action=Respond/, "break"); },
'R': function() { RTmatch_link(/Action=Respond/); },
's': function() { RTmatch_link(/Action=Steal/); },
't': function() { RTmatch_link(/Action=Take/); },
'T': {
'a': function() { RTmatch_link(/Search\/Edit.html/); },
'b': function() { RTmatch_link(/Bulk.html/); },
'e': function() { RTmatch_link(/Search\/Build.html\?Format=/); },
'g': function() { RTmatch_link(/Chart.html/); },
'n': function() { RTmatch_link(/Search\/Build.html\?NewQuery=1/); },
's': function() { RTmatch_link(/Search\/Results.html\?Format=/); }
},
'V': function() { alert(myVersion); return true; },
// CHANGEME: This function requires that you have added a form to RT to move a ticket to a spam
// queue. I'll try to get the code or a pointer to it later...
'x': function() { RTform_submit("quick-spam"); }
};
}
/*
* ===========================================================
* Shortcuts Library: Supported Sites
* This greasemonkey script matches site URL against the
* property name and gets the source of the function
* specified as property value.
* ===========================================================
*/
var SupportedSites = {
// CHANGEME
'kth.se': RTSource,
'rt.reuteras.com': RTSource,
'rt.cpan.org': RTSource
};
/*
* ===========================================================
* Shortcuts Library: Loader
* Copyright (c) 2008 Pluron, Inc.
* ===========================================================
*/
var addScript = function(ShortcutsSource) {
var getSource = function (func) {
var js = func.toString();
var i = js.indexOf('{');
js = js.substr(i + 1, js.length - i - 2);
return js;
};
var script = document.createElement('script');
var source = getSource(ShortcutsSource);
for (var site in SupportedSites) {
if(SupportedSites.hasOwnProperty(site)){
if (typeof(site) != 'string') { continue; }
if (location.href.match(site)) {
source += getSource(SupportedSites[site]) + '\n window.Cursor.init();';
break;
}
}
}
var text = document.createTextNode(source);
script.appendChild(text);
script.setAttribute('id','RTKeyboardShortcuts');
if (!document.getElementById('RTKeyboardShortcuts')) {
document.body.appendChild(script);
}
};
addScript(ShortcutsSource);
| rtkeyboardshortcuts.user.js | /*
* RT Keyboard Shortcuts is an extension for RT from bestpractical.org.
* The extension is an adaptation by Peter Reuterås of Acunote Shortcuts
* from Acunote. A very good tool that was extremly easy to adopt for
* this purpose!
*
* Adds keyboard navigation for:
* ticket.sys.kth.se
* rt.reuteras.com
* rt.cpan.org
*
* Add your own installation to the @include section below and in the
* SupportedSites section. Search for the string CHANGEME and change to
* values suitable for your environment.
*
* Original message from Acunote:
*
* Acunote Shortcuts.
*
* Acunote Shortcuts is a greasemonkey script based on
* Javascript Keyboard Shortcuts library extracted from Acunote
* http://www.acunote.com/open-source/javascript-keyboard-shortcuts
*
* Shortcuts Library Copyright (c) 2007-2008 Pluron, Inc.
* Reddit, Digg and YCNews Scripts Copyright (c) 2008 Pluron, Inc.
* Other scripts are copyright of their respective authors.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*jslint browser:true */
// --------------------------------------------------------------------
//
// ==UserScript==
// @name RT Keyboard Shortcuts
// @description Adds keyboard shortcuts to RT.
// @include https://ticket.sys.kth.se/*
// @include https://rt.reuteras.com/*
// @include https://rt.cpan.org/*
// @grant none
// @downloadURL https://github.com/reuteras/RT-keyboard-shortcuts/raw/master/rtkeyboardshortcuts.user.js
// @updateURL https://github.com/reuteras/RT-keyboard-shortcuts/raw/master/rtkeyboardshortcuts.meta.js
// @version 0.1.1
// ==/UserScript==
// CHANGEME
/*
* ===========================================================
* Acunote Shortcuts: The Library
* Copyright (c) 2007-2008 Pluron, Inc.
* ===========================================================
*/
function ShortcutsSource() {
var myVersion = "Version of RT keyboard shourtcuts is 0.1.1", shortcutListener = {
listen: true,
shortcut: null,
combination: '',
lastKeypress: 0,
clearTimeout: 2000,
// Keys we don't listen to
keys: {
KEY_BACKSPACE: 8,
KEY_TAB: 9,
KEY_ENTER: 13,
KEY_SHIFT: 16,
KEY_CTRL: 17,
KEY_ALT: 18,
KEY_ESC: 27,
KEY_SPACE: 32,
KEY_LEFT: 37,
KEY_UP: 38,
KEY_RIGHT: 39,
KEY_DOWN: 40,
KEY_DELETE: 46,
KEY_HOME: 36,
KEY_END: 35,
KEY_PAGEUP: 33,
KEY_PAGEDOWN: 34
},
init: function() {
if (!window.SHORTCUTS) { return false; }
this.createStatusArea();
this.setObserver();
},
isInputTarget: function(e) {
var target = e.target || e.srcElement;
if (target && target.nodeName) {
var targetNodeName = target.nodeName.toLowerCase();
if (targetNodeName === "textarea" || targetNodeName === "select" ||
(targetNodeName === "input" && target.type &&
(target.type.toLowerCase() === "text" ||
target.type.toLowerCase() === "password"))
) {
return true;
}
}
return false;
},
stopEvent: function(event) {
if (event.preventDefault) {
event.preventDefault();
event.stopPropagation();
} else {
event.returnValue = false;
event.cancelBubble = true;
}
},
// shortcut notification/status area
createStatusArea: function() {
var area = document.createElement('div');
area.setAttribute('id', 'shortcut_status');
area.style.display = 'none';
document.body.appendChild(area);
},
showStatus: function() {
document.getElementById('shortcut_status').style.display = '';
},
hideStatus: function() {
document.getElementById('shortcut_status').style.display = 'none';
},
showCombination: function() {
var bar = document.getElementById('shortcut_status');
bar.innerHTML = this.combination;
this.showStatus();
},
// This method creates event observer for the whole document
// This is the common way of setting event observer that works
// in all modern brwosers with "keypress" fix for
// Konqueror/Safari/KHTML borrowed from Prototype.js
setObserver: function() {
var name = 'keypress';
if (navigator.appVersion.match(/Konqueror|Safari|KHTML/) || document.detachEvent) {
name = 'keydown';
}
if (document.addEventListener) {
document.addEventListener(name, function(e) {shortcutListener.keyCollector(e);}, false);
} else if (document.attachEvent) {
document.attachEvent('on'+name, function(e) {shortcutListener.keyCollector(e); });
}
},
// Key press collector. Collects all keypresses into combination
// and checks it we have action for it
keyCollector: function(e) {
// do not listen if no shortcuts defined
if (!window.SHORTCUTS) { return false; }
// do not listen if listener was explicitly turned off
if (!shortcutListener.listen) { return false; }
// leave modifiers for browser
if (e.altKey || e.ctrlKey || e.metaKey) { return false; }
var keyCode = e.keyCode;
// do not listen for Ctrl, Alt, Tab, Space, Esc and others
for (key in this.keys) {
if (e.keyCode === this.keys[key]) { return false; }
}
// do not listen for functional keys
if (navigator.userAgent.match(/Gecko/)) {
if (e.keyCode >= 112 && e.keyCode <=123) { return false; }
}
// do not listen in input/select/textarea fields
if (this.isInputTarget(e)) { return false; }
// get letter pressed for different browsers
var code = e.which ? e.which : e.keyCode;
var letter = String.fromCharCode(code).toLowerCase();
if (e.shiftKey) { letter = letter.toUpperCase(); }
// IE hack to support "?"
if (window.ie && (code === 191) && e.shiftKey) {
letter = '?';
}
if (shortcutListener.process(letter)) { shortcutListener.stopEvent(e); }
},
// process keys
process: function(letter) {
if (!window.SHORTCUTS) { return false; }
if (!shortcutListener.listen) { return false; }
// if no combination then start from the begining
if (!shortcutListener.shortcut) { shortcutListener.shortcut = SHORTCUTS; }
// if unknown letter then say goodbye
if (!shortcutListener.shortcut[letter]) { return false; }
if (typeof(shortcutListener.shortcut[letter]) === "function") {
shortcutListener.shortcut[letter]();
shortcutListener.clearCombination();
} else {
shortcutListener.shortcut = shortcutListener.shortcut[letter];
// append combination
shortcutListener.combination = shortcutListener.combination + letter;
if (shortcutListener.combination.length > 0) {
shortcutListener.showCombination();
// save last keypress timestamp (for autoclear)
var d = new Date();
shortcutListener.lastKeypress = d.getTime();
// autoclear combination in 2 seconds
setTimeout("shortcutListener.clearCombinationOnTimeout()", shortcutListener.clearTimeout);
}
}
return true;
},
// clear combination
clearCombination: function() {
shortcutListener.shortcut = null;
shortcutListener.combination = '';
this.hideStatus();
},
clearCombinationOnTimeout: function() {
var d = new Date();
// check if last keypress was earlier than (now - clearTimeout)
// 100ms here is used just to be sure that this will work in superfast browsers :)
if ((d.getTime() - shortcutListener.lastKeypress) >= (shortcutListener.clearTimeout - 100)) {
shortcutListener.clearCombination();
}
}
};
}
/*
* ===========================================================
* RT Keyboard Support
* Copyright (c) 2010 Peter Reuterås <[email protected]>.
* ===========================================================
*/
function RTSource() {
var Cursor = {
init: function() {
shortcutListener.init();
}
};
var RThelp = function () {
var RCursorHelp =
'\n=== Ticket ===\n' +
'# - open ticket with number\n' +
'a - resolve\n' +
'b - bookmark\n' +
'c - comment\n' +
'C - comment on last\n' +
'd - display current ticket or first from a list\n' +
'e -> Edit:\n' +
' b - Basics\n' +
' d - Dates\n' +
' h - History\n' +
' j - Jumbo\n' +
' l - Links\n' +
' p - People\n' +
' r - Reminders\n' +
'f - forward current ticket\n' +
'o - open ticket\n' +
'q - open queue with name from prompt\n' +
'Q - open queue with name from prompt and show new messages\n' +
'r - reply\n' +
'R - reply on last\n' +
's - steal ticket\n' +
't - take ticket\n' +
'x - Mark as spam\n' +
'\n=== Ticket navigation ===\n' +
'F - open first ticket\n' +
'L - open last ticket\n' +
'n - open next ticket\n'+
'p - open previous ticket\n' +
'\n=== General navigation ===\n' +
'g -> \n' +
' a - Approvals\n' +
' b - Bulk update\n' +
' c - Configuration (if you have access)\n' +
' d - Developer docs (if installed)\n' +
' h - go to front page\n' +
' l - logout\n' +
' p - Preferences\n' +
' s - simple search\n' +
' S - search result page\n' +
' t -> \n' +
' i - Ticket page\n' +
' o - Tools page\n' +
'\n=== Other ===\n' +
'N - Create new ticket in default queue\n' +
'V - Show version number\n' +
'/ - Search\n' +
'? - this help\n';
alert(RCursorHelp);
return true;
};
// Submit the form named formName
function RTform_submit(formName) {
if (document.getElementById(formName)){
document.forms[formName].submit();
} else {
event.returnValue = false;
return false;
}
return true;
}
// Navigoation using the rel links in the page from RT
function RTnext_or_prev(direction) {
var links = document.getElementsByTagName("link");
var link=-1;
for ( var i = 0; i < links.length; i++) {
if (links[i].hasAttribute("rel") && links[i].rel === direction) {
link=i;
}
}
if (link === -1){
event.returnValue = false;
return false;
}
// Ugly replace, have to check if our last upgrade introduced a conf error CHANGEME
window.location = links[link].href.replace(/Ticket/,"/Ticket");
return true;
}
// Get the link for the element matchstring and follow it
function RTmatch_name(matchString) {
var link = document.getElementsByName(matchString);
if (link){
window.location = link.href;
return true;
}
event.returnValue = false;
return false;
}
// Match a part of a url and follow it
function RTmatch_link(matchString) {
var breakOn = (arguments[1]) ? arguments[1] : "" ;
var links = document.getElementsByTagName("a");
var link=-1;
for ( var i = 0; i < links.length; i++) {
if (links[i].href.match(matchString)) {
link=i;
if (breakOn === "break") { break; }
}
}
if (link === -1){
event.returnValue = false;
alert("nothing to do");
return false;
}
window.location = links[link].href;
return true;
}
// Find base url
function RTbaseurl() {
var scripts = document.getElementsByTagName("script");
var link=-1;
for ( var i = 0; i < scripts.length; i++) {
if (scripts[i].hasAttribute("src") && scripts[i].src.match("/ckeditor.js")) {
link=i;
}
}
if (link === -1){
return false;
}
var url = scripts[link].src.replace(/static\/RichText\/ckeditor.js/,"");
var base = "/" + window.location.protocol + "\/\/" + window.location.host + "/";
url.replace(base);
return url;
}
// RT home
function RThome(){
var url = RTbaseurl();
if (url) {
window.location = url + "index.html";
return true;
}
event.returnValue = false;
return false;
}
// Open ticket number given by prompt number
function RTgototicket() {
var nr = prompt("Open ticket:", "");
if (nr){
var url = RTbaseurl();
window.location = url + "Ticket/Display.html?id=" + nr;
return true;
}
event.returnValue = false;
return false;
}
// Open the first queue matched by the text from the prompt
function RTqueue() {
var queue = prompt("Open queue:", "");
if (queue){
if(arguments[0] === "new" ){
queue=queue + ".*new";
RTmatch_link(queue);
}else{
RTmatch_link(queue, "break");
}
return true;
}
event.returnValue = false;
return false;
}
var SHORTCUTS = {
'?': function() { RThelp(); },
'/': function() { RTmatch_link(/Search\/Build.html/); },
'#': function() { RTgototicket(); },
'a': function() { RTmatch_link(/Status=resolved/); },
'b': function() { RTmatch_link(/TicketBookmark/); },
'c': function() { RTmatch_link(/Action=Comment/, "break"); },
'C': function() { RTmatch_link(/Action=Comment/); },
'e': {
'b': function() { RTmatch_link(/Modify.html/); },
'd': function() { RTmatch_link(/ModifyDates.html/); },
'h': function() { RTmatch_link(/History.html/); },
'j': function() { RTmatch_link(/ModifyAll.html/); },
'l': function() { RTmatch_link(/ModifyLinks.html/); },
'p': function() { RTmatch_link(/ModifyPeople.html/); },
'r': function() { RTmatch_link(/Reminders.html/); }
},
'd': function() { RTmatch_link(/\/Display.html/, "break"); },
'f': function() { RTmatch_link(/Forward.html/); },
'F': function() { RTnext_or_prev("first"); },
'g': {
'a': function() { RTmatch_link(/Approvals/); },
'b': function() { RTmatch_link(/Bulk.html/); },
'c': function() { RTmatch_link(/Admin/); },
// If you have the documentation installed
'd': function() { RTmatch_link(/Developer\/Perldoc/); },
'h': function() { RThome(); },
'l': function() { RTmatch_link(/NoAuth\/Logout.html/); },
'p': function() { RTmatch_link(/Prefs\/Other.html/); },
'S': function() { RTmatch_link(/Results.html\?Format/); },
's': function() { RTmatch_link(/Simple.html/); },
't': {
'i': function() { RTmatch_link(/Search\/Build.html/); },
'o': function() { RTmatch_link(/Tools/); }
}
},
'L': function() { RTnext_or_prev("last"); },
'n': function() { RTnext_or_prev("next"); },
'N': function() { RTform_submit("CreateTicketInQueue"); },
'o': function() { RTmatch_link(/Status=open/); },
'p': function() { RTnext_or_prev("prev"); },
'q': function() { RTqueue(); },
'Q': function() { RTqueue("new"); },
'r': function() { RTmatch_link(/Action=Respond/, "break"); },
'R': function() { RTmatch_link(/Action=Respond/); },
's': function() { RTmatch_link(/Action=Steal/); },
't': function() { RTmatch_link(/Action=Take/); },
'T': {
'a': function() { RTmatch_link(/Search\/Edit.html/); },
'b': function() { RTmatch_link(/Bulk.html/); },
'e': function() { RTmatch_link(/Search\/Build.html\?Format=/); },
'g': function() { RTmatch_link(/Chart.html/); },
'n': function() { RTmatch_link(/Search\/Build.html\?NewQuery=1/); },
's': function() { RTmatch_link(/Search\/Results.html\?Format=/); }
},
'V': function() { alert(myVersion); return true; },
// CHANGEME: This function requires that you have added a form to RT to move a ticket to a spam
// queue. I'll try to get the code or a pointer to it later...
'x': function() { RTform_submit("quick-spam"); }
};
}
/*
* ===========================================================
* Shortcuts Library: Supported Sites
* This greasemonkey script matches site URL against the
* property name and gets the source of the function
* specified as property value.
* ===========================================================
*/
var SupportedSites = {
// CHANGEME
'kth.se': RTSource,
'rt.reuteras.com': RTSource,
'rt.cpan.org': RTSource
};
/*
* ===========================================================
* Shortcuts Library: Loader
* Copyright (c) 2008 Pluron, Inc.
* ===========================================================
*/
var addScript = function(ShortcutsSource) {
var getSource = function (func) {
var js = func.toString();
var i = js.indexOf('{');
js = js.substr(i + 1, js.length - i - 2);
return js;
};
var script = document.createElement('script');
var source = getSource(ShortcutsSource);
for (var site in SupportedSites) {
if(SupportedSites.hasOwnProperty(site)){
if (typeof(site) != 'string') { continue; }
if (location.href.match(site)) {
source += getSource(SupportedSites[site]) + '\n window.Cursor.init();';
break;
}
}
}
var text = document.createTextNode(source);
script.appendChild(text);
script.setAttribute('id','RTKeyboardShortcuts');
if (!document.getElementById('RTKeyboardShortcuts')) {
document.body.appendChild(script);
}
};
addScript(ShortcutsSource);
| Space and more (jslint fixes)
| rtkeyboardshortcuts.user.js | Space and more (jslint fixes) | <ide><path>tkeyboardshortcuts.user.js
<ide> },
<ide>
<ide> isInputTarget: function(e) {
<del> var target = e.target || e.srcElement;
<add> var targetNodeName, target;
<add> target = e.target || e.srcElement;
<ide> if (target && target.nodeName) {
<del> var targetNodeName = target.nodeName.toLowerCase();
<add> targetNodeName = target.nodeName.toLowerCase();
<ide> if (targetNodeName === "textarea" || targetNodeName === "select" ||
<ide> (targetNodeName === "input" && target.type &&
<ide> (target.type.toLowerCase() === "text" ||
<ide> name = 'keydown';
<ide> }
<ide> if (document.addEventListener) {
<del> document.addEventListener(name, function(e) {shortcutListener.keyCollector(e);}, false);
<add> document.addEventListener(name, function(e) {shortcutListener.keyCollector(e); }, false);
<ide> } else if (document.attachEvent) {
<del> document.attachEvent('on'+name, function(e) {shortcutListener.keyCollector(e); });
<add> document.attachEvent('on' + name, function(e) {shortcutListener.keyCollector(e); });
<ide> }
<ide> },
<ide>
<ide> // Key press collector. Collects all keypresses into combination
<ide> // and checks it we have action for it
<ide> keyCollector: function(e) {
<add> var key;
<ide> // do not listen if no shortcuts defined
<ide> if (!window.SHORTCUTS) { return false; }
<ide> // do not listen if listener was explicitly turned off |
|
Java | apache-2.0 | f7dede7a666277b38d7b3a467966bcc26b8a6b6b | 0 | LinuxSuRen/phoenix.webui.framework | /**
* Copyright © 1998-2016, Glodon Inc. All Rights Reserved.
*/
package org.suren.autotest.web.framework.selenium;
import static org.suren.autotest.web.framework.settings.DriverConstants.DRIVER_CHROME;
import static org.suren.autotest.web.framework.settings.DriverConstants.DRIVER_FIREFOX;
import static org.suren.autotest.web.framework.settings.DriverConstants.DRIVER_IE;
import static org.suren.autotest.web.framework.settings.DriverConstants.DRIVER_OPERA;
import static org.suren.autotest.web.framework.settings.DriverConstants.DRIVER_SAFARI;
import static org.suren.autotest.web.framework.settings.DriverConstants.ENGINE_CONFIG_FILE_NAME;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.UnsupportedCommandException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Window;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.opera.OperaDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.safari.SafariDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.suren.autotest.web.framework.util.BrowserUtil;
/**
* 浏览器引擎封装类
* @author suren
* @since jdk1.6 2016年6月29日
*/
@Component
public class SeleniumEngine
{
private static final Logger logger = LoggerFactory.getLogger(SeleniumEngine.class);
private Properties enginePro = new Properties(); //引擎参数集合
private WebDriver driver;
private String driverStr;
private String remoteStr;
private long timeout;
private boolean fullScreen;
private boolean maximize;
private int width;
private int height;
private int toolbarHeight;
/**
* 浏览器引擎初始化
*/
public void init()
{
InputStream inputStream = null;
try
{
ClassLoader classLoader = this.getClass().getClassLoader();
loadDefaultEnginePath(classLoader, enginePro); //加载默认配置
System.getProperties().putAll(enginePro);
}
finally
{
IOUtils.closeQuietly(inputStream);
}
DesiredCapabilities capability = null;
String curDriverStr = getDriverStr();
if(DRIVER_CHROME.equals(curDriverStr))
{
capability = DesiredCapabilities.chrome();
//chrome://version/
ChromeOptions options = new ChromeOptions();
Iterator<Object> chromeKeys = enginePro.keySet().iterator();
while(chromeKeys.hasNext())
{
String key = chromeKeys.next().toString();
if(!key.startsWith("chrome"))
{
continue;
}
if(key.startsWith("chrome.args"))
{
String arg = key.replace("chrome.args.", "") + "=" + enginePro.getProperty(key);
if(arg.endsWith("="))
{
arg = arg.substring(0, arg.length() - 1);
}
options.addArguments(arg);
logger.info(String.format("chrome arguments : [%s]", arg));
}
else if(key.startsWith("chrome.cap.proxy.http"))
{
String val = enginePro.getProperty(key);
Proxy proxy = new Proxy();
proxy.setHttpProxy(val);
capability.setCapability("proxy", proxy);
}
}
capability.setCapability(ChromeOptions.CAPABILITY, options);
driver = new ChromeDriver(capability);
}
else if(DRIVER_IE.equals(curDriverStr))
{
capability = DesiredCapabilities.internetExplorer();
capability.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
driver = new InternetExplorerDriver(capability);
}
else if(DRIVER_FIREFOX.equals(curDriverStr))
{
String proFile = System.getProperty("firefox.profile", null);
FirefoxProfile profile = new FirefoxProfile(proFile != null ? new File(proFile) : null);
fireFoxPreSet(profile);
driver = new FirefoxDriver(profile);
}
else if(DRIVER_SAFARI.equals(curDriverStr))
{
capability = DesiredCapabilities.safari();
driver = new SafariDriver(capability);
}
else if(DRIVER_OPERA.equals(curDriverStr))
{
capability = DesiredCapabilities.operaBlink();
driver = new OperaDriver(capability);
}
if(getRemoteStr() != null)
{
// try
// {
// driver = new RemoteWebDriver(new URL(getRemoteStr()), capability);
// }
// catch (MalformedURLException e)
// {
// throw new AutoTestException();
// }
}
if(timeout > 0)
{
driver.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);
}
Window window = driver.manage().window();
if(fullScreen)
{
try
{
// window.fullscreen();
}
catch(UnsupportedCommandException e)
{
logger.error("Unsupported fullScreen command.", e);
}
}
if(maximize)
{
window.maximize();
}
if(getWidth() > 0)
{
window.setSize(new Dimension(getWidth(), window.getSize().getHeight()));
}
if(getHeight() > 0)
{
window.setSize(new Dimension(window.getSize().getWidth(), getHeight()));
}
}
/**
* 设定firefox首选项
* @param profile
*/
private void fireFoxPreSet(FirefoxProfile profile)
{
BrowserUtil browserUtil = new BrowserUtil();
Map<String, Boolean> boolMap = browserUtil.getFirefoxPreBoolMap();
Iterator<String> boolIt = boolMap.keySet().iterator();
while(boolIt.hasNext())
{
String key = boolIt.next();
profile.setPreference(key, boolMap.get(key));
}
Map<String, Integer> intMap = browserUtil.getFirefoxPreIntMap();
Iterator<String> intIt = intMap.keySet().iterator();
while(intIt.hasNext())
{
String key = intIt.next();
profile.setPreference(key, intMap.get(key));
}
Map<String, Integer> strMap = browserUtil.getFirefoxPreIntMap();
Iterator<String> strIt = intMap.keySet().iterator();
while(strIt.hasNext())
{
String key = strIt.next();
profile.setPreference(key, strMap.get(key));
}
}
/**
* 加载默认的engine
* @param enginePro
*/
private void loadDefaultEnginePath(ClassLoader classLoader, Properties enginePro)
{
URL ieDriverURL = classLoader.getResource("IEDriverServer.exe");
URL chromeDrvierURL = classLoader.getResource("chromedriver.exe");
enginePro.put("webdriver.ie.driver", getLocalFilePath(ieDriverURL));
enginePro.put("webdriver.chrome.driver", getLocalFilePath(chromeDrvierURL));
Enumeration<URL> resurceUrls = null;
URL defaultResourceUrl = null;
try
{
resurceUrls = classLoader.getResources(ENGINE_CONFIG_FILE_NAME);
defaultResourceUrl = classLoader.getResource(ENGINE_CONFIG_FILE_NAME);
}
catch (IOException e)
{
logger.error("Engine properties loading error.", e);
}
if(resurceUrls == null)
{
return;
}
try
{
loadFromURL(enginePro, defaultResourceUrl);
}
catch (IOException e)
{
logger.error("loading engine error.", e);
}
while(resurceUrls.hasMoreElements())
{
URL url = resurceUrls.nextElement();
if(url == defaultResourceUrl)
{
continue;
}
try
{
loadFromURL(enginePro, url);
}
catch (IOException e)
{
logger.error("loading engine error.", e);
}
}
// TODO 没有实现对多个操作系统的兼容性设置
String os = System.getProperty("os.name");
if(!"Linux".equals(os))
{
}
else
{
}
}
private void loadFromURL(Properties enginePro, URL url) throws IOException
{
try(InputStream inputStream = url.openStream())
{
enginePro.load(inputStream);
}
}
private String getLocalFilePath(URL url)
{
if(url == null)
{
return "";
}
File driverFile = null;
if("jar".equals(url.getProtocol()))
{
OutputStream output = null;
driverFile = new File("surenpi.com." + new File(url.getFile()).getName());
if(driverFile.exists())
{
return driverFile.getAbsolutePath();
}
try(InputStream inputStream = url.openStream())
{
output = new FileOutputStream(driverFile);
IOUtils.copy(inputStream, output);
}
catch (IOException e)
{
logger.error("Driver file copy error.", e);
}
finally
{
IOUtils.closeQuietly(output);
}
}
else
{
try
{
driverFile = new File(URLDecoder.decode(url.getFile(), "utf-8"));
}
catch (UnsupportedEncodingException e)
{
logger.error(e.getMessage(), e);
}
}
if(driverFile != null)
{
return driverFile.getAbsolutePath();
}
else
{
return "";
}
}
/**
* 转为为初始化的驱动
* @param driver
* @return
*/
public WebDriver turnToRootDriver(WebDriver driver)
{
return driver.switchTo().defaultContent();
}
/**
* 打开指定地址
* @param url
*/
public void openUrl(String url)
{
driver.get(url);
}
/**
* 关闭浏览器引擎
*/
public void close()
{
if(driver != null)
{
driver.quit();
}
}
/**
* @return 引擎对象
*/
public WebDriver getDriver()
{
return driver;
}
/**
* @return 引擎名称
*/
public String getDriverStr()
{
return driverStr;
}
/**
* 设置引擎名称
* @param driverStr
*/
public void setDriverStr(String driverStr)
{
this.driverStr = driverStr;
}
public String getRemoteStr()
{
return remoteStr;
}
public void setRemoteStr(String remoteStr)
{
this.remoteStr = remoteStr;
}
/**
* @return 超时时间
*/
public long getTimeout()
{
return timeout;
}
/**
* 设定超时时间
* @param timeout
*/
public void setTimeout(long timeout)
{
this.timeout = timeout;
}
/**
* @return 全屏返回true,否则返回false
*/
public boolean isFullScreen()
{
return fullScreen;
}
/**
* 设置是否要全屏
* @param fullScreen
*/
public void setFullScreen(boolean fullScreen)
{
this.fullScreen = fullScreen;
}
/**
* @return 浏览器宽度
*/
public int getWidth()
{
return width;
}
/**
* 设置浏览器宽度
* @param width
*/
public void setWidth(int width)
{
this.width = width;
}
/**
* @return 浏览器高度
*/
public int getHeight()
{
return height;
}
/**
* 设置浏览器高度
* @param height
*/
public void setHeight(int height)
{
this.height = height;
}
/**
* @return the maximize
*/
public boolean isMaximize()
{
return maximize;
}
/**
* @param maximize the maximize to set
*/
public void setMaximize(boolean maximize)
{
this.maximize = maximize;
}
/**
* 计算工具栏高度
* @return
*/
public int computeToolbarHeight()
{
JavascriptExecutor jsExe = (JavascriptExecutor) driver;
Object objectHeight = jsExe.executeScript("return window.outerHeight - window.innerHeight;");
if(objectHeight instanceof Long)
{
toolbarHeight = ((Long) objectHeight).intValue();
}
return toolbarHeight;
}
/**
* @return the toolbarHeight
*/
public int getToolbarHeight()
{
return toolbarHeight;
}
}
| src/main/java/org/suren/autotest/web/framework/selenium/SeleniumEngine.java | /**
* Copyright © 1998-2016, Glodon Inc. All Rights Reserved.
*/
package org.suren.autotest.web.framework.selenium;
import static org.suren.autotest.web.framework.settings.DriverConstants.DRIVER_CHROME;
import static org.suren.autotest.web.framework.settings.DriverConstants.DRIVER_FIREFOX;
import static org.suren.autotest.web.framework.settings.DriverConstants.DRIVER_IE;
import static org.suren.autotest.web.framework.settings.DriverConstants.DRIVER_OPERA;
import static org.suren.autotest.web.framework.settings.DriverConstants.DRIVER_SAFARI;
import static org.suren.autotest.web.framework.settings.DriverConstants.ENGINE_CONFIG_FILE_NAME;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.UnsupportedCommandException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Window;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.opera.OperaDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.suren.autotest.web.framework.core.AutoTestException;
import org.suren.autotest.web.framework.util.BrowserUtil;
/**
* 浏览器引擎封装类
* @author suren
* @since jdk1.6 2016年6月29日
*/
@Component
public class SeleniumEngine
{
private static final Logger logger = LoggerFactory.getLogger(SeleniumEngine.class);
private Properties enginePro = new Properties(); //引擎参数集合
private WebDriver driver;
private String driverStr;
private String remoteStr;
private long timeout;
private boolean fullScreen;
private boolean maximize;
private int width;
private int height;
private int toolbarHeight;
/**
* 浏览器引擎初始化
*/
public void init()
{
InputStream inputStream = null;
try
{
ClassLoader classLoader = this.getClass().getClassLoader();
loadDefaultEnginePath(classLoader, enginePro); //加载默认配置
System.getProperties().putAll(enginePro);
}
finally
{
IOUtils.closeQuietly(inputStream);
}
DesiredCapabilities capability = null;
String curDriverStr = getDriverStr();
if(DRIVER_CHROME.equals(curDriverStr))
{
capability = DesiredCapabilities.chrome();
driver = new ChromeDriver(capability);
}
else if(DRIVER_IE.equals(curDriverStr))
{
capability = DesiredCapabilities.internetExplorer();
capability.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
driver = new InternetExplorerDriver(capability);
}
else if(DRIVER_FIREFOX.equals(curDriverStr))
{
String proFile = System.getProperty("firefox.profile", null);
FirefoxProfile profile = new FirefoxProfile(proFile != null ? new File(proFile) : null);
fireFoxPreSet(profile);
driver = new FirefoxDriver(profile);
}
else if(DRIVER_SAFARI.equals(curDriverStr))
{
capability = DesiredCapabilities.safari();
driver = new SafariDriver(capability);
}
else if(DRIVER_OPERA.equals(curDriverStr))
{
capability = DesiredCapabilities.operaBlink();
driver = new OperaDriver(capability);
}
if(getRemoteStr() != null)
{
try
{
driver = new RemoteWebDriver(new URL(getRemoteStr()), capability);
}
catch (MalformedURLException e)
{
throw new AutoTestException();
}
}
if(timeout > 0)
{
driver.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);
}
Window window = driver.manage().window();
if(fullScreen)
{
try
{
// window.fullscreen();
}
catch(UnsupportedCommandException e)
{
logger.error("Unsupported fullScreen command.", e);
}
}
if(maximize)
{
window.maximize();
}
if(getWidth() > 0)
{
window.setSize(new Dimension(getWidth(), window.getSize().getHeight()));
}
if(getHeight() > 0)
{
window.setSize(new Dimension(window.getSize().getWidth(), getHeight()));
}
}
/**
* 设定firefox首选项
* @param profile
*/
private void fireFoxPreSet(FirefoxProfile profile)
{
BrowserUtil browserUtil = new BrowserUtil();
Map<String, Boolean> boolMap = browserUtil.getFirefoxPreBoolMap();
Iterator<String> boolIt = boolMap.keySet().iterator();
while(boolIt.hasNext())
{
String key = boolIt.next();
profile.setPreference(key, boolMap.get(key));
}
Map<String, Integer> intMap = browserUtil.getFirefoxPreIntMap();
Iterator<String> intIt = intMap.keySet().iterator();
while(intIt.hasNext())
{
String key = intIt.next();
profile.setPreference(key, intMap.get(key));
}
Map<String, Integer> strMap = browserUtil.getFirefoxPreIntMap();
Iterator<String> strIt = intMap.keySet().iterator();
while(strIt.hasNext())
{
String key = strIt.next();
profile.setPreference(key, strMap.get(key));
}
}
/**
* 加载默认的engine
* @param enginePro
*/
private void loadDefaultEnginePath(ClassLoader classLoader, Properties enginePro)
{
URL ieDriverURL = classLoader.getResource("IEDriverServer.exe");
URL chromeDrvierURL = classLoader.getResource("chromedriver.exe");
enginePro.put("webdriver.ie.driver", getLocalFilePath(ieDriverURL));
enginePro.put("webdriver.chrome.driver", getLocalFilePath(chromeDrvierURL));
Enumeration<URL> resurceUrls = null;
URL defaultResourceUrl = null;
try
{
resurceUrls = classLoader.getResources(ENGINE_CONFIG_FILE_NAME);
defaultResourceUrl = classLoader.getResource(ENGINE_CONFIG_FILE_NAME);
}
catch (IOException e)
{
logger.error("Engine properties loading error.", e);
}
if(resurceUrls == null)
{
return;
}
try
{
loadFromURL(enginePro, defaultResourceUrl);
}
catch (IOException e)
{
logger.error("loading engine error.", e);
}
while(resurceUrls.hasMoreElements())
{
URL url = resurceUrls.nextElement();
if(url == defaultResourceUrl)
{
continue;
}
try
{
loadFromURL(enginePro, url);
}
catch (IOException e)
{
logger.error("loading engine error.", e);
}
}
// TODO 没有实现对多个操作系统的兼容性设置
String os = System.getProperty("os.name");
if(!"Linux".equals(os))
{
}
else
{
}
}
private void loadFromURL(Properties enginePro, URL url) throws IOException
{
try(InputStream inputStream = url.openStream())
{
enginePro.load(inputStream);
}
}
private String getLocalFilePath(URL url)
{
if(url == null)
{
return "";
}
File driverFile = null;
if("jar".equals(url.getProtocol()))
{
OutputStream output = null;
driverFile = new File("surenpi.com." + new File(url.getFile()).getName());
if(driverFile.exists())
{
return driverFile.getAbsolutePath();
}
try(InputStream inputStream = url.openStream())
{
output = new FileOutputStream(driverFile);
IOUtils.copy(inputStream, output);
}
catch (IOException e)
{
logger.error("Driver file copy error.", e);
}
finally
{
IOUtils.closeQuietly(output);
}
}
else
{
try
{
driverFile = new File(URLDecoder.decode(url.getFile(), "utf-8"));
}
catch (UnsupportedEncodingException e)
{
logger.error(e.getMessage(), e);
}
}
if(driverFile != null)
{
return driverFile.getAbsolutePath();
}
else
{
return "";
}
}
/**
* 转为为初始化的驱动
* @param driver
* @return
*/
public WebDriver turnToRootDriver(WebDriver driver)
{
return driver.switchTo().defaultContent();
}
/**
* 打开指定地址
* @param url
*/
public void openUrl(String url)
{
driver.get(url);
}
/**
* 关闭浏览器引擎
*/
public void close()
{
if(driver != null)
{
driver.quit();
}
}
/**
* @return 引擎对象
*/
public WebDriver getDriver()
{
return driver;
}
/**
* @return 引擎名称
*/
public String getDriverStr()
{
return driverStr;
}
/**
* 设置引擎名称
* @param driverStr
*/
public void setDriverStr(String driverStr)
{
this.driverStr = driverStr;
}
public String getRemoteStr()
{
return remoteStr;
}
public void setRemoteStr(String remoteStr)
{
this.remoteStr = remoteStr;
}
/**
* @return 超时时间
*/
public long getTimeout()
{
return timeout;
}
/**
* 设定超时时间
* @param timeout
*/
public void setTimeout(long timeout)
{
this.timeout = timeout;
}
/**
* @return 全屏返回true,否则返回false
*/
public boolean isFullScreen()
{
return fullScreen;
}
/**
* 设置是否要全屏
* @param fullScreen
*/
public void setFullScreen(boolean fullScreen)
{
this.fullScreen = fullScreen;
}
/**
* @return 浏览器宽度
*/
public int getWidth()
{
return width;
}
/**
* 设置浏览器宽度
* @param width
*/
public void setWidth(int width)
{
this.width = width;
}
/**
* @return 浏览器高度
*/
public int getHeight()
{
return height;
}
/**
* 设置浏览器高度
* @param height
*/
public void setHeight(int height)
{
this.height = height;
}
/**
* @return the maximize
*/
public boolean isMaximize()
{
return maximize;
}
/**
* @param maximize the maximize to set
*/
public void setMaximize(boolean maximize)
{
this.maximize = maximize;
}
/**
* 计算工具栏高度
* @return
*/
public int computeToolbarHeight()
{
JavascriptExecutor jsExe = (JavascriptExecutor) driver;
Object objectHeight = jsExe.executeScript("return window.outerHeight - window.innerHeight;");
if(objectHeight instanceof Long)
{
toolbarHeight = ((Long) objectHeight).intValue();
}
return toolbarHeight;
}
/**
* @return the toolbarHeight
*/
public int getToolbarHeight()
{
return toolbarHeight;
}
}
| 增加对chrome配置的支持 | src/main/java/org/suren/autotest/web/framework/selenium/SeleniumEngine.java | 增加对chrome配置的支持 | <ide><path>rc/main/java/org/suren/autotest/web/framework/selenium/SeleniumEngine.java
<ide> import java.io.InputStream;
<ide> import java.io.OutputStream;
<ide> import java.io.UnsupportedEncodingException;
<del>import java.net.MalformedURLException;
<ide> import java.net.URL;
<ide> import java.net.URLDecoder;
<ide> import java.util.Enumeration;
<ide> import org.apache.commons.io.IOUtils;
<ide> import org.openqa.selenium.Dimension;
<ide> import org.openqa.selenium.JavascriptExecutor;
<add>import org.openqa.selenium.Proxy;
<ide> import org.openqa.selenium.UnsupportedCommandException;
<ide> import org.openqa.selenium.WebDriver;
<ide> import org.openqa.selenium.WebDriver.Window;
<ide> import org.openqa.selenium.chrome.ChromeDriver;
<add>import org.openqa.selenium.chrome.ChromeOptions;
<ide> import org.openqa.selenium.firefox.FirefoxDriver;
<ide> import org.openqa.selenium.firefox.FirefoxProfile;
<ide> import org.openqa.selenium.ie.InternetExplorerDriver;
<ide> import org.openqa.selenium.opera.OperaDriver;
<ide> import org.openqa.selenium.remote.DesiredCapabilities;
<del>import org.openqa.selenium.remote.RemoteWebDriver;
<ide> import org.openqa.selenium.safari.SafariDriver;
<ide> import org.slf4j.Logger;
<ide> import org.slf4j.LoggerFactory;
<ide> import org.springframework.stereotype.Component;
<del>import org.suren.autotest.web.framework.core.AutoTestException;
<ide> import org.suren.autotest.web.framework.util.BrowserUtil;
<ide>
<ide> /**
<ide> if(DRIVER_CHROME.equals(curDriverStr))
<ide> {
<ide> capability = DesiredCapabilities.chrome();
<add>
<add> //chrome://version/
<add> ChromeOptions options = new ChromeOptions();
<add> Iterator<Object> chromeKeys = enginePro.keySet().iterator();
<add> while(chromeKeys.hasNext())
<add> {
<add> String key = chromeKeys.next().toString();
<add> if(!key.startsWith("chrome"))
<add> {
<add> continue;
<add> }
<add>
<add> if(key.startsWith("chrome.args"))
<add> {
<add> String arg = key.replace("chrome.args.", "") + "=" + enginePro.getProperty(key);
<add> if(arg.endsWith("="))
<add> {
<add> arg = arg.substring(0, arg.length() - 1);
<add> }
<add> options.addArguments(arg);
<add> logger.info(String.format("chrome arguments : [%s]", arg));
<add> }
<add> else if(key.startsWith("chrome.cap.proxy.http"))
<add> {
<add> String val = enginePro.getProperty(key);
<add>
<add> Proxy proxy = new Proxy();
<add> proxy.setHttpProxy(val);
<add> capability.setCapability("proxy", proxy);
<add> }
<add> }
<add> capability.setCapability(ChromeOptions.CAPABILITY, options);
<add>
<ide> driver = new ChromeDriver(capability);
<ide> }
<ide> else if(DRIVER_IE.equals(curDriverStr))
<ide>
<ide> if(getRemoteStr() != null)
<ide> {
<del> try
<del> {
<del> driver = new RemoteWebDriver(new URL(getRemoteStr()), capability);
<del> }
<del> catch (MalformedURLException e)
<del> {
<del> throw new AutoTestException();
<del> }
<add>// try
<add>// {
<add>// driver = new RemoteWebDriver(new URL(getRemoteStr()), capability);
<add>// }
<add>// catch (MalformedURLException e)
<add>// {
<add>// throw new AutoTestException();
<add>// }
<ide> }
<ide>
<ide> if(timeout > 0) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.