repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
vam-google/google-cloud-java
google-cloud-clients/google-cloud-dns/src/test/java/com/google/cloud/dns/it/ITDnsTest.java
88484
/* * Copyright 2016 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.dns.it; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.google.api.gax.paging.Page; import com.google.cloud.dns.ChangeRequest; import com.google.cloud.dns.ChangeRequestInfo; import com.google.cloud.dns.Dns; import com.google.cloud.dns.Dns.ChangeRequestField; import com.google.cloud.dns.Dns.ProjectField; import com.google.cloud.dns.Dns.RecordSetField; import com.google.cloud.dns.Dns.ZoneField; import com.google.cloud.dns.DnsBatch; import com.google.cloud.dns.DnsBatchResult; import com.google.cloud.dns.DnsException; import com.google.cloud.dns.DnsOptions; import com.google.cloud.dns.ProjectInfo; import com.google.cloud.dns.RecordSet; import com.google.cloud.dns.Zone; import com.google.cloud.dns.ZoneInfo; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; public class ITDnsTest { private static final String PREFIX = "gcldjvit-"; private static final Dns DNS = DnsOptions.getDefaultInstance().getService(); private static final String ZONE_NAME1 = (PREFIX + UUID.randomUUID()).substring(0, 32); private static final String ZONE_NAME_EMPTY_DESCRIPTION = (PREFIX + UUID.randomUUID()).substring(0, 32); private static final String ZONE_NAME_TOO_LONG = ZONE_NAME1 + UUID.randomUUID(); private static final String ZONE_DESCRIPTION1 = "first zone"; private static final String ZONE_DNS_NAME1 = ZONE_NAME1 + ".com."; private static final String ZONE_DNS_EMPTY_DESCRIPTION = ZONE_NAME_EMPTY_DESCRIPTION + ".com."; private static final String ZONE_DNS_NAME_NO_PERIOD = ZONE_NAME1 + ".com"; private static final ZoneInfo ZONE1 = ZoneInfo.of(ZONE_NAME1, ZONE_DNS_EMPTY_DESCRIPTION, ZONE_DESCRIPTION1); private static final ZoneInfo ZONE_EMPTY_DESCRIPTION = ZoneInfo.of(ZONE_NAME_EMPTY_DESCRIPTION, ZONE_DNS_NAME1, ZONE_DESCRIPTION1); private static final ZoneInfo ZONE_NAME_ERROR = ZoneInfo.of(ZONE_NAME_TOO_LONG, ZONE_DNS_NAME1, ZONE_DESCRIPTION1); private static final ZoneInfo ZONE_DNS_NO_PERIOD = ZoneInfo.of(ZONE_NAME1, ZONE_DNS_NAME_NO_PERIOD, ZONE_DESCRIPTION1); private static final RecordSet A_RECORD_ZONE1 = RecordSet.newBuilder("www." + ZONE1.getDnsName(), RecordSet.Type.A) .setRecords(ImmutableList.of("123.123.55.1")) .setTtl(25, TimeUnit.SECONDS) .build(); private static final RecordSet AAAA_RECORD_ZONE1 = RecordSet.newBuilder("www." + ZONE1.getDnsName(), RecordSet.Type.AAAA) .setRecords(ImmutableList.of("ed:ed:12:aa:36:3:3:105")) .setTtl(25, TimeUnit.SECONDS) .build(); private static final ChangeRequestInfo CHANGE_ADD_ZONE1 = ChangeRequest.newBuilder().add(A_RECORD_ZONE1).add(AAAA_RECORD_ZONE1).build(); private static final ChangeRequestInfo CHANGE_DELETE_ZONE1 = ChangeRequest.newBuilder().delete(A_RECORD_ZONE1).delete(AAAA_RECORD_ZONE1).build(); private static final List<String> ZONE_NAMES = ImmutableList.of(ZONE_NAME1, ZONE_NAME_EMPTY_DESCRIPTION); @Rule public Timeout globalTimeout = Timeout.seconds(300); private static void clear() { for (String zoneName : ZONE_NAMES) { Zone zone = DNS.getZone(zoneName); if (zone != null) { /* We wait for all changes to complete before retrieving a list of DNS records to be deleted. Waiting is necessary as changes potentially might create more records between when the list has been retrieved and executing the subsequent delete operation. */ Iterator<ChangeRequest> iterator = zone.listChangeRequests().iterateAll().iterator(); while (iterator.hasNext()) { waitForChangeToComplete(zoneName, iterator.next().getGeneratedId()); } Iterator<RecordSet> recordSetIterator = zone.listRecordSets().iterateAll().iterator(); List<RecordSet> toDelete = new LinkedList<>(); while (recordSetIterator.hasNext()) { RecordSet recordSet = recordSetIterator.next(); if (!ImmutableList.of(RecordSet.Type.NS, RecordSet.Type.SOA) .contains(recordSet.getType())) { toDelete.add(recordSet); } } if (!toDelete.isEmpty()) { ChangeRequest deletion = zone.applyChangeRequest(ChangeRequest.newBuilder().setDeletions(toDelete).build()); waitForChangeToComplete(zone.getName(), deletion.getGeneratedId()); } zone.delete(); } } } private static List<Zone> filter(Iterator<Zone> iterator) { List<Zone> result = new LinkedList<>(); while (iterator.hasNext()) { Zone zone = iterator.next(); if (ZONE_NAMES.contains(zone.getName())) { result.add(zone); } } return result; } @BeforeClass public static void before() { clear(); } @AfterClass public static void after() { clear(); } private static void assertEqChangesIgnoreStatus(ChangeRequest expected, ChangeRequest actual) { assertEquals(expected.getAdditions(), actual.getAdditions()); assertEquals(expected.getDeletions(), actual.getDeletions()); assertEquals(expected.getGeneratedId(), actual.getGeneratedId()); assertEquals(expected.getStartTimeMillis(), actual.getStartTimeMillis()); } private static void waitForChangeToComplete(String zoneName, String changeId) { ChangeRequest changeRequest = DNS.getChangeRequest( zoneName, changeId, Dns.ChangeRequestOption.fields(ChangeRequestField.STATUS)); waitForChangeToComplete(changeRequest); } private static void waitForChangeToComplete(ChangeRequest changeRequest) { while (!changeRequest.isDone()) { try { Thread.sleep(500); } catch (InterruptedException e) { fail("Thread was interrupted while waiting for change processing."); } } } @Test public void testCreateValidZone() { try { Zone created = DNS.create(ZONE1); assertEquals(ZONE1.getDescription(), created.getDescription()); assertEquals(ZONE1.getDnsName(), created.getDnsName()); assertEquals(ZONE1.getName(), created.getName()); assertNotNull(created.getCreationTimeMillis()); assertNotNull(created.getNameServers()); assertNull(created.getNameServerSet()); assertNotNull(created.getGeneratedId()); Zone retrieved = DNS.getZone(ZONE1.getName()); assertEquals(created, retrieved); created = DNS.create(ZONE_EMPTY_DESCRIPTION); assertEquals(ZONE_EMPTY_DESCRIPTION.getDescription(), created.getDescription()); assertEquals(ZONE_EMPTY_DESCRIPTION.getDnsName(), created.getDnsName()); assertEquals(ZONE_EMPTY_DESCRIPTION.getName(), created.getName()); assertNotNull(created.getCreationTimeMillis()); assertNotNull(created.getNameServers()); assertNull(created.getNameServerSet()); assertNotNull(created.getGeneratedId()); retrieved = DNS.getZone(ZONE_EMPTY_DESCRIPTION.getName()); assertEquals(created, retrieved); } finally { DNS.delete(ZONE1.getName()); DNS.delete(ZONE_EMPTY_DESCRIPTION.getName()); } } @Test public void testCreateZoneWithErrors() { try { try { DNS.create(ZONE_NAME_ERROR); fail("Zone name is too long. The service returns an error."); } catch (DnsException ex) { // expected assertFalse(ex.isRetryable()); } try { DNS.create(ZONE_DNS_NO_PERIOD); fail("Zone name is missing a period. The service returns an error."); } catch (DnsException ex) { // expected assertFalse(ex.isRetryable()); } } finally { DNS.delete(ZONE_NAME_ERROR.getName()); DNS.delete(ZONE_DNS_NO_PERIOD.getName()); } } @Test public void testCreateZoneWithOptions() { try { Zone created = DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.CREATION_TIME)); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNotNull(created.getCreationTimeMillis()); assertNull(created.getDescription()); assertNull(created.getDnsName()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNull(created.getNameServerSet()); assertNull(created.getGeneratedId()); created.delete(); created = DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.DESCRIPTION)); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertEquals(ZONE1.getDescription(), created.getDescription()); assertNull(created.getDnsName()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNull(created.getNameServerSet()); assertNull(created.getGeneratedId()); created.delete(); created = DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.DNS_NAME)); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertEquals(ZONE1.getDnsName(), created.getDnsName()); assertNull(created.getDescription()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNull(created.getNameServerSet()); assertNull(created.getGeneratedId()); created.delete(); created = DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME)); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertNull(created.getDnsName()); assertNull(created.getDescription()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNull(created.getNameServerSet()); assertNull(created.getGeneratedId()); created.delete(); created = DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME_SERVER_SET)); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertNull(created.getDnsName()); assertNull(created.getDescription()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNull(created.getNameServerSet()); // we did not set it assertNull(created.getGeneratedId()); created.delete(); created = DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME_SERVERS)); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertNull(created.getDnsName()); assertNull(created.getDescription()); assertFalse(created.getNameServers().isEmpty()); assertNull(created.getNameServerSet()); assertNull(created.getGeneratedId()); created.delete(); created = DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.ZONE_ID)); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertNull(created.getDnsName()); assertNull(created.getDescription()); assertNotNull(created.getNameServers()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNotNull(created.getGeneratedId()); created.delete(); // combination of multiple things created = DNS.create( ZONE1, Dns.ZoneOption.fields( ZoneField.ZONE_ID, ZoneField.NAME_SERVERS, ZoneField.NAME_SERVER_SET, ZoneField.DESCRIPTION)); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertNull(created.getDnsName()); assertEquals(ZONE1.getDescription(), created.getDescription()); assertFalse(created.getNameServers().isEmpty()); assertNull(created.getNameServerSet()); // we did not set it assertNotNull(created.getGeneratedId()); } finally { DNS.delete(ZONE1.getName()); } } @Test public void testGetZone() { try { DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME)); Zone created = DNS.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.CREATION_TIME)); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNotNull(created.getCreationTimeMillis()); assertNull(created.getDescription()); assertNull(created.getDnsName()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNull(created.getNameServerSet()); assertNull(created.getGeneratedId()); created = DNS.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.DESCRIPTION)); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertEquals(ZONE1.getDescription(), created.getDescription()); assertNull(created.getDnsName()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNull(created.getNameServerSet()); assertNull(created.getGeneratedId()); created = DNS.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.DNS_NAME)); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertEquals(ZONE1.getDnsName(), created.getDnsName()); assertNull(created.getDescription()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNull(created.getNameServerSet()); assertNull(created.getGeneratedId()); created = DNS.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.NAME)); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertNull(created.getDnsName()); assertNull(created.getDescription()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNull(created.getNameServerSet()); assertNull(created.getGeneratedId()); created = DNS.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.NAME_SERVER_SET)); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertNull(created.getDnsName()); assertNull(created.getDescription()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNull(created.getNameServerSet()); // we did not set it assertNull(created.getGeneratedId()); created = DNS.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.NAME_SERVERS)); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertNull(created.getDnsName()); assertNull(created.getDescription()); assertFalse(created.getNameServers().isEmpty()); assertNull(created.getNameServerSet()); assertNull(created.getGeneratedId()); created = DNS.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.ZONE_ID)); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertNull(created.getDnsName()); assertNull(created.getDescription()); assertNotNull(created.getNameServers()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNotNull(created.getGeneratedId()); // combination of multiple things created = DNS.getZone( ZONE1.getName(), Dns.ZoneOption.fields( ZoneField.ZONE_ID, ZoneField.NAME_SERVERS, ZoneField.NAME_SERVER_SET, ZoneField.DESCRIPTION)); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertNull(created.getDnsName()); assertEquals(ZONE1.getDescription(), created.getDescription()); assertFalse(created.getNameServers().isEmpty()); assertNull(created.getNameServerSet()); // we did not set it assertNotNull(created.getGeneratedId()); } finally { DNS.delete(ZONE1.getName()); } } @Test public void testListZones() { try { List<Zone> zones = filter(DNS.listZones().iterateAll().iterator()); assertEquals(0, zones.size()); // some zones exists Zone created = DNS.create(ZONE1); zones = filter(DNS.listZones().iterateAll().iterator()); assertEquals(created, zones.get(0)); assertEquals(1, zones.size()); created = DNS.create(ZONE_EMPTY_DESCRIPTION); zones = filter(DNS.listZones().iterateAll().iterator()); assertEquals(2, zones.size()); assertTrue(zones.contains(created)); // error in options try { DNS.listZones(Dns.ZoneListOption.pageSize(0)); fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.getCode()); assertFalse(ex.isRetryable()); } try { DNS.listZones(Dns.ZoneListOption.pageSize(-1)); fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.getCode()); assertFalse(ex.isRetryable()); } // ok size zones = filter(DNS.listZones(Dns.ZoneListOption.pageSize(1000)).iterateAll().iterator()); assertEquals(2, zones.size()); // we still have only 2 zones // dns name problems try { DNS.listZones(Dns.ZoneListOption.dnsName("aaaaa")); fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.getCode()); assertFalse(ex.isRetryable()); } // ok name zones = filter( DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.getDnsName())) .iterateAll() .iterator()); assertEquals(1, zones.size()); // field options Iterator<Zone> zoneIterator = DNS.listZones( Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(ZoneField.ZONE_ID)) .iterateAll() .iterator(); Zone zone = zoneIterator.next(); assertNull(zone.getCreationTimeMillis()); assertNotNull(zone.getName()); assertNull(zone.getDnsName()); assertNull(zone.getDescription()); assertNull(zone.getNameServerSet()); assertTrue(zone.getNameServers().isEmpty()); assertNotNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); zoneIterator = DNS.listZones( Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(ZoneField.CREATION_TIME)) .iterateAll() .iterator(); zone = zoneIterator.next(); assertNotNull(zone.getCreationTimeMillis()); assertNotNull(zone.getName()); assertNull(zone.getDnsName()); assertNull(zone.getDescription()); assertNull(zone.getNameServerSet()); assertTrue(zone.getNameServers().isEmpty()); assertNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); zoneIterator = DNS.listZones( Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(ZoneField.DNS_NAME)) .iterateAll() .iterator(); zone = zoneIterator.next(); assertNull(zone.getCreationTimeMillis()); assertNotNull(zone.getName()); assertNotNull(zone.getDnsName()); assertNull(zone.getDescription()); assertNull(zone.getNameServerSet()); assertTrue(zone.getNameServers().isEmpty()); assertNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); zoneIterator = DNS.listZones( Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(ZoneField.DESCRIPTION)) .iterateAll() .iterator(); zone = zoneIterator.next(); assertNull(zone.getCreationTimeMillis()); assertNotNull(zone.getName()); assertNull(zone.getDnsName()); assertNotNull(zone.getDescription()); assertNull(zone.getNameServerSet()); assertTrue(zone.getNameServers().isEmpty()); assertNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); zoneIterator = DNS.listZones( Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(ZoneField.NAME_SERVERS)) .iterateAll() .iterator(); zone = zoneIterator.next(); assertNull(zone.getCreationTimeMillis()); assertNotNull(zone.getName()); assertNull(zone.getDnsName()); assertNull(zone.getDescription()); assertNull(zone.getNameServerSet()); assertFalse(zone.getNameServers().isEmpty()); assertNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); zoneIterator = DNS.listZones( Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(ZoneField.NAME_SERVER_SET)) .iterateAll() .iterator(); zone = zoneIterator.next(); assertNull(zone.getCreationTimeMillis()); assertNotNull(zone.getName()); assertNull(zone.getDnsName()); assertNull(zone.getDescription()); assertNull(zone.getNameServerSet()); // we cannot set it using google-cloud assertTrue(zone.getNameServers().isEmpty()); assertNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); // several combined zones = filter( DNS.listZones( Dns.ZoneListOption.fields(ZoneField.ZONE_ID, ZoneField.DESCRIPTION), Dns.ZoneListOption.pageSize(1)) .iterateAll() .iterator()); assertEquals(2, zones.size()); for (Zone current : zones) { assertNull(current.getCreationTimeMillis()); assertNotNull(current.getName()); assertNull(current.getDnsName()); assertNotNull(current.getDescription()); assertNull(current.getNameServerSet()); assertTrue(zone.getNameServers().isEmpty()); assertNotNull(current.getGeneratedId()); } } finally { DNS.delete(ZONE1.getName()); DNS.delete(ZONE_EMPTY_DESCRIPTION.getName()); } } @Test public void testDeleteZone() { try { Zone created = DNS.create(ZONE1); assertEquals(created, DNS.getZone(ZONE1.getName())); DNS.delete(ZONE1.getName()); assertNull(DNS.getZone(ZONE1.getName())); } finally { DNS.delete(ZONE1.getName()); } } @Test public void testCreateChange() { try { DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME)); ChangeRequest created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1); assertEquals(CHANGE_ADD_ZONE1.getAdditions(), created.getAdditions()); assertNotNull(created.getStartTimeMillis()); assertTrue(created.getDeletions().isEmpty()); assertNotNull(created.getGeneratedId()); assertTrue( ImmutableList.of(ChangeRequest.Status.PENDING, ChangeRequest.Status.DONE) .contains(created.status())); assertEqChangesIgnoreStatus(created, DNS.getChangeRequest(ZONE1.getName(), "1")); waitForChangeToComplete(created); created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1); waitForChangeToComplete(created); // with options created = DNS.applyChangeRequest( ZONE1.getName(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.ID)); assertTrue(created.getAdditions().isEmpty()); assertNull(created.getStartTimeMillis()); assertTrue(created.getDeletions().isEmpty()); assertNotNull(created.getGeneratedId()); assertNull(created.status()); waitForChangeToComplete(created); created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1); waitForChangeToComplete(created); created = DNS.applyChangeRequest( ZONE1.getName(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.STATUS)); assertTrue(created.getAdditions().isEmpty()); assertNull(created.getStartTimeMillis()); assertTrue(created.getDeletions().isEmpty()); assertNotNull(created.getGeneratedId()); assertNotNull(created.status()); waitForChangeToComplete(created); created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1); waitForChangeToComplete(created); created = DNS.applyChangeRequest( ZONE1.getName(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.START_TIME)); assertTrue(created.getAdditions().isEmpty()); assertNotNull(created.getStartTimeMillis()); assertTrue(created.getDeletions().isEmpty()); assertNotNull(created.getGeneratedId()); assertNull(created.status()); waitForChangeToComplete(created); created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1); waitForChangeToComplete(created); created = DNS.applyChangeRequest( ZONE1.getName(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.ADDITIONS)); assertEquals(CHANGE_ADD_ZONE1.getAdditions(), created.getAdditions()); assertNull(created.getStartTimeMillis()); assertTrue(created.getDeletions().isEmpty()); assertNotNull(created.getGeneratedId()); assertNull(created.status()); // finishes with delete otherwise we cannot delete the zone waitForChangeToComplete(created); created = DNS.applyChangeRequest( ZONE1.getName(), CHANGE_DELETE_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.DELETIONS)); waitForChangeToComplete(created); assertEquals(CHANGE_DELETE_ZONE1.getDeletions(), created.getDeletions()); assertNull(created.getStartTimeMillis()); assertTrue(created.getAdditions().isEmpty()); assertNotNull(created.getGeneratedId()); assertNull(created.status()); waitForChangeToComplete(created); } finally { clear(); } } @Test public void testInvalidChangeRequest() { Zone zone = DNS.create(ZONE1); RecordSet validA = RecordSet.newBuilder("subdomain." + zone.getDnsName(), RecordSet.Type.A) .setRecords(ImmutableList.of("0.255.1.5")) .build(); boolean recordAdded = false; try { ChangeRequestInfo validChange = ChangeRequest.newBuilder().add(validA).build(); zone.applyChangeRequest(validChange); recordAdded = true; try { zone.applyChangeRequest(validChange); fail("Created a record set which already exists."); } catch (DnsException ex) { // expected assertFalse(ex.isRetryable()); assertEquals(409, ex.getCode()); } // delete with field mismatch RecordSet mismatch = validA.toBuilder().setTtl(20, TimeUnit.SECONDS).build(); ChangeRequestInfo deletion = ChangeRequest.newBuilder().delete(mismatch).build(); try { zone.applyChangeRequest(deletion); fail("Deleted a record set without a complete match."); } catch (DnsException ex) { // expected assertEquals(412, ex.getCode()); assertFalse(ex.isRetryable()); } // delete and add SOA Iterator<RecordSet> recordSetIterator = zone.listRecordSets().iterateAll().iterator(); LinkedList<RecordSet> deletions = new LinkedList<>(); LinkedList<RecordSet> additions = new LinkedList<>(); while (recordSetIterator.hasNext()) { RecordSet recordSet = recordSetIterator.next(); if (recordSet.getType() == RecordSet.Type.SOA) { deletions.add(recordSet); // the subdomain is necessary to get 400 instead of 412 RecordSet copy = recordSet.toBuilder().setName("x." + recordSet.getName()).build(); additions.add(copy); break; } } deletion = deletion.toBuilder().setDeletions(deletions).build(); ChangeRequestInfo addition = ChangeRequest.newBuilder().setAdditions(additions).build(); try { zone.applyChangeRequest(deletion); fail("Deleted SOA."); } catch (DnsException ex) { // expected assertFalse(ex.isRetryable()); assertEquals(400, ex.getCode()); } try { zone.applyChangeRequest(addition); fail("Added second SOA."); } catch (DnsException ex) { // expected assertFalse(ex.isRetryable()); assertEquals(400, ex.getCode()); } } finally { if (recordAdded) { ChangeRequestInfo deletion = ChangeRequest.newBuilder().delete(validA).build(); ChangeRequest request = zone.applyChangeRequest(deletion); waitForChangeToComplete(zone.getName(), request.getGeneratedId()); } zone.delete(); } } @Test public void testListChanges() { try { // no such zone exists try { DNS.listChangeRequests(ZONE1.getName()); fail(); } catch (DnsException ex) { // expected assertEquals(404, ex.getCode()); assertFalse(ex.isRetryable()); } // zone exists but has no changes DNS.create(ZONE1); ImmutableList<ChangeRequest> changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.getName()).iterateAll()); assertEquals(1, changes.size()); // default change creating SOA and NS // zone has changes ChangeRequest change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1); waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1); waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1); waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1); waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.getName()).iterateAll()); assertEquals(5, changes.size()); // error in options try { DNS.listChangeRequests(ZONE1.getName(), Dns.ChangeRequestListOption.pageSize(0)); fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.getCode()); assertFalse(ex.isRetryable()); } try { DNS.listChangeRequests(ZONE1.getName(), Dns.ChangeRequestListOption.pageSize(-1)); fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.getCode()); assertFalse(ex.isRetryable()); } // sorting order ImmutableList<ChangeRequest> ascending = ImmutableList.copyOf( DNS.listChangeRequests( ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING)) .iterateAll()); ImmutableList<ChangeRequest> descending = ImmutableList.copyOf( DNS.listChangeRequests( ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.DESCENDING)) .iterateAll()); int size = 5; assertEquals(size, descending.size()); assertEquals(size, ascending.size()); for (int i = 0; i < size; i++) { assertEquals(descending.get(i), ascending.get(size - i - 1)); } // field options changes = ImmutableList.copyOf( DNS.listChangeRequests( ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), Dns.ChangeRequestListOption.fields(ChangeRequestField.ADDITIONS)) .iterateAll()); change = changes.get(1); assertEquals(CHANGE_ADD_ZONE1.getAdditions(), change.getAdditions()); assertTrue(change.getDeletions().isEmpty()); assertNotNull(change.getGeneratedId()); assertNull(change.getStartTimeMillis()); assertNull(change.status()); changes = ImmutableList.copyOf( DNS.listChangeRequests( ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), Dns.ChangeRequestListOption.fields(ChangeRequestField.DELETIONS)) .iterateAll()); change = changes.get(2); assertTrue(change.getAdditions().isEmpty()); assertNotNull(change.getDeletions()); assertNotNull(change.getGeneratedId()); assertNull(change.getStartTimeMillis()); assertNull(change.status()); changes = ImmutableList.copyOf( DNS.listChangeRequests( ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), Dns.ChangeRequestListOption.fields(ChangeRequestField.ID)) .iterateAll()); change = changes.get(1); assertTrue(change.getAdditions().isEmpty()); assertTrue(change.getDeletions().isEmpty()); assertNotNull(change.getGeneratedId()); assertNull(change.getStartTimeMillis()); assertNull(change.status()); changes = ImmutableList.copyOf( DNS.listChangeRequests( ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), Dns.ChangeRequestListOption.fields(ChangeRequestField.START_TIME)) .iterateAll()); change = changes.get(1); assertTrue(change.getAdditions().isEmpty()); assertTrue(change.getDeletions().isEmpty()); assertNotNull(change.getGeneratedId()); assertNotNull(change.getStartTimeMillis()); assertNull(change.status()); changes = ImmutableList.copyOf( DNS.listChangeRequests( ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), Dns.ChangeRequestListOption.fields(ChangeRequestField.STATUS)) .iterateAll()); change = changes.get(1); assertTrue(change.getAdditions().isEmpty()); assertTrue(change.getDeletions().isEmpty()); assertNotNull(change.getGeneratedId()); assertNull(change.getStartTimeMillis()); assertEquals(ChangeRequest.Status.DONE, change.status()); } finally { clear(); } } @Test public void testGetChange() { try { Zone zone = DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME)); ChangeRequest created = zone.applyChangeRequest(CHANGE_ADD_ZONE1); ChangeRequest retrieved = DNS.getChangeRequest(zone.getName(), created.getGeneratedId()); assertEqChangesIgnoreStatus(created, retrieved); waitForChangeToComplete(zone.getName(), created.getGeneratedId()); zone.applyChangeRequest(CHANGE_DELETE_ZONE1); // with options created = zone.applyChangeRequest( CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.ID)); retrieved = DNS.getChangeRequest( zone.getName(), created.getGeneratedId(), Dns.ChangeRequestOption.fields(ChangeRequestField.ID)); assertEqChangesIgnoreStatus(created, retrieved); waitForChangeToComplete(zone.getName(), created.getGeneratedId()); zone.applyChangeRequest(CHANGE_DELETE_ZONE1); created = zone.applyChangeRequest( CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.STATUS)); retrieved = DNS.getChangeRequest( zone.getName(), created.getGeneratedId(), Dns.ChangeRequestOption.fields(ChangeRequestField.STATUS)); assertEqChangesIgnoreStatus(created, retrieved); waitForChangeToComplete(zone.getName(), created.getGeneratedId()); zone.applyChangeRequest(CHANGE_DELETE_ZONE1); created = zone.applyChangeRequest( CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.START_TIME)); retrieved = DNS.getChangeRequest( zone.getName(), created.getGeneratedId(), Dns.ChangeRequestOption.fields(ChangeRequestField.START_TIME)); assertEqChangesIgnoreStatus(created, retrieved); waitForChangeToComplete(zone.getName(), created.getGeneratedId()); zone.applyChangeRequest(CHANGE_DELETE_ZONE1); created = zone.applyChangeRequest( CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.ADDITIONS)); retrieved = DNS.getChangeRequest( zone.getName(), created.getGeneratedId(), Dns.ChangeRequestOption.fields(ChangeRequestField.ADDITIONS)); assertEqChangesIgnoreStatus(created, retrieved); waitForChangeToComplete(zone.getName(), created.getGeneratedId()); // finishes with delete otherwise we cannot delete the zone created = zone.applyChangeRequest( CHANGE_DELETE_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.DELETIONS)); retrieved = DNS.getChangeRequest( zone.getName(), created.getGeneratedId(), Dns.ChangeRequestOption.fields(ChangeRequestField.DELETIONS)); assertEqChangesIgnoreStatus(created, retrieved); waitForChangeToComplete(zone.getName(), created.getGeneratedId()); } finally { clear(); } } @Test public void testGetProject() { // fetches all fields ProjectInfo project = DNS.getProject(); assertNotNull(project.getQuota()); // options project = DNS.getProject(Dns.ProjectOption.fields(ProjectField.QUOTA)); assertNotNull(project.getQuota()); project = DNS.getProject(Dns.ProjectOption.fields(ProjectField.PROJECT_ID)); assertNull(project.getQuota()); project = DNS.getProject(Dns.ProjectOption.fields(ProjectField.PROJECT_NUMBER)); assertNull(project.getQuota()); project = DNS.getProject( Dns.ProjectOption.fields( ProjectField.PROJECT_NUMBER, ProjectField.QUOTA, ProjectField.PROJECT_ID)); assertNotNull(project.getQuota()); } @Test public void testListDnsRecords() { try { Zone zone = DNS.create(ZONE1); ImmutableList<RecordSet> recordSets = ImmutableList.copyOf(DNS.listRecordSets(zone.getName()).iterateAll()); assertEquals(2, recordSets.size()); ImmutableList<RecordSet.Type> defaultRecords = ImmutableList.of(RecordSet.Type.NS, RecordSet.Type.SOA); for (RecordSet recordSet : recordSets) { assertTrue(defaultRecords.contains(recordSet.getType())); } // field options Iterator<RecordSet> recordSetIterator = DNS.listRecordSets(zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.TTL)) .iterateAll() .iterator(); int counter = 0; while (recordSetIterator.hasNext()) { RecordSet recordSet = recordSetIterator.next(); assertEquals(recordSets.get(counter).getTtl(), recordSet.getTtl()); assertEquals(recordSets.get(counter).getName(), recordSet.getName()); assertEquals(recordSets.get(counter).getType(), recordSet.getType()); assertTrue(recordSet.getRecords().isEmpty()); counter++; } assertEquals(2, counter); recordSetIterator = DNS.listRecordSets(zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.NAME)) .iterateAll() .iterator(); counter = 0; while (recordSetIterator.hasNext()) { RecordSet recordSet = recordSetIterator.next(); assertEquals(recordSets.get(counter).getName(), recordSet.getName()); assertEquals(recordSets.get(counter).getType(), recordSet.getType()); assertTrue(recordSet.getRecords().isEmpty()); assertNull(recordSet.getTtl()); counter++; } assertEquals(2, counter); recordSetIterator = DNS.listRecordSets( zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.DNS_RECORDS)) .iterateAll() .iterator(); counter = 0; while (recordSetIterator.hasNext()) { RecordSet recordSet = recordSetIterator.next(); assertEquals(recordSets.get(counter).getRecords(), recordSet.getRecords()); assertEquals(recordSets.get(counter).getName(), recordSet.getName()); assertEquals(recordSets.get(counter).getType(), recordSet.getType()); assertNull(recordSet.getTtl()); counter++; } assertEquals(2, counter); recordSetIterator = DNS.listRecordSets( zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.TYPE), Dns.RecordSetListOption.pageSize(1)) .iterateAll() .iterator(); // also test paging counter = 0; while (recordSetIterator.hasNext()) { RecordSet recordSet = recordSetIterator.next(); assertEquals(recordSets.get(counter).getType(), recordSet.getType()); assertEquals(recordSets.get(counter).getName(), recordSet.getName()); assertTrue(recordSet.getRecords().isEmpty()); assertNull(recordSet.getTtl()); counter++; } assertEquals(2, counter); // test page size Page<RecordSet> recordSetPage = DNS.listRecordSets( zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.TYPE), Dns.RecordSetListOption.pageSize(1)); assertEquals(1, ImmutableList.copyOf(recordSetPage.getValues().iterator()).size()); // test name filter ChangeRequest change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1); waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); recordSetIterator = DNS.listRecordSets( ZONE1.getName(), Dns.RecordSetListOption.dnsName(A_RECORD_ZONE1.getName())) .iterateAll() .iterator(); counter = 0; while (recordSetIterator.hasNext()) { RecordSet recordSet = recordSetIterator.next(); assertTrue( ImmutableList.of(A_RECORD_ZONE1.getType(), AAAA_RECORD_ZONE1.getType()) .contains(recordSet.getType())); counter++; } assertEquals(2, counter); // test type filter waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); recordSetIterator = DNS.listRecordSets( ZONE1.getName(), Dns.RecordSetListOption.dnsName(A_RECORD_ZONE1.getName()), Dns.RecordSetListOption.type(A_RECORD_ZONE1.getType())) .iterateAll() .iterator(); counter = 0; while (recordSetIterator.hasNext()) { RecordSet recordSet = recordSetIterator.next(); assertEquals(A_RECORD_ZONE1, recordSet); counter++; } assertEquals(1, counter); change = zone.applyChangeRequest(CHANGE_DELETE_ZONE1); // check wrong arguments try { // name is not set DNS.listRecordSets(ZONE1.getName(), Dns.RecordSetListOption.type(A_RECORD_ZONE1.getType())); fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.getCode()); assertFalse(ex.isRetryable()); } try { DNS.listRecordSets(ZONE1.getName(), Dns.RecordSetListOption.pageSize(0)); fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.getCode()); assertFalse(ex.isRetryable()); } try { DNS.listRecordSets(ZONE1.getName(), Dns.RecordSetListOption.pageSize(-1)); fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.getCode()); assertFalse(ex.isRetryable()); } waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); } finally { clear(); } } @Test public void testListZonesBatch() { try { DnsBatch batch = DNS.batch(); DnsBatchResult<Page<Zone>> result = batch.listZones(); batch.submit(); List<Zone> zones = filter(result.get().iterateAll().iterator()); assertEquals(0, zones.size()); // some zones exists Zone firstZone = DNS.create(ZONE1); batch = DNS.batch(); result = batch.listZones(); batch.submit(); zones = filter(result.get().iterateAll().iterator()); assertEquals(1, zones.size()); assertEquals(firstZone, zones.get(0)); Zone created = DNS.create(ZONE_EMPTY_DESCRIPTION); batch = DNS.batch(); result = batch.listZones(); DnsBatchResult<Page<Zone>> zeroSizeError = batch.listZones(Dns.ZoneListOption.pageSize(0)); DnsBatchResult<Page<Zone>> negativeSizeError = batch.listZones(Dns.ZoneListOption.pageSize(-1)); DnsBatchResult<Page<Zone>> okSize = batch.listZones(Dns.ZoneListOption.pageSize(1)); DnsBatchResult<Page<Zone>> nameError = batch.listZones(Dns.ZoneListOption.dnsName("aaaaa")); DnsBatchResult<Page<Zone>> okName = batch.listZones(Dns.ZoneListOption.dnsName(ZONE1.getDnsName())); DnsBatchResult<Page<Zone>> idResult = batch.listZones( Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(ZoneField.ZONE_ID)); DnsBatchResult<Page<Zone>> timeResult = batch.listZones( Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(ZoneField.CREATION_TIME)); DnsBatchResult<Page<Zone>> dnsNameResult = batch.listZones( Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(ZoneField.DNS_NAME)); DnsBatchResult<Page<Zone>> descriptionResult = batch.listZones( Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(ZoneField.DESCRIPTION)); DnsBatchResult<Page<Zone>> nameServersResult = batch.listZones( Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(ZoneField.NAME_SERVERS)); DnsBatchResult<Page<Zone>> nameServerSetResult = batch.listZones( Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(ZoneField.NAME_SERVER_SET)); DnsBatchResult<Page<Zone>> combinationResult = batch.listZones( Dns.ZoneListOption.fields(ZoneField.ZONE_ID, ZoneField.DESCRIPTION), Dns.ZoneListOption.pageSize(1)); batch.submit(); zones = filter(result.get().iterateAll().iterator()); assertEquals(2, zones.size()); assertTrue(zones.contains(firstZone)); assertTrue(zones.contains(created)); // error in options try { zeroSizeError.get(); fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.getCode()); assertFalse(ex.isRetryable()); } try { negativeSizeError.get(); fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.getCode()); assertFalse(ex.isRetryable()); } // ok size assertEquals(1, Iterables.size(okSize.get().getValues())); // dns name problems try { nameError.get(); fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.getCode()); assertFalse(ex.isRetryable()); } // ok name zones = filter(okName.get().iterateAll().iterator()); assertEquals(1, zones.size()); // field options Iterator<Zone> zoneIterator = idResult.get().iterateAll().iterator(); Zone zone = zoneIterator.next(); assertNull(zone.getCreationTimeMillis()); assertNotNull(zone.getName()); assertNull(zone.getDnsName()); assertNull(zone.getDescription()); assertNull(zone.getNameServerSet()); assertTrue(zone.getNameServers().isEmpty()); assertNotNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); zoneIterator = timeResult.get().iterateAll().iterator(); zone = zoneIterator.next(); assertNotNull(zone.getCreationTimeMillis()); assertNotNull(zone.getName()); assertNull(zone.getDnsName()); assertNull(zone.getDescription()); assertNull(zone.getNameServerSet()); assertTrue(zone.getNameServers().isEmpty()); assertNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); zoneIterator = dnsNameResult.get().iterateAll().iterator(); zone = zoneIterator.next(); assertNull(zone.getCreationTimeMillis()); assertNotNull(zone.getName()); assertNotNull(zone.getDnsName()); assertNull(zone.getDescription()); assertNull(zone.getNameServerSet()); assertTrue(zone.getNameServers().isEmpty()); assertNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); zoneIterator = descriptionResult.get().iterateAll().iterator(); zone = zoneIterator.next(); assertNull(zone.getCreationTimeMillis()); assertNotNull(zone.getName()); assertNull(zone.getDnsName()); assertNotNull(zone.getDescription()); assertNull(zone.getNameServerSet()); assertTrue(zone.getNameServers().isEmpty()); assertNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); zoneIterator = nameServersResult.get().iterateAll().iterator(); zone = zoneIterator.next(); assertNull(zone.getCreationTimeMillis()); assertNotNull(zone.getName()); assertNull(zone.getDnsName()); assertNull(zone.getDescription()); assertNull(zone.getNameServerSet()); assertFalse(zone.getNameServers().isEmpty()); assertNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); zoneIterator = nameServerSetResult.get().iterateAll().iterator(); zone = zoneIterator.next(); assertNull(zone.getCreationTimeMillis()); assertNotNull(zone.getName()); assertNull(zone.getDnsName()); assertNull(zone.getDescription()); assertNull(zone.getNameServerSet()); // we cannot set it using google-cloud assertTrue(zone.getNameServers().isEmpty()); assertNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); // several combined zones = filter(combinationResult.get().iterateAll().iterator()); assertEquals(2, zones.size()); for (Zone current : zones) { assertNull(current.getCreationTimeMillis()); assertNotNull(current.getName()); assertNull(current.getDnsName()); assertNotNull(current.getDescription()); assertNull(current.getNameServerSet()); assertTrue(zone.getNameServers().isEmpty()); assertNotNull(current.getGeneratedId()); } } finally { DNS.delete(ZONE1.getName()); DNS.delete(ZONE_EMPTY_DESCRIPTION.getName()); } } @Test public void testCreateValidZoneBatch() { try { DnsBatch batch = DNS.batch(); DnsBatchResult<Zone> completeZoneResult = batch.createZone(ZONE1); DnsBatchResult<Zone> partialZoneResult = batch.createZone(ZONE_EMPTY_DESCRIPTION); batch.submit(); Zone created = completeZoneResult.get(); assertEquals(ZONE1.getDescription(), created.getDescription()); assertEquals(ZONE1.getDnsName(), created.getDnsName()); assertEquals(ZONE1.getName(), created.getName()); assertNotNull(created.getCreationTimeMillis()); assertNotNull(created.getNameServers()); assertNull(created.getNameServerSet()); assertNotNull(created.getGeneratedId()); Zone retrieved = DNS.getZone(ZONE1.getName()); assertEquals(created, retrieved); created = partialZoneResult.get(); assertEquals(ZONE_EMPTY_DESCRIPTION.getDescription(), created.getDescription()); assertEquals(ZONE_EMPTY_DESCRIPTION.getDnsName(), created.getDnsName()); assertEquals(ZONE_EMPTY_DESCRIPTION.getName(), created.getName()); assertNotNull(created.getCreationTimeMillis()); assertNotNull(created.getNameServers()); assertNull(created.getNameServerSet()); assertNotNull(created.getGeneratedId()); retrieved = DNS.getZone(ZONE_EMPTY_DESCRIPTION.getName()); assertEquals(created, retrieved); } finally { DNS.delete(ZONE1.getName()); DNS.delete(ZONE_EMPTY_DESCRIPTION.getName()); } } @Test public void testCreateZoneWithErrorsBatch() { try { DnsBatch batch = DNS.batch(); DnsBatchResult<Zone> nameErrorResult = batch.createZone(ZONE_NAME_ERROR); DnsBatchResult<Zone> noPeriodResult = batch.createZone(ZONE_DNS_NO_PERIOD); batch.submit(); try { nameErrorResult.get(); fail("Zone name is too long. The service returns an error."); } catch (DnsException ex) { // expected assertFalse(ex.isRetryable()); } try { noPeriodResult.get(); fail("Zone name is missing a period. The service returns an error."); } catch (DnsException ex) { // expected assertFalse(ex.isRetryable()); } } finally { DNS.delete(ZONE_NAME_ERROR.getName()); DNS.delete(ZONE_DNS_NO_PERIOD.getName()); } } @Test public void testCreateZoneWithOptionsBatch() { try { DnsBatch batch = DNS.batch(); DnsBatchResult<Zone> batchResult = batch.createZone(ZONE1, Dns.ZoneOption.fields(ZoneField.CREATION_TIME)); batch.submit(); Zone created = batchResult.get(); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNotNull(created.getCreationTimeMillis()); assertNull(created.getDescription()); assertNull(created.getDnsName()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNull(created.getNameServerSet()); assertNull(created.getGeneratedId()); created.delete(); batch = DNS.batch(); batchResult = batch.createZone(ZONE1, Dns.ZoneOption.fields(ZoneField.DESCRIPTION)); batch.submit(); created = batchResult.get(); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertEquals(ZONE1.getDescription(), created.getDescription()); assertNull(created.getDnsName()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNull(created.getNameServerSet()); assertNull(created.getGeneratedId()); created.delete(); batch = DNS.batch(); batchResult = batch.createZone(ZONE1, Dns.ZoneOption.fields(ZoneField.DNS_NAME)); batch.submit(); created = batchResult.get(); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertEquals(ZONE1.getDnsName(), created.getDnsName()); assertNull(created.getDescription()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNull(created.getNameServerSet()); assertNull(created.getGeneratedId()); created.delete(); batch = DNS.batch(); batchResult = batch.createZone(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME)); batch.submit(); created = batchResult.get(); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertNull(created.getDnsName()); assertNull(created.getDescription()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNull(created.getNameServerSet()); assertNull(created.getGeneratedId()); created.delete(); batch = DNS.batch(); batchResult = batch.createZone(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME_SERVER_SET)); batch.submit(); created = batchResult.get(); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertNull(created.getDnsName()); assertNull(created.getDescription()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNull(created.getNameServerSet()); // we did not set it assertNull(created.getGeneratedId()); created.delete(); batch = DNS.batch(); batchResult = batch.createZone(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME_SERVERS)); batch.submit(); created = batchResult.get(); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertNull(created.getDnsName()); assertNull(created.getDescription()); assertFalse(created.getNameServers().isEmpty()); assertNull(created.getNameServerSet()); assertNull(created.getGeneratedId()); created.delete(); batch = DNS.batch(); batchResult = batch.createZone(ZONE1, Dns.ZoneOption.fields(ZoneField.ZONE_ID)); batch.submit(); created = batchResult.get(); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertNull(created.getDnsName()); assertNull(created.getDescription()); assertNotNull(created.getNameServers()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNotNull(created.getGeneratedId()); created.delete(); batch = DNS.batch(); batchResult = batch.createZone( ZONE1, Dns.ZoneOption.fields( ZoneField.ZONE_ID, ZoneField.NAME_SERVERS, ZoneField.NAME_SERVER_SET, ZoneField.DESCRIPTION)); batch.submit(); // combination of multiple things created = batchResult.get(); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertNull(created.getDnsName()); assertEquals(ZONE1.getDescription(), created.getDescription()); assertFalse(created.getNameServers().isEmpty()); assertNull(created.getNameServerSet()); // we did not set it assertNotNull(created.getGeneratedId()); } finally { DNS.delete(ZONE1.getName()); } } @Test public void testGetZoneBatch() { try { DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME)); DnsBatch batch = DNS.batch(); DnsBatchResult<Zone> timeResult = batch.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.CREATION_TIME)); DnsBatchResult<Zone> descriptionResult = batch.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.DESCRIPTION)); DnsBatchResult<Zone> dnsNameResult = batch.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.DNS_NAME)); DnsBatchResult<Zone> nameResult = batch.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.NAME)); DnsBatchResult<Zone> nameServerSetResult = batch.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.NAME_SERVER_SET)); DnsBatchResult<Zone> nameServersResult = batch.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.NAME_SERVERS)); DnsBatchResult<Zone> idResult = batch.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.ZONE_ID)); DnsBatchResult<Zone> combinationResult = batch.getZone( ZONE1.getName(), Dns.ZoneOption.fields( ZoneField.ZONE_ID, ZoneField.NAME_SERVERS, ZoneField.NAME_SERVER_SET, ZoneField.DESCRIPTION)); batch.submit(); Zone created = timeResult.get(); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNotNull(created.getCreationTimeMillis()); assertNull(created.getDescription()); assertNull(created.getDnsName()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNull(created.getNameServerSet()); assertNull(created.getGeneratedId()); created = descriptionResult.get(); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertEquals(ZONE1.getDescription(), created.getDescription()); assertNull(created.getDnsName()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNull(created.getNameServerSet()); assertNull(created.getGeneratedId()); created = dnsNameResult.get(); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertEquals(ZONE1.getDnsName(), created.getDnsName()); assertNull(created.getDescription()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNull(created.getNameServerSet()); assertNull(created.getGeneratedId()); created = nameResult.get(); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertNull(created.getDnsName()); assertNull(created.getDescription()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNull(created.getNameServerSet()); assertNull(created.getGeneratedId()); created = nameServerSetResult.get(); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertNull(created.getDnsName()); assertNull(created.getDescription()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNull(created.getNameServerSet()); // we did not set it assertNull(created.getGeneratedId()); created = nameServersResult.get(); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertNull(created.getDnsName()); assertNull(created.getDescription()); assertFalse(created.getNameServers().isEmpty()); assertNull(created.getNameServerSet()); assertNull(created.getGeneratedId()); created = idResult.get(); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertNull(created.getDnsName()); assertNull(created.getDescription()); assertNotNull(created.getNameServers()); assertTrue(created.getNameServers().isEmpty()); // never returns null assertNotNull(created.getGeneratedId()); // combination of multiple things created = combinationResult.get(); assertEquals(ZONE1.getName(), created.getName()); // always returned assertNull(created.getCreationTimeMillis()); assertNull(created.getDnsName()); assertEquals(ZONE1.getDescription(), created.getDescription()); assertFalse(created.getNameServers().isEmpty()); assertNull(created.getNameServerSet()); // we did not set it assertNotNull(created.getGeneratedId()); } finally { DNS.delete(ZONE1.getName()); } } @Test public void testDeleteZoneBatch() { try { Zone created = DNS.create(ZONE1); assertEquals(created, DNS.getZone(ZONE1.getName())); DnsBatch batch = DNS.batch(); DnsBatchResult<Boolean> result = batch.deleteZone(ZONE1.getName()); batch.submit(); assertNull(DNS.getZone(ZONE1.getName())); assertTrue(result.get()); } finally { DNS.delete(ZONE1.getName()); } } @Test public void testGetProjectBatch() { // fetches all fields DnsBatch batch = DNS.batch(); DnsBatchResult<ProjectInfo> result = batch.getProject(); DnsBatchResult<ProjectInfo> resultQuota = batch.getProject(Dns.ProjectOption.fields(ProjectField.QUOTA)); DnsBatchResult<ProjectInfo> resultId = batch.getProject(Dns.ProjectOption.fields(ProjectField.PROJECT_ID)); DnsBatchResult<ProjectInfo> resultNumber = batch.getProject(Dns.ProjectOption.fields(ProjectField.PROJECT_NUMBER)); DnsBatchResult<ProjectInfo> resultCombination = batch.getProject( Dns.ProjectOption.fields( ProjectField.PROJECT_NUMBER, ProjectField.QUOTA, ProjectField.PROJECT_ID)); batch.submit(); assertNotNull(result.get().getQuota()); assertNotNull(resultQuota.get().getQuota()); assertNull(resultId.get().getQuota()); assertNull(resultNumber.get().getQuota()); assertNotNull(resultCombination.get().getQuota()); } @Test public void testCreateChangeBatch() { try { DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME)); DnsBatch batch = DNS.batch(); DnsBatchResult<ChangeRequest> result = batch.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1); batch.submit(); ChangeRequest created = result.get(); assertEquals(CHANGE_ADD_ZONE1.getAdditions(), created.getAdditions()); assertNotNull(created.getStartTimeMillis()); assertTrue(created.getDeletions().isEmpty()); assertNotNull(created.getGeneratedId()); assertTrue( ImmutableList.of(ChangeRequest.Status.PENDING, ChangeRequest.Status.DONE) .contains(created.status())); assertEqChangesIgnoreStatus(created, DNS.getChangeRequest(ZONE1.getName(), "1")); waitForChangeToComplete(created); created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1); waitForChangeToComplete(created); // with options batch = DNS.batch(); result = batch.applyChangeRequest( ZONE1.getName(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.ID)); batch.submit(); created = result.get(); assertTrue(created.getAdditions().isEmpty()); assertNull(created.getStartTimeMillis()); assertTrue(created.getDeletions().isEmpty()); assertNotNull(created.getGeneratedId()); assertNull(created.status()); waitForChangeToComplete(created); created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1); waitForChangeToComplete(created); batch = DNS.batch(); result = batch.applyChangeRequest( ZONE1.getName(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.STATUS)); batch.submit(); created = result.get(); assertTrue(created.getAdditions().isEmpty()); assertNull(created.getStartTimeMillis()); assertTrue(created.getDeletions().isEmpty()); assertNotNull(created.getGeneratedId()); assertNotNull(created.status()); waitForChangeToComplete(created); created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1); waitForChangeToComplete(created); batch = DNS.batch(); result = batch.applyChangeRequest( ZONE1.getName(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.START_TIME)); batch.submit(); created = result.get(); assertTrue(created.getAdditions().isEmpty()); assertNotNull(created.getStartTimeMillis()); assertTrue(created.getDeletions().isEmpty()); assertNotNull(created.getGeneratedId()); assertNull(created.status()); waitForChangeToComplete(created); created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1); waitForChangeToComplete(created); batch = DNS.batch(); result = batch.applyChangeRequest( ZONE1.getName(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.ADDITIONS)); batch.submit(); created = result.get(); assertEquals(CHANGE_ADD_ZONE1.getAdditions(), created.getAdditions()); assertNull(created.getStartTimeMillis()); assertTrue(created.getDeletions().isEmpty()); assertNotNull(created.getGeneratedId()); assertNull(created.status()); // finishes with delete otherwise we cannot delete the zone waitForChangeToComplete(created); batch = DNS.batch(); result = batch.applyChangeRequest( ZONE1.getName(), CHANGE_DELETE_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.DELETIONS)); batch.submit(); created = result.get(); waitForChangeToComplete(created); assertEquals(CHANGE_DELETE_ZONE1.getDeletions(), created.getDeletions()); assertNull(created.getStartTimeMillis()); assertTrue(created.getAdditions().isEmpty()); assertNotNull(created.getGeneratedId()); assertNull(created.status()); waitForChangeToComplete(created); } finally { clear(); } } @Test public void testGetChangeBatch() { try { Zone zone = DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME)); ChangeRequest created = zone.applyChangeRequest(CHANGE_ADD_ZONE1); waitForChangeToComplete(zone.getName(), created.getGeneratedId()); DnsBatch batch = DNS.batch(); DnsBatchResult<ChangeRequest> completeResult = batch.getChangeRequest(zone.getName(), created.getGeneratedId()); DnsBatchResult<ChangeRequest> idResult = batch.getChangeRequest( zone.getName(), created.getGeneratedId(), Dns.ChangeRequestOption.fields(ChangeRequestField.ID)); DnsBatchResult<ChangeRequest> statusResult = batch.getChangeRequest( zone.getName(), created.getGeneratedId(), Dns.ChangeRequestOption.fields(ChangeRequestField.STATUS)); DnsBatchResult<ChangeRequest> timeResult = batch.getChangeRequest( zone.getName(), created.getGeneratedId(), Dns.ChangeRequestOption.fields(ChangeRequestField.START_TIME)); DnsBatchResult<ChangeRequest> additionsResult = batch.getChangeRequest( zone.getName(), created.getGeneratedId(), Dns.ChangeRequestOption.fields(ChangeRequestField.ADDITIONS)); batch.submit(); assertEqChangesIgnoreStatus(created, completeResult.get()); // with options ChangeRequest retrieved = idResult.get(); assertEquals(created.getGeneratedId(), retrieved.getGeneratedId()); assertEquals(0, retrieved.getAdditions().size()); assertEquals(0, retrieved.getDeletions().size()); assertNull(retrieved.getStartTimeMillis()); assertNull(retrieved.status()); retrieved = statusResult.get(); assertEquals(created.getGeneratedId(), retrieved.getGeneratedId()); assertEquals(0, retrieved.getAdditions().size()); assertEquals(0, retrieved.getDeletions().size()); assertNull(retrieved.getStartTimeMillis()); assertEquals(ChangeRequestInfo.Status.DONE, retrieved.status()); retrieved = timeResult.get(); assertEquals(created.getGeneratedId(), retrieved.getGeneratedId()); assertEquals(0, retrieved.getAdditions().size()); assertEquals(0, retrieved.getDeletions().size()); assertEquals(created.getStartTimeMillis(), retrieved.getStartTimeMillis()); assertNull(retrieved.status()); retrieved = additionsResult.get(); assertEquals(created.getGeneratedId(), retrieved.getGeneratedId()); assertEquals(2, retrieved.getAdditions().size()); assertTrue(retrieved.getAdditions().contains(A_RECORD_ZONE1)); assertTrue(retrieved.getAdditions().contains(AAAA_RECORD_ZONE1)); assertEquals(0, retrieved.getDeletions().size()); assertNull(retrieved.getStartTimeMillis()); assertNull(retrieved.status()); // finishes with delete otherwise we cannot delete the zone created = zone.applyChangeRequest( CHANGE_DELETE_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.DELETIONS)); batch = DNS.batch(); DnsBatchResult<ChangeRequest> deletionsResult = batch.getChangeRequest( zone.getName(), created.getGeneratedId(), Dns.ChangeRequestOption.fields(ChangeRequestField.DELETIONS)); batch.submit(); retrieved = deletionsResult.get(); assertEquals(created.getGeneratedId(), retrieved.getGeneratedId()); assertEquals(0, retrieved.getAdditions().size()); assertEquals(2, retrieved.getDeletions().size()); assertTrue(retrieved.getDeletions().contains(AAAA_RECORD_ZONE1)); assertTrue(retrieved.getDeletions().contains(A_RECORD_ZONE1)); assertNull(retrieved.getStartTimeMillis()); assertNull(retrieved.status()); waitForChangeToComplete(zone.getName(), created.getGeneratedId()); } finally { clear(); } } @Test public void testListChangesBatch() { try { DnsBatch batch = DNS.batch(); DnsBatchResult<Page<ChangeRequest>> result = batch.listChangeRequests(ZONE1.getName()); batch.submit(); try { result.get(); fail("Zone does not exist yet"); } catch (DnsException ex) { // expected assertEquals(404, ex.getCode()); assertFalse(ex.isRetryable()); } // zone exists but has no changes DNS.create(ZONE1); batch = DNS.batch(); result = batch.listChangeRequests(ZONE1.getName()); batch.submit(); // default change creating SOA and NS assertEquals(1, Iterables.size(result.get().getValues())); // zone has changes ChangeRequest change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1); waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1); waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); batch = DNS.batch(); result = batch.listChangeRequests(ZONE1.getName()); DnsBatchResult<Page<ChangeRequest>> errorPageSize = batch.listChangeRequests(ZONE1.getName(), Dns.ChangeRequestListOption.pageSize(0)); DnsBatchResult<Page<ChangeRequest>> errorPageNegative = batch.listChangeRequests(ZONE1.getName(), Dns.ChangeRequestListOption.pageSize(-1)); DnsBatchResult<Page<ChangeRequest>> resultAscending = batch.listChangeRequests( ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING)); DnsBatchResult<Page<ChangeRequest>> resultDescending = batch.listChangeRequests( ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.DESCENDING)); DnsBatchResult<Page<ChangeRequest>> resultAdditions = batch.listChangeRequests( ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), Dns.ChangeRequestListOption.fields(ChangeRequestField.ADDITIONS)); DnsBatchResult<Page<ChangeRequest>> resultDeletions = batch.listChangeRequests( ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), Dns.ChangeRequestListOption.fields(ChangeRequestField.DELETIONS)); DnsBatchResult<Page<ChangeRequest>> resultId = batch.listChangeRequests( ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), Dns.ChangeRequestListOption.fields(ChangeRequestField.ID)); DnsBatchResult<Page<ChangeRequest>> resultTime = batch.listChangeRequests( ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), Dns.ChangeRequestListOption.fields(ChangeRequestField.START_TIME)); DnsBatchResult<Page<ChangeRequest>> resultStatus = batch.listChangeRequests( ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), Dns.ChangeRequestListOption.fields(ChangeRequestField.STATUS)); batch.submit(); assertEquals(3, Iterables.size(result.get().getValues())); // error in options try { errorPageSize.get(); fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.getCode()); assertFalse(ex.isRetryable()); } try { errorPageNegative.get(); fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.getCode()); assertFalse(ex.isRetryable()); } // sorting order ImmutableList<ChangeRequest> ascending = ImmutableList.copyOf(resultAscending.get().iterateAll()); ImmutableList<ChangeRequest> descending = ImmutableList.copyOf(resultDescending.get().iterateAll()); int size = 3; assertEquals(size, descending.size()); assertEquals(size, ascending.size()); for (int i = 0; i < size; i++) { assertEquals(descending.get(i), ascending.get(size - i - 1)); } // field options change = Iterables.get(resultAdditions.get().getValues(), 1); assertEquals(CHANGE_ADD_ZONE1.getAdditions(), change.getAdditions()); assertTrue(change.getDeletions().isEmpty()); assertNotNull(change.getGeneratedId()); assertNull(change.getStartTimeMillis()); assertNull(change.status()); change = Iterables.get(resultDeletions.get().getValues(), 2); assertTrue(change.getAdditions().isEmpty()); assertNotNull(change.getDeletions()); assertNotNull(change.getGeneratedId()); assertNull(change.getStartTimeMillis()); assertNull(change.status()); change = Iterables.get(resultId.get().getValues(), 1); assertTrue(change.getAdditions().isEmpty()); assertTrue(change.getDeletions().isEmpty()); assertNotNull(change.getGeneratedId()); assertNull(change.getStartTimeMillis()); assertNull(change.status()); change = Iterables.get(resultTime.get().getValues(), 1); assertTrue(change.getAdditions().isEmpty()); assertTrue(change.getDeletions().isEmpty()); assertNotNull(change.getGeneratedId()); assertNotNull(change.getStartTimeMillis()); assertNull(change.status()); change = Iterables.get(resultStatus.get().getValues(), 1); assertTrue(change.getAdditions().isEmpty()); assertTrue(change.getDeletions().isEmpty()); assertNotNull(change.getGeneratedId()); assertNull(change.getStartTimeMillis()); assertEquals(ChangeRequest.Status.DONE, change.status()); } finally { clear(); } } @Test public void testListDnsRecordSetsBatch() { try { Zone zone = DNS.create(ZONE1); DnsBatch batch = DNS.batch(); DnsBatchResult<Page<RecordSet>> result = batch.listRecordSets(zone.getName()); batch.submit(); ImmutableList<RecordSet> recordSets = ImmutableList.copyOf(result.get().iterateAll()); assertEquals(2, recordSets.size()); ImmutableList<RecordSet.Type> defaultRecords = ImmutableList.of(RecordSet.Type.NS, RecordSet.Type.SOA); for (RecordSet recordSet : recordSets) { assertTrue(defaultRecords.contains(recordSet.getType())); } // field options batch = DNS.batch(); DnsBatchResult<Page<RecordSet>> ttlResult = batch.listRecordSets(zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.TTL)); DnsBatchResult<Page<RecordSet>> nameResult = batch.listRecordSets(zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.NAME)); DnsBatchResult<Page<RecordSet>> recordsResult = batch.listRecordSets( zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.DNS_RECORDS)); DnsBatchResult<Page<RecordSet>> pageSizeResult = batch.listRecordSets( zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.TYPE), Dns.RecordSetListOption.pageSize(1)); batch.submit(); Iterator<RecordSet> recordSetIterator = ttlResult.get().iterateAll().iterator(); int counter = 0; while (recordSetIterator.hasNext()) { RecordSet recordSet = recordSetIterator.next(); assertEquals(recordSets.get(counter).getTtl(), recordSet.getTtl()); assertEquals(recordSets.get(counter).getName(), recordSet.getName()); assertEquals(recordSets.get(counter).getType(), recordSet.getType()); assertTrue(recordSet.getRecords().isEmpty()); counter++; } assertEquals(2, counter); recordSetIterator = nameResult.get().iterateAll().iterator(); counter = 0; while (recordSetIterator.hasNext()) { RecordSet recordSet = recordSetIterator.next(); assertEquals(recordSets.get(counter).getName(), recordSet.getName()); assertEquals(recordSets.get(counter).getType(), recordSet.getType()); assertTrue(recordSet.getRecords().isEmpty()); assertNull(recordSet.getTtl()); counter++; } assertEquals(2, counter); recordSetIterator = recordsResult.get().iterateAll().iterator(); counter = 0; while (recordSetIterator.hasNext()) { RecordSet recordSet = recordSetIterator.next(); assertEquals(recordSets.get(counter).getRecords(), recordSet.getRecords()); assertEquals(recordSets.get(counter).getName(), recordSet.getName()); assertEquals(recordSets.get(counter).getType(), recordSet.getType()); assertNull(recordSet.getTtl()); counter++; } assertEquals(2, counter); recordSetIterator = pageSizeResult.get().iterateAll().iterator(); // also test paging counter = 0; while (recordSetIterator.hasNext()) { RecordSet recordSet = recordSetIterator.next(); assertEquals(recordSets.get(counter).getType(), recordSet.getType()); assertEquals(recordSets.get(counter).getName(), recordSet.getName()); assertTrue(recordSet.getRecords().isEmpty()); assertNull(recordSet.getTtl()); counter++; } assertEquals(2, counter); // test page size Page<RecordSet> recordSetPage = pageSizeResult.get(); assertEquals(1, ImmutableList.copyOf(recordSetPage.getValues().iterator()).size()); // test name filter ChangeRequest change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1); waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); batch = DNS.batch(); result = batch.listRecordSets( ZONE1.getName(), Dns.RecordSetListOption.dnsName(A_RECORD_ZONE1.getName())); batch.submit(); recordSetIterator = result.get().iterateAll().iterator(); counter = 0; while (recordSetIterator.hasNext()) { RecordSet recordSet = recordSetIterator.next(); assertTrue( ImmutableList.of(A_RECORD_ZONE1.getType(), AAAA_RECORD_ZONE1.getType()) .contains(recordSet.getType())); counter++; } assertEquals(2, counter); // test type filter batch = DNS.batch(); result = batch.listRecordSets( ZONE1.getName(), Dns.RecordSetListOption.dnsName(A_RECORD_ZONE1.getName()), Dns.RecordSetListOption.type(A_RECORD_ZONE1.getType())); batch.submit(); recordSetIterator = result.get().iterateAll().iterator(); counter = 0; while (recordSetIterator.hasNext()) { RecordSet recordSet = recordSetIterator.next(); assertEquals(A_RECORD_ZONE1, recordSet); counter++; } assertEquals(1, counter); batch = DNS.batch(); DnsBatchResult<Page<RecordSet>> noNameError = batch.listRecordSets( ZONE1.getName(), Dns.RecordSetListOption.type(A_RECORD_ZONE1.getType())); DnsBatchResult<Page<RecordSet>> zeroSizeError = batch.listRecordSets(ZONE1.getName(), Dns.RecordSetListOption.pageSize(0)); DnsBatchResult<Page<RecordSet>> negativeSizeError = batch.listRecordSets(ZONE1.getName(), Dns.RecordSetListOption.pageSize(-1)); batch.submit(); // check wrong arguments try { // name is not set noNameError.get(); fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.getCode()); assertFalse(ex.isRetryable()); } try { zeroSizeError.get(); fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.getCode()); assertFalse(ex.isRetryable()); } try { negativeSizeError.get(); fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.getCode()); assertFalse(ex.isRetryable()); } waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); } finally { clear(); } } @Test public void testBatchCombined() { // only testing that the combination is possible // the results are validated in the other test methods try { DNS.create(ZONE1); DnsBatch batch = DNS.batch(); DnsBatchResult<Zone> zoneResult = batch.getZone(ZONE_NAME1); DnsBatchResult<ChangeRequest> changeRequestResult = batch.getChangeRequest(ZONE_NAME1, "0"); DnsBatchResult<Page<RecordSet>> pageResult = batch.listRecordSets(ZONE_NAME1); DnsBatchResult<ProjectInfo> projectResult = batch.getProject(); assertFalse(zoneResult.completed()); try { zoneResult.get(); fail("this should be submitted first"); } catch (IllegalStateException ex) { // expected } batch.submit(); assertNotNull(zoneResult.get().getCreationTimeMillis()); assertEquals(ZONE1.getDnsName(), zoneResult.get().getDnsName()); assertEquals(ZONE1.getDescription(), zoneResult.get().getDescription()); assertFalse(zoneResult.get().getNameServers().isEmpty()); assertNull(zoneResult.get().getNameServerSet()); // we did not set it assertNotNull(zoneResult.get().getGeneratedId()); assertNotNull(projectResult.get().getQuota()); assertEquals(2, Iterables.size(pageResult.get().getValues())); assertNotNull(changeRequestResult.get()); } finally { DNS.delete(ZONE1.getName()); } } }
apache-2.0
taegeonum/incubator-reef
lang/java/reef-io/src/main/java/org/apache/reef/io/network/group/impl/driver/TopologyUpdateWaitHandler.java
4136
/* * 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.reef.io.network.group.impl.driver; import org.apache.reef.io.network.group.api.driver.TaskNode; import org.apache.reef.io.network.group.impl.GroupCommunicationMessage; import org.apache.reef.io.network.group.impl.utils.Utils; import org.apache.reef.io.network.proto.ReefNetworkGroupCommProtos; import org.apache.reef.tang.annotations.Name; import org.apache.reef.wake.EStage; import org.apache.reef.wake.EventHandler; import java.util.List; import java.util.logging.Logger; /** * */ public class TopologyUpdateWaitHandler implements EventHandler<List<TaskNode>> { private static final Logger LOG = Logger.getLogger(TopologyUpdateWaitHandler.class.getName()); private final EStage<GroupCommunicationMessage> senderStage; private final Class<? extends Name<String>> groupName; private final Class<? extends Name<String>> operName; private final String driverId; private final int driverVersion; private final String dstId; private final int dstVersion; private final String qualifiedName; /** * The handler will wait for all nodes to acquire topoLock * and send TopologySetup msg. Then it will send TopologyUpdated * msg. However, any local topology changes are not in effect * till driver sends TopologySetup once statusMap is emptied * The operations in the tasks that have topology changes will * wait for this. However other tasks that do not have any changes * will continue their regular operation */ public TopologyUpdateWaitHandler(final EStage<GroupCommunicationMessage> senderStage, final Class<? extends Name<String>> groupName, final Class<? extends Name<String>> operName, final String driverId, final int driverVersion, final String dstId, final int dstVersion, final String qualifiedName) { super(); this.senderStage = senderStage; this.groupName = groupName; this.operName = operName; this.driverId = driverId; this.driverVersion = driverVersion; this.dstId = dstId; this.dstVersion = dstVersion; this.qualifiedName = qualifiedName; } @Override public void onNext(final List<TaskNode> nodes) { LOG.entering("TopologyUpdateWaitHandler", "onNext", new Object[]{qualifiedName, nodes}); for (final TaskNode node : nodes) { LOG.fine(qualifiedName + "Waiting for " + node + " to enter TopologyUdate phase"); node.waitForTopologySetupOrFailure(); if (node.isRunning()) { LOG.fine(qualifiedName + node + " is in TopologyUpdate phase"); } else { LOG.fine(qualifiedName + node + " has failed"); } } LOG.finest(qualifiedName + "NodeTopologyUpdateWaitStage All to be updated nodes " + "have received TopologySetup"); LOG.fine(qualifiedName + "All affected parts of the topology are in TopologyUpdate phase. Will send a note to (" + dstId + "," + dstVersion + ")"); senderStage.onNext(Utils.bldVersionedGCM(groupName, operName, ReefNetworkGroupCommProtos.GroupCommMessage.Type.TopologyUpdated, driverId, driverVersion, dstId, dstVersion, Utils.EMPTY_BYTE_ARR)); LOG.exiting("TopologyUpdateWaitHandler", "onNext", qualifiedName); } }
apache-2.0
milg0/onvif-java-lib
src/org/onvif/ver10/media/wsdl/CreateProfile.java
2297
// // Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2 generiert // Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // �nderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren. // Generiert: 2014.02.19 um 02:35:56 PM CET // package org.onvif.ver10.media.wsdl; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p> * Java-Klasse f�r anonymous complex type. * * <p> * Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="Name" type="{http://www.onvif.org/ver10/schema}Name"/> * <element name="Token" type="{http://www.onvif.org/ver10/schema}ReferenceToken" minOccurs="0"/> * </sequence> * </restriction> * </complexContent> * </complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "name", "token" }) @XmlRootElement(name = "CreateProfile") public class CreateProfile { @XmlElement(name = "Name", required = true) protected String name; @XmlElement(name = "Token") protected String token; /** * Ruft den Wert der name-Eigenschaft ab. * * @return possible object is {@link String } * */ public String getName() { return name; } /** * Legt den Wert der name-Eigenschaft fest. * * @param value * allowed object is {@link String } * */ public void setName(String value) { this.name = value; } /** * Ruft den Wert der token-Eigenschaft ab. * * @return possible object is {@link String } * */ public String getToken() { return token; } /** * Legt den Wert der token-Eigenschaft fest. * * @param value * allowed object is {@link String } * */ public void setToken(String value) { this.token = value; } }
apache-2.0
oleg-cherednik/hackerrank
Tutorials/Interview Preparation Kit/Linked Lists/Find Merge Point of Two Lists/Solution.java
3072
import java.util.Scanner; /** * @author Oleg Cherednik * @since 04.08.2018 */ public class Solution { static class SinglyLinkedListNode { public int data; public SinglyLinkedListNode next; public SinglyLinkedListNode(int nodeData) { this.data = nodeData; this.next = null; } } static class SinglyLinkedList { public SinglyLinkedListNode head; public SinglyLinkedListNode tail; public SinglyLinkedList() { this.head = null; this.tail = null; } public void insertNode(int nodeData) { SinglyLinkedListNode node = new SinglyLinkedListNode(nodeData); if (this.head == null) { this.head = node; } else { this.tail.next = node; } this.tail = node; } } static int findMergeNode(SinglyLinkedListNode head1, SinglyLinkedListNode head2) { SinglyLinkedListNode it1 = head1; SinglyLinkedListNode it2 = head2; while (it1 != it2) { it1 = it1.next != null ? it1.next : head2; it2 = it2.next != null ? it2.next : head1; } return it1.data; } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int tests = scanner.nextInt(); scanner.skip("\r\n|([\n\r\u2028\u2029\u0085])?"); for (int testsItr = 0; testsItr < tests; testsItr++) { int index = scanner.nextInt(); scanner.skip("\r\n|([\n\r\u2028\u2029\u0085])?"); SinglyLinkedList llist1 = new SinglyLinkedList(); int llist1Count = scanner.nextInt(); scanner.skip("\r\n|([\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < llist1Count; i++) { int llistItem = scanner.nextInt(); scanner.skip("\r\n|([\n\r\u2028\u2029\u0085])?"); llist1.insertNode(llistItem); } SinglyLinkedList llist2 = new SinglyLinkedList(); int llist2Count = scanner.nextInt(); scanner.skip("\r\n|([\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < llist2Count; i++) { int llist2Item = scanner.nextInt(); scanner.skip("\r\n|([\n\r\u2028\u2029\u0085])?"); llist2.insertNode(llist2Item); } SinglyLinkedListNode ptr1 = llist1.head; SinglyLinkedListNode ptr2 = llist2.head; for (int i = 0; i < llist1Count; i++) { if (i < index) { ptr1 = ptr1.next; } } for (int i = 0; i < llist2Count; i++) { if (i != llist2Count - 1) { ptr2 = ptr2.next; } } ptr2.next = ptr1; int result = findMergeNode(llist1.head, llist2.head); System.out.println(String.valueOf(result)); } scanner.close(); } }
apache-2.0
346674058/SuRui
code/myit-server/src/main/java/com/myit/server/service/admin/impl/MenuServiceImpl.java
4661
package com.myit.server.service.admin.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.myit.common.beans.PageQueryParam; import com.myit.common.beans.PageQueryResult; import com.myit.intf.bean.admin.Menu; import com.myit.intf.service.admin.MenuService; import com.myit.server.dao.admin.MenuDao; @Service("menuService") public class MenuServiceImpl implements MenuService { private Logger logger = Logger.getLogger(this.getClass()); @Autowired private MenuDao menuDao; public Menu findMenuById(Long id) throws Exception { logger.info("findMenuById in."); Menu menu = null; if (logger.isDebugEnabled()) { logger.debug("parameters: id=" + id); } // 调用dao查询板块 logger.info("invoke plateDao.findMenuById"); com.myit.server.model.admin.Menu plate = menuDao.findMenuById(id); logger.info("findMenuById out."); return menu; } public List<Menu> findAllMenus() throws Exception { logger.info("findAllMenus in."); List<Menu> menus = null; List<com.myit.server.model.admin.Menu> plates = menuDao.findAllMenus(); logger.info("findAllMenus out."); return menus; } public int getMenusCount(Menu menu) throws Exception { logger.info("getMenusCount in."); // 调用dao查询板块记录数 com.myit.server.model.admin.Menu menuBean = null; int platesCount = menuDao.getMenusCount(menuBean); logger.info("getMenusCount out."); return platesCount; } public PageQueryResult<Menu> findMenus(PageQueryParam<Menu> pageQueryParam) throws Exception { logger.info("findMenus in."); if (logger.isDebugEnabled()) { logger.debug("pageQueryParam=" + pageQueryParam); } int total = 0; PageQueryResult<Menu> pageQueryResult = null; try { com.myit.server.model.admin.Menu menuBean = null; // 调用dao查询板块总数 total = menuDao.getMenusCount(menuBean); PageQueryResult<com.myit.server.model.admin.Menu> pageQueryResultTemp = new PageQueryResult<com.myit.server.model.admin.Menu>(total, pageQueryParam.getPageNo(), pageQueryParam.getPageSize()); if (total > 0) { // 调用dao分页查询板块 List<com.myit.server.model.admin.Menu> menus = menuDao.findMenus(pageQueryResult.getStart(), pageQueryResult.getPageSize(), menuBean); pageQueryResultTemp.setRows(menus); } } catch (Exception e) { logger.warn("Exception occured", e); throw e; } if (logger.isDebugEnabled()) { logger.debug("pageQueryResult=" + pageQueryResult); } logger.info("findMenus out."); return pageQueryResult; } public boolean saveMenu(Menu menu) throws Exception { logger.info("saveMenu in."); // 调用dao保存板块信息 com.myit.server.model.admin.Menu menuBean = null; boolean isSuccess = menuDao.persistMenu(menuBean); if (logger.isDebugEnabled()) { logger.debug("isSuccess=" + isSuccess); } logger.info("saveMenu out."); return isSuccess; } public List<Menu> getLoginMenus(Long uId) throws Exception { logger.info("getLoginMenus in."); List<Menu> menus = null; // 调用dao查询板块信息 List<com.myit.server.model.admin.Menu> menuBeans = menuDao.findMenusByUId(uId); if (menus != null) { logger.debug("menus.size=" + menus.size()); } logger.info("getLoginMenus out."); return menus; } public List<Menu> findChildMenus(Long mId) throws Exception { logger.info("findPlatesByRId in."); List<Menu> menus = null; Map<String, Object> queryParam = new HashMap<String, Object>(); queryParam.put("pId", mId); // 调用dao查询板块信息 List<com.myit.server.model.admin.Menu> menuBeans = menuDao.findChildMenus(queryParam); if (menus != null) { logger.debug("menus.size=" + menus.size()); } logger.info("findPlatesByRId out."); return menus; } }
apache-2.0
android-art-intel/Nougat
art-extension/opttests/src/OptimizationTests/ShortMethodsInliningNonVirtualInvokes/InvokeSuperAObjectThrowNullGet_001/Test.java
1106
/* * Copyright (C) 2016 Intel Corporation * * 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 OptimizationTests.ShortMethodsInliningNonVirtualInvokes.InvokeSuperAObjectThrowNullGet_001; // The test checks that stack after NullPointerException occurs is correct despite inlining class Test extends SuperTest { Test(int iterations) { super(iterations); } public Foo getThingies(Foo[] arr, int i) { return super.getThingies(arr, i); } public void setThingies(Foo[] arr, Foo newThingy, int i) { super.setThingies(arr, newThingy, i); } }
apache-2.0
kuali/kpme
pm/impl/src/test/java/org/kuali/kpme/pm/position/PositionBoTest.java
8006
/** * Copyright 2004-2014 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kpme.pm.position; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.joda.time.DateTime; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.kuali.kpme.core.api.groupkey.HrGroupKey; import org.kuali.kpme.core.groupkey.HrGroupKeyBoTest; import org.kuali.kpme.core.kfs.coa.businessobject.Account; import org.kuali.kpme.pm.api.classification.qual.ClassificationQualification; import org.kuali.kpme.pm.api.position.Position; import org.kuali.kpme.pm.api.position.PositionDuty; import org.kuali.kpme.pm.api.position.PositionQualification; import org.kuali.kpme.pm.api.position.PstnFlag; import org.kuali.kpme.pm.api.position.funding.PositionFunding; import org.kuali.kpme.pm.api.positiondepartment.PositionDepartment; import org.kuali.kpme.pm.api.positionresponsibility.PositionResponsibility; import org.kuali.kpme.pm.classification.ClassificationBo; import org.kuali.kpme.pm.classification.qual.ClassificationQualificationBoTest; import org.kuali.kpme.pm.position.funding.PositionFundingBoTest; import org.kuali.kpme.pm.positionresponsibility.PositionResponsibilityBoTest; import org.kuali.rice.krad.service.BusinessObjectService; public class PositionBoTest { private static Map<String, Position> testPositionBos; public static Position.Builder builder = Position.Builder.create("1", "ISU-IA"); private BusinessObjectService mockBusinessObjectService; static { testPositionBos = new HashMap<String, Position>(); builder.setActive(true); builder.setBenefitsEligible("N"); builder.setCategory("category"); builder.setClassificationTitle("classTitle"); builder.setContract("contract"); builder.setContractType("contractType"); builder.setCreateTime(DateTime.now()); builder.setDescription("desc"); builder.setGroupKeyCode("ISU-IA"); builder.setGroupKey(HrGroupKey.Builder.create(HrGroupKeyBoTest.getTestHrGroupKey("ISU-IA"))); builder.setHrPositionId("KPME_TEST_00001"); builder.setId(builder.getHrPositionId()); builder.setLeaveEligible("leaveEligible"); builder.setMaxPoolHeadCount(0); builder.setObjectId("0804716a-cbb7-11e3-9cd3-51a754ad6a0a"); builder.setPayGrade("XH"); builder.setPayStep("YY"); builder.setPositionNumber("1"); builder.setPositionClass("positionClass"); builder.setAppointmentType("appt"); builder.setReportsToWorkingTitle("rptToWorkTitle"); builder.setPrimaryDepartment("dept1"); builder.setProcess("process"); builder.setPmPositionClassId("KPME_TEST_2000"); List<PositionResponsibility.Builder> positionResponsilityList = new ArrayList<PositionResponsibility.Builder>(); PositionResponsibility.Builder responsibilityBuilder = PositionResponsibility.Builder.create(PositionResponsibilityBoTest.getPositionResponsibility("TST-PSTNRESPOPT")); responsibilityBuilder.setHrPositionId(builder.getHrPositionId()); positionResponsilityList.add(responsibilityBuilder); builder.setPositionResponsibilityList(positionResponsilityList); List<PositionDepartment.Builder> positionDeptList = new ArrayList<PositionDepartment.Builder>(); PositionDepartment.Builder deptBuilder = PositionDepartment.Builder.create(PositionDataBoTest.getPositionDepartment("TST-PSTNDEPT")); deptBuilder.setHrPositionId(builder.getHrPositionId()); positionDeptList.add(deptBuilder); builder.setDepartmentList(positionDeptList); List<PstnFlag.Builder> pstnFlagList = new ArrayList<PstnFlag.Builder>(); PstnFlag.Builder flagBuilder = PstnFlag.Builder.create(PstnFlagBoTest.getPstnFlag("TST-PSTNFLAG")); flagBuilder.setHrPositionId(builder.getHrPositionId()); pstnFlagList.add(flagBuilder); builder.setFlagList(pstnFlagList); List<PositionDuty.Builder> positionDutyList = new ArrayList<PositionDuty.Builder>(); PositionDuty.Builder dutyBuilder = PositionDuty.Builder.create(PositionDutyBoTest.getPositionDutyBo("TST-PSTNDUTY")); dutyBuilder.setHrPositionId(builder.getHrPositionId()); positionDutyList.add(dutyBuilder); builder.setDutyList(positionDutyList); List<PositionFunding.Builder> positionFundingList = new ArrayList<PositionFunding.Builder>(); PositionFunding.Builder fundingBuilder = PositionFunding.Builder.create(PositionFundingBoTest.getPositionFunding("9999")); fundingBuilder.setHrPositionId(builder.getHrPositionId()); fundingBuilder.setAccount("KPME_TEST_ACCOUNT"); positionFundingList.add(fundingBuilder); builder.setFundingList(positionFundingList); List<PositionQualification.Builder> positionQualificationList = new ArrayList<PositionQualification.Builder>(); PositionQualification.Builder qualificationBuilder = PositionQualification.Builder.create(PositionQualificationBoTest.getPositionQualificationBo("TST-PSTNQLFCTN")); qualificationBuilder.setHrPositionId(builder.getHrPositionId()); positionQualificationList.add(qualificationBuilder); builder.setQualificationList(positionQualificationList); List<ClassificationQualification.Builder> classificationQualificationList = new ArrayList<ClassificationQualification.Builder>(); ClassificationQualification.Builder classQualBuilder = ClassificationQualification.Builder.create(ClassificationQualificationBoTest.getClassificationQualificationBo("TST-CLASSFCTNQLFCTN")); classQualBuilder.setPmPositionClassId("KPME_TEST_2000"); classificationQualificationList.add(classQualBuilder); builder.setRequiredQualList(classificationQualificationList); testPositionBos.put("TST-PSTN", builder.build()); } @Test public void testNotEqualsWithGroup() { Position immutable = PositionBoTest.getPosition("TST-PSTN"); PositionBo bo = PositionBo.from(immutable); Assert.assertFalse(bo.equals(immutable)); Assert.assertFalse(immutable.equals(bo)); // this is simply to prevent invocations of refresh reference ClassificationBo classificationBo = new ClassificationBo(); bo.getRequiredQualList().get(0).setOwner(classificationBo); //bo.getFundingList().get(0).setBusinessObjectService(mockBusinessObjectService); Position im2 = PositionBo.to(bo); PositionBo bo2 = PositionBo.from(im2); // this is simply to prevent invocations of refresh reference bo2.getRequiredQualList().get(0).setOwner(classificationBo); //bo2.getFundingList().get(0).setBusinessObjectService(mockBusinessObjectService); Position im3 = PositionBo.to(bo2); Assert.assertEquals(im2, im3); } public static Position getPosition(String Position) { Position position = testPositionBos.get(Position); return position; } @Before public void setup() throws Exception { Account account = new Account(); account.setAccountNumber("KPME_TEST_ACCOUNT"); account.setChartOfAccountsCode("MC"); account.setActive(true); Map<String, String> fields = new HashMap<String, String>(); fields.put("accountNumber", "KPME_TEST_ACCOUNT"); fields.put("active", "true"); mockBusinessObjectService = mock(BusinessObjectService.class); { when(mockBusinessObjectService.findByPrimaryKey(Account.class, fields)).thenReturn(account); } } }
apache-2.0
josealmeida/opereffa
Opereffa/src/uk/ac/ucl/chime/web/RandomGroupIdAdapter.java
2256
/******************************************************************************* * Copyright 2012 Sevket Seref Arikan, David Ingram * * 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 uk.ac.ucl.chime.web; import gov.nih.nci.cagrid.gums.client.GetGridProxy; import java.util.ArrayList; import javax.el.ELContext; import javax.faces.context.FacesContext; import javax.faces.model.SelectItem; import org.apache.poi.hssf.record.formula.Ptg; import uk.ac.ucl.chime.utilities.TextValueInfo; import uk.ac.ucl.chime.utils.RMDataTypeAdapter; import uk.ac.ucl.chime.wrappers.archetypewrappers.ArchetypeWrapper; /* * This class descends from RMDataTypeAdapter to use its syntax resolving mechanism * it is not an adapter for a data type operation, instead it provides access to a groupId * using the node path as key. so same nodeId from a set of components gets back a random guid * everytime the request level bean is initialized. this is not a nice trick, but JSF does not leave much choice in this case. * */ public class RandomGroupIdAdapter extends RMDataTypeAdapter { public RandomGroupIdAdapter(ArchetypeWrapper pArchetypeWrapper) { archetypeWrapper = pArchetypeWrapper; } @Override protected Object getValue() throws Exception { ELContext elContext = FacesContext.getCurrentInstance().getELContext(); ConnectorBean connector = (ConnectorBean) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "connectorBean"); return connector.getGroupGUID(targetNodePath); } @Override protected void setValue(String nodePath, Object value) throws Exception { //simply ignore set value } }
apache-2.0
Pravian/LALParser
src/test/java/net/pravian/lalparser/LALFileTest.java
2524
/* * Copyright 2015 Jerom van der Sar. * * 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.pravian.lalparser; import java.io.File; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class LALFileTest { private LALParser parser; private Login simpleLogin; private File simpleFile; private File complexFile; private final Login[] complexLogins = new Login[]{ new Login("// Comment"), new Login("user", "pass"), new Login("user", "pass", "display"), new Login("user", "pass", "display", "email", null, true), new Login("user", "pass", "display", "email", "oldpass", false), new Login("user", "pass", "display", "email", "oldpass", true),}; @Before public void setUp() { parser = new LALParser(); simpleLogin = new Login("user", "pass", "display", "email", "oldpass", true); simpleFile = getResource("simple.txt"); complexFile = getResource("complex.txt"); if (!simpleFile.exists() || !complexFile.exists()) { Assert.fail(); } } @Test(expected = Exception.class) public void testNull() { parser.load((String) null); } @Test public void testFileParseSimple() { parser.clear(); parser.load(simpleFile); Assert.assertTrue(parser.size() == 1); Assert.assertTrue(parser.contains(simpleLogin)); Assert.assertTrue(parser.get(0).strictEquals(simpleLogin)); } @Test public void testFileParseComplex() { parser.clear(); parser.load(complexFile); Assert.assertTrue(parser.size() == complexLogins.length); for (int i = 0; i < parser.size(); i++) { Assert.assertTrue("Testing: " + parser.get(i).toString(), parser.get(i).strictEquals(complexLogins[i])); } } private File getResource(String fileName) { return new File(getClass().getClassLoader().getResource(fileName).getFile()); } }
apache-2.0
nengxu/OrientDB
core/src/main/java/com/orientechnologies/orient/core/version/ODistributedVersion.java
12956
/* * Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.core.version; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.OutputStream; import com.orientechnologies.common.serialization.OBinaryConverter; import com.orientechnologies.common.serialization.OBinaryConverterFactory; import com.orientechnologies.orient.core.serialization.OBinaryProtocol; import com.orientechnologies.orient.core.storage.fs.OFile; /** * Implementation of {@link ORecordVersion} adapted to distributed environment. Opposite of {@link OSimpleVersion} contains * additional information about timestamp of last change and mac address of server that made this change. * * @see OVersionFactory * @see ORecordVersion * * @author <a href="mailto:enisher@gmail.com">Artem Orobets</a> */ public final class ODistributedVersion implements ORecordVersion { public static final int STREAMED_SIZE = OBinaryProtocol.SIZE_INT + OBinaryProtocol.SIZE_LONG + OBinaryProtocol.SIZE_LONG; public static final OBinaryConverter CONVERTER = OBinaryConverterFactory.getConverter(); private int counter; private long timestamp; private long macAddress; public ODistributedVersion() { } public ODistributedVersion(int counter) { this.counter = counter; this.timestamp = System.currentTimeMillis(); this.macAddress = OVersionFactory.instance().getMacAddress(); } public ODistributedVersion(int counter, long timestamp, long macAddress) { this.counter = counter; this.timestamp = timestamp; this.macAddress = macAddress; } @Override public void increment() { if (isTombstone()) throw new IllegalStateException("Record was deleted and can not be updated."); counter++; timestamp = System.currentTimeMillis(); macAddress = OVersionFactory.instance().getMacAddress(); } @Override public void decrement() { if (isTombstone()) throw new IllegalStateException("Record was deleted and can not be updated."); counter--; timestamp = System.currentTimeMillis(); macAddress = OVersionFactory.instance().getMacAddress(); } @Override public boolean isUntracked() { return counter == -1; } @Override public boolean isTemporary() { return counter < -1; } @Override public boolean isValid() { return counter > -1; } @Override public void setCounter(int iVersion) { counter = iVersion; } @Override public int getCounter() { return counter; } @Override public boolean isTombstone() { return counter < 0; } public void convertToTombstone() { if (isTombstone()) throw new IllegalStateException("Record was deleted and can not be updated."); counter++; counter = -counter; timestamp = System.currentTimeMillis(); macAddress = OVersionFactory.instance().getMacAddress(); } @Override public void copyFrom(ORecordVersion version) { ODistributedVersion other = (ODistributedVersion) version; update(other.counter, other.timestamp, other.macAddress); } public void update(int recordVersion, long timestamp, long macAddress) { this.counter = recordVersion; this.timestamp = timestamp; this.macAddress = macAddress; } @Override public void reset() { counter = 0; timestamp = System.currentTimeMillis(); macAddress = OVersionFactory.instance().getMacAddress(); } @Override public void setRollbackMode() { counter = Integer.MIN_VALUE + counter; } @Override public void clearRollbackMode() { counter = counter - Integer.MIN_VALUE; } @Override public void disable() { counter = -1; } @Override public void revive() { counter = -counter; } @Override public ORecordVersion copy() { ODistributedVersion copy = new ODistributedVersion(); copy.counter = counter; copy.timestamp = timestamp; copy.macAddress = macAddress; return copy; } @Override public ORecordVersionSerializer getSerializer() { return ODistributedVersionSerializer.INSTANCE; } @Override public boolean equals(Object other) { return other instanceof ODistributedVersion && ((ODistributedVersion) other).compareTo(this) == 0; } @Override public int hashCode() { int result = counter; result = 31 * result + (int) (timestamp ^ (timestamp >>> 32)); result = 31 * result + (int) (macAddress ^ (macAddress >>> 32)); return result; } @Override public String toString() { return ODistributedVersionSerializer.INSTANCE.toString(this); } @Override public int compareTo(ORecordVersion o) { ODistributedVersion other = (ODistributedVersion) o; final int myCounter; if (isTombstone()) myCounter = -counter; else myCounter = counter; final int otherCounter; if (o.isTombstone()) otherCounter = -o.getCounter(); else otherCounter = o.getCounter(); if (myCounter != otherCounter) return myCounter > otherCounter ? 1 : -1; if (timestamp != other.timestamp) return (timestamp > other.timestamp) ? 1 : -1; if (macAddress > other.macAddress) return 1; else if (macAddress < other.macAddress) return -1; else return 0; } public long getTimestamp() { return timestamp; } public long getMacAddress() { return macAddress; } @Override public void writeExternal(ObjectOutput out) throws IOException { ODistributedVersionSerializer.INSTANCE.writeTo(out, this); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { ODistributedVersionSerializer.INSTANCE.readFrom(in, this); } private static final class ODistributedVersionSerializer implements ORecordVersionSerializer { private static final ODistributedVersionSerializer INSTANCE = new ODistributedVersionSerializer(); @Override public void writeTo(DataOutput out, ORecordVersion version) throws IOException { final ODistributedVersion distributedVersion = (ODistributedVersion) version; out.writeInt(distributedVersion.counter); out.writeLong(distributedVersion.timestamp); out.writeLong(distributedVersion.macAddress); } @Override public void readFrom(DataInput in, ORecordVersion version) throws IOException { final ODistributedVersion distributedVersion = (ODistributedVersion) version; distributedVersion.counter = in.readInt(); distributedVersion.timestamp = in.readLong(); distributedVersion.macAddress = in.readLong(); } @Override public void writeTo(OutputStream stream, ORecordVersion version) throws IOException { final ODistributedVersion distributedVersion = (ODistributedVersion) version; OBinaryProtocol.int2bytes(distributedVersion.counter, stream); OBinaryProtocol.long2bytes(distributedVersion.timestamp, stream); OBinaryProtocol.long2bytes(distributedVersion.macAddress, stream); } @Override public void readFrom(InputStream stream, ORecordVersion version) throws IOException { final ODistributedVersion distributedVersion = (ODistributedVersion) version; distributedVersion.counter = OBinaryProtocol.bytes2int(stream); distributedVersion.timestamp = OBinaryProtocol.bytes2long(stream); distributedVersion.macAddress = OBinaryProtocol.bytes2long(stream); } @Override public int writeTo(byte[] stream, int pos, ORecordVersion version) { final ODistributedVersion distributedVersion = (ODistributedVersion) version; int len = 0; OBinaryProtocol.int2bytes(distributedVersion.counter, stream, pos + len); len += OBinaryProtocol.SIZE_INT; OBinaryProtocol.long2bytes(distributedVersion.timestamp, stream, pos + len); len += OBinaryProtocol.SIZE_LONG; OBinaryProtocol.long2bytes(distributedVersion.macAddress, stream, pos + len); len += OBinaryProtocol.SIZE_LONG; return len; } @Override public int readFrom(byte[] iStream, int pos, ORecordVersion version) { final ODistributedVersion distributedVersion = (ODistributedVersion) version; int len = 0; distributedVersion.counter = OBinaryProtocol.bytes2int(iStream, pos + len); len += OBinaryProtocol.SIZE_INT; distributedVersion.timestamp = OBinaryProtocol.bytes2long(iStream, pos + len); len += OBinaryProtocol.SIZE_LONG; distributedVersion.macAddress = OBinaryProtocol.bytes2long(iStream, pos + len); len += OBinaryProtocol.SIZE_LONG; return len; } @Override public int writeTo(OFile file, long pos, ORecordVersion version) throws IOException { final ODistributedVersion distributedVersion = (ODistributedVersion) version; int len = 0; file.writeInt(pos + len, distributedVersion.counter); len += OBinaryProtocol.SIZE_INT; file.writeLong(pos + len, distributedVersion.timestamp); len += OBinaryProtocol.SIZE_LONG; file.writeLong(pos + len, distributedVersion.macAddress); len += OBinaryProtocol.SIZE_LONG; return len; } @Override public long readFrom(OFile file, long pos, ORecordVersion version) throws IOException { final ODistributedVersion distributedVersion = (ODistributedVersion) version; int len = 0; distributedVersion.counter = file.readInt(pos + len); len += OBinaryProtocol.SIZE_INT; distributedVersion.timestamp = file.readLong(pos + len); len += OBinaryProtocol.SIZE_LONG; distributedVersion.macAddress = file.readLong(pos + len); len += OBinaryProtocol.SIZE_LONG; return len; } @Override public int fastWriteTo(byte[] iStream, int pos, ORecordVersion version) { final ODistributedVersion distributedVersion = (ODistributedVersion) version; int len = 0; CONVERTER.putInt(iStream, pos + len, distributedVersion.counter); len += OBinaryProtocol.SIZE_INT; CONVERTER.putLong(iStream, pos + len, distributedVersion.timestamp); len += OBinaryProtocol.SIZE_LONG; CONVERTER.putLong(iStream, pos + len, distributedVersion.macAddress); len += OBinaryProtocol.SIZE_LONG; return len; } @Override public int fastReadFrom(byte[] iStream, int pos, ORecordVersion version) { final ODistributedVersion distributedVersion = (ODistributedVersion) version; int len = 0; distributedVersion.counter = CONVERTER.getInt(iStream, pos + len); len += OBinaryProtocol.SIZE_INT; distributedVersion.timestamp = CONVERTER.getLong(iStream, pos + len); len += OBinaryProtocol.SIZE_LONG; distributedVersion.macAddress = CONVERTER.getLong(iStream, pos + len); len += OBinaryProtocol.SIZE_LONG; return len; } @Override public byte[] toByteArray(ORecordVersion version) { int size = OBinaryProtocol.SIZE_INT + OBinaryProtocol.SIZE_LONG + OBinaryProtocol.SIZE_LONG; byte[] buffer = new byte[size]; fastWriteTo(buffer, 0, version); return buffer; } @Override public String toString(ORecordVersion version) { final ODistributedVersion distributedVersion = (ODistributedVersion) version; return distributedVersion.counter + "." + distributedVersion.timestamp + "." + distributedVersion.macAddress; } @Override public void fromString(String string, ORecordVersion version) { final ODistributedVersion distributedVersion = (ODistributedVersion) version; String[] parts = string.split("\\."); if (parts.length != 3) throw new IllegalArgumentException( "Not correct format of distributed version. Expected <recordVersion>.<timestamp>.<macAddress>"); distributedVersion.counter = Integer.valueOf(parts[0]); distributedVersion.timestamp = Long.valueOf(parts[1]); distributedVersion.macAddress = Long.valueOf(parts[2]); } } }
apache-2.0
xiao125/LatteDamo
latte-ui/src/main/java/com/latte/ui/recycler/MultipleFields.java
225
package com.latte.ui.recycler; /** * Created by Administrator on 2017/9/18 0018. */ public enum MultipleFields { ITEM_TYPE, TITLE, TEXT, IMAGE_URL, BANNERS, SPAN_SIZE, ID, NAME, TAG }
apache-2.0
x-huihui/x-huihui.github.io
src/main/java/com/xhuihui/app/json/json.java
100
package com.xhuihui.app.json; /** * Created by lihuiguang on 2017/7/13. */ public class json { }
apache-2.0
floodlight/loxigen-artifacts
openflowj/gen-src/main/java/org/projectfloodlight/openflow/protocol/oxm/OFOxmBsnInPorts128.java
2170
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template of_interface.java // Do not modify package org.projectfloodlight.openflow.protocol.oxm; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.stat.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.oxs.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import io.netty.buffer.ByteBuf; public interface OFOxmBsnInPorts128 extends OFObject, OFOxm<OFBitMask128> { long getTypeLen(); OFBitMask128 getValue(); MatchField<OFBitMask128> getMatchField(); boolean isMasked(); OFOxm<OFBitMask128> getCanonical(); OFBitMask128 getMask(); OFVersion getVersion(); void writeTo(ByteBuf channelBuffer); Builder createBuilder(); public interface Builder extends OFOxm.Builder<OFBitMask128> { OFOxmBsnInPorts128 build(); long getTypeLen(); OFBitMask128 getValue(); Builder setValue(OFBitMask128 value); MatchField<OFBitMask128> getMatchField(); boolean isMasked(); OFOxm<OFBitMask128> getCanonical(); OFBitMask128 getMask(); OFVersion getVersion(); } }
apache-2.0
MarchMachao/ZHFS-WEB
src/main/java/com/smates/dbc2/utils/SysConst.java
573
package com.smates.dbc2.utils; /** * 参数 * @author 刘晓庆 * */ public class SysConst { //md5加密时用到的盐值 public static final String SALTSOURCE = "baijw"; //七牛云外连接域名 public static final String QNIUYUNURL = "http://ohyi4k153.bkt.clouddn.com/"; //七牛云图片处理样式 public static final String QNIUYUNSTYLE = "?imageView2/2/w/80/h/100/interlace/0/q/50"; //资源type public static final String VIP = "0"; public static final String LEARN = "1"; public static final String GAME = "2"; }
apache-2.0
phac-nml/irida
src/main/java/ca/corefacility/bioinformatics/irida/ria/web/services/UIClientService.java
7213
package ca.corefacility.bioinformatics.irida.ria.web.services; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.stream.Collectors; import javax.validation.ConstraintViolationException; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.context.MessageSource; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.jpa.domain.Specification; import org.springframework.security.oauth2.provider.NoSuchClientException; import org.springframework.stereotype.Component; import ca.corefacility.bioinformatics.irida.exceptions.EntityExistsException; import ca.corefacility.bioinformatics.irida.model.IridaClientDetails; import ca.corefacility.bioinformatics.irida.repositories.specification.IridaClientDetailsSpecification; import ca.corefacility.bioinformatics.irida.ria.web.ajax.dto.clients.ClientTableModel; import ca.corefacility.bioinformatics.irida.ria.web.ajax.dto.clients.ClientTableRequest; import ca.corefacility.bioinformatics.irida.ria.web.ajax.dto.clients.CreateUpdateClientDetails; import ca.corefacility.bioinformatics.irida.ria.web.models.tables.TableResponse; import ca.corefacility.bioinformatics.irida.service.IridaClientDetailsService; import com.google.common.collect.Sets; /** * UI Service to handle IRIDA Clients */ @Component public class UIClientService { private final IridaClientDetailsService clientDetailsService; private final MessageSource messageSource; private final String AUTO_APPROVE = "auto"; private final String SCOPE_READ = "read"; private final String SCOPE_WRITE = "write"; private final String GRANT_TYPE_AUTH_CODE = "authorization_code"; public UIClientService(IridaClientDetailsService clientDetailsService, MessageSource messageSource) { this.clientDetailsService = clientDetailsService; this.messageSource = messageSource; } /** * Get a listing of clients based on the table request. * * @param tableRequest Information about the sort and page of the table. * @return Current status of the table */ public TableResponse<ClientTableModel> getClientList(ClientTableRequest tableRequest) { Specification<IridaClientDetails> specification = IridaClientDetailsSpecification.searchClient( tableRequest.getSearch()); Page<IridaClientDetails> page = clientDetailsService.search(specification, PageRequest.of(tableRequest.getCurrent(), tableRequest.getPageSize(), tableRequest.getSort())); List<ClientTableModel> models = page.getContent() .stream() .map(client -> new ClientTableModel(client, clientDetailsService.countActiveTokensForClient(client))) .collect(Collectors.toList()); return new TableResponse<>(models, page.getTotalElements()); } /** * Revoke all tokens for a specific client * * @param id Identifier for a client */ public void deleteClientTokens(Long id) { IridaClientDetails details = clientDetailsService.read(id); clientDetailsService.revokeTokensForClient(details); } /** * Validate a client identifier for a new client * * @param clientId Identifier to check to see if it exists * @throws NoSuchClientException thrown if a client does not exist with the given client id. */ public void validateClientId(String clientId) throws NoSuchClientException { clientDetailsService.loadClientByClientId(clientId); } /** * Create a new client * * @param request Details about the new client * @param locale Current users {@link Locale} * @return A message to the user about the result of the create/update * @throws EntityExistsException thrown if the client id already is used. * @throws ConstraintViolationException thrown if the client id violates any of its constraints */ public String createOrUpdateClient(CreateUpdateClientDetails request, Locale locale) throws EntityExistsException, ConstraintViolationException { IridaClientDetails client; if (request.getId() != null) { // Existing client client = clientDetailsService.read(request.getId()); } else { // New client, so need to set up a few things that cannot be mutated in an existing one client = new IridaClientDetails(); client.setClientSecret(generateClientSecret()); client.setClientId(request.getClientId()); } client.setAccessTokenValiditySeconds(request.getTokenValidity()); // Let's set up the scopes for this client Set<String> scopes = new HashSet<>(); Set<String> autoScopes = new HashSet<>(); // 1. Read scope if (request.getRead() .equals(SCOPE_READ)) { scopes.add(SCOPE_READ); } else if (request.getRead() .equals(AUTO_APPROVE)) { scopes.add(SCOPE_READ); autoScopes.add(SCOPE_READ); } // 2. Write scope if (request.getWrite() .equals(SCOPE_WRITE)) { scopes.add(SCOPE_WRITE); } else if (request.getWrite() .equals(AUTO_APPROVE)) { scopes.add(SCOPE_WRITE); autoScopes.add(SCOPE_WRITE); } client.setScope(scopes); client.setAutoApprovableScopes(autoScopes); // Set the grant type client.setAuthorizedGrantTypes(Sets.newHashSet(request.getGrantType())); if (request.getGrantType() .equals(GRANT_TYPE_AUTH_CODE)) { client.setRegisteredRedirectUri(request.getRedirectURI()); } // See if allowed refresh tokens if (request.getRefreshToken() > 0) { client.getAuthorizedGrantTypes().add("refresh_token"); client.setRefreshTokenValiditySeconds(request.getRefreshToken()); } if (client.getId() != null) { clientDetailsService.update(client); return messageSource.getMessage("server.UpdateClientForm.success", new Object[] { client.getClientId() }, locale); } else { client = clientDetailsService.create(client); return messageSource.getMessage("server.AddClientForm.success", new Object[] { client.getClientId() }, locale); } } /** * Delete a client * * @param id Identifier for the client to delete */ public void deleteClient(Long id) { clientDetailsService.delete(id); } /** * Generate a new client secret * * @param id identifier for a client */ public void regenerateClientSecret(Long id) { IridaClientDetails details = clientDetailsService.read(id); String secret = generateClientSecret(); details.setClientSecret(secret); clientDetailsService.update(details); } private String generateClientSecret() { return RandomStringUtils.randomAlphanumeric(42); } }
apache-2.0
sarvex/MINA
core/src/main/java/org/apache/mina/common/ThreadModel.java
1632
/* * 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.mina.common; /** * Represents a thread model of an {@link IoService}. There's no essential * difference from {@link IoFilterChainBuilder}. The only difference is that * {@link ThreadModel} is executed later than the {@link IoFilterChainBuilder} * you specified. However, please don't abuse this internal behavior; it can * change. * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public interface ThreadModel extends IoFilterChainBuilder { /** * A {@link ThreadModel} which make MINA not manage a thread model at all. */ static final ThreadModel MANUAL = new ThreadModel() { public void buildFilterChain(IoFilterChain chain) throws Exception { // Do nothing. } }; }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-managedblockchain/src/main/java/com/amazonaws/services/managedblockchain/model/transform/DeleteMemberRequestProtocolMarshaller.java
2674
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.managedblockchain.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.managedblockchain.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * DeleteMemberRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DeleteMemberRequestProtocolMarshaller implements Marshaller<Request<DeleteMemberRequest>, DeleteMemberRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON) .requestUri("/networks/{networkId}/members/{memberId}").httpMethodName(HttpMethodName.DELETE).hasExplicitPayloadMember(false) .hasPayloadMembers(false).serviceName("AmazonManagedBlockchain").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public DeleteMemberRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<DeleteMemberRequest> marshall(DeleteMemberRequest deleteMemberRequest) { if (deleteMemberRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<DeleteMemberRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, deleteMemberRequest); protocolMarshaller.startMarshalling(); DeleteMemberRequestMarshaller.getInstance().marshall(deleteMemberRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
triathematician/blaisemath
blaise-graph-theory-ui/src/test/java/com/googlecode/blaisemath/graph/test/DynamicGraphTestFrame.java
14531
package com.googlecode.blaisemath.graph.test; /* * #%L * BlaiseGraphTheory * -- * Copyright (C) 2009 - 2021 Elisha Peterson * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.google.common.graph.Graph; import com.google.common.graph.Graphs; import com.googlecode.blaisemath.graph.layout.CircleLayout; import com.googlecode.blaisemath.graph.layout.CircleLayout.CircleLayoutParameters; import com.googlecode.blaisemath.graph.layout.RandomBoxLayout; import com.googlecode.blaisemath.graph.layout.RandomBoxLayout.BoxLayoutParameters; import com.googlecode.blaisemath.graph.layout.SpringLayout; import com.googlecode.blaisemath.graph.layout.SpringLayoutParameters; import com.googlecode.blaisemath.graph.view.GraphComponent; import com.googlecode.blaisemath.graph.view.VisualGraph; import com.googlecode.blaisemath.graphics.Graphic; import com.googlecode.blaisemath.util.Instrument; import com.googlecode.blaisemath.firestarter.editor.EditorRegistration; import com.googlecode.blaisemath.firestarter.property.PropertySheet; import com.googlecode.blaisemath.firestarter.swing.RollupPanel; import javax.swing.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.Rectangle2D; @SuppressWarnings("ALL") public class DynamicGraphTestFrame extends javax.swing.JFrame { VisualGraph pga; /** Flag for when el needs points updated */ boolean updateEL = true; SpringLayout energyLayout; final SpringLayoutParameters layoutParams; final MyTestGraph graph = new MyTestGraph(); Graph<String> graphCopy; public DynamicGraphTestFrame() { EditorRegistration.registerEditors(); initComponents(); graphCopy = Graphs.copyOf(graph); plot.setGraph(graphCopy); plot.getAdapter().getViewGraph().setDragEnabled(true); plot.getAdapter().getViewGraph().setPointSelectionEnabled(true); // PANELS energyLayout = new SpringLayout(); layoutParams = energyLayout.createParameters(); rollupPanel1.add("Energy Layout", PropertySheet.forBean(layoutParams)); for (Graphic p : plot.getGraphicRoot().getGraphics()) { rollupPanel1.add(p.toString(), PropertySheet.forBean(p)); } addWindowListener(new WindowAdapter(){ @Override public void windowClosing(WindowEvent e) { Instrument.print(System.out, 50); } }); } /** 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. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jToolBar1 = new javax.swing.JToolBar(); randomLB = new javax.swing.JButton(); circleLB = new javax.swing.JButton(); jSeparator1 = new javax.swing.JToolBar.Separator(); jLabel1 = new javax.swing.JLabel(); energyIB = new javax.swing.JButton(); energyAB = new javax.swing.JButton(); energySB = new javax.swing.JButton(); jSeparator2 = new javax.swing.JToolBar.Separator(); jLabel2 = new javax.swing.JLabel(); addEdgesB = new javax.swing.JButton(); rewireB = new javax.swing.JButton(); addThreadedB = new javax.swing.JButton(); addNodesB = new javax.swing.JButton(); threadStopB = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); rollupPanel1 = new RollupPanel(); plot = new GraphComponent(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBackground(new java.awt.Color(0, 0, 0)); jToolBar1.setRollover(true); randomLB.setText("Random Layout"); randomLB.setFocusable(false); randomLB.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); randomLB.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); randomLB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { randomLBActionPerformed(evt); } }); jToolBar1.add(randomLB); circleLB.setText("Circle Layout"); circleLB.setFocusable(false); circleLB.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); circleLB.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); circleLB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { circleLBActionPerformed(evt); } }); jToolBar1.add(circleLB); jToolBar1.add(jSeparator1); jLabel1.setText("ENERGY:"); jToolBar1.add(jLabel1); energyIB.setText("iterate"); energyIB.setFocusable(false); energyIB.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); energyIB.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); energyIB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { energyIBActionPerformed(evt); } }); jToolBar1.add(energyIB); energyAB.setText("animate"); energyAB.setFocusable(false); energyAB.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); energyAB.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); energyAB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { energyABActionPerformed(evt); } }); jToolBar1.add(energyAB); energySB.setText("stop"); energySB.setFocusable(false); energySB.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); energySB.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); energySB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { energySBActionPerformed(evt); } }); jToolBar1.add(energySB); jToolBar1.add(jSeparator2); jLabel2.setText("ADD:"); jToolBar1.add(jLabel2); addNodesB.setText("nodes"); addNodesB.setFocusable(false); addNodesB.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); addNodesB.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); addNodesB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addNodesBActionPerformed(evt); } }); jToolBar1.add(addNodesB); addEdgesB.setText("edges"); addEdgesB.setFocusable(false); addEdgesB.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); addEdgesB.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); addEdgesB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addEdgesBActionPerformed(evt); } }); jToolBar1.add(addEdgesB); rewireB.setText("rewire"); rewireB.setFocusable(false); rewireB.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); rewireB.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); rewireB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { rewireBActionPerformed(evt); } }); jToolBar1.add(rewireB); addThreadedB.setText("threaded"); addThreadedB.setFocusable(false); addThreadedB.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); addThreadedB.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); addThreadedB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addThreadedBActionPerformed(evt); } }); jToolBar1.add(addThreadedB); threadStopB.setText("stop"); threadStopB.setFocusable(false); threadStopB.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); threadStopB.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); threadStopB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { threadStopBActionPerformed(evt); } }); jToolBar1.add(threadStopB); getContentPane().add(jToolBar1, java.awt.BorderLayout.PAGE_START); jScrollPane1.setViewportView(rollupPanel1); getContentPane().add(jScrollPane1, java.awt.BorderLayout.EAST); getContentPane().add(plot, java.awt.BorderLayout.CENTER); pack(); }// </editor-fold>//GEN-END:initComponents private void randomLBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_randomLBActionPerformed updateEL = true; plot.getLayoutManager().applyLayout(RandomBoxLayout.getInstance(), null, new BoxLayoutParameters(new Rectangle2D.Double(-500, -500, 1000, 1000))); }//GEN-LAST:event_randomLBActionPerformed private void circleLBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_circleLBActionPerformed updateEL = true; plot.getLayoutManager().applyLayout(CircleLayout.getInstance(), null, new CircleLayoutParameters(500.0)); }//GEN-LAST:event_circleLBActionPerformed private void energyIBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_energyIBActionPerformed if (energyLayout == null) { energyLayout = new SpringLayout(); } plot.getLayoutManager().setLayoutAlgorithm(energyLayout); plot.getLayoutManager().setLayoutParameters(layoutParams); plot.getLayoutManager().iterateLayout(); updateEL = false; }//GEN-LAST:event_energyIBActionPerformed private void energyABActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_energyABActionPerformed if (energyLayout == null) { energyLayout = new SpringLayout(); } plot.getLayoutManager().setLayoutAlgorithm(energyLayout); plot.getLayoutManager().setLayoutParameters(layoutParams); plot.getLayoutManager().setLayoutTaskActive(true); }//GEN-LAST:event_energyABActionPerformed private void energySBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_energySBActionPerformed plot.getLayoutManager().setLayoutTaskActive(false); }//GEN-LAST:event_energySBActionPerformed private synchronized void updateGraph() { SwingUtilities.invokeLater(() -> { graphCopy = Graphs.copyOf(graph); plot.getLayoutManager().setGraph(graphCopy); plot.getAdapter().getViewGraph().setEdgeSet(graphCopy.edges()); }); } private void addNodesBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addNodesBActionPerformed graph.addNodes(5); updateGraph(); }//GEN-LAST:event_addNodesBActionPerformed private void addEdgesBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addEdgesBActionPerformed graph.addEdges(5); updateGraph(); }//GEN-LAST:event_addEdgesBActionPerformed private void rewireBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rewireBActionPerformed graph.rewire(50, 5); updateGraph(); }//GEN-LAST:event_rewireBActionPerformed final java.util.Timer t = new java.util.Timer(); java.util.TimerTask tt; private void addThreadedBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addThreadedBActionPerformed if (tt != null) { tt.cancel(); } tt = new java.util.TimerTask() { @Override public void run() { graph.removeEdges(10); graph.addNodes(1); graph.removeNodes(1); graph.addEdges(2); updateGraph(); } }; t.schedule(tt, 100, 500); }//GEN-LAST:event_addThreadedBActionPerformed private void threadStopBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_threadStopBActionPerformed if (tt != null) { tt.cancel(); } }//GEN-LAST:event_threadStopBActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(() -> new DynamicGraphTestFrame().setVisible(true)); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addEdgesB; private javax.swing.JButton addThreadedB; private javax.swing.JButton addNodesB; private javax.swing.JButton circleLB; private javax.swing.JButton energyAB; private javax.swing.JButton energyIB; private javax.swing.JButton energySB; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JToolBar.Separator jSeparator1; private javax.swing.JToolBar.Separator jSeparator2; private javax.swing.JToolBar jToolBar1; private GraphComponent plot; private javax.swing.JButton randomLB; private javax.swing.JButton rewireB; private RollupPanel rollupPanel1; private javax.swing.JButton threadStopB; // End of variables declaration//GEN-END:variables }
apache-2.0
christianfranco/the-clean-code-bay
geo-match/server/core/src/main/java/com/github/christianfranco/geomatch/exception/PhoneNumberRepositoryException.java
498
package com.github.christianfranco.geomatch.exception; import com.github.christianfranco.geomatch.entities.ErrorCode; /** * Created by Christian Franco on 12/12/2016 14:03. */ public class PhoneNumberRepositoryException extends GeoMathException { public PhoneNumberRepositoryException(ErrorCode errorCode) { super(errorCode); } public PhoneNumberRepositoryException(ErrorCode errorCode, String... parameters) { super(errorCode, parameters); } }
apache-2.0
ljcservice/autumnprogram
src/main/java/com/ts/util/doctor/DoctorConst.java
1159
package com.ts.util.doctor; import java.util.HashMap; import java.util.Map; public class DoctorConst { public static Map<String,String> rstypeMap = new HashMap<String,String>(); static{ rstypeMap.put("diaginfo","禁"); rstypeMap.put("dosage","法"); rstypeMap.put("ingredien","重"); rstypeMap.put("interaction","相"); rstypeMap.put("iv_effect","配"); rstypeMap.put("side","反"); rstypeMap.put("administrator","途"); rstypeMap.put("specpeople","特"); rstypeMap.put("manager","管"); rstypeMap.put("manager4Two", "管"); } public static Map<String,String> rstypeColorMap = new HashMap<String,String>(); static{ rstypeColorMap.put("diaginfo","btn-pink"); rstypeColorMap.put("dosage","btn-warning"); rstypeColorMap.put("ingredien","btn-success"); rstypeColorMap.put("interaction","btn-yellow"); rstypeColorMap.put("iv_effect","btn-grey"); rstypeColorMap.put("side","btn-danger"); rstypeColorMap.put("administrator","btn-info"); rstypeColorMap.put("specpeople","btn-purple"); rstypeColorMap.put("manager","btn-success"); rstypeColorMap.put("manager4Two","btn-success"); } }
apache-2.0
xxxllluuu/uavstack
com.creditease.uav.agent.heartbeat/src/main/java/com/creditease/agent/feature/hbagent/HeartBeatQueryListenWorker.java
1807
/*- * << * UAVStack * == * Copyright (C) 2016 - 2017 UAVStack * == * 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.creditease.agent.feature.hbagent; import com.creditease.agent.http.api.UAVHttpMessage; import com.creditease.agent.spi.AbstractHttpServiceComponent; import com.creditease.agent.spi.HttpMessage; public class HeartBeatQueryListenWorker extends AbstractHttpServiceComponent<UAVHttpMessage> { public HeartBeatQueryListenWorker(String cName, String feature, String initHandlerKey) { super(cName, feature, initHandlerKey); } @Override protected UAVHttpMessage adaptRequest(HttpMessage message) { String messageBody = message.getRequestBodyAsString("UTF-8"); if (log.isDebugEnable()) { log.debug(this, "HeartBeatQueryListenWorker Request: " + messageBody); } UAVHttpMessage msg = new UAVHttpMessage(messageBody); return msg; } @Override protected void adaptResponse(HttpMessage message, UAVHttpMessage t) { String response = t.getResponseAsJsonString(); message.putResponseBodyInString(response, 200, "utf-8"); if (log.isDebugEnable()) { log.debug(this, "HeartBeatQueryListenWorker Response: " + response); } } }
apache-2.0
learning-layers/LivingDocumentsServer
ld-etherpad/src/main/java/de/hska/ld/etherpad/service/UserEtherpadInfoService.java
1589
/* * Code contributed to the Learning Layers project * http://www.learning-layers.eu * Development is partly funded by the FP7 Programme of the European * Commission under Grant Agreement FP7-ICT-318209. * Copyright (c) 2016, Karlsruhe University of Applied Sciences. * For a list of contributors see the AUTHORS file at the top-level directory * of this distribution. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.hska.ld.etherpad.service; import de.hska.ld.etherpad.persistence.domain.UserEtherpadInfo; public interface UserEtherpadInfoService { public UserEtherpadInfo save(UserEtherpadInfo userEtherpadInfo); public UserEtherpadInfo findById(Long id); public void storeSessionForUser(String sessionId, String groupId, Long validUntil, UserEtherpadInfo userEtherpadInfo); public void storeAuthorIdForCurrentUser(String authorId); public UserEtherpadInfo getUserEtherpadInfoForCurrentUser(); public UserEtherpadInfo findByAuthorId(String authorId); UserEtherpadInfo findBySessionId(String sessionId); }
apache-2.0
z123/datacollector
container/src/main/java/com/streamsets/datacollector/config/ModelDefinition.java
3255
/* * Copyright 2017 StreamSets Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.streamsets.datacollector.config; import com.streamsets.pipeline.api.impl.Utils; import java.util.HashMap; import java.util.List; import java.util.Map; public class ModelDefinition { private final ModelType modelType; private final String valuesProviderClass; private final List<ConfigDefinition> configDefinitions; private final Map<String, ConfigDefinition> configDefinitionsAsMap; private List<String> values; private List<String> labels; private final Class listBeanClass; public static ModelDefinition localizedValueChooser(ModelDefinition model, List<String> values, List<String> labels) { return new ModelDefinition(model.getModelType(), model.getValuesProviderClass(), values, labels, model.getListBeanClass(), model.getConfigDefinitions()); } public static ModelDefinition localizedComplexField(ModelDefinition model, List<ConfigDefinition> configDefs) { return new ModelDefinition(model.getModelType(), model.getValuesProviderClass(), model.getValues(), model.getLabels(), model.getListBeanClass(), configDefs); } public ModelDefinition(ModelType modelType, String valuesProviderClass, List<String> values, List<String> labels, Class listBeanClass, List<ConfigDefinition> configDefinitions) { this.modelType = modelType; this.valuesProviderClass = valuesProviderClass; this.configDefinitions = configDefinitions; configDefinitionsAsMap = new HashMap<>(); if (configDefinitions != null) { for (ConfigDefinition def : configDefinitions) { configDefinitionsAsMap.put(def.getName(), def); } } this.values = values; this.labels = labels; this.listBeanClass = listBeanClass; } public ModelType getModelType() { return modelType; } public List<String> getValues() { return values; } public List<String> getLabels() { return labels; } public String getValuesProviderClass() { return valuesProviderClass; } public void setValues(List<String> values) { this.values = values; } public void setLabels(List<String> labels) { this.labels = labels; } public Class getListBeanClass() { return listBeanClass; } public List<ConfigDefinition> getConfigDefinitions() { return configDefinitions; } public Map<String, ConfigDefinition> getConfigDefinitionsAsMap() { return configDefinitionsAsMap; } @Override public String toString() { return Utils.format("ModelDefinition[type='{}' valuesProviderClass='{}' values='{}']", getModelType(), getValues(), getValuesProviderClass()); } }
apache-2.0
dmarius99/ImplementationDiscriminator
src/test/java/any/ejbtest/MoviesImplWrapper.java
826
package any.ejbtest; import com.dms.Discriminated; import java.util.List; /** * MoviesImplEjb, 02.03.2015 * * Copyright (c) 2014 Marius Dinu. All rights reserved. * * @author mdinu * @version $Id$ */ //@Named @Discriminated(isResultAggregated = true) public class MoviesImplWrapper implements Movies { private Movies movies; public void setMovies(Movies movies) { this.movies = movies; } public Movies getMovies() { return movies; } @Override public void addMovie(Movie movie) throws Exception { movies.addMovie(movie); } @Override public void deleteMovie(Movie movie) throws Exception { movies.deleteMovie(movie); } @Override public List<Movie> getAllMovies() throws Exception { return movies.getAllMovies(); } }
apache-2.0
statefulj/statefulj
statefulj-persistence/statefulj-persistence-jpa/src/test/java/org/statefulj/persistence/jpa/embedded/EmbeddedJPAPersisterTest.java
4425
/*** * * Copyright 2014 Andrew Hall * * 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.statefulj.persistence.jpa.embedded; import static org.junit.Assert.*; import java.lang.reflect.Field; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.statefulj.fsm.Persister; import org.statefulj.fsm.StaleStateException; import org.statefulj.fsm.model.State; import org.statefulj.persistence.jpa.model.StatefulEntity; import org.statefulj.persistence.jpa.utils.UnitTestUtils; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"/applicationContext-JPAPersisterTests.xml"}) public class EmbeddedJPAPersisterTest { @Resource Persister<EmbeddedOrder> embeddedJPAPersister; @Resource EmbeddedOrderRepository embeddedOrderRepo; @Resource JpaTransactionManager transactionManager; @Resource State<EmbeddedOrder> stateA; @Resource State<EmbeddedOrder> stateB; @Resource State<EmbeddedOrder> stateC; @Test public void testValidStateChange() throws StaleStateException, IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { UnitTestUtils.startTransaction(transactionManager); // Verify that a new Order without a state set, we return the Start State // EmbeddedOrderId id = new EmbeddedOrderId(); id.setId(1L); EmbeddedOrder order = new EmbeddedOrder(id); order.setAmount(20); order = this.embeddedOrderRepo.save(order); State<EmbeddedOrder> currentState = embeddedJPAPersister.getCurrent(order); assertEquals(stateA, currentState); // Verify that qualified a change in state works // embeddedJPAPersister.setCurrent(order, stateA, stateB); assertEquals(order.getState(), stateB.getName()); EmbeddedOrder dbOrder = embeddedOrderRepo.findOne(order.getOrderId()); assertEquals(order.getState(), dbOrder.getState()); embeddedJPAPersister.setCurrent(order, stateB, stateC); assertEquals(order.getState(), stateC.getName()); dbOrder = embeddedOrderRepo.findOne(order.getOrderId()); assertEquals(order.getState(), dbOrder.getState()); // Verify that updating the state without going through the Persister doesn't wok // id = new EmbeddedOrderId(); id.setId(2L); order = new EmbeddedOrder(id); embeddedJPAPersister.setCurrent(order, stateA, stateB); order = this.embeddedOrderRepo.save(order); dbOrder = embeddedOrderRepo.findOne(order.getOrderId()); currentState = embeddedJPAPersister.getCurrent(dbOrder); assertEquals(stateB, currentState); Field stateField = StatefulEntity.class.getDeclaredField("state"); stateField.setAccessible(true); stateField.set(dbOrder, "stateD"); dbOrder.setAmount(100); this.embeddedOrderRepo.save(dbOrder); UnitTestUtils.commitTransaction(transactionManager); UnitTestUtils.startTransaction(transactionManager); dbOrder = this.embeddedOrderRepo.findOne(dbOrder.getOrderId()); currentState = embeddedJPAPersister.getCurrent(dbOrder); assertEquals(stateB.getName(), currentState.getName()); assertEquals(100, dbOrder.getAmount()); UnitTestUtils.commitTransaction(transactionManager); } @Test(expected=StaleStateException.class) public void testInvalidStateChange() throws StaleStateException { UnitTestUtils.startTransaction(transactionManager); EmbeddedOrderId id = new EmbeddedOrderId(); id.setId(1L); EmbeddedOrder order = new EmbeddedOrder(id); order.setAmount(20); embeddedOrderRepo.save(order); State<EmbeddedOrder> currentState = embeddedJPAPersister.getCurrent(order); assertEquals(stateA, currentState); embeddedJPAPersister.setCurrent(order, stateB, stateC); UnitTestUtils.commitTransaction(transactionManager); } }
apache-2.0
hotpads/datarouter
datarouter-mysql/src/main/java/io/datarouter/client/mysql/ddl/domain/SqlIndex.java
1493
/* * Copyright © 2009 HotPads (admin@hotpads.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.datarouter.client.mysql.ddl.domain; import java.util.List; import java.util.Objects; public class SqlIndex{ private final String name; private final List<String> columnNames; public SqlIndex(String name, List<String> columns){ this.name = name; this.columnNames = columns; } public String getName(){ return name; } public List<String> getColumnNames(){ return columnNames; } @Override public int hashCode(){ return Objects.hash(name, columnNames); } @Override public boolean equals(Object obj){ if(this == obj){ return true; } if(!(obj instanceof SqlIndex)){ return false; } SqlIndex other = (SqlIndex)obj; return Objects.equals(name, other.name) && Objects.equals(columnNames, other.columnNames); } public static SqlIndex createPrimaryKey(List<String> columns){ return new SqlIndex("PRIMARY", columns); } }
apache-2.0
SES-fortiss/SmartGridCoSimulation
core/cim15/src/CIM15/IEC61970/Wires/PerLengthPhaseImpedance.java
10430
/** */ package CIM15.IEC61970.Wires; import CIM15.IEC61970.Core.IdentifiedObject; import java.util.Collection; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.util.BasicInternalEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Per Length Phase Impedance</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link CIM15.IEC61970.Wires.PerLengthPhaseImpedance#getLineSegments <em>Line Segments</em>}</li> * <li>{@link CIM15.IEC61970.Wires.PerLengthPhaseImpedance#getConductorCount <em>Conductor Count</em>}</li> * <li>{@link CIM15.IEC61970.Wires.PerLengthPhaseImpedance#getPhaseImpedanceData <em>Phase Impedance Data</em>}</li> * </ul> * </p> * * @generated */ public class PerLengthPhaseImpedance extends IdentifiedObject { /** * The cached value of the '{@link #getLineSegments() <em>Line Segments</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLineSegments() * @generated * @ordered */ protected EList<ACLineSegment> lineSegments; /** * The default value of the '{@link #getConductorCount() <em>Conductor Count</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getConductorCount() * @generated * @ordered */ protected static final int CONDUCTOR_COUNT_EDEFAULT = 0; /** * The cached value of the '{@link #getConductorCount() <em>Conductor Count</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getConductorCount() * @generated * @ordered */ protected int conductorCount = CONDUCTOR_COUNT_EDEFAULT; /** * This is true if the Conductor Count attribute has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ protected boolean conductorCountESet; /** * The cached value of the '{@link #getPhaseImpedanceData() <em>Phase Impedance Data</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPhaseImpedanceData() * @generated * @ordered */ protected EList<PhaseImpedanceData> phaseImpedanceData; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected PerLengthPhaseImpedance() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return WiresPackage.Literals.PER_LENGTH_PHASE_IMPEDANCE; } /** * Returns the value of the '<em><b>Line Segments</b></em>' reference list. * The list contents are of type {@link CIM15.IEC61970.Wires.ACLineSegment}. * It is bidirectional and its opposite is '{@link CIM15.IEC61970.Wires.ACLineSegment#getPhaseImpedance <em>Phase Impedance</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Line Segments</em>' reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Line Segments</em>' reference list. * @see CIM15.IEC61970.Wires.ACLineSegment#getPhaseImpedance * @generated */ public EList<ACLineSegment> getLineSegments() { if (lineSegments == null) { lineSegments = new BasicInternalEList<ACLineSegment>(ACLineSegment.class); } return lineSegments; } /** * Returns the value of the '<em><b>Conductor Count</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Conductor Count</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Conductor Count</em>' attribute. * @see #isSetConductorCount() * @see #unsetConductorCount() * @see #setConductorCount(int) * @generated */ public int getConductorCount() { return conductorCount; } /** * Sets the value of the '{@link CIM15.IEC61970.Wires.PerLengthPhaseImpedance#getConductorCount <em>Conductor Count</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Conductor Count</em>' attribute. * @see #isSetConductorCount() * @see #unsetConductorCount() * @see #getConductorCount() * @generated */ public void setConductorCount(int newConductorCount) { conductorCount = newConductorCount; conductorCountESet = true; } /** * Unsets the value of the '{@link CIM15.IEC61970.Wires.PerLengthPhaseImpedance#getConductorCount <em>Conductor Count</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetConductorCount() * @see #getConductorCount() * @see #setConductorCount(int) * @generated */ public void unsetConductorCount() { conductorCount = CONDUCTOR_COUNT_EDEFAULT; conductorCountESet = false; } /** * Returns whether the value of the '{@link CIM15.IEC61970.Wires.PerLengthPhaseImpedance#getConductorCount <em>Conductor Count</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Conductor Count</em>' attribute is set. * @see #unsetConductorCount() * @see #getConductorCount() * @see #setConductorCount(int) * @generated */ public boolean isSetConductorCount() { return conductorCountESet; } /** * Returns the value of the '<em><b>Phase Impedance Data</b></em>' reference list. * The list contents are of type {@link CIM15.IEC61970.Wires.PhaseImpedanceData}. * It is bidirectional and its opposite is '{@link CIM15.IEC61970.Wires.PhaseImpedanceData#getPhaseImpedance <em>Phase Impedance</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Phase Impedance Data</em>' reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Phase Impedance Data</em>' reference list. * @see CIM15.IEC61970.Wires.PhaseImpedanceData#getPhaseImpedance * @generated */ public EList<PhaseImpedanceData> getPhaseImpedanceData() { if (phaseImpedanceData == null) { phaseImpedanceData = new BasicInternalEList<PhaseImpedanceData>(PhaseImpedanceData.class); } return phaseImpedanceData; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__LINE_SEGMENTS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getLineSegments()).basicAdd(otherEnd, msgs); case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__PHASE_IMPEDANCE_DATA: return ((InternalEList<InternalEObject>)(InternalEList<?>)getPhaseImpedanceData()).basicAdd(otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__LINE_SEGMENTS: return ((InternalEList<?>)getLineSegments()).basicRemove(otherEnd, msgs); case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__PHASE_IMPEDANCE_DATA: return ((InternalEList<?>)getPhaseImpedanceData()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__LINE_SEGMENTS: return getLineSegments(); case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__CONDUCTOR_COUNT: return getConductorCount(); case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__PHASE_IMPEDANCE_DATA: return getPhaseImpedanceData(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__LINE_SEGMENTS: getLineSegments().clear(); getLineSegments().addAll((Collection<? extends ACLineSegment>)newValue); return; case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__CONDUCTOR_COUNT: setConductorCount((Integer)newValue); return; case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__PHASE_IMPEDANCE_DATA: getPhaseImpedanceData().clear(); getPhaseImpedanceData().addAll((Collection<? extends PhaseImpedanceData>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__LINE_SEGMENTS: getLineSegments().clear(); return; case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__CONDUCTOR_COUNT: unsetConductorCount(); return; case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__PHASE_IMPEDANCE_DATA: getPhaseImpedanceData().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__LINE_SEGMENTS: return lineSegments != null && !lineSegments.isEmpty(); case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__CONDUCTOR_COUNT: return isSetConductorCount(); case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__PHASE_IMPEDANCE_DATA: return phaseImpedanceData != null && !phaseImpedanceData.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (conductorCount: "); if (conductorCountESet) result.append(conductorCount); else result.append("<unset>"); result.append(')'); return result.toString(); } } // PerLengthPhaseImpedance
apache-2.0
OurFriendIrony/MediaNotifier
app/src/main/java/uk/co/ourfriendirony/medianotifier/clients/tmdb/movie/get/MovieGet.java
11616
package uk.co.ourfriendirony.medianotifier.clients.tmdb.movie.get; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "adult", "backdrop_path", "belongs_to_collection", "budget", "movieGetGenres", "homepage", "id", "imdb_id", "original_language", "original_title", "overview", "popularity", "poster_path", "production_companies", "production_countries", "release_date", "revenue", "runtime", "spoken_languages", "status", "tagline", "title", "video", "vote_average", "vote_count", "external_ids" }) public class MovieGet { @JsonProperty("adult") private Boolean adult; @JsonProperty("backdrop_path") private String backdropPath; @JsonProperty("belongs_to_collection") private MovieGetBelongsToCollection belongsToCollection; @JsonProperty("budget") private Integer budget; @JsonProperty("movieGetGenres") private List<MovieGetGenre> movieGetGenres = null; @JsonProperty("homepage") private String homepage; @JsonProperty("id") private Integer id; @JsonProperty("imdb_id") private String imdbId; @JsonProperty("original_language") private String originalLanguage; @JsonProperty("original_title") private String originalTitle; @JsonProperty("overview") private String overview; @JsonProperty("popularity") private Double popularity; @JsonProperty("poster_path") private String posterPath; @JsonProperty("production_companies") private List<MovieGetProductionCompany> productionCompanies = null; @JsonProperty("production_countries") private List<MovieGetProductionCountry> productionCountries = null; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") @JsonProperty("release_date") private Date releaseDate; @JsonProperty("revenue") private Integer revenue; @JsonProperty("runtime") private Integer runtime; @JsonProperty("spoken_languages") private List<MovieGetSpokenLanguage> movieGetSpokenLanguages = null; @JsonProperty("status") private String status; @JsonProperty("tagline") private String tagline; @JsonProperty("title") private String title; @JsonProperty("video") private Boolean video; @JsonProperty("vote_average") private Double voteAverage; @JsonProperty("vote_count") private Integer voteCount; @JsonProperty("external_ids") private MovieGetExternalIds movieGetExternalIds; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("adult") public Boolean getAdult() { return adult; } @JsonProperty("adult") public void setAdult(Boolean adult) { this.adult = adult; } @JsonProperty("backdrop_path") public String getBackdropPath() { return backdropPath; } @JsonProperty("backdrop_path") public void setBackdropPath(String backdropPath) { this.backdropPath = backdropPath; } @JsonProperty("belongs_to_collection") public MovieGetBelongsToCollection getBelongsToCollection() { return belongsToCollection; } @JsonProperty("belongs_to_collection") public void setBelongsToCollection(MovieGetBelongsToCollection belongsToCollection) { this.belongsToCollection = belongsToCollection; } @JsonProperty("budget") public Integer getBudget() { return budget; } @JsonProperty("budget") public void setBudget(Integer budget) { this.budget = budget; } @JsonProperty("movieGetGenres") public List<MovieGetGenre> getMovieGetGenres() { return movieGetGenres; } @JsonProperty("movieGetGenres") public void setMovieGetGenres(List<MovieGetGenre> movieGetGenres) { this.movieGetGenres = movieGetGenres; } @JsonProperty("homepage") public String getHomepage() { return homepage; } @JsonProperty("homepage") public void setHomepage(String homepage) { this.homepage = homepage; } @JsonProperty("id") public Integer getId() { return id; } @JsonProperty("id") public void setId(Integer id) { this.id = id; } @JsonProperty("imdb_id") public String getImdbId() { return imdbId; } @JsonProperty("imdb_id") public void setImdbId(String imdbId) { this.imdbId = imdbId; } @JsonProperty("original_language") public String getOriginalLanguage() { return originalLanguage; } @JsonProperty("original_language") public void setOriginalLanguage(String originalLanguage) { this.originalLanguage = originalLanguage; } @JsonProperty("original_title") public String getOriginalTitle() { return originalTitle; } @JsonProperty("original_title") public void setOriginalTitle(String originalTitle) { this.originalTitle = originalTitle; } @JsonProperty("overview") public String getOverview() { return overview; } @JsonProperty("overview") public void setOverview(String overview) { this.overview = overview; } @JsonProperty("popularity") public Double getPopularity() { return popularity; } @JsonProperty("popularity") public void setPopularity(Double popularity) { this.popularity = popularity; } @JsonProperty("poster_path") public String getPosterPath() { return posterPath; } @JsonProperty("poster_path") public void setPosterPath(String posterPath) { this.posterPath = posterPath; } @JsonProperty("production_companies") public List<MovieGetProductionCompany> getProductionCompanies() { return productionCompanies; } @JsonProperty("production_companies") public void setProductionCompanies(List<MovieGetProductionCompany> productionCompanies) { this.productionCompanies = productionCompanies; } @JsonProperty("production_countries") public List<MovieGetProductionCountry> getProductionCountries() { return productionCountries; } @JsonProperty("production_countries") public void setProductionCountries(List<MovieGetProductionCountry> productionCountries) { this.productionCountries = productionCountries; } @JsonProperty("release_date") public Date getReleaseDate() { return releaseDate; } @JsonProperty("release_date") public void setReleaseDate(Date releaseDate) { this.releaseDate = releaseDate; } @JsonProperty("revenue") public Integer getRevenue() { return revenue; } @JsonProperty("revenue") public void setRevenue(Integer revenue) { this.revenue = revenue; } @JsonProperty("runtime") public Integer getRuntime() { return runtime; } @JsonProperty("runtime") public void setRuntime(Integer runtime) { this.runtime = runtime; } @JsonProperty("spoken_languages") public List<MovieGetSpokenLanguage> getMovieGetSpokenLanguages() { return movieGetSpokenLanguages; } @JsonProperty("spoken_languages") public void setMovieGetSpokenLanguages(List<MovieGetSpokenLanguage> movieGetSpokenLanguages) { this.movieGetSpokenLanguages = movieGetSpokenLanguages; } @JsonProperty("status") public String getStatus() { return status; } @JsonProperty("status") public void setStatus(String status) { this.status = status; } @JsonProperty("tagline") public String getTagline() { return tagline; } @JsonProperty("tagline") public void setTagline(String tagline) { this.tagline = tagline; } @JsonProperty("title") public String getTitle() { return title; } @JsonProperty("title") public void setTitle(String title) { this.title = title; } @JsonProperty("video") public Boolean getVideo() { return video; } @JsonProperty("video") public void setVideo(Boolean video) { this.video = video; } @JsonProperty("vote_average") public Double getVoteAverage() { return voteAverage; } @JsonProperty("vote_average") public void setVoteAverage(Double voteAverage) { this.voteAverage = voteAverage; } @JsonProperty("vote_count") public Integer getVoteCount() { return voteCount; } @JsonProperty("vote_count") public void setVoteCount(Integer voteCount) { this.voteCount = voteCount; } @JsonProperty("external_ids") public MovieGetExternalIds getMovieGetExternalIds() { return movieGetExternalIds; } @JsonProperty("external_ids") public void setMovieGetExternalIds(MovieGetExternalIds movieGetExternalIds) { this.movieGetExternalIds = movieGetExternalIds; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } } //@JsonInclude(JsonInclude.Include.NON_NULL) //@JsonPropertyOrder({ // "id", // "name", // "poster_path", // "backdrop_path" //}) //class MovieGetBelongsToCollection { // // @JsonProperty("id") // private Integer id; // @JsonProperty("name") // private String name; // @JsonProperty("poster_path") // private String posterPath; // @JsonProperty("backdrop_path") // private String backdropPath; // @JsonIgnore // private Map<String, Object> additionalProperties = new HashMap<String, Object>(); // // @JsonProperty("id") // public Integer getId() { // return id; // } // // @JsonProperty("id") // public void setId(Integer id) { // this.id = id; // } // // @JsonProperty("name") // public String getName() { // return name; // } // // @JsonProperty("name") // public void setName(String name) { // this.name = name; // } // // @JsonProperty("poster_path") // public String getPosterPath() { // return posterPath; // } // // @JsonProperty("poster_path") // public void setPosterPath(String posterPath) { // this.posterPath = posterPath; // } // // @JsonProperty("backdrop_path") // public String getBackdropPath() { // return backdropPath; // } // // @JsonProperty("backdrop_path") // public void setBackdropPath(String backdropPath) { // this.backdropPath = backdropPath; // } // // @JsonAnyGetter // public Map<String, Object> getAdditionalProperties() { // return this.additionalProperties; // } // // @JsonAnySetter // public void setAdditionalProperty(String name, Object value) { // this.additionalProperties.put(name, value); // } // //}
apache-2.0
bjorndm/prebake
code/third_party/bdb/examples/je/gettingStarted/ExampleInventoryRead.java
7325
// file ExampleInventoryRead // $Id: ExampleInventoryRead.java,v 1.10 2009/01/09 22:10:13 mark Exp $ package je.gettingStarted; import java.io.File; import java.io.IOException; import com.sleepycat.bind.EntryBinding; import com.sleepycat.bind.serial.SerialBinding; import com.sleepycat.bind.tuple.TupleBinding; import com.sleepycat.je.Cursor; import com.sleepycat.je.DatabaseEntry; import com.sleepycat.je.DatabaseException; import com.sleepycat.je.LockMode; import com.sleepycat.je.OperationStatus; import com.sleepycat.je.SecondaryCursor; public class ExampleInventoryRead { private static File myDbEnvPath = new File("/tmp/JEDB"); // Encapsulates the database environment and databases. private static MyDbEnv myDbEnv = new MyDbEnv(); private static TupleBinding inventoryBinding; private static EntryBinding vendorBinding; // The item to locate if the -s switch is used private static String locateItem; private static void usage() { System.out.println("ExampleInventoryRead [-h <env directory>]" + "[-s <item to locate>]"); System.exit(-1); } public static void main(String args[]) { ExampleInventoryRead eir = new ExampleInventoryRead(); try { eir.run(args); } catch (DatabaseException dbe) { System.err.println("ExampleInventoryRead: " + dbe.toString()); dbe.printStackTrace(); } finally { myDbEnv.close(); } System.out.println("All done."); } private void run(String args[]) throws DatabaseException { // Parse the arguments list parseArgs(args); myDbEnv.setup(myDbEnvPath, // path to the environment home true); // is this environment read-only? // Setup our bindings. inventoryBinding = new InventoryBinding(); vendorBinding = new SerialBinding(myDbEnv.getClassCatalog(), Vendor.class); if (locateItem != null) { showItem(); } else { showAllInventory(); } } private void showItem() throws DatabaseException { SecondaryCursor secCursor = null; try { // searchKey is the key that we want to find in the // secondary db. DatabaseEntry searchKey = new DatabaseEntry(locateItem.getBytes("UTF-8")); // foundKey and foundData are populated from the primary // entry that is associated with the secondary db key. DatabaseEntry foundKey = new DatabaseEntry(); DatabaseEntry foundData = new DatabaseEntry(); // open a secondary cursor secCursor = myDbEnv.getNameIndexDB().openSecondaryCursor(null, null); // Search for the secondary database entry. OperationStatus retVal = secCursor.getSearchKey(searchKey, foundKey, foundData, LockMode.DEFAULT); // Display the entry, if one is found. Repeat until no more // secondary duplicate entries are found while(retVal == OperationStatus.SUCCESS) { Inventory theInventory = (Inventory)inventoryBinding.entryToObject(foundData); displayInventoryRecord(foundKey, theInventory); retVal = secCursor.getNextDup(searchKey, foundKey, foundData, LockMode.DEFAULT); } } catch (Exception e) { System.err.println("Error on inventory secondary cursor:"); System.err.println(e.toString()); e.printStackTrace(); } finally { if (secCursor != null) { secCursor.close(); } } } private void showAllInventory() throws DatabaseException { // Get a cursor Cursor cursor = myDbEnv.getInventoryDB().openCursor(null, null); // DatabaseEntry objects used for reading records DatabaseEntry foundKey = new DatabaseEntry(); DatabaseEntry foundData = new DatabaseEntry(); try { // always want to make sure the cursor gets closed while (cursor.getNext(foundKey, foundData, LockMode.DEFAULT) == OperationStatus.SUCCESS) { Inventory theInventory = (Inventory)inventoryBinding.entryToObject(foundData); displayInventoryRecord(foundKey, theInventory); } } catch (Exception e) { System.err.println("Error on inventory cursor:"); System.err.println(e.toString()); e.printStackTrace(); } finally { cursor.close(); } } private void displayInventoryRecord(DatabaseEntry theKey, Inventory theInventory) throws DatabaseException { DatabaseEntry searchKey = null; try { String theSKU = new String(theKey.getData(), "UTF-8"); System.out.println(theSKU + ":"); System.out.println("\t " + theInventory.getItemName()); System.out.println("\t " + theInventory.getCategory()); System.out.println("\t " + theInventory.getVendor()); System.out.println("\t\tNumber in stock: " + theInventory.getVendorInventory()); System.out.println("\t\tPrice per unit: " + theInventory.getVendorPrice()); System.out.println("\t\tContact: "); searchKey = new DatabaseEntry(theInventory.getVendor().getBytes("UTF-8")); } catch (IOException willNeverOccur) {} DatabaseEntry foundVendor = new DatabaseEntry(); if (myDbEnv.getVendorDB().get(null, searchKey, foundVendor, LockMode.DEFAULT) != OperationStatus.SUCCESS) { System.out.println("Could not find vendor: " + theInventory.getVendor() + "."); System.exit(-1); } else { Vendor theVendor = (Vendor)vendorBinding.entryToObject(foundVendor); System.out.println("\t\t " + theVendor.getAddress()); System.out.println("\t\t " + theVendor.getCity() + ", " + theVendor.getState() + " " + theVendor.getZipcode()); System.out.println("\t\t Business Phone: " + theVendor.getBusinessPhoneNumber()); System.out.println("\t\t Sales Rep: " + theVendor.getRepName()); System.out.println("\t\t " + theVendor.getRepPhoneNumber()); } } protected ExampleInventoryRead() {} private static void parseArgs(String args[]) { for(int i = 0; i < args.length; ++i) { if (args[i].startsWith("-")) { switch(args[i].charAt(1)) { case 'h': myDbEnvPath = new File(args[++i]); break; case 's': locateItem = new String(args[++i]); break; default: usage(); } } } } }
apache-2.0
markhobson/contacts
client/src/main/java/org/hobsoft/contacts/client/contact/ContactDeleteDriver.java
2326
/* * 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.hobsoft.contacts.client.contact; import org.hobsoft.contacts.client.AbstractPageDriver; import org.hobsoft.contacts.client.DriverConfiguration; import org.hobsoft.microbrowser.MicrodataDocument; import org.hobsoft.microbrowser.MicrodataItem; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import static org.hobsoft.contacts.client.MicrodataSchema.PERSON; /** * Driver for the delete contact page. */ @Component public class ContactDeleteDriver extends AbstractPageDriver { // ---------------------------------------------------------------------------------------------------------------- // constructors // ---------------------------------------------------------------------------------------------------------------- @Autowired public ContactDeleteDriver(DriverConfiguration config, MicrodataDocument document) { super(config, document, "/contact/\\d+/delete"); } // ---------------------------------------------------------------------------------------------------------------- // public methods // ---------------------------------------------------------------------------------------------------------------- public Contact get() { checkVisible(); MicrodataItem item = document().getItem(PERSON); return ContactParser.parse(item); } public ContactsViewDriver delete() { checkVisible(); MicrodataDocument document = document().getForm("contactDelete").submit(); return new ContactsViewDriver(getConfiguration(), document); } public ContactViewDriver cancel() { checkVisible(); MicrodataDocument document = document().getLink("cancel").follow(); return new ContactViewDriver(getConfiguration(), document); } }
apache-2.0
etirelli/droolsjbpm-integration
kie-server-parent/kie-server-tests/kie-server-integ-tests-optaplanner/src/test/java/org/kie/server/integrationtests/optaplanner/OptaplannerIntegrationTest.java
30201
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * 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.kie.server.integrationtests.optaplanner; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.BeforeClass; import org.junit.Test; import org.kie.api.KieServices; import org.kie.server.api.exception.KieServicesException; import org.kie.server.api.model.ReleaseId; import org.kie.server.api.model.instance.ScoreWrapper; import org.kie.server.api.model.instance.SolverInstance; import org.kie.server.integrationtests.shared.KieServerAssert; import org.kie.server.integrationtests.shared.KieServerDeployer; import org.kie.server.integrationtests.shared.KieServerReflections; import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore; import org.optaplanner.core.impl.solver.ProblemFactChange; import static org.junit.Assert.*; public class OptaplannerIntegrationTest extends OptaplannerKieServerBaseIntegrationTest { private static final ReleaseId kjar1 = new ReleaseId( "org.kie.server.testing", "cloudbalance", "1.0.0.Final"); private static final String NOT_EXISTING_CONTAINER_ID = "no_container"; private static final String CONTAINER_1_ID = "cloudbalance"; private static final String SOLVER_1_ID = "cloudsolver"; private static final String SOLVER_1_CONFIG = "cloudbalance-solver.xml"; private static final String SOLVER_1_REALTIME_CONFIG = "cloudbalance-realtime-planning-solver.xml"; private static final String SOLVER_1_REALTIME_DAEMON_CONFIG = "cloudbalance-realtime-planning-daemon-solver.xml"; private static final String CLASS_CLOUD_BALANCE = "org.kie.server.testing.CloudBalance"; private static final String CLASS_CLOUD_COMPUTER = "org.kie.server.testing.CloudComputer"; private static final String CLASS_CLOUD_PROCESS = "org.kie.server.testing.CloudProcess"; private static final String CLASS_ADD_COMPUTER_PROBLEM_FACT_CHANGE = "org.kie.server.testing.AddComputerProblemFactChange"; private static final String CLASS_DELETE_COMPUTER_PROBLEM_FACT_CHANGE = "org.kie.server.testing.DeleteComputerProblemFactChange"; private static final String CLASS_CLOUD_GENERATOR = "org.kie.server.testing.CloudBalancingGenerator"; @BeforeClass public static void deployArtifacts() { KieServerDeployer.buildAndDeployCommonMavenParent(); KieServerDeployer.buildAndDeployMavenProject(ClassLoader.class.getResource("/kjars-sources/cloudbalance").getFile()); kieContainer = KieServices.Factory.get().newKieContainer(kjar1); createContainer(CONTAINER_1_ID, kjar1); } @Override protected void addExtraCustomClasses(Map<String, Class<?>> extraClasses) throws ClassNotFoundException { extraClasses.put(CLASS_CLOUD_BALANCE, Class.forName(CLASS_CLOUD_BALANCE, true, kieContainer.getClassLoader())); extraClasses.put(CLASS_CLOUD_COMPUTER, Class.forName(CLASS_CLOUD_COMPUTER, true, kieContainer.getClassLoader())); extraClasses.put(CLASS_CLOUD_PROCESS, Class.forName(CLASS_CLOUD_PROCESS, true, kieContainer.getClassLoader())); extraClasses.put(CLASS_ADD_COMPUTER_PROBLEM_FACT_CHANGE, Class.forName(CLASS_ADD_COMPUTER_PROBLEM_FACT_CHANGE, true, kieContainer.getClassLoader())); extraClasses.put(CLASS_DELETE_COMPUTER_PROBLEM_FACT_CHANGE, Class.forName(CLASS_DELETE_COMPUTER_PROBLEM_FACT_CHANGE, true, kieContainer.getClassLoader())); } @Test public void testCreateDisposeSolver() { solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, SOLVER_1_CONFIG); solverClient.disposeSolver(CONTAINER_1_ID, SOLVER_1_ID); } @Test public void testCreateSolverFromNotExistingContainer() { try { solverClient.createSolver(NOT_EXISTING_CONTAINER_ID, SOLVER_1_ID, SOLVER_1_CONFIG); fail("A KieServicesException should have been thrown by now."); } catch (KieServicesException e) { KieServerAssert.assertResultContainsStringRegex(e.getMessage(), ".*Container '" + NOT_EXISTING_CONTAINER_ID + "' is not instantiated or cannot find container for alias '" + NOT_EXISTING_CONTAINER_ID + "'.*"); } } @Test(expected = IllegalArgumentException.class) public void testCreateSolverWithoutConfigPath() { solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, null); } @Test public void testCreateSolverWrongConfigPath() { try { solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, "NonExistingPath"); fail("A KieServicesException should have been thrown by now."); } catch (KieServicesException e) { KieServerAssert.assertResultContainsStringRegex(e.getMessage(), ".*The solverConfigResource \\(.*\\) does not exist as a classpath resource in the classLoader \\(.*\\)*"); } } @Test(expected = IllegalArgumentException.class) public void testCreateSolverNullContainer() { solverClient.createSolver(null, SOLVER_1_ID, SOLVER_1_CONFIG); } @Test public void testCreateDuplicitSolver() { SolverInstance solverInstance = solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, SOLVER_1_CONFIG); assertNotNull(solverInstance); try { solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, SOLVER_1_CONFIG); fail("A KieServicesException should have been thrown by now."); } catch (KieServicesException e) { KieServerAssert.assertResultContainsStringRegex(e.getMessage(), ".*Failed to create solver. Solver .* already exists for container .*"); } } @Test public void testDisposeNotExistingSolver() { try { solverClient.disposeSolver(CONTAINER_1_ID, SOLVER_1_ID); fail("A KieServicesException should have been thrown by now."); } catch (KieServicesException e) { KieServerAssert.assertResultContainsStringRegex(e.getMessage(), ".*Solver.*from container.*not found.*"); } } @Test public void testGetSolverState() { SolverInstance solverInstance = solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, SOLVER_1_CONFIG); assertNotNull(solverInstance); solverInstance = solverClient.getSolver(CONTAINER_1_ID, SOLVER_1_ID); assertNotNull(solverInstance); assertEquals(CONTAINER_1_ID, solverInstance.getContainerId()); assertEquals(SOLVER_1_CONFIG, solverInstance.getSolverConfigFile()); assertEquals(SOLVER_1_ID, solverInstance.getSolverId()); assertEquals(SolverInstance.getSolverInstanceKey(CONTAINER_1_ID, SOLVER_1_ID), solverInstance.getSolverInstanceKey()); assertEquals(SolverInstance.SolverStatus.NOT_SOLVING, solverInstance.getStatus()); assertNotNull(solverInstance.getScoreWrapper()); assertNull(solverInstance.getScoreWrapper().toScore()); } @Test public void testGetNotExistingSolverState() { try { solverClient.getSolver(CONTAINER_1_ID, SOLVER_1_ID); fail("A KieServicesException should have been thrown by now."); } catch (KieServicesException e) { KieServerAssert.assertResultContainsStringRegex(e.getMessage(), ".*Solver.*not found in container.*"); } } @Test public void testGetSolvers() { List<SolverInstance> solverInstanceList = solverClient.getSolvers(CONTAINER_1_ID); assertNotNull(solverInstanceList); assertEquals(0, solverInstanceList.size()); solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, SOLVER_1_CONFIG); solverInstanceList = solverClient.getSolvers(CONTAINER_1_ID); assertNotNull(solverInstanceList); assertEquals(1, solverInstanceList.size()); SolverInstance returnedInstance = solverInstanceList.get(0); assertEquals(CONTAINER_1_ID, returnedInstance.getContainerId()); assertEquals(SOLVER_1_CONFIG, returnedInstance.getSolverConfigFile()); assertEquals(SOLVER_1_ID, returnedInstance.getSolverId()); assertEquals(SolverInstance.getSolverInstanceKey(CONTAINER_1_ID, SOLVER_1_ID), returnedInstance.getSolverInstanceKey()); assertEquals(SolverInstance.SolverStatus.NOT_SOLVING, returnedInstance.getStatus()); assertNotNull(returnedInstance.getScoreWrapper()); assertNull(returnedInstance.getScoreWrapper().toScore()); } @Test public void testExecuteSolver() throws Exception { SolverInstance solverInstance = solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, SOLVER_1_CONFIG); assertNotNull(solverInstance); assertEquals(SolverInstance.SolverStatus.NOT_SOLVING, solverInstance.getStatus()); // the following status starts the solver Object planningProblem = loadPlanningProblem(5, 15); solverClient.solvePlanningProblem(CONTAINER_1_ID, SOLVER_1_ID, planningProblem); solverInstance = solverClient.getSolver(CONTAINER_1_ID, SOLVER_1_ID); // solver should finish in 5 seconds, but we wait up to 15s before timing out for (int i = 0; i < 5 && solverInstance.getStatus() == SolverInstance.SolverStatus.SOLVING; i++) { Thread.sleep(3000); solverInstance = solverClient.getSolver(CONTAINER_1_ID, SOLVER_1_ID); assertNotNull(solverInstance); } assertEquals(SolverInstance.SolverStatus.NOT_SOLVING, solverInstance.getStatus()); solverClient.disposeSolver(CONTAINER_1_ID, SOLVER_1_ID); } @Test(timeout = 60_000) public void testExecuteRealtimePlanningSolverSingleItemSubmit() throws Exception { testExecuteRealtimePlanningSolverSingleItemSubmit(false); } @Test(timeout = 60_000) public void testExecuteRealtimePlanningSolverSingleItemSubmitDaemonEnabled() throws Exception { testExecuteRealtimePlanningSolverSingleItemSubmit(true); } private void testExecuteRealtimePlanningSolverSingleItemSubmit(boolean daemon) throws Exception { SolverInstance solverInstance = solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, daemon ? SOLVER_1_REALTIME_DAEMON_CONFIG : SOLVER_1_REALTIME_CONFIG); assertNotNull(solverInstance); assertEquals(SolverInstance.SolverStatus.NOT_SOLVING, solverInstance.getStatus()); final int computerCount = 5; final int numberOfComputersToAdd = 5; final Object planningProblem = loadPlanningProblem(computerCount, 15); solverClient.solvePlanningProblem(CONTAINER_1_ID, SOLVER_1_ID, planningProblem); SolverInstance solver = solverClient.getSolver(CONTAINER_1_ID, SOLVER_1_ID); assertEquals(SolverInstance.SolverStatus.SOLVING, solver.getStatus()); Thread.sleep(3000); List computerList = null; for (int i = 0; i < numberOfComputersToAdd; i++) { ProblemFactChange<?> problemFactChange = loadAddProblemFactChange(computerCount + i); solverClient.addProblemFactChange(CONTAINER_1_ID, SOLVER_1_ID, problemFactChange); do { final Object bestSolution = verifySolverAndGetBestSolution(); computerList = getCloudBalanceComputerList(bestSolution); } while (computerCount + i + 1 != computerList.size()); } assertTrue(solverClient.isEveryProblemFactChangeProcessed(CONTAINER_1_ID, SOLVER_1_ID)); Thread.sleep(3000); assertNotNull(computerList); for (int i = 0; i < numberOfComputersToAdd; i++) { ProblemFactChange<?> problemFactChange = loadDeleteProblemFactChange(computerList.get(i)); solverClient.addProblemFactChange(CONTAINER_1_ID, SOLVER_1_ID, problemFactChange); do { final Object bestSolution = verifySolverAndGetBestSolution(); computerList = getCloudBalanceComputerList(bestSolution); } while (computerCount + numberOfComputersToAdd - i - 1 != computerList.size()); } assertTrue(solverClient.isEveryProblemFactChangeProcessed(CONTAINER_1_ID, SOLVER_1_ID)); solverClient.disposeSolver(CONTAINER_1_ID, SOLVER_1_ID); } @Test(timeout = 60_000) public void testExecuteRealtimePlanningSolverBulkItemSubmit() throws Exception { testExecuteRealtimePlanningSolverBulkItemSubmit(false); } @Test(timeout = 60_000) public void testExecuteRealtimePlanningSolverBulkItemSubmitDaemonEnabled() throws Exception { testExecuteRealtimePlanningSolverBulkItemSubmit(true); } private void testExecuteRealtimePlanningSolverBulkItemSubmit(boolean daemon) throws Exception { SolverInstance solverInstance = solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, daemon ? SOLVER_1_REALTIME_DAEMON_CONFIG : SOLVER_1_REALTIME_CONFIG); assertNotNull(solverInstance); assertEquals(SolverInstance.SolverStatus.NOT_SOLVING, solverInstance.getStatus()); final int initialComputerCount = 5; final int numberOfComputersToAdd = 5; final Object planningProblem = loadPlanningProblem(initialComputerCount, 15); solverClient.solvePlanningProblem(CONTAINER_1_ID, SOLVER_1_ID, planningProblem); SolverInstance solver = solverClient.getSolver(CONTAINER_1_ID, SOLVER_1_ID); assertEquals(SolverInstance.SolverStatus.SOLVING, solver.getStatus()); Thread.sleep(3000); List<ProblemFactChange> problemFactChangeList = new ArrayList<>(numberOfComputersToAdd); for (int i = 0; i < numberOfComputersToAdd; i++) { problemFactChangeList.add(loadAddProblemFactChange(initialComputerCount + i)); } solverClient.addProblemFactChanges(CONTAINER_1_ID, SOLVER_1_ID, problemFactChangeList); List computerList = null; do { final Object bestSolution = verifySolverAndGetBestSolution(); computerList = getCloudBalanceComputerList(bestSolution); } while (initialComputerCount + numberOfComputersToAdd != computerList.size()); assertNotNull(computerList); assertTrue(solverClient.isEveryProblemFactChangeProcessed(CONTAINER_1_ID, SOLVER_1_ID)); Thread.sleep(3000); problemFactChangeList.clear(); for (int i = 0; i < numberOfComputersToAdd; i++) { problemFactChangeList.add(loadDeleteProblemFactChange(computerList.get(i))); } solverClient.addProblemFactChanges(CONTAINER_1_ID, SOLVER_1_ID, problemFactChangeList); do { final Object bestSolution = verifySolverAndGetBestSolution(); computerList = getCloudBalanceComputerList(bestSolution); } while (initialComputerCount != computerList.size()); assertTrue(solverClient.isEveryProblemFactChangeProcessed(CONTAINER_1_ID, SOLVER_1_ID)); solverClient.disposeSolver(CONTAINER_1_ID, SOLVER_1_ID); } private Object verifySolverAndGetBestSolution() { SolverInstance solver = solverClient.getSolverWithBestSolution(CONTAINER_1_ID, SOLVER_1_ID); assertEquals(SolverInstance.SolverStatus.SOLVING, solver.getStatus()); Object bestSolution = solver.getBestSolution(); assertEquals(bestSolution.getClass().getName(), CLASS_CLOUD_BALANCE); return bestSolution; } private List getCloudBalanceComputerList(final Object cloudBalance) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Method computerListMethod = cloudBalance.getClass().getDeclaredMethod("getComputerList"); return (List) computerListMethod.invoke(cloudBalance); } @Test public void testExecuteRunningSolver() throws Exception { SolverInstance solverInstance = solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, SOLVER_1_CONFIG); assertNotNull(solverInstance); assertEquals(SolverInstance.SolverStatus.NOT_SOLVING, solverInstance.getStatus()); // start solver Object planningProblem = loadPlanningProblem(5, 15); solverClient.solvePlanningProblem(CONTAINER_1_ID, SOLVER_1_ID, planningProblem); // start solver again try { solverClient.solvePlanningProblem(CONTAINER_1_ID, SOLVER_1_ID, planningProblem); fail("A KieServicesException should have been thrown by now."); } catch (KieServicesException e) { KieServerAssert.assertResultContainsStringRegex(e.getMessage(), ".*Solver .* on container .* is already executing.*"); } solverClient.disposeSolver(CONTAINER_1_ID, SOLVER_1_ID); } @Test(timeout = 60000) public void testGetBestSolution() throws Exception { SolverInstance solverInstance = solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, SOLVER_1_CONFIG); // Start the solver Object planningProblem = loadPlanningProblem(10, 30); solverClient.solvePlanningProblem(CONTAINER_1_ID, SOLVER_1_ID, planningProblem); Object solution = null; HardSoftScore score = null; // It can take a while for the Construction Heuristic to initialize the solution // The test timeout will interrupt this thread if it takes too long while (!Thread.currentThread().isInterrupted()) { solverInstance = solverClient.getSolverWithBestSolution(CONTAINER_1_ID, SOLVER_1_ID); assertNotNull(solverInstance); solution = solverInstance.getBestSolution(); ScoreWrapper scoreWrapper = solverInstance.getScoreWrapper(); assertNotNull(scoreWrapper); if (scoreWrapper.toScore() != null) { assertEquals(HardSoftScore.class, scoreWrapper.getScoreClass()); score = (HardSoftScore) scoreWrapper.toScore(); } // Wait until the solver finished initializing the solution if (solution != null && score != null && score.isSolutionInitialized()) { break; } Thread.sleep(1000); } assertNotNull(score); assertTrue(score.isSolutionInitialized()); assertTrue(score.getHardScore() <= 0); // A soft score of 0 is impossible because we'll always need at least 1 computer assertTrue(score.getSoftScore() < 0); List<?> computerList = (List<?>) KieServerReflections.valueOf(solution, "computerList"); assertEquals(10, computerList.size()); List<?> processList = (List<?>) KieServerReflections.valueOf(solution, "processList"); assertEquals(30, processList.size()); for (Object process : processList) { Object computer = KieServerReflections.valueOf(process, "computer"); assertNotNull(computer); // TODO: Change to identity comparation after @XmlID is implemented assertTrue(computerList.contains(computer)); } solverClient.disposeSolver(CONTAINER_1_ID, SOLVER_1_ID); } @Test public void testGetBestSolutionNotExistingSolver() { try { solverClient.getSolverWithBestSolution(CONTAINER_1_ID, SOLVER_1_ID); fail("A KieServicesException should have been thrown by now."); } catch (KieServicesException e) { KieServerAssert.assertResultContainsStringRegex(e.getMessage(), ".*Solver.*not found in container.*"); } } @Test public void testTerminateEarlyNotExistingSolver() { try { solverClient.terminateSolverEarly(CONTAINER_1_ID, SOLVER_1_ID); fail("A KieServicesException should have been thrown by now."); } catch (KieServicesException e) { KieServerAssert.assertResultContainsStringRegex(e.getMessage(), ".*Solver.*not found in container.*"); } } @Test public void testTerminateEarlyStoppedSolver() { solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, SOLVER_1_CONFIG); try { solverClient.terminateSolverEarly(CONTAINER_1_ID, SOLVER_1_ID); fail("A KieServicesException should have been thrown by now."); } catch (KieServicesException e) { KieServerAssert.assertResultContainsStringRegex(e.getMessage(), ".*Solver.*from container.*is not executing.*"); } } @Test public void testTerminateEarly() throws Exception { solverClient.createSolver(CONTAINER_1_ID, SOLVER_1_ID, SOLVER_1_CONFIG); // start solver solverClient.solvePlanningProblem(CONTAINER_1_ID, SOLVER_1_ID, loadPlanningProblem(50, 150)); SolverInstance instance = solverClient.getSolver(CONTAINER_1_ID, SOLVER_1_ID); assertEquals(SolverInstance.SolverStatus.SOLVING, instance.getStatus()); // and then terminate it solverClient.terminateSolverEarly(CONTAINER_1_ID, SOLVER_1_ID); instance = solverClient.getSolver(CONTAINER_1_ID, SOLVER_1_ID); assertTrue(instance.getStatus() == SolverInstance.SolverStatus.TERMINATING_EARLY || instance.getStatus() == SolverInstance.SolverStatus.NOT_SOLVING); solverClient.disposeSolver(CONTAINER_1_ID, SOLVER_1_ID); } private Object loadPlanningProblem(int computerListSize, int processListSize) throws NoSuchMethodException, ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException { Class<?> cbgc = kieContainer.getClassLoader().loadClass(CLASS_CLOUD_GENERATOR); Object cbgi = cbgc.newInstance(); Method method = cbgc.getMethod("createCloudBalance", int.class, int.class); return method.invoke(cbgi, computerListSize, processListSize); } private ProblemFactChange<?> loadAddProblemFactChange(final int currentNumberOfComputers) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { Class<?> cbgc = kieContainer.getClassLoader().loadClass(CLASS_CLOUD_GENERATOR); Object cbgi = cbgc.newInstance(); Method method = cbgc.getMethod("createCloudComputer", int.class); Object cloudComputer = method.invoke(cbgi, currentNumberOfComputers); Class<?> cloudComputerClass = kieContainer.getClassLoader().loadClass(CLASS_CLOUD_COMPUTER); Class<?> problemFactChangeClass = kieContainer.getClassLoader().loadClass(CLASS_ADD_COMPUTER_PROBLEM_FACT_CHANGE); Constructor<?> constructor = problemFactChangeClass.getConstructor(cloudComputerClass); return (ProblemFactChange) constructor.newInstance(cloudComputer); } private ProblemFactChange<?> loadDeleteProblemFactChange(final Object cloudComputer) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Class<?> cloudComputerClass = kieContainer.getClassLoader().loadClass(CLASS_CLOUD_COMPUTER); Class<?> problemFactChangeClass = kieContainer.getClassLoader().loadClass(CLASS_DELETE_COMPUTER_PROBLEM_FACT_CHANGE); Constructor<?> constructor = problemFactChangeClass.getConstructor(cloudComputerClass); return (ProblemFactChange) constructor.newInstance(cloudComputer); } }
apache-2.0
qweek/rsocket-java
rsocket-transport-local/src/main/java/io/rsocket/transport/local/LocalUriHandler.java
1377
/* * Copyright 2016 Netflix, 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 io.rsocket.transport.local; import io.rsocket.transport.ClientTransport; import io.rsocket.transport.ServerTransport; import io.rsocket.uri.UriHandler; import java.net.URI; import java.util.Optional; public class LocalUriHandler implements UriHandler { @Override public Optional<ClientTransport> buildClient(URI uri) { if ("local".equals(uri.getScheme())) { return Optional.of(LocalClientTransport.create(uri.getSchemeSpecificPart())); } return UriHandler.super.buildClient(uri); } @Override public Optional<ServerTransport> buildServer(URI uri) { if ("local".equals(uri.getScheme())) { return Optional.of(LocalServerTransport.create(uri.getSchemeSpecificPart())); } return UriHandler.super.buildServer(uri); } }
apache-2.0
Hack23/cia
citizen-intelligence-agency/src/test/java/com/hack23/cia/systemintegrationtest/ChartTest.java
3413
/* * Copyright 2010-2021 James Pether Sörling * * 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. * * $Id$ * $HeadURL$ */ package com.hack23.cia.systemintegrationtest; import java.util.Map; import java.util.Map.Entry; import org.dussan.vaadin.dcharts.base.elements.XYaxis; import org.dussan.vaadin.dcharts.base.elements.XYseries; import org.dussan.vaadin.dcharts.helpers.ClassHelper; import org.dussan.vaadin.dcharts.helpers.ObjectHelper; import org.dussan.vaadin.dcharts.metadata.XYaxes; import org.junit.Assert; import org.junit.Test; public final class ChartTest extends Assert { /** * To json string. * * @param object * the object * @return the string */ public static String toJsonString(final Object object) { try { final Map<String, Object> values = ClassHelper.getFieldValues(object); final StringBuilder builder = new StringBuilder(); for (final Entry<String, Object> entry : values.entrySet()) { final String fieldName = entry.getKey(); Object fieldValue = entry.getValue(); if (!fieldName.contains("jacocoData")) { if (ObjectHelper.isArray(fieldValue)) { if (fieldValue instanceof Object[][]) { fieldValue = ObjectHelper .toArrayString((Object[][]) fieldValue); } else if (fieldValue instanceof boolean[]) { } else { fieldValue = ObjectHelper .toArrayString((Object[]) fieldValue); } } if (fieldValue != null) { fieldValue = !ObjectHelper.isString(fieldValue) ? fieldValue : fieldValue.toString().replaceAll("\"", "'"); builder.append(builder.length() > 0 ? ", " : ""); builder.append(fieldName).append(": "); builder.append(ObjectHelper.isString(fieldValue) ? "\"" : ""); builder.append(fieldValue); builder.append(ObjectHelper.isString(fieldValue) ? "\"" : ""); } } } return builder.insert(0, "{").append("}").toString(); } catch (final Exception e) { e.printStackTrace(); return null; } } /** * Adds the serie test. */ @Test public void addSerieTest() { final XYseries label = new XYseriesFix(); label.setLabel("sune"); toJsonString(label); assertNotNull("Problem with toJsonString, no label",label); } static class XYaxisFix extends XYaxis { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** * Instantiates a new x yaxis fix. */ public XYaxisFix() { super(); } /** * Instantiates a new x yaxis fix. * * @param y * the y */ public XYaxisFix(final XYaxes y) { super(y); } @Override public String getValue() { return toJsonString(this); } } static class XYseriesFix extends XYseries { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; @Override public String getValue() { return toJsonString(this); } } }
apache-2.0
jalmela/BasicMathCalculator
BasicMathCalculator/src/es/josealmela/BasicMathCalculator/client/ConverNumberServiceAsync.java
335
package es.josealmela.BasicMathCalculator.client; import com.google.gwt.user.client.rpc.AsyncCallback; /** * The async counterpart of <code>convertNumberService</code>. */ public interface ConverNumberServiceAsync { void convertNumbertServer(String input, AsyncCallback<String> callback) throws IllegalArgumentException; }
apache-2.0
Victory/TreasureHuntPWA
backspark/src/main/java/org/dfhu/thpwa/routing/RouteAdder.java
730
package org.dfhu.thpwa.routing; abstract class RouteAdder<T extends Route> { /** * Get the url pattern for this route */ protected abstract String getPath(); /** * get the HTTP request method */ protected abstract Route.METHOD getMethod(); public void doGet(RouteAdder<T> routeAdder) { Halting.haltNotImplemented(); } public void doPost(RouteAdder<T> routeAdder) { Halting.haltNotImplemented(); } public void addRoute() { Route.METHOD method = getMethod(); switch (method) { case GET: doGet(this); break; case POST: doPost(this); break; default: throw new RuntimeException("Request Method not implemented"); } } }
apache-2.0
takezoe/xlsbeans
src/test/java/com/github/takezoe/xlsbeans/LanguageIDE.java
665
package com.github.takezoe.xlsbeans; import com.github.takezoe.xlsbeans.annotation.Column; import com.github.takezoe.xlsbeans.annotation.MapColumns; import java.util.Map; public class LanguageIDE { private String name; private Map<String, String> attributes; public Map<String, String> getAttributes() { return attributes; } @MapColumns(previousColumnName = "Name") public void setAttributes(Map<String, String> attributes) { this.attributes = attributes; } public String getName() { return name; } @Column(columnName = "Name") public void setName(String name) { this.name = name; } }
apache-2.0
iamironz/binaryprefs
library/src/main/java/com/ironz/binaryprefs/BinaryPreferencesEditor.java
10537
package com.ironz.binaryprefs; import com.ironz.binaryprefs.cache.candidates.CacheCandidateProvider; import com.ironz.binaryprefs.cache.provider.CacheProvider; import com.ironz.binaryprefs.event.EventBridge; import com.ironz.binaryprefs.exception.TransactionInvalidatedException; import com.ironz.binaryprefs.file.transaction.FileTransaction; import com.ironz.binaryprefs.file.transaction.TransactionElement; import com.ironz.binaryprefs.serialization.SerializerFactory; import com.ironz.binaryprefs.serialization.serializer.persistable.Persistable; import com.ironz.binaryprefs.serialization.strategy.SerializationStrategy; import com.ironz.binaryprefs.serialization.strategy.impl.*; import com.ironz.binaryprefs.task.barrier.FutureBarrier; import com.ironz.binaryprefs.task.TaskExecutor; import java.util.*; import java.util.concurrent.locks.Lock; final class BinaryPreferencesEditor implements PreferencesEditor { private static final String TRANSACTED_TWICE_MESSAGE = "Transaction should be applied or committed only once!"; private final Map<String, SerializationStrategy> strategyMap = new HashMap<>(); private final Set<String> removeSet = new HashSet<>(); private final FileTransaction fileTransaction; private final EventBridge bridge; private final TaskExecutor taskExecutor; private final SerializerFactory serializerFactory; private final CacheProvider cacheProvider; private final CacheCandidateProvider candidateProvider; private final Lock writeLock; private boolean invalidated; BinaryPreferencesEditor(FileTransaction fileTransaction, EventBridge bridge, TaskExecutor taskExecutor, SerializerFactory serializerFactory, CacheProvider cacheProvider, CacheCandidateProvider candidateProvider, Lock writeLock) { this.fileTransaction = fileTransaction; this.bridge = bridge; this.taskExecutor = taskExecutor; this.serializerFactory = serializerFactory; this.cacheProvider = cacheProvider; this.candidateProvider = candidateProvider; this.writeLock = writeLock; } @Override public PreferencesEditor putString(String key, String value) { if (value == null) { return remove(key); } writeLock.lock(); try { SerializationStrategy strategy = new StringSerializationStrategy(value, serializerFactory); strategyMap.put(key, strategy); return this; } finally { writeLock.unlock(); } } @Override public PreferencesEditor putStringSet(String key, Set<String> value) { if (value == null) { return remove(key); } writeLock.lock(); try { SerializationStrategy strategy = new StringSetSerializationStrategy(value, serializerFactory); strategyMap.put(key, strategy); return this; } finally { writeLock.unlock(); } } @Override public PreferencesEditor putInt(String key, int value) { writeLock.lock(); try { SerializationStrategy strategy = new IntegerSerializationStrategy(value, serializerFactory); strategyMap.put(key, strategy); return this; } finally { writeLock.unlock(); } } @Override public PreferencesEditor putLong(String key, long value) { writeLock.lock(); try { SerializationStrategy strategy = new LongSerializationStrategy(value, serializerFactory); strategyMap.put(key, strategy); return this; } finally { writeLock.unlock(); } } @Override public PreferencesEditor putFloat(String key, float value) { writeLock.lock(); try { SerializationStrategy strategy = new FloatSerializationStrategy(value, serializerFactory); strategyMap.put(key, strategy); return this; } finally { writeLock.unlock(); } } @Override public PreferencesEditor putBoolean(String key, boolean value) { writeLock.lock(); try { SerializationStrategy strategy = new BooleanSerializationStrategy(value, serializerFactory); strategyMap.put(key, strategy); return this; } finally { writeLock.unlock(); } } @Override public <T extends Persistable> PreferencesEditor putPersistable(String key, T value) { if (value == null) { return remove(key); } writeLock.lock(); try { SerializationStrategy strategy = new PersistableSerializationStrategy(value, serializerFactory); strategyMap.put(key, strategy); return this; } finally { writeLock.unlock(); } } @Override public PreferencesEditor putByte(String key, byte value) { writeLock.lock(); try { SerializationStrategy strategy = new ByteSerializationStrategy(value, serializerFactory); strategyMap.put(key, strategy); return this; } finally { writeLock.unlock(); } } @Override public PreferencesEditor putShort(String key, short value) { writeLock.lock(); try { SerializationStrategy strategy = new ShortSerializationStrategy(value, serializerFactory); strategyMap.put(key, strategy); return this; } finally { writeLock.unlock(); } } @Override public PreferencesEditor putChar(String key, char value) { writeLock.lock(); try { SerializationStrategy strategy = new CharSerializationStrategy(value, serializerFactory); strategyMap.put(key, strategy); return this; } finally { writeLock.unlock(); } } @Override public PreferencesEditor putDouble(String key, double value) { writeLock.lock(); try { SerializationStrategy strategy = new DoubleSerializationStrategy(value, serializerFactory); strategyMap.put(key, strategy); return this; } finally { writeLock.unlock(); } } @Override public PreferencesEditor putByteArray(String key, byte[] value) { writeLock.lock(); try { SerializationStrategy strategy = new ByteArraySerializationStrategy(value, serializerFactory); strategyMap.put(key, strategy); return this; } finally { writeLock.unlock(); } } @Override public PreferencesEditor remove(String key) { writeLock.lock(); try { removeSet.add(key); return this; } finally { writeLock.unlock(); } } @Override public PreferencesEditor clear() { writeLock.lock(); try { Set<String> all = candidateProvider.keys(); removeSet.addAll(all); return this; } finally { writeLock.unlock(); } } @Override public void apply() { writeLock.lock(); try { performTransaction(); } finally { writeLock.unlock(); } } @Override public boolean commit() { writeLock.lock(); try { FutureBarrier barrier = performTransaction(); return barrier.completeBlockingWithStatus(); } finally { writeLock.unlock(); } } private FutureBarrier performTransaction() { removeCache(); storeCache(); invalidate(); return taskExecutor.submit(new Runnable() { @Override public void run() { commitTransaction(); } }); } private void removeCache() { for (String name : removeSet) { candidateProvider.remove(name); cacheProvider.remove(name); } } private void storeCache() { for (String name : strategyMap.keySet()) { SerializationStrategy strategy = strategyMap.get(name); Object value = strategy.getValue(); candidateProvider.put(name); cacheProvider.put(name, value); } } private void invalidate() { if (invalidated) { throw new TransactionInvalidatedException(TRANSACTED_TWICE_MESSAGE); } invalidated = true; } private void commitTransaction() { List<TransactionElement> transaction = createTransaction(); fileTransaction.commit(transaction); notifyListeners(transaction); } private List<TransactionElement> createTransaction() { List<TransactionElement> elements = new LinkedList<>(); elements.addAll(removePersistence()); elements.addAll(storePersistence()); return elements; } private List<TransactionElement> removePersistence() { List<TransactionElement> elements = new LinkedList<>(); for (String name : removeSet) { TransactionElement e = TransactionElement.createRemovalElement(name); elements.add(e); } return elements; } private List<TransactionElement> storePersistence() { Set<String> strings = strategyMap.keySet(); List<TransactionElement> elements = new LinkedList<>(); for (String name : strings) { SerializationStrategy strategy = strategyMap.get(name); byte[] bytes = strategy.serialize(); TransactionElement e = TransactionElement.createUpdateElement(name, bytes); elements.add(e); } return elements; } private void notifyListeners(List<TransactionElement> transaction) { for (TransactionElement element : transaction) { String name = element.getName(); byte[] bytes = element.getContent(); if (element.getAction() == TransactionElement.ACTION_REMOVE) { bridge.notifyListenersRemove(name); } if (element.getAction() == TransactionElement.ACTION_UPDATE) { bridge.notifyListenersUpdate(name, bytes); } } } }
apache-2.0
jrenner/gdx-proto
core/src/org/jrenner/fps/utils/Compression.java
1974
package org.jrenner.fps.utils; import com.badlogic.gdx.utils.Array; import org.jrenner.fps.Log; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; public class Compression { public static byte[] writeCompressedString(String s) { GZIPOutputStream gzout = null; try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); gzout = new GZIPOutputStream(bout); gzout.write(s.getBytes()); gzout.flush(); gzout.close(); return bout.toByteArray(); } catch (IOException e) { e.printStackTrace(); } finally { if (gzout != null) { try { gzout.flush(); gzout.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } public static String decompressToString(byte[] bytes) { GZIPInputStream gzin = null; try { gzin = new GZIPInputStream(new ByteArrayInputStream(bytes)); byte[] buf = new byte[8192]; byte[] storage = new byte[65536]; int n = 0; int total = 0; while (true) { n = gzin.read(buf); if (n == -1) break; // expand to meet needs if (total + n >= storage.length) { byte[] expanded = new byte[storage.length * 2]; System.arraycopy(storage, 0, expanded, 0, storage.length); storage = expanded; } System.out.printf("blen: %d, storlen: %d, total: %d, n: %d\n", buf.length, storage.length, total, n); System.arraycopy(buf, 0, storage, total, n); total += n; } Log.debug("read " + total + " bytes from compressed files"); byte[] result = new byte[total]; System.arraycopy(storage, 0, result, 0, total); return new String(result); } catch (Exception e) { e.printStackTrace(); } finally { if (gzin != null) { try { gzin.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } }
apache-2.0
haghard/docker-compose-akka-cluster
src/main/scala/demo/hashing/CassandraHash.java
4268
package demo.hashing; import java.nio.ByteBuffer; public class CassandraHash { private static long getblock(ByteBuffer key, int offset, int index) { int i_8 = index << 3; return ((long) key.get(offset + i_8 + 0) & 0xff) + (((long) key.get(offset + i_8 + 1) & 0xff) << 8) + (((long) key.get(offset + i_8 + 2) & 0xff) << 16) + (((long) key.get(offset + i_8 + 3) & 0xff) << 24) + (((long) key.get(offset + i_8 + 4) & 0xff) << 32) + (((long) key.get(offset + i_8 + 5) & 0xff) << 40) + (((long) key.get(offset + i_8 + 6) & 0xff) << 48) + (((long) key.get(offset + i_8 + 7) & 0xff) << 56); } private static long rotl64(long v, int n) { return ((v << n) | (v >>> (64 - n))); } private static long fmix(long k) { k ^= k >>> 33; k *= 0xff51afd7ed558ccdL; k ^= k >>> 33; k *= 0xc4ceb9fe1a85ec53L; k ^= k >>> 33; return k; } //taken from com.twitter.algebird.CassandraMurmurHash public static long[] hash3_x64_128(ByteBuffer key, int offset, int length, long seed) { final int nblocks = length >> 4; // Process as 128-bit blocks. long h1 = seed; long h2 = seed; long c1 = 0x87c37b91114253d5L; long c2 = 0x4cf5ad432745937fL; //---------- // body for (int i = 0; i < nblocks; i++) { long k1 = getblock(key, offset, i * 2 + 0); long k2 = getblock(key, offset, i * 2 + 1); k1 *= c1; k1 = rotl64(k1, 31); k1 *= c2; h1 ^= k1; h1 = rotl64(h1, 27); h1 += h2; h1 = h1 * 5 + 0x52dce729; k2 *= c2; k2 = rotl64(k2, 33); k2 *= c1; h2 ^= k2; h2 = rotl64(h2, 31); h2 += h1; h2 = h2 * 5 + 0x38495ab5; } //---------- // tail // Advance offset to the unprocessed tail of the data. offset += nblocks * 16; long k1 = 0; long k2 = 0; switch (length & 15) { case 15: k2 ^= ((long) key.get(offset + 14)) << 48; case 14: k2 ^= ((long) key.get(offset + 13)) << 40; case 13: k2 ^= ((long) key.get(offset + 12)) << 32; case 12: k2 ^= ((long) key.get(offset + 11)) << 24; case 11: k2 ^= ((long) key.get(offset + 10)) << 16; case 10: k2 ^= ((long) key.get(offset + 9)) << 8; case 9: k2 ^= ((long) key.get(offset + 8)) << 0; k2 *= c2; k2 = rotl64(k2, 33); k2 *= c1; h2 ^= k2; case 8: k1 ^= ((long) key.get(offset + 7)) << 56; case 7: k1 ^= ((long) key.get(offset + 6)) << 48; case 6: k1 ^= ((long) key.get(offset + 5)) << 40; case 5: k1 ^= ((long) key.get(offset + 4)) << 32; case 4: k1 ^= ((long) key.get(offset + 3)) << 24; case 3: k1 ^= ((long) key.get(offset + 2)) << 16; case 2: k1 ^= ((long) key.get(offset + 1)) << 8; case 1: k1 ^= ((long) key.get(offset)); k1 *= c1; k1 = rotl64(k1, 31); k1 *= c2; h1 ^= k1; } ; //---------- // finalization h1 ^= length; h2 ^= length; h1 += h2; h2 += h1; h1 = fmix(h1); h2 = fmix(h2); h1 += h2; h2 += h1; return (new long[]{h1, h2}); } //kafka utils public static int murmur2(final byte[] data) { int length = data.length; int seed = 0x9747b28c; // 'm' and 'r' are mixing constants generated offline. // They're not really 'magic', they just happen to work well. final int m = 0x5bd1e995; final int r = 24; // Initialize the hash to a random value int h = seed ^ length; int length4 = length / 4; for (int i = 0; i < length4; i++) { final int i4 = i * 4; int k = (data[i4 + 0] & 0xff) + ((data[i4 + 1] & 0xff) << 8) + ((data[i4 + 2] & 0xff) << 16) + ((data[i4 + 3] & 0xff) << 24); k *= m; k ^= k >>> r; k *= m; h *= m; h ^= k; } // Handle the last few bytes of the input array switch (length % 4) { case 3: h ^= (data[(length & ~3) + 2] & 0xff) << 16; case 2: h ^= (data[(length & ~3) + 1] & 0xff) << 8; case 1: h ^= (data[length & ~3] & 0xff); h *= m; } h ^= h >>> 13; h *= m; h ^= h >>> 15; return h; } }
apache-2.0
OpenGamma/Strata
modules/pricer/src/main/java/com/opengamma/strata/pricer/swaption/NormalSwaptionExpiryStrikeVolatilities.java
19774
/* * Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.pricer.swaption; import java.io.Serializable; import java.time.LocalDate; import java.time.ZonedDateTime; import java.util.Map; import java.util.NoSuchElementException; import java.util.Optional; import java.util.OptionalInt; import org.joda.beans.Bean; import org.joda.beans.BeanBuilder; import org.joda.beans.ImmutableBean; import org.joda.beans.JodaBeanUtils; import org.joda.beans.MetaBean; import org.joda.beans.MetaProperty; import org.joda.beans.gen.BeanDefinition; import org.joda.beans.gen.ImmutableConstructor; import org.joda.beans.gen.PropertyDefinition; import org.joda.beans.impl.direct.DirectMetaBean; import org.joda.beans.impl.direct.DirectMetaProperty; import org.joda.beans.impl.direct.DirectMetaPropertyMap; import org.joda.beans.impl.direct.DirectPrivateBeanBuilder; import com.opengamma.strata.basics.date.DayCount; import com.opengamma.strata.collect.ArgChecker; import com.opengamma.strata.data.MarketDataName; import com.opengamma.strata.market.ValueType; import com.opengamma.strata.market.param.CurrencyParameterSensitivities; import com.opengamma.strata.market.param.CurrencyParameterSensitivity; import com.opengamma.strata.market.param.ParameterMetadata; import com.opengamma.strata.market.param.ParameterPerturbation; import com.opengamma.strata.market.param.UnitParameterSensitivity; import com.opengamma.strata.market.sensitivity.PointSensitivities; import com.opengamma.strata.market.sensitivity.PointSensitivity; import com.opengamma.strata.market.surface.InterpolatedNodalSurface; import com.opengamma.strata.market.surface.Surface; import com.opengamma.strata.market.surface.SurfaceInfoType; import com.opengamma.strata.market.surface.Surfaces; import com.opengamma.strata.pricer.impl.option.NormalFormulaRepository; import com.opengamma.strata.product.common.PutCall; import com.opengamma.strata.product.swap.type.FixedFloatSwapConvention; import com.opengamma.strata.product.swap.type.FixedIborSwapConvention; /** * Volatility for swaptions in the normal or Bachelier model based on a surface. * <p> * The volatility is represented by a surface on the expiry and strike dimensions. */ @BeanDefinition(builderScope = "private") public final class NormalSwaptionExpiryStrikeVolatilities implements NormalSwaptionVolatilities, ImmutableBean, Serializable { /** * The swap convention that the volatilities are to be used for. */ @PropertyDefinition(validate = "notNull", overrideGet = true) private final FixedFloatSwapConvention convention; /** * The valuation date-time. * <p> * The volatilities are calibrated for this date-time. */ @PropertyDefinition(validate = "notNull", overrideGet = true) private final ZonedDateTime valuationDateTime; /** * The normal volatility surface. * <p> * The x-value of the surface is the expiry, as a year fraction. * The y-value of the surface is the strike, as a rate. */ @PropertyDefinition(validate = "notNull") private final Surface surface; /** * The day count convention of the surface. */ private final transient DayCount dayCount; // cached, not a property //------------------------------------------------------------------------- /** * Obtains an instance from the implied volatility surface and the date-time for which it is valid. * <p> * The surface is specified by an instance of {@link Surface}, such as {@link InterpolatedNodalSurface}. * The surface must contain the correct metadata: * <ul> * <li>The x-value type must be {@link ValueType#YEAR_FRACTION} * <li>The y-value type must be {@link ValueType#STRIKE} * <li>The z-value type must be {@link ValueType#NORMAL_VOLATILITY} * <li>The day count must be set in the additional information using {@link SurfaceInfoType#DAY_COUNT} * </ul> * Suitable surface metadata can be created using * {@link Surfaces#normalVolatilityByExpiryStrike(String, DayCount)}. * * @param convention the swap convention that the volatilities are to be used for * @param valuationDateTime the valuation date-time * @param surface the implied volatility surface * @return the volatilities */ public static NormalSwaptionExpiryStrikeVolatilities of( FixedFloatSwapConvention convention, ZonedDateTime valuationDateTime, Surface surface) { return new NormalSwaptionExpiryStrikeVolatilities(convention, valuationDateTime, surface); } @ImmutableConstructor private NormalSwaptionExpiryStrikeVolatilities( FixedFloatSwapConvention convention, ZonedDateTime valuationDateTime, Surface surface) { ArgChecker.notNull(convention, "convention"); ArgChecker.notNull(valuationDateTime, "valuationDateTime"); ArgChecker.notNull(surface, "surface"); surface.getMetadata().getXValueType().checkEquals( ValueType.YEAR_FRACTION, "Incorrect x-value type for Normal volatilities"); surface.getMetadata().getYValueType().checkEquals( ValueType.STRIKE, "Incorrect y-value type for Normal volatilities"); surface.getMetadata().getZValueType().checkEquals( ValueType.NORMAL_VOLATILITY, "Incorrect z-value type for Normal volatilities"); DayCount dayCount = surface.getMetadata().findInfo(SurfaceInfoType.DAY_COUNT) .orElseThrow(() -> new IllegalArgumentException("Incorrect surface metadata, missing DayCount")); this.valuationDateTime = valuationDateTime; this.surface = surface; this.convention = convention; this.dayCount = dayCount; } // ensure standard constructor is invoked private Object readResolve() { return new NormalSwaptionExpiryStrikeVolatilities(convention, valuationDateTime, surface); } //------------------------------------------------------------------------- @Override public SwaptionVolatilitiesName getName() { return SwaptionVolatilitiesName.of(surface.getName().getName()); } @Override public <T> Optional<T> findData(MarketDataName<T> name) { if (surface.getName().equals(name)) { return Optional.of(name.getMarketDataType().cast(surface)); } return Optional.empty(); } @Override public int getParameterCount() { return surface.getParameterCount(); } @Override public double getParameter(int parameterIndex) { return surface.getParameter(parameterIndex); } @Override public ParameterMetadata getParameterMetadata(int parameterIndex) { return surface.getParameterMetadata(parameterIndex); } @Override public OptionalInt findParameterIndex(ParameterMetadata metadata) { return surface.findParameterIndex(metadata); } @Override public NormalSwaptionExpiryStrikeVolatilities withParameter(int parameterIndex, double newValue) { return new NormalSwaptionExpiryStrikeVolatilities( convention, valuationDateTime, surface.withParameter(parameterIndex, newValue)); } @Override public NormalSwaptionExpiryStrikeVolatilities withPerturbation(ParameterPerturbation perturbation) { return new NormalSwaptionExpiryStrikeVolatilities( convention, valuationDateTime, surface.withPerturbation(perturbation)); } //------------------------------------------------------------------------- @Override public double volatility(double expiry, double tenor, double strike, double forwardRate) { return surface.zValue(expiry, strike); } @Override public CurrencyParameterSensitivities parameterSensitivity(PointSensitivities pointSensitivities) { CurrencyParameterSensitivities sens = CurrencyParameterSensitivities.empty(); for (PointSensitivity point : pointSensitivities.getSensitivities()) { if (point instanceof SwaptionSensitivity) { SwaptionSensitivity pt = (SwaptionSensitivity) point; if (pt.getVolatilitiesName().equals(getName())) { sens = sens.combinedWith(parameterSensitivity(pt)); } } } return sens; } private CurrencyParameterSensitivity parameterSensitivity(SwaptionSensitivity point) { double expiry = point.getExpiry(); double strike = point.getStrike(); UnitParameterSensitivity unitSens = surface.zValueParameterSensitivity(expiry, strike); return unitSens.multipliedBy(point.getCurrency(), point.getSensitivity()); } //------------------------------------------------------------------------- @Override public double price(double expiry, double tenor, PutCall putCall, double strike, double forward, double volatility) { return NormalFormulaRepository.price(forward, strike, expiry, volatility, putCall); } @Override public double priceDelta(double expiry, double tenor, PutCall putCall, double strike, double forward, double volatility) { return NormalFormulaRepository.delta(forward, strike, expiry, volatility, putCall); } @Override public double priceGamma(double expiry, double tenor, PutCall putCall, double strike, double forward, double volatility) { return NormalFormulaRepository.gamma(forward, strike, expiry, volatility, putCall); } @Override public double priceTheta(double expiry, double tenor, PutCall putCall, double strike, double forward, double volatility) { return NormalFormulaRepository.theta(forward, strike, expiry, volatility, putCall); } @Override public double priceVega(double expiry, double tenor, PutCall putCall, double strike, double forward, double volatility) { return NormalFormulaRepository.vega(forward, strike, expiry, volatility, putCall); } //------------------------------------------------------------------------- @Override public double relativeTime(ZonedDateTime dateTime) { ArgChecker.notNull(dateTime, "dateTime"); LocalDate valuationDate = valuationDateTime.toLocalDate(); LocalDate date = dateTime.toLocalDate(); return dayCount.relativeYearFraction(valuationDate, date); } @Override public double tenor(LocalDate startDate, LocalDate endDate) { // rounded number of months. the rounding is to ensure that an integer number of year even with holidays/leap year return Math.round((endDate.toEpochDay() - startDate.toEpochDay()) / 365.25 * 12) / 12; } //------------------------- AUTOGENERATED START ------------------------- /** * The meta-bean for {@code NormalSwaptionExpiryStrikeVolatilities}. * @return the meta-bean, not null */ public static NormalSwaptionExpiryStrikeVolatilities.Meta meta() { return NormalSwaptionExpiryStrikeVolatilities.Meta.INSTANCE; } static { MetaBean.register(NormalSwaptionExpiryStrikeVolatilities.Meta.INSTANCE); } /** * The serialization version id. */ private static final long serialVersionUID = 1L; @Override public NormalSwaptionExpiryStrikeVolatilities.Meta metaBean() { return NormalSwaptionExpiryStrikeVolatilities.Meta.INSTANCE; } //----------------------------------------------------------------------- /** * Gets the swap convention that the volatilities are to be used for. * @return the value of the property, not null */ @Override public FixedFloatSwapConvention getConvention() { return convention; } //----------------------------------------------------------------------- /** * Gets the valuation date-time. * <p> * The volatilities are calibrated for this date-time. * @return the value of the property, not null */ @Override public ZonedDateTime getValuationDateTime() { return valuationDateTime; } //----------------------------------------------------------------------- /** * Gets the normal volatility surface. * <p> * The x-value of the surface is the expiry, as a year fraction. * The y-value of the surface is the strike, as a rate. * @return the value of the property, not null */ public Surface getSurface() { return surface; } //----------------------------------------------------------------------- @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == this.getClass()) { NormalSwaptionExpiryStrikeVolatilities other = (NormalSwaptionExpiryStrikeVolatilities) obj; return JodaBeanUtils.equal(convention, other.convention) && JodaBeanUtils.equal(valuationDateTime, other.valuationDateTime) && JodaBeanUtils.equal(surface, other.surface); } return false; } @Override public int hashCode() { int hash = getClass().hashCode(); hash = hash * 31 + JodaBeanUtils.hashCode(convention); hash = hash * 31 + JodaBeanUtils.hashCode(valuationDateTime); hash = hash * 31 + JodaBeanUtils.hashCode(surface); return hash; } @Override public String toString() { StringBuilder buf = new StringBuilder(128); buf.append("NormalSwaptionExpiryStrikeVolatilities{"); buf.append("convention").append('=').append(JodaBeanUtils.toString(convention)).append(',').append(' '); buf.append("valuationDateTime").append('=').append(JodaBeanUtils.toString(valuationDateTime)).append(',').append(' '); buf.append("surface").append('=').append(JodaBeanUtils.toString(surface)); buf.append('}'); return buf.toString(); } //----------------------------------------------------------------------- /** * The meta-bean for {@code NormalSwaptionExpiryStrikeVolatilities}. */ public static final class Meta extends DirectMetaBean { /** * The singleton instance of the meta-bean. */ static final Meta INSTANCE = new Meta(); /** * The meta-property for the {@code convention} property. */ private final MetaProperty<FixedFloatSwapConvention> convention = DirectMetaProperty.ofImmutable( this, "convention", NormalSwaptionExpiryStrikeVolatilities.class, FixedFloatSwapConvention.class); /** * The meta-property for the {@code valuationDateTime} property. */ private final MetaProperty<ZonedDateTime> valuationDateTime = DirectMetaProperty.ofImmutable( this, "valuationDateTime", NormalSwaptionExpiryStrikeVolatilities.class, ZonedDateTime.class); /** * The meta-property for the {@code surface} property. */ private final MetaProperty<Surface> surface = DirectMetaProperty.ofImmutable( this, "surface", NormalSwaptionExpiryStrikeVolatilities.class, Surface.class); /** * The meta-properties. */ private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap( this, null, "convention", "valuationDateTime", "surface"); /** * Restricted constructor. */ private Meta() { } @Override protected MetaProperty<?> metaPropertyGet(String propertyName) { switch (propertyName.hashCode()) { case 2039569265: // convention return convention; case -949589828: // valuationDateTime return valuationDateTime; case -1853231955: // surface return surface; } return super.metaPropertyGet(propertyName); } @Override public BeanBuilder<? extends NormalSwaptionExpiryStrikeVolatilities> builder() { return new NormalSwaptionExpiryStrikeVolatilities.Builder(); } @Override public Class<? extends NormalSwaptionExpiryStrikeVolatilities> beanType() { return NormalSwaptionExpiryStrikeVolatilities.class; } @Override public Map<String, MetaProperty<?>> metaPropertyMap() { return metaPropertyMap$; } //----------------------------------------------------------------------- /** * The meta-property for the {@code convention} property. * @return the meta-property, not null */ public MetaProperty<FixedFloatSwapConvention> convention() { return convention; } /** * The meta-property for the {@code valuationDateTime} property. * @return the meta-property, not null */ public MetaProperty<ZonedDateTime> valuationDateTime() { return valuationDateTime; } /** * The meta-property for the {@code surface} property. * @return the meta-property, not null */ public MetaProperty<Surface> surface() { return surface; } //----------------------------------------------------------------------- @Override protected Object propertyGet(Bean bean, String propertyName, boolean quiet) { switch (propertyName.hashCode()) { case 2039569265: // convention return ((NormalSwaptionExpiryStrikeVolatilities) bean).getConvention(); case -949589828: // valuationDateTime return ((NormalSwaptionExpiryStrikeVolatilities) bean).getValuationDateTime(); case -1853231955: // surface return ((NormalSwaptionExpiryStrikeVolatilities) bean).getSurface(); } return super.propertyGet(bean, propertyName, quiet); } @Override protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) { metaProperty(propertyName); if (quiet) { return; } throw new UnsupportedOperationException("Property cannot be written: " + propertyName); } } //----------------------------------------------------------------------- /** * The bean-builder for {@code NormalSwaptionExpiryStrikeVolatilities}. */ private static final class Builder extends DirectPrivateBeanBuilder<NormalSwaptionExpiryStrikeVolatilities> { private FixedFloatSwapConvention convention; private ZonedDateTime valuationDateTime; private Surface surface; /** * Restricted constructor. */ private Builder() { } //----------------------------------------------------------------------- @Override public Object get(String propertyName) { switch (propertyName.hashCode()) { case 2039569265: // convention return convention; case -949589828: // valuationDateTime return valuationDateTime; case -1853231955: // surface return surface; default: throw new NoSuchElementException("Unknown property: " + propertyName); } } @Override public Builder set(String propertyName, Object newValue) { switch (propertyName.hashCode()) { case 2039569265: // convention this.convention = (FixedFloatSwapConvention) newValue; break; case -949589828: // valuationDateTime this.valuationDateTime = (ZonedDateTime) newValue; break; case -1853231955: // surface this.surface = (Surface) newValue; break; default: throw new NoSuchElementException("Unknown property: " + propertyName); } return this; } @Override public NormalSwaptionExpiryStrikeVolatilities build() { return new NormalSwaptionExpiryStrikeVolatilities( convention, valuationDateTime, surface); } //----------------------------------------------------------------------- @Override public String toString() { StringBuilder buf = new StringBuilder(128); buf.append("NormalSwaptionExpiryStrikeVolatilities.Builder{"); buf.append("convention").append('=').append(JodaBeanUtils.toString(convention)).append(',').append(' '); buf.append("valuationDateTime").append('=').append(JodaBeanUtils.toString(valuationDateTime)).append(',').append(' '); buf.append("surface").append('=').append(JodaBeanUtils.toString(surface)); buf.append('}'); return buf.toString(); } } //-------------------------- AUTOGENERATED END -------------------------- }
apache-2.0
EricssonResearch/scott-eu
lyo-services/domain-pddl/src/main/java/eu/scott/warehouse/domains/pddl/IStep.java
5144
// Start of user code Copyright /******************************************************************************* * Copyright (c) 2012 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v. 1.0 which accompanies this distribution. * * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * * Russell Boykin - initial API and implementation * Alberto Giammaria - initial API and implementation * Chris Peters - initial API and implementation * Gianluca Bernardini - initial API and implementation * Sam Padgett - initial API and implementation * Michael Fiedler - adapted for OSLC4J * Jad El-khoury - initial implementation of code generator (https://bugs.eclipse.org/bugs/show_bug.cgi?id=422448) * * This file is generated by org.eclipse.lyo.oslc4j.codegenerator *******************************************************************************/ // End of user code package eu.scott.warehouse.domains.pddl; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.text.SimpleDateFormat; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.Iterator; import org.eclipse.lyo.oslc4j.core.annotation.OslcAllowedValue; import org.eclipse.lyo.oslc4j.core.annotation.OslcDescription; import org.eclipse.lyo.oslc4j.core.annotation.OslcMemberProperty; import org.eclipse.lyo.oslc4j.core.annotation.OslcName; import org.eclipse.lyo.oslc4j.core.annotation.OslcNamespace; import org.eclipse.lyo.oslc4j.core.annotation.OslcOccurs; import org.eclipse.lyo.oslc4j.core.annotation.OslcPropertyDefinition; import org.eclipse.lyo.oslc4j.core.annotation.OslcRange; import org.eclipse.lyo.oslc4j.core.annotation.OslcReadOnly; import org.eclipse.lyo.oslc4j.core.annotation.OslcRepresentation; import org.eclipse.lyo.oslc4j.core.annotation.OslcResourceShape; import org.eclipse.lyo.oslc4j.core.annotation.OslcTitle; import org.eclipse.lyo.oslc4j.core.annotation.OslcValueType; import org.eclipse.lyo.oslc4j.core.model.AbstractResource; import org.eclipse.lyo.oslc4j.core.model.Link; import org.eclipse.lyo.oslc4j.core.model.Occurs; import org.eclipse.lyo.oslc4j.core.model.OslcConstants; import org.eclipse.lyo.oslc4j.core.model.Representation; import org.eclipse.lyo.oslc4j.core.model.ValueType; import eu.scott.warehouse.domains.pddl.PddlDomainConstants; import eu.scott.warehouse.domains.pddl.PddlDomainConstants; import eu.scott.warehouse.domains.pddl.IAction; // Start of user code imports // End of user code @OslcNamespace(PddlDomainConstants.STEP_NAMESPACE) @OslcName(PddlDomainConstants.STEP_LOCALNAME) @OslcResourceShape(title = "Step Resource Shape", describes = PddlDomainConstants.STEP_TYPE) public interface IStep { public void addAdding(final Link adding ); public void addDeleting(final Link deleting ); public void addUpdating(final Link updating ); @OslcName("action") @OslcPropertyDefinition(PddlDomainConstants.SCOTT_PDDL_2_1_SUBSET_SPEC_NAMSPACE + "action") @OslcDescription("Action of the plan step.") @OslcOccurs(Occurs.ExactlyOne) @OslcValueType(ValueType.Resource) @OslcRange({PddlDomainConstants.ACTION_TYPE}) @OslcReadOnly(false) public Link getAction(); @OslcName("adding") @OslcPropertyDefinition(PddlDomainConstants.SCOTT_PDDL_2_1_SUBSET_SPEC_NAMSPACE + "adding") @OslcDescription("Step additions.") @OslcOccurs(Occurs.ZeroOrMany) @OslcValueType(ValueType.Resource) @OslcReadOnly(false) public Set<Link> getAdding(); @OslcName("deleting") @OslcPropertyDefinition(PddlDomainConstants.SCOTT_PDDL_2_1_SUBSET_SPEC_NAMSPACE + "deleting") @OslcDescription("Step deletions.") @OslcOccurs(Occurs.ZeroOrMany) @OslcValueType(ValueType.Resource) @OslcReadOnly(false) public Set<Link> getDeleting(); @OslcName("updating") @OslcPropertyDefinition(PddlDomainConstants.SCOTT_PDDL_2_1_SUBSET_SPEC_NAMSPACE + "updating") @OslcDescription("Step updates.") @OslcOccurs(Occurs.ZeroOrMany) @OslcValueType(ValueType.Resource) @OslcReadOnly(false) public Set<Link> getUpdating(); @OslcName("order") @OslcPropertyDefinition(PddlDomainConstants.SCOTT_PDDL_2_1_SUBSET_SPEC_NAMSPACE + "order") @OslcDescription("Parameter order.") @OslcOccurs(Occurs.ExactlyOne) @OslcValueType(ValueType.Integer) @OslcReadOnly(false) public Integer getOrder(); public void setAction(final Link action ); public void setAdding(final Set<Link> adding ); public void setDeleting(final Set<Link> deleting ); public void setUpdating(final Set<Link> updating ); public void setOrder(final Integer order ); }
apache-2.0
Otaka/mydifferentprojects
nes-java/test/com/nes/processor/SbcTest.java
1413
package com.nes.processor; import com.nes.NesAbstractTst; import org.junit.Test; /** * * @author Dmitry */ public class SbcTest extends NesAbstractTst { @Test public void testSbc() { String[] lines; lines = new String[]{ "clc", "lda #$50", "sbc #$5" }; testAlu(lines, 0x4a, 0x00, 0, 0xfd, 0x606, true, false, false, false); lines = new String[]{ "sec", "lda #$50", "sbc #$5" }; testAlu(lines, 0x4b, 0x00, 0, 0xfd, 0x606, true, false, false, false); lines = new String[]{ "sec", "lda #$5", "sbc #$55" }; testAlu(lines, 0xb0, 0x00, 0, 0xfd, 0x606, false, false, true, false); lines = new String[]{ "clc", "lda #$80", "sbc #$20" }; testAlu(lines, 0x5f, 0x00, 0, 0xfd, 0x606, true, false, false, true); lines = new String[]{ "clc", "lda #$20", "sbc #$80" }; testAlu(lines, 0x9f, 0x00, 0, 0xfd, 0x606, false, false, true, true); lines = new String[]{ "sec", "lda #$20", "sbc #$80" }; testAlu(lines, 0xa0, 0x00, 0, 0xfd, 0x606, false, false, true, true); } }
apache-2.0
LableOrg/java-bitsandbytes
src/main/java/org/lable/oss/bitsandbytes/BitMask.java
3928
/* * Copyright © 2015 Lable (info@lable.nl) * * 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.lable.oss.bitsandbytes; /** * Create bit or byte masks, where respectively each bit or the bytes 0x0 and 0x1 represent the mask, from a pattern * specification. */ public class BitMask { BitMask() { // Static utility class. } /** * Convert a pattern description into a byte array where each byte (not bit) is either a 0 or a 1. This format is * used by the {@code FuzzyRowFilter} in HBase. * <p> * Through the pattern passed as argument to this method you specify the alternating groups of ones and zeroes, * so {@code byteMask(2, 4, 1)} returns a byte array containing {@code 0x00 0x00 0x01 0x01 0x01 0x01 0x00}. * <p> * To start the mask with ones, pass 0 as the first number in the pattern. * * @param pattern The mask pattern, alternately specifying the length of the groups of zeroes and ones. * @return A byte array. */ public static byte[] byteMask(int... pattern) { if (pattern == null) { return new byte[0]; } int length = 0; for (int blockLength : pattern) { length += blockLength; } byte[] mask = new byte[length]; int blockOffset = 0; boolean writeZero = true; for (int blockLength : pattern) { for (int i = 0; i < blockLength; i++) { mask[blockOffset + i] = (byte) (writeZero ? 0x00 : 0x01); } blockOffset += blockLength; writeZero = !writeZero; } return mask; } /** * Convert a pattern description into a byte array where the pattern is represented by its bits. * <p> * Through the pattern passed as argument to this method you specify the alternating groups of ones and zeroes, * so {@code byteMask(8, 8)} returns a byte arrays containing {@code 0x00 0xFF}. If the pattern is not cleanly * divisible by eight, the bitmask returned will be padded with zeroes. So {@code byteMask(0, 4)} returns * {@code 0x0F}. * <p> * To start the mask with ones, pass 0 as the first number in the pattern. * * @param pattern The mask pattern, alternately specifying the length of the groups of zeroes and ones. * @return A byte array. */ public static byte[] bitMask(int... pattern) { if (pattern == null) { return new byte[0]; } int length = 0; for (int blockLength : pattern) { length += blockLength; } boolean cleanlyDivisible = length % 8 == 0; // Start at an offset when the pattern is not exactly divisible by 8. int blockOffset = cleanlyDivisible ? 0 : 8 - (length % 8); byte[] mask = new byte[(length / 8) + (cleanlyDivisible ? 0 : 1)]; boolean writeZero = true; for (int blockLength : pattern) { if (!writeZero) { for (int i = 0; i < blockLength; i++) { int bytePosition = (blockOffset + i) / 8; int bitPosition = (blockOffset + i) % 8; mask[bytePosition] = (byte) (mask[bytePosition] ^ 1 << (7 - bitPosition)); } } blockOffset += blockLength; writeZero = !writeZero; } return mask; } }
apache-2.0
lesfurets/dOOv
core/src/main/java/io/doov/core/dsl/DslField.java
1096
/* * Copyright 2017 Courtanet * * 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.doov.core.dsl; import io.doov.core.FieldId; import io.doov.core.dsl.impl.DefaultCondition; import io.doov.core.dsl.lang.Readable; /** * Interface for all field types. * * Generic type parameter {@link T} defines the type of the field. */ public interface DslField<T> extends Readable { FieldId id(); /** * Returns a new default condition that will use this as a field. * * @return the default condition */ DefaultCondition<T> getDefaultCondition(); }
apache-2.0
scana/ok-gradle
plugin/src/main/java/me/scana/okgradle/internal/dsl/parser/elements/GradleDslLiteral.java
5565
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.scana.okgradle.internal.dsl.parser.elements; import me.scana.okgradle.internal.dsl.api.ext.ReferenceTo; import me.scana.okgradle.internal.dsl.parser.GradleReferenceInjection; import me.scana.okgradle.internal.dsl.parser.elements.GradleDslElement; import me.scana.okgradle.internal.dsl.parser.elements.GradleDslSettableExpression; import me.scana.okgradle.internal.dsl.parser.elements.GradleNameElement; import com.google.common.collect.ImmutableList; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.Computable; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import static me.scana.okgradle.internal.dsl.api.ext.GradlePropertyModel.iStr; /** * Represents a literal element. */ public final class GradleDslLiteral extends GradleDslSettableExpression { public GradleDslLiteral(@NotNull me.scana.okgradle.internal.dsl.parser.elements.GradleDslElement parent, @NotNull GradleNameElement name) { super(parent, null, name, null); // Will be set in the call to #setValue myIsReference = false; } public GradleDslLiteral(@NotNull me.scana.okgradle.internal.dsl.parser.elements.GradleDslElement parent, @NotNull PsiElement psiElement, @NotNull GradleNameElement name, @NotNull PsiElement literal, boolean isReference) { super(parent, psiElement, name, literal); myIsReference = isReference; } @Override @Nullable public Object produceValue() { PsiElement element = getCurrentElement(); if (element == null) { return null; } return ApplicationManager.getApplication() .runReadAction((Computable<Object>)() -> getDslFile().getParser().extractValue(this, element, true)); } @Override @Nullable public Object produceUnresolvedValue() { PsiElement element = getCurrentElement(); if (element == null) { return null; } return ApplicationManager.getApplication() .runReadAction((Computable<Object>)() -> getDslFile().getParser().extractValue(this, element, false)); } @Override public void setValue(@NotNull Object value) { checkForValidValue(value); PsiElement element = ApplicationManager.getApplication().runReadAction((Computable<PsiElement>)() -> { PsiElement psiElement = getDslFile().getParser().convertToPsiElement(value); getDslFile().getParser().setUpForNewValue(this, psiElement); return psiElement; }); setUnsavedValue(element); valueChanged(); } @Nullable @Override public Object produceRawValue() { PsiElement currentElement = getCurrentElement(); if (currentElement == null) { return null; } return ApplicationManager.getApplication() .runReadAction((Computable<Object>)() -> { boolean shouldInterpolate = getDslFile().getParser().shouldInterpolate(this); Object val = getDslFile().getParser().extractValue(this, currentElement, false); if (val instanceof String && shouldInterpolate) { return iStr((String)val); } return val; }); } @NotNull @Override public GradleDslLiteral copy() { assert myParent != null; GradleDslLiteral literal = new GradleDslLiteral(myParent, GradleNameElement.copy(myName)); Object v = getRawValue(); if (v != null) { literal.setValue(isReference() ? new ReferenceTo((String)v) : v); } return literal; } @Override public String toString() { Object value = getValue(); return value != null ? value.toString() : super.toString(); } @Override @NotNull public Collection<GradleDslElement> getChildren() { return ImmutableList.of(); } @Override @Nullable public PsiElement create() { return getDslFile().getWriter().createDslLiteral(this); } @Override public void delete() { getDslFile().getWriter().deleteDslLiteral(this); } @Override protected void apply() { getDslFile().getWriter().applyDslLiteral(this); } @Nullable public GradleReferenceInjection getReferenceInjection() { return myDependencies.isEmpty() ? null : myDependencies.get(0); } @Override @Nullable public String getReferenceText() { if (!myIsReference) { return null; } PsiElement element = getCurrentElement(); return element != null ? getPsiText(element) : null; } @Override public void reset() { super.reset(); ApplicationManager.getApplication().runReadAction(() -> getDslFile().getParser().setUpForNewValue(this, getCurrentElement())); } }
apache-2.0
lucastheisen/mina-sshd
sshd-fs/src/main/java/org/apache/sftp/protocol/packetdata/ExtendedImplementation.java
338
package org.apache.sftp.protocol.packetdata; import org.apache.sftp.protocol.Response; public interface ExtendedImplementation<T extends Extended<T, S>, S extends Response<S>> extends Implementation<T> { public String getExtendedRequest(); public Implementation<S> getExtendedReplyImplementation(); }
apache-2.0
myntra/CoachMarks
coachmarks/src/main/java/com/myntra/coachmarks/builder/CoachMarkPixelInfo.java
3163
package com.myntra.coachmarks.builder; import android.graphics.Rect; import android.os.Parcelable; import com.google.auto.value.AutoValue; @AutoValue public abstract class CoachMarkPixelInfo implements Parcelable { public static CoachMarkPixelInfo.Builder create() { return new AutoValue_CoachMarkPixelInfo.Builder() .setImageWidthInPixels(0) .setImageHeightInPixels(0) .setMarginRectInPixels(new Rect(0, 0, 0, 0)) .setPopUpWidthInPixelsWithOffset(0) .setPopUpHeightInPixelsWithOffset(0) .setPopUpWidthInPixels(0) .setPopUpHeightInPixels(0) .setScreenWidthInPixels(0) .setScreenHeightInPixels(0) .setNotchDimenInPixels(0) .setActionBarHeightPixels(0) .setFooterHeightPixels(0) .setMarginOffsetForNotchInPixels(0) .setWidthHeightOffsetForCoachMarkPopUp(0); } public abstract int getImageWidthInPixels(); public abstract int getImageHeightInPixels(); public abstract Rect getMarginRectInPixels(); public abstract int getPopUpWidthInPixelsWithOffset(); public abstract int getPopUpHeightInPixelsWithOffset(); public abstract int getPopUpWidthInPixels(); public abstract int getPopUpHeightInPixels(); public abstract int getScreenWidthInPixels(); public abstract int getScreenHeightInPixels(); public abstract int getNotchDimenInPixels(); public abstract int getActionBarHeightPixels(); public abstract int getFooterHeightPixels(); public abstract int getMarginOffsetForNotchInPixels(); public abstract int getWidthHeightOffsetForCoachMarkPopUp(); @AutoValue.Builder public static abstract class Builder { public abstract Builder setImageWidthInPixels(int imageWidthInPixels); public abstract Builder setImageHeightInPixels(int imageHeightInPixels); public abstract Builder setMarginRectInPixels(Rect coachMarkMarginRectInPixels); public abstract Builder setPopUpWidthInPixelsWithOffset(int coachMarkPopUpWidthInPixelsWithOffset); public abstract Builder setPopUpHeightInPixelsWithOffset(int coachMarkPopUpHeightInPixelsWithOffset); public abstract Builder setPopUpWidthInPixels(int coachMarkPopUpWidthInPixels); public abstract Builder setPopUpHeightInPixels(int coachMarkPopUpHeightInPixels); public abstract Builder setScreenWidthInPixels(int screenWidthInPixels); public abstract Builder setScreenHeightInPixels(int screenHeightInPixels); public abstract Builder setNotchDimenInPixels(int notchDimenInPixels); public abstract Builder setActionBarHeightPixels(int actionBarHeightPixels); public abstract Builder setFooterHeightPixels(int footerHeightPixels); public abstract Builder setMarginOffsetForNotchInPixels(int marginOffsetForNotchInPixels); public abstract Builder setWidthHeightOffsetForCoachMarkPopUp(int widthHeightOffsetForCoachMarkPopUp); public abstract CoachMarkPixelInfo build(); } }
apache-2.0
komoot/graphhopper
reader-gtfs/src/main/java/com/graphhopper/reader/gtfs/PtFlagEncoder.java
3249
/* * Licensed to GraphHopper GmbH under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper GmbH licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.graphhopper.reader.gtfs; import com.graphhopper.reader.ReaderRelation; import com.graphhopper.reader.ReaderWay; import com.graphhopper.routing.profiles.EncodedValue; import com.graphhopper.routing.profiles.IntEncodedValue; import com.graphhopper.routing.profiles.SimpleIntEncodedValue; import com.graphhopper.routing.util.AbstractFlagEncoder; import com.graphhopper.routing.util.EncodingManager; import com.graphhopper.storage.IntsRef; import com.graphhopper.util.EdgeIteratorState; import java.util.List; public class PtFlagEncoder extends AbstractFlagEncoder { private IntEncodedValue timeEnc; private IntEncodedValue transfersEnc; private IntEncodedValue validityIdEnc; private IntEncodedValue typeEnc; public PtFlagEncoder() { super(0, 1, 0); } @Override public void createEncodedValues(List<EncodedValue> list, String prefix, int index) { // do we really need 2 bits for pt.access? super.createEncodedValues(list, prefix, index); list.add(validityIdEnc = new SimpleIntEncodedValue(prefix + "validity_id", 20, false)); list.add(transfersEnc = new SimpleIntEncodedValue(prefix + "transfers", 1, false)); list.add(typeEnc = new SimpleIntEncodedValue(prefix + "type", 4, false)); list.add(timeEnc = new SimpleIntEncodedValue(prefix + "time", 17, false)); } @Override public long handleRelationTags(long oldRelationFlags, ReaderRelation relation) { return oldRelationFlags; } @Override public EncodingManager.Access getAccess(ReaderWay way) { return EncodingManager.Access.CAN_SKIP; } @Override public IntsRef handleWayTags(IntsRef edgeFlags, ReaderWay way, EncodingManager.Access access, long relationFlags) { return edgeFlags; } public IntEncodedValue getTimeEnc() { return timeEnc; } public IntEncodedValue getTransfersEnc() { return transfersEnc; } public IntEncodedValue getValidityIdEnc() { return validityIdEnc; } GtfsStorage.EdgeType getEdgeType(EdgeIteratorState edge) { return GtfsStorage.EdgeType.values()[edge.get(typeEnc)]; } void setEdgeType(EdgeIteratorState edge, GtfsStorage.EdgeType edgeType) { edge.set(typeEnc, edgeType.ordinal()); } public String toString() { return "pt"; } @Override public int getVersion() { return 1; } }
apache-2.0
underclocker/Blob-Game
BlobGame/src/org/siggd/actor/Cannon.java
10975
package org.siggd.actor; import org.siggd.ContactHandler; import org.siggd.Convert; import org.siggd.Game; import org.siggd.Level; import org.siggd.StableContact; import org.siggd.Timer; import org.siggd.view.BodySprite; import org.siggd.view.CompositeDrawable; import org.siggd.view.Drawable; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.CircleShape; import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.RayCastCallback; public class Cannon extends Actor implements RayCastCallback { private class HitScanDrawable implements Drawable { @Override public void drawSprite(SpriteBatch batch) { // no sprite to draw } @Override public void drawElse(ShapeRenderer shapeRender) { // draw laser! if(targetAcquired) { shapeRender.begin(ShapeType.Line); shapeRender.setColor(1, 0, 0, 1); shapeRender.line(startOfLaser.x, startOfLaser.y, mLaserEnd.x, mLaserEnd.y); shapeRender.end(); } } @Override public void drawDebug(Camera camera) { // use? } } private String mTex; private Timer mSpawnTimer; private Fixture mSensorBall; float detectRadius = 6f; Blob rememberBlob; int initialAngle; int shotsFired = 0; boolean immediateRefire = false; long previousID; boolean targetAcquired = false; //private ShapeRenderer mShapeRenderer; private Vector2 mLaserEnd = new Vector2(); private final float mLaserLength = 1000; Vector2 startOfLaser = new Vector2(); boolean checkingLOS = false; public Cannon(Level level, long id) { super(level, id); mName = "lightbulb"; mTex = "data/" + Game.get().getBodyEditorLoader().getImagePath(mName); Vector2 origin = new Vector2(); mBody = makeBody(mName, 128, BodyType.KinematicBody, origin, true); ((CompositeDrawable) mDrawable).mDrawables.add(new BodySprite(mBody, origin, mTex)); CircleShape circle = new CircleShape(); circle.setPosition(new Vector2(0, 0)); circle.setRadius(detectRadius); FixtureDef fd = new FixtureDef(); fd.shape = circle; fd.isSensor = true; mSensorBall = mBody.createFixture(fd); mSpawnTimer = new Timer(); mSpawnTimer.setTimer(Convert.getInt(this.getProp("Rate"))); mSpawnTimer.unpause(); this.setProp("Rate", 120); this.setProp("Exit Velocity", 25); this.setProp("Layer", 4); // 0 - Explode Ball 1 - Implode Ball this.setProp("Ammo", 0); this.setProp("explodeTime", 180); this.setProp("Alternate", 0); ((CompositeDrawable) mDrawable).mDrawables.add(new BodySprite(mBody, origin, mTex)); ((CompositeDrawable) mDrawable).mDrawables.add(new HitScanDrawable()); } @Override public void loadResources() { AssetManager man = Game.get().getAssetManager(); man.load(mTex, Texture.class); } public void update() { // Hitscan Stuff float daAngle = (Convert.getDegrees(mBody.getAngle()) - 90); if (daAngle < 0) daAngle += 360; if (daAngle > 360) daAngle -= 360; Vector2 finalStart = new Vector2(mBody.getPosition().cpy().x + 0.585f, mBody.getPosition() .cpy().y); finalStart.sub(mBody.getPosition().cpy()); finalStart.rotate(Convert.getDegrees(mBody.getAngle())); Vector2 start = new Vector2(mBody.getPosition().cpy().x, mBody.getPosition().cpy().y); start.add(finalStart); startOfLaser = start; Vector2 end = new Vector2(0, mLaserLength).rotate(daAngle); mLaserEnd = end.add(start); setProp("Actor Hit", -1); mLevel.getWorld().rayCast(this, start, mLaserEnd.cpy()); Iterable<StableContact> contacts = Game.get().getLevel().getContactHandler() .getContacts(this); Iterable<Actor> actors = ContactHandler.getActors(contacts); boolean enemySeen = false; super.update(); for (Actor a : actors) { if (a instanceof Blob) { checkingLOS = true; Blob seeCheck = (Blob) a; Vector2 seeCheckPos = new Vector2(seeCheck.getX(), seeCheck.getY()); mLevel.getWorld().rayCast(this, mBody.getPosition(), seeCheckPos); checkingLOS = false; if(!targetAcquired) { continue; } if (rememberBlob != null) { Vector2 rememberDist = new Vector2( rememberBlob.getX(), rememberBlob.getY() ); rememberDist.sub(mBody.getPosition()); float remDist = Math.abs(rememberDist.len()); if (remDist > detectRadius) { rememberBlob = null; } } if (rememberBlob == null) { rememberBlob = (Blob) a; } enemySeen = true; Blob blob = rememberBlob; Vector2 blobPos = new Vector2(blob.getX(), blob.getY()); Vector2 blobCpy = blobPos.cpy(); blobCpy.sub(mBody.getPosition()); float blobDistance = blobCpy.len(); blobCpy.nor(); int desiredAngle; int currentAngle = Convert.getInt(getProp("Angle")); if (Convert.getFloat(blob.getProp("Velocity X")) > 0) { desiredAngle = 2; } else { desiredAngle = -2; } if (blobPos.y > mBody.getPosition().y) { desiredAngle += (int) (Math.acos(Convert.getDouble(blobCpy.x)) * (180 / Math.PI)); } else { if (blobPos.x > mBody.getPosition().x) { desiredAngle += (int) ((Math.asin(Convert.getDouble(blobCpy.y)) + 2 * Math.PI) * (180 / Math.PI)); } else { desiredAngle += (int) ((Math.PI + (Math.abs(Math.asin(Convert .getDouble(blobCpy.y))))) * (180 / Math.PI)); } } int totalRotation = desiredAngle - currentAngle; int swapper = 1; if (totalRotation > 180 || totalRotation < -180) { swapper = -1; } float rotSpeed = 1.5f; // System.out.println("Current: " + currentAngle); // System.out.println(" Desired: " + desiredAngle); float spawnCheckTotal = desiredAngle - currentAngle; if (spawnCheckTotal > 360) spawnCheckTotal -= 360; if (spawnCheckTotal < -360) spawnCheckTotal += 360; // 3 is because of the aiming offset if ((Math.abs(spawnCheckTotal) < 3 || Math.abs(spawnCheckTotal) > 357) && targetAcquired) { if (immediateRefire && shotsFired >= 1) { if (Game.get().getLevel().getActorById(previousID) != null) { if (!Game.get().getLevel().getActorById(previousID).isActive()) { spawnActor(); shotsFired++; mSpawnTimer.reset(); } } } else { mSpawnTimer.update(); if (mSpawnTimer.isTriggered() || shotsFired == 0) { spawnActor(); shotsFired++; mSpawnTimer.reset(); } } } if (currentAngle == desiredAngle) { mBody.setAngularVelocity(0f); } else if (desiredAngle > currentAngle) { mBody.setAngularVelocity(swapper * (rotSpeed)); } else if (desiredAngle < currentAngle) { mBody.setAngularVelocity(swapper * (-rotSpeed)); } } } if (!enemySeen) { shotsFired = 0; int currentAngle = Convert.getInt(getProp("Angle")); int desiredAngle = initialAngle; float totalRotation = desiredAngle - currentAngle; int swapper = 1; if (totalRotation > 180f || totalRotation < -180f) { swapper = -1; } float rotSpeed = 1.5f; if (totalRotation > 360) { totalRotation -= 360; } if (totalRotation < -360) { totalRotation += 360; } if (Math.abs(totalRotation) < 30 || Math.abs(totalRotation) > 330) { rotSpeed = 0.5f; } if (currentAngle == desiredAngle) { mBody.setAngularVelocity(0f); } else if (desiredAngle > currentAngle) { mBody.setAngularVelocity(swapper * (rotSpeed)); } else if (desiredAngle < currentAngle) { mBody.setAngularVelocity(swapper * (-rotSpeed)); } } } private void spawnActor() { Level thisHereLevel = Game.get().getLevel(); long nextID = thisHereLevel.getId(); previousID = nextID; Actor toSpawn; if (Convert.getInt(getProp("Alternate")) == 1) { if ((((shotsFired + 1) % 2) == 0 && Convert.getInt(getProp("Ammo")) == 0) || (((shotsFired + 1) % 2) == 1 && Convert.getInt(getProp("Ammo")) == 1)) { toSpawn = new ImplodeBall(thisHereLevel, nextID, Convert.getInt(getProp("explodeTime"))); } else { toSpawn = new ExplodeBall(thisHereLevel, nextID, Convert.getInt(getProp("explodeTime"))); } } else { if (Convert.getInt(getProp("Ammo")) == 1) { toSpawn = new ImplodeBall(thisHereLevel, nextID, Convert.getInt(getProp("explodeTime"))); } else { toSpawn = new ExplodeBall(thisHereLevel, nextID, Convert.getInt(getProp("explodeTime"))); } } Vector2 pos = mBody.getPosition(); toSpawn.setX(pos.x); toSpawn.setY(pos.y); toSpawn.setProp("Angle", mBody.getAngle()); Game.get().getLevel().addActor(toSpawn); Vector2 vel = new Vector2(Convert.getInt(getProp("Exit Velocity")), 0); vel.rotate(Convert.getDegrees(mBody.getAngle())); toSpawn.setProp("Velocity X", vel.x); toSpawn.setProp("Velocity Y", vel.y); } public void setProp(String name, Object val) { if (name.equals("Rate")) { if (Convert.getInt(val) == -1) { // it wont even use this timer, kindof, I THINK ESNARF! mSpawnTimer.setTimer(5000); immediateRefire = true; } else { immediateRefire = false; mSpawnTimer.setTimer(Convert.getInt(val)); } } if (name.equals("Angle")) { initialAngle = Convert.getInt(val); } super.setProp(name, val); } @Override public void loadBodies() { } @Override public void postLoad() { } @Override public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) { Actor intersect = (Actor) fixture.getBody().getUserData(); if (intersect != null) { // ignore things like wind/redirectors if (intersect.mBody.getFixtureList().get(0).isSensor() || intersect instanceof VacuumBot || intersect instanceof ExplodeBall || intersect instanceof ImplodeBall) { return -1; } if (intersect instanceof Blob) { targetAcquired = true; } else { targetAcquired = false; } setProp("Actor Hit", intersect.getId()); if(!checkingLOS) { mLaserEnd = point.cpy(); } // clip at the first actor return fraction; } else { // there was no actor tied to this fixture, ignore it return -1; } } }
apache-2.0
smanvi-pivotal/geode
geode-core/src/test/java/org/apache/geode/internal/logging/LogServiceIntegrationJUnitTest.java
8584
/* * 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.geode.internal.logging; import static org.apache.geode.internal.logging.LogServiceIntegrationTestSupport.*; import static org.assertj.core.api.Assertions.*; import java.io.File; import java.net.URL; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.Appender; import org.apache.logging.log4j.core.Logger; import org.apache.logging.log4j.core.config.ConfigurationFactory; import org.apache.logging.log4j.status.StatusLogger; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.SystemErrRule; import org.junit.contrib.java.lang.system.SystemOutRule; import org.junit.experimental.categories.Category; import org.junit.rules.ExternalResource; import org.junit.rules.TemporaryFolder; import org.apache.geode.internal.logging.log4j.Configurator; import org.apache.geode.test.junit.categories.IntegrationTest; /** * Integration tests for LogService and how it configures and uses log4j2 * */ @Category(IntegrationTest.class) public class LogServiceIntegrationJUnitTest { private static final String DEFAULT_CONFIG_FILE_NAME = "log4j2.xml"; private static final String CLI_CONFIG_FILE_NAME = "log4j2-cli.xml"; @Rule public final SystemErrRule systemErrRule = new SystemErrRule().enableLog(); @Rule public final SystemOutRule systemOutRule = new SystemOutRule().enableLog(); @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); @Rule public final ExternalResource externalResource = new ExternalResource() { @Override protected void before() { beforeConfigFileProp = System.getProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY); beforeLevel = StatusLogger.getLogger().getLevel(); System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY); StatusLogger.getLogger().setLevel(Level.OFF); Configurator.shutdown(); } @Override protected void after() { Configurator.shutdown(); System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY); if (beforeConfigFileProp != null) { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, beforeConfigFileProp); } StatusLogger.getLogger().setLevel(beforeLevel); LogService.reconfigure(); assertThat(LogService.isUsingGemFireDefaultConfig()).as(LogService.getConfigInformation()) .isTrue(); } }; private String beforeConfigFileProp; private Level beforeLevel; private URL defaultConfigUrl; private URL cliConfigUrl; @Before public void setUp() { this.defaultConfigUrl = LogService.class.getResource(LogService.DEFAULT_CONFIG); this.cliConfigUrl = LogService.class.getResource(LogService.CLI_CONFIG); } @After public void after() { // if either of these fail then log4j2 probably logged a failure to stdout assertThat(this.systemErrRule.getLog()).isEmpty(); assertThat(this.systemOutRule.getLog()).isEmpty(); } @Test public void shouldPreferConfigurationFilePropertyIfSet() throws Exception { final File configFile = this.temporaryFolder.newFile(DEFAULT_CONFIG_FILE_NAME); final String configFileName = configFile.toURI().toString(); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, configFileName); writeConfigFile(configFile, Level.DEBUG); LogService.reconfigure(); assertThat(LogService.isUsingGemFireDefaultConfig()).as(LogService.getConfigInformation()) .isFalse(); assertThat(System.getProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY)) .isEqualTo(configFileName); assertThat(LogService.getLogger().getName()).isEqualTo(getClass().getName()); } @Test public void shouldUseDefaultConfigIfNotConfigured() throws Exception { LogService.reconfigure(); assertThat(LogService.isUsingGemFireDefaultConfig()).as(LogService.getConfigInformation()) .isTrue(); assertThat(System.getProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY)) .isNullOrEmpty(); } @Test public void defaultConfigShouldIncludeStdout() { LogService.reconfigure(); final Logger rootLogger = (Logger) LogService.getRootLogger(); assertThat(LogService.isUsingGemFireDefaultConfig()).as(LogService.getConfigInformation()) .isTrue(); assertThat(rootLogger.getAppenders().get(LogService.STDOUT)).isNotNull(); } @Test public void removeConsoleAppenderShouldRemoveStdout() { LogService.reconfigure(); final Logger rootLogger = (Logger) LogService.getRootLogger(); LogService.removeConsoleAppender(); assertThat(rootLogger.getAppenders().get(LogService.STDOUT)).isNull(); } @Test public void restoreConsoleAppenderShouldRestoreStdout() { LogService.reconfigure(); final Logger rootLogger = (Logger) LogService.getRootLogger(); LogService.removeConsoleAppender(); assertThat(rootLogger.getAppenders().get(LogService.STDOUT)).isNull(); LogService.restoreConsoleAppender(); assertThat(rootLogger.getAppenders().get(LogService.STDOUT)).isNotNull(); } @Test public void removeAndRestoreConsoleAppenderShouldAffectRootLogger() { LogService.reconfigure(); assertThat(LogService.isUsingGemFireDefaultConfig()).as(LogService.getConfigInformation()) .isTrue(); final Logger rootLogger = (Logger) LogService.getRootLogger(); // assert "Console" is present for ROOT Appender appender = rootLogger.getAppenders().get(LogService.STDOUT); assertThat(appender).isNotNull(); LogService.removeConsoleAppender(); // assert "Console" is not present for ROOT appender = rootLogger.getAppenders().get(LogService.STDOUT); assertThat(appender).isNull(); LogService.restoreConsoleAppender(); // assert "Console" is present for ROOT appender = rootLogger.getAppenders().get(LogService.STDOUT); assertThat(appender).isNotNull(); } @Test public void shouldNotUseDefaultConfigIfCliConfigSpecified() throws Exception { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, this.cliConfigUrl.toString()); LogService.reconfigure(); assertThat(LogService.isUsingGemFireDefaultConfig()).as(LogService.getConfigInformation()) .isFalse(); assertThat(System.getProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY)) .isEqualTo(this.cliConfigUrl.toString()); assertThat(LogService.getLogger().getName()).isEqualTo(getClass().getName()); } @Test public void isUsingGemFireDefaultConfigShouldBeTrueIfDefaultConfig() throws Exception { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, this.defaultConfigUrl.toString()); assertThat(LogService.getConfiguration().getConfigurationSource().toString()) .contains(DEFAULT_CONFIG_FILE_NAME); assertThat(LogService.isUsingGemFireDefaultConfig()).isTrue(); } @Test public void isUsingGemFireDefaultConfigShouldBeFalseIfCliConfig() throws Exception { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, this.cliConfigUrl.toString()); assertThat(LogService.getConfiguration().getConfigurationSource().toString()) .doesNotContain(DEFAULT_CONFIG_FILE_NAME); assertThat(LogService.isUsingGemFireDefaultConfig()).isFalse(); } @Test public void shouldUseCliConfigIfCliConfigIsSpecifiedViaClasspath() throws Exception { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "classpath:" + CLI_CONFIG_FILE_NAME); assertThat(LogService.getConfiguration().getConfigurationSource().toString()) .contains(CLI_CONFIG_FILE_NAME); assertThat(LogService.isUsingGemFireDefaultConfig()).isFalse(); } }
apache-2.0
tseen/Federated-HDFS
tseenliu/FedHDFS-hadoop-src/hadoop-hdfs-project/hadoop-hdfs/src/main/java/ncku/hpds/hadoop/fedhdfs/shell/DeleteDir.java
2262
package ncku.hpds.hadoop.fedhdfs.shell; import java.io.BufferedOutputStream; import java.io.ObjectInputStream; import java.net.InetSocketAddress; import java.net.Socket; import ncku.hpds.hadoop.fedhdfs.GlobalNamespaceObject; public class DeleteDir { private String SNaddress = "127.0.0.1"; private int SNport = 8765; private int port = 8764; public void rmGlobalFileFromGN(String command, String globalFileName) { Socket client = new Socket(); ObjectInputStream ObjectIn; InetSocketAddress isa = new InetSocketAddress(this.SNaddress, this.port); try { client.connect(isa, 10000); ObjectIn = new ObjectInputStream(client.getInputStream()); // received object GlobalNamespaceObject GN = new GlobalNamespaceObject(); try { GN = (GlobalNamespaceObject) ObjectIn.readObject(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } //doing... if (GN.getGlobalNamespace().getLogicalDrive().getLogicalMappingTable().containsKey(globalFileName)) { Socket SNclient = new Socket(); InetSocketAddress SNisa = new InetSocketAddress(this.SNaddress, this.SNport); try { SNclient.connect(SNisa, 10000); BufferedOutputStream out = new BufferedOutputStream(SNclient .getOutputStream()); // send message String message = command + " " + globalFileName; out.write(message.getBytes()); out.flush(); out.close(); out = null; SNclient.close(); SNclient = null; } catch (java.io.IOException e) { System.out.println("Socket connect error"); System.out.println("IOException :" + e.toString()); } } else { System.out.println("Error: " + globalFileName + " not found "); } ObjectIn.close(); ObjectIn = null; client.close(); } catch (java.io.IOException e) { System.out.println("Socket connection error"); System.out.println("IOException :" + e.toString()); } System.out.println("globalFileName : " + globalFileName); } }
apache-2.0
quarkusio/quarkus
extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/ReflectiveBeanClassesProcessor.java
1559
package io.quarkus.arc.deployment; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.jandex.Type; import io.quarkus.arc.processor.BeanInfo; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.runtime.annotations.RegisterForReflection; public class ReflectiveBeanClassesProcessor { @BuildStep void implicitReflectiveBeanClasses(BuildProducer<ReflectiveBeanClassBuildItem> reflectiveBeanClasses, BeanDiscoveryFinishedBuildItem beanDiscoveryFinished) { DotName registerForReflection = DotName.createSimple(RegisterForReflection.class.getName()); for (BeanInfo classBean : beanDiscoveryFinished.beanStream().classBeans()) { ClassInfo beanClass = classBean.getTarget().get().asClass(); AnnotationInstance annotation = beanClass.classAnnotation(registerForReflection); if (annotation != null) { Type[] targets = annotation.value("targets") != null ? annotation.value("targets").asClassArray() : new Type[] {}; String[] classNames = annotation.value("classNames") != null ? annotation.value("classNames").asStringArray() : new String[] {}; if (targets.length == 0 && classNames.length == 0) { reflectiveBeanClasses.produce(new ReflectiveBeanClassBuildItem(beanClass)); } } } } }
apache-2.0
diyanfilipov/potlach-client
src/com/android/potlach/cloud/client/UnsafeHttpsClient.java
4431
package com.android.potlach.cloud.client; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.client.HttpClient; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; /** * This is an example of an HTTP client that does not properly * validate SSL certificates that are used for HTTPS. You should * NEVER use a client like this in a production application. Self-signed * certificates are ususally only OK for testing purposes, such as * this use case. * * @author jules * */ public class UnsafeHttpsClient { private static class MySSLSocketFactory extends SSLSocketFactory { SSLContext sslContext = SSLContext.getInstance("TLS"); public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(truststore); TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) {} public void checkServerTrusted(X509Certificate[] chain, String authType) {} public X509Certificate[] getAcceptedIssuers() { return null; } }; sslContext.init(null, new TrustManager[] { tm }, null); } public MySSLSocketFactory(SSLContext context) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException { super(null); sslContext = context; } @Override public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); } @Override public Socket createSocket() throws IOException { return sslContext.getSocketFactory().createSocket(); } } public static HttpClient createUnsafeClient() { try { HttpClient client = new DefaultHttpClient(); client = sslClient(client); // Execute HTTP Post Request // HttpGet post = new HttpGet(new URI("https://google.com")); // HttpResponse result = client.execute(post); // Log.v("test", EntityUtils.toString(result.getEntity())); // KeyStore trusted = KeyStore.getInstance("BKS"); // SSLContextBuilder builder = new SSLContextBuilder(); // builder.loadTrustMaterial(null, new AllowAllHostnameVerifier()); // // SSLConnectionSocketFactory sslsf = new SSLSocketFactory( // builder.build()); // CloseableHttpClient httpclient = HttpClients.custom() // .setSSLSocketFactory(sslsf).build(); return client; } catch (Exception e) { throw new RuntimeException(e); } } private static HttpClient sslClient(HttpClient client) { try { X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, new TrustManager[]{tm}, null); SSLSocketFactory ssf = new MySSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = client.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", ssf, 8443)); return new DefaultHttpClient(ccm, client.getParams()); } catch (Exception ex) { return null; } } }
apache-2.0
hujiaweibujidao/XSolutions
java/leetcode/BestTimetoBuyandSellStock_121.java
654
/** * hujiawei - 15/3/21. * <p/> * 贪心 * <p/> * https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ */ public class BestTimetoBuyandSellStock_121 { public static void main(String[] args) { System.out.println(new BestTimetoBuyandSellStock_121().maxProfit(new int[]{2, 5, 3, 8, 1, 10})); } public int maxProfit(int[] prices) { if (prices.length <= 1) return 0; int max = 0, low = prices[0]; for (int i = 1; i < prices.length; i++) { if (prices[i] < low) low = prices[i]; else if (prices[i] - low > max) max = prices[i] - low; } return max; } }
apache-2.0
songzhw/AndroidTestDemo
IntoJFace/src/cn/six/tutor/table2/Table2Util.java
1025
package cn.six.tutor.table2; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import java.net.MalformedURLException; import java.net.URL; /** * Created by songzhw on 2016/3/5. */ public class Table2Util { private static ImageRegistry imgReg; public static URL newUrl(String urlName){ try { return new URL(urlName); } catch (MalformedURLException e) { e.printStackTrace(); return null; } } public static ImageRegistry getImageRegister() { if(imgReg == null){ imgReg = new ImageRegistry(); imgReg.put("folder", ImageDescriptor.createFromURL(newUrl("file:images/ic_box_16.png"))); imgReg.put("file", ImageDescriptor.createFromURL(newUrl("file:images/ic_file_16.png"))); } return imgReg; } public static ImageDescriptor getImageDesp(String url){ return ImageDescriptor.createFromURL(Table2Util.newUrl(url)); } }
apache-2.0
lixwcqs/funny
src/main/java/com.cqs/socket/example/SocketServerEncrypt.java
2461
package com.cqs.socket.example; import javax.net.ServerSocketFactory; import javax.net.ssl.SSLServerSocketFactory; import java.io.BufferedInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; /** * Created by cqs on 10/29/16. */ public class SocketServerEncrypt { private final static Logger logger = Logger.getLogger(SocketServerEncrypt.class.getName()); public static void main(String[] args) { try { ServerSocketFactory factory = SSLServerSocketFactory.getDefault(); ServerSocket server = factory.createServerSocket(10000); while (true) { Socket socket = server.accept(); invoke(socket); } } catch (Exception ex) { ex.printStackTrace(); } } private static void invoke(final Socket socket) throws IOException { new Thread(new Runnable() { public void run() { ObjectInputStream is = null; ObjectOutputStream os = null; try { is = new ObjectInputStream(new BufferedInputStream(socket.getInputStream())); os = new ObjectOutputStream(socket.getOutputStream()); Object obj = is.readObject(); User user = (User) obj; System.out.println("user: " + user.getName() + "/" + user.getPassword()); user.setName(user.getName() + "_new"); user.setPassword(user.getPassword() + "_new"); os.writeObject(user); os.flush(); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { logger.log(Level.SEVERE, null, ex); } finally { try { is.close(); } catch (Exception ex) { } try { os.close(); } catch (Exception ex) { } try { socket.close(); } catch (Exception ex) { } } } }).start(); } }
apache-2.0
lgoldstein/communitychest
chest/gui/swing/src/test/java/net/community/chest/test/gui/ResourcesTester.java
3969
package net.community.chest.test.gui; import java.io.BufferedReader; import java.io.PrintStream; import net.community.chest.Triplet; import net.community.chest.awt.dom.converter.InsetsValueInstantiator; import net.community.chest.awt.layout.gridbag.ExtendedGridBagConstraints; import net.community.chest.awt.layout.gridbag.GridBagGridSizingType; import net.community.chest.awt.layout.gridbag.GridBagXYValueStringInstantiator; import net.community.chest.dom.DOMUtils; import net.community.chest.test.TestBase; import org.w3c.dom.Element; /** * <P>Copyright 2007 as per GPLv2</P> * * @author Lyor G. * @since Aug 7, 2007 2:09:18 PM */ public class ResourcesTester extends TestBase { private static final int testElementDataParsing (final PrintStream out, final BufferedReader in, final String elemData, final Element elem) { for ( ; ; ) { out.println(elemData); try { final ExtendedGridBagConstraints gbc=new ExtendedGridBagConstraints(elem); out.println("\tgridx=" + (gbc.isAbsoluteGridX() ? String.valueOf(gbc.gridx) : GridBagXYValueStringInstantiator.RELATIVE_VALUE)); out.println("\tgridy=" + (gbc.isAbsoluteGridY() ? String.valueOf(gbc.gridy) : GridBagXYValueStringInstantiator.RELATIVE_VALUE)); final GridBagGridSizingType wt=gbc.getGridWithType(), ht=gbc.getGridHeightType(); out.println("\tgridwidth=" + ((null == wt) ? String.valueOf(gbc.gridwidth) : wt.name())); out.println("\tgridheight=" + ((null == ht) ? String.valueOf(gbc.gridheight) : ht.name())); out.println("\tfill=" + gbc.getFillType()); out.println("\tipadx=" + gbc.ipadx); out.println("\tipady=" + gbc.ipady); out.println("\tinsets=" + InsetsValueInstantiator.toString(gbc.insets)); out.println("\tanchor=" + gbc.getAnchorType()); out.println("\tweightx=" + gbc.weightx); out.println("\tweighty=" + gbc.weighty); } catch(Exception e) { System.err.println("testElementDataParsing(" + elemData + ") " + e.getClass().getName() + ": " + e.getMessage()); } final String ans=getval(out, in, "again (y)/[n]"); if ((null == ans) || (ans.length() <= 0) || (Character.toLowerCase(ans.charAt(0)) != 'y')) break; } return 0; } // each argument is an XML element string to be parsed private static final int testGridBagConstraintsParsing (final PrintStream out, final BufferedReader in, final String ... args) { final int numArgs=(null == args) ? 0 : args.length; for (int aIndex=0; ; aIndex++) { final String elemData=(aIndex < numArgs) ? args[aIndex] : getval(out, in, "XML element data (or Quit)"); if ((null == elemData) || (elemData.length() <= 0)) continue; if (isQuit(elemData)) break; try { final Triplet<? extends Element,?,?> pe= DOMUtils.parseElementString(elemData); testElementDataParsing(out, in, elemData, (null == pe) ? null : pe.getV1()); } catch(Exception e) { System.err.println("testGridBagConstraintsParsing(" + elemData + ") " + e.getClass().getName() + ": " + e.getMessage()); } } return 0; } ////////////////////////////////////////////////////////////////////////// public static void main (String[] args) { final BufferedReader in=getStdin(); final int nErr=testGridBagConstraintsParsing(System.out, in, args); if (nErr != 0) System.err.println("test failed (err=" + nErr + ")"); else System.out.println("OK"); } }
apache-2.0
antoniocarlon/jummyshapefile
src/main/java/com/jummyshapefile/dbf/model/DBFFieldDescriptor.java
2717
/* * Copyright 2015 ANTONIO CARLON * * 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.jummyshapefile.dbf.model; /** * Represents the properties of a DBF Field. * <p> * http://www.dbase.com/Knowledgebase/INT/db7_file_fmt.htm */ public class DBFFieldDescriptor { private String name; private String type; private int length = -1; private int decimalCount = -1; /** * Returns the name of the DBF field. * * @return the name of the DBF field */ public String getName() { return name; } /** * Sets the name of the DBF field. * * @param the * name of the DBF field */ public void setName(final String name) { this.name = name; } /** * Returns the type of the field, as defined in the documentation. * <p> * Field type in ASCII (B, C, D, N, L, M, @, I, +, F, 0 or G). * * @return the type of the field, as defined in the documentation */ public String getType() { return type; } /** * Sets the type of the field, as defined in the documentation. * <p> * Field type in ASCII (B, C, D, N, L, M, @, I, +, F, 0 or G). * * @param type * the type of the field, as defined in the documentation */ public void setType(final String type) { this.type = type; } /** * Returns the length of the field in bytes. * * @return the length of the field in bytes */ public int getLength() { return length; } /** * Sets the length of the field in bytes. * * @param length * the length of the field in bytes */ public void setLength(final int length) { this.length = length; } /** * Returns the field decimal count. * * @return the field decimal count */ public int getDecimalCount() { return decimalCount; } /** * Sets the field decimal count. * * @param decimalCount * the decimal count */ public void setDecimalCount(final int decimalCount) { this.decimalCount = decimalCount; } @Override public String toString() { return "--- FIELD DESCRIPTOR: " + name + " / " + type + " / " + length + " / " + decimalCount; } }
apache-2.0
HubSpot/hbase
hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestAsyncTableScanException.java
6339
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.client; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import org.apache.hadoop.hbase.DoNotRetryIOException; import org.apache.hadoop.hbase.HBaseClassTestRule; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.coprocessor.ObserverContext; import org.apache.hadoop.hbase.coprocessor.RegionCoprocessor; import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment; import org.apache.hadoop.hbase.coprocessor.RegionObserver; import org.apache.hadoop.hbase.exceptions.ScannerResetException; import org.apache.hadoop.hbase.regionserver.InternalScanner; import org.apache.hadoop.hbase.testclassification.ClientTests; import org.apache.hadoop.hbase.testclassification.MediumTests; import org.apache.hadoop.hbase.util.Bytes; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.apache.hbase.thirdparty.com.google.common.io.Closeables; @Category({ MediumTests.class, ClientTests.class }) public class TestAsyncTableScanException { @ClassRule public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestAsyncTableScanException.class); private static final HBaseTestingUtility UTIL = new HBaseTestingUtility(); private static TableName TABLE_NAME = TableName.valueOf("scan"); private static byte[] FAMILY = Bytes.toBytes("family"); private static byte[] QUAL = Bytes.toBytes("qual"); private static AsyncConnection CONN; private static AtomicInteger REQ_COUNT = new AtomicInteger(); private static volatile int ERROR_AT; private static volatile boolean ERROR; private static volatile boolean DO_NOT_RETRY; private static final int ROW_COUNT = 100; public static final class ErrorCP implements RegionObserver, RegionCoprocessor { @Override public Optional<RegionObserver> getRegionObserver() { return Optional.of(this); } @Override public boolean postScannerNext(ObserverContext<RegionCoprocessorEnvironment> c, InternalScanner s, List<Result> result, int limit, boolean hasNext) throws IOException { REQ_COUNT.incrementAndGet(); if ((ERROR_AT == REQ_COUNT.get()) || ERROR) { if (DO_NOT_RETRY) { throw new DoNotRetryIOException("Injected exception"); } else { throw new IOException("Injected exception"); } } return RegionObserver.super.postScannerNext(c, s, result, limit, hasNext); } } @BeforeClass public static void setUp() throws Exception { UTIL.startMiniCluster(1); UTIL.getAdmin() .createTable(TableDescriptorBuilder.newBuilder(TABLE_NAME) .setColumnFamily(ColumnFamilyDescriptorBuilder.of(FAMILY)) .setCoprocessor(ErrorCP.class.getName()).build()); try (Table table = UTIL.getConnection().getTable(TABLE_NAME)) { for (int i = 0; i < ROW_COUNT; i++) { table.put(new Put(Bytes.toBytes(i)).addColumn(FAMILY, QUAL, Bytes.toBytes(i))); } } CONN = ConnectionFactory.createAsyncConnection(UTIL.getConfiguration()).get(); } @AfterClass public static void tearDown() throws Exception { Closeables.close(CONN, true); UTIL.shutdownMiniCluster(); } @Before public void setUpBeforeTest() { REQ_COUNT.set(0); ERROR_AT = 0; ERROR = false; DO_NOT_RETRY = false; } @Test(expected = DoNotRetryIOException.class) public void testDoNotRetryIOException() throws IOException { ERROR_AT = 1; DO_NOT_RETRY = true; try (ResultScanner scanner = CONN.getTable(TABLE_NAME).getScanner(FAMILY)) { scanner.next(); } } @Test public void testIOException() throws IOException { ERROR = true; try (ResultScanner scanner = CONN.getTableBuilder(TABLE_NAME).setMaxAttempts(3).build().getScanner(FAMILY)) { scanner.next(); fail(); } catch (RetriesExhaustedException e) { // expected assertThat(e.getCause(), instanceOf(ScannerResetException.class)); } assertTrue(REQ_COUNT.get() >= 3); } private void count() throws IOException { try (ResultScanner scanner = CONN.getTable(TABLE_NAME).getScanner(new Scan().setCaching(1))) { for (int i = 0; i < ROW_COUNT; i++) { Result result = scanner.next(); assertArrayEquals(Bytes.toBytes(i), result.getRow()); assertArrayEquals(Bytes.toBytes(i), result.getValue(FAMILY, QUAL)); } } } @Test public void testRecoveryFromScannerResetWhileOpening() throws IOException { ERROR_AT = 1; count(); // we should at least request 1 time otherwise the error will not be triggered, and then we // need at least one more request to get the remaining results. assertTrue(REQ_COUNT.get() >= 2); } @Test public void testRecoveryFromScannerResetInTheMiddle() throws IOException { ERROR_AT = 2; count(); // we should at least request 2 times otherwise the error will not be triggered, and then we // need at least one more request to get the remaining results. assertTrue(REQ_COUNT.get() >= 3); } }
apache-2.0
dagnir/aws-sdk-java
aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/transform/WriteSegmentRequestMarshaller.java
2302
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.pinpoint.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.pinpoint.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * WriteSegmentRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class WriteSegmentRequestMarshaller { private static final MarshallingInfo<StructuredPojo> DIMENSIONS_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Dimensions").build(); private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Name").build(); private static final WriteSegmentRequestMarshaller instance = new WriteSegmentRequestMarshaller(); public static WriteSegmentRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(WriteSegmentRequest writeSegmentRequest, ProtocolMarshaller protocolMarshaller) { if (writeSegmentRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(writeSegmentRequest.getDimensions(), DIMENSIONS_BINDING); protocolMarshaller.marshall(writeSegmentRequest.getName(), NAME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
tanliu/fruit
fruit-core/src/main/java/com/fruit/service/management/QualityService.java
2193
package com.fruit.service.management; import com.fruit.base.BaseService; import com.fruit.entity.management.Quality; import java.util.Map; /** * 产品质量检测 Service * @author CSH * */ public interface QualityService extends BaseService<Quality> { /**返回当前质检人员的质检记录 * @param page * @param pageSize * @param ownid 当id小于0时,表示不采用该条件 * @param params * @return */ public String showRecords(Integer page,Integer pageSize,int ownid,Map<String, String> params); /**返回整个公司的质检记录 * @param page * @param pageSize * @param ownid 当id小于0时,表示不采用该条件 * @param params * @return */ public String showRecordsByAdmin(Integer page,Integer pageSize,int companyId,Map<String, String> params); /**更新质检记录 * @return */ public Integer updateRecords(Integer inspectorId,String name,String way,String checkResult,String picture,String date,String endNumber, String barcodes); /**更新质检记录 * @return */ public Integer updateRecordToAll(Integer inspectorId,String name,String way,String checkResult,String picture,String date,String endNumber, String likeBarcode); /**获取详细信息 * @param id * @return */ public String getDetail(int id); /**获取详细信息 * @param id * @return */ public String getQualityDetail(Integer id); /** * 删除产品质量检测记录 * @param id */ // public void deleteQuality(int id) { // Quality quality = qualityDao.getById(id); // List<ImageBean> pictures = ImageBean.getImageList(quality.getPictures()); // for (ImageBean picture : pictures){ // FileManager.deleteImageFile(picture.getName()); // } // qualityDao.delete(id); // } /** * 获取质检记录柱状图数据 * @param page * @param pageSize * @param id * @param params * @return */ public String getChartData(Integer page,Integer pageSize,Integer id,Map<String, String> params); /** * 获取饼图数据 * @param page * @param pageSize * @param id * @param params * @return */ public String getPieChartData(Integer page,Integer pageSize,Integer id,Map<String, String> params); }
apache-2.0
d0k1/jitloganalyzer
analyzer/src/main/java/com/focusit/jitloganalyzer/tty/model/WriterEvent.java
637
package com.focusit.jitloganalyzer.tty.model; /** * Created by doki on 08.11.16. * <writer thread='139821162608384'/> */ public class WriterEvent extends AbstractTTYEvent implements TTYEvent, HasThreadId { private final static String START_TOKEN = "<writer"; private long threadId; @Override public boolean suitable(String line) { return line.startsWith(START_TOKEN); } @Override public void processLine(String line) { } public long getThreadId() { return threadId; } public void setThreadId(long threadId) { this.threadId = threadId; } }
apache-2.0
herve-quiroz/autonomous-ships
src/org/tc/autonomous/RetreatCommand3HullMod.java
163
package org.tc.autonomous; public class RetreatCommand3HullMod extends AbstractRetreatCommandHullMod { public RetreatCommand3HullMod() { super(3); } }
apache-2.0
hazendaz/assertj-core
src/test/java/org/assertj/core/api/biginteger/BigIntegerAssert_isCloseToPercentage_Test.java
1420
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2021 the original author or authors. */ package org.assertj.core.api.biginteger; import org.assertj.core.api.BigIntegerAssert; import org.assertj.core.api.BigIntegerAssertBaseTest; import org.assertj.core.data.Percentage; import java.math.BigInteger; import static org.assertj.core.data.Percentage.withPercentage; import static org.mockito.Mockito.verify; class BigIntegerAssert_isCloseToPercentage_Test extends BigIntegerAssertBaseTest { private final Percentage percentage = withPercentage(5); private final BigInteger value = BigInteger.TEN; @Override protected BigIntegerAssert invoke_api_method() { return assertions.isCloseTo(value, percentage); } @Override protected void verify_internal_effects() { verify(bigIntegers).assertIsCloseToPercentage(getInfo(assertions), getActual(assertions), value, percentage); } }
apache-2.0
intuit/QuickBooks-V3-Java-SDK
payments-api/src/test/java/com/intuit/payment/services/ChargeServiceTest.java
19665
/******************************************************************************* * Copyright (c) 2019 Intuit * * 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.intuit.payment.services; import com.intuit.payment.config.RequestContext; import com.intuit.payment.data.Capture; import com.intuit.payment.data.Card; import com.intuit.payment.data.Charge; import com.intuit.payment.data.DeviceInfo; import com.intuit.payment.data.PaymentContext; import com.intuit.payment.data.Refund; import com.intuit.payment.exception.BaseException; import com.intuit.payment.http.Request; import com.intuit.payment.http.Response; import com.intuit.payment.services.base.ServiceBase; import com.intuit.payment.util.JsonUtil; import mockit.Expectations; import mockit.Mocked; import org.testng.Assert; import org.testng.annotations.Test; import java.math.BigDecimal; import java.util.Date; public class ChargeServiceTest { @Mocked private ServiceBase serviceBase; @Test public void testChargeServiceCreation() { ChargeService chargeService = new ChargeService(); Assert.assertNull(chargeService.getRequestContext()); } @Test public void testChargeServiceRequestContext() { RequestContext requestContext = new RequestContext(); requestContext.setBaseUrl("SomeBaseUrl"); ChargeService chargeService = new ChargeService(requestContext); Assert.assertEquals(requestContext, chargeService.getRequestContext()); RequestContext secondRequestContext = new RequestContext(); secondRequestContext.setBaseUrl("AnotherBaseUrl"); chargeService.setRequestContext(secondRequestContext); Assert.assertEquals(secondRequestContext, chargeService.getRequestContext()); } @Test public void testCreateCharge() throws BaseException { // Build response object Charge expectedCharge = new Charge.Builder() .amount(new BigDecimal(1234)) .currency("SomeCurrency") .card(new Card.Builder().name("SomeCardName").build()) .build(); // Serialize response object as JSON string final String serializedResponseString = JsonUtil.serialize(expectedCharge); final Response mockedResponse = new Response(200, serializedResponseString, "some_intuit_tid"); mockedResponse.setResponseObject(expectedCharge); new Expectations() {{ serviceBase.sendRequest((Request) any); result = mockedResponse; }}; RequestContext requestContext = new RequestContext(); requestContext.setBaseUrl("SomeBaseUrl"); // Set mock RequestContext against ChargeService ChargeService chargeService = new ChargeService(requestContext); Charge chargeRequest = new Charge(); Charge actualCharge = chargeService.create(chargeRequest); Assert.assertEquals(expectedCharge.getAmount(), actualCharge.getAmount()); Assert.assertEquals(expectedCharge.getCurrency(), actualCharge.getCurrency()); Assert.assertEquals(expectedCharge.getCard().getName(), actualCharge.getCard().getName()); } @Test(expectedExceptions = BaseException.class) public void testCreateChargeServiceFailure() throws BaseException { // Build response object Charge expectedCharge = new Charge.Builder() .amount(new BigDecimal(1234)) .currency("SomeCurrency") .card(new Card.Builder().name("SomeCardName").build()) .build(); // Serialize response object as JSON string final String serializedResponseString = JsonUtil.serialize(expectedCharge); final Response mockedResponse = new Response(200, serializedResponseString, "some_intuit_tid"); mockedResponse.setResponseObject(expectedCharge); new Expectations() {{ serviceBase.sendRequest((Request) any); result = new BaseException("Unexpected Error , service response object was null "); }}; RequestContext requestContext = new RequestContext(); requestContext.setBaseUrl("SomeBaseUrl"); // Set mock RequestContext against ChargeService ChargeService chargeService = new ChargeService(requestContext); Charge chargeRequest = new Charge(); Charge actualCharge = chargeService.create(chargeRequest); // Should throw exception } @Test public void testRetrieveCharge() throws BaseException { // Build response object Charge expectedCharge = new Charge.Builder() .amount(new BigDecimal(1234)) .currency("SomeCurrency") .card(new Card.Builder().name("SomeCardName").build()) .build(); // Serialize response object as JSON string final String serializedResponseString = JsonUtil.serialize(expectedCharge); final Response mockedResponse = new Response(200, serializedResponseString, "some_intuit_tid"); mockedResponse.setResponseObject(expectedCharge); new Expectations() {{ serviceBase.sendRequest((Request) any); result = mockedResponse; }}; RequestContext requestContext = new RequestContext(); requestContext.setBaseUrl("SomeBaseUrl"); // Set mock RequestContext against ChargeService ChargeService chargeService = new ChargeService(requestContext); Charge actualCharge = chargeService.retrieve("SomeChargeId"); Assert.assertEquals(expectedCharge.getAmount(), actualCharge.getAmount()); Assert.assertEquals(expectedCharge.getCurrency(), actualCharge.getCurrency()); Assert.assertEquals(expectedCharge.getCard().getName(), actualCharge.getCard().getName()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testRetrieveChargeInvalidChargeId() throws BaseException { RequestContext requestContext = new RequestContext(); requestContext.setBaseUrl("SomeBaseUrl"); // Set mock RequestContext against ChargeService ChargeService chargeService = new ChargeService(requestContext); // Pass in null ChargeId Charge actualCharge = chargeService.retrieve(null); } @Test public void testCaptureCharge() throws BaseException { // Build response object Charge expectedCharge = new Charge.Builder() .amount(new BigDecimal(1234)) .context(new PaymentContext.Builder().mobile("false").isEcommerce("true").build()) .build(); // Serialize response object as JSON string final String serializedResponseString = JsonUtil.serialize(expectedCharge); final Response mockedResponse = new Response(200, serializedResponseString, "some_intuit_tid"); mockedResponse.setResponseObject(expectedCharge); new Expectations() {{ serviceBase.sendRequest((Request) any); result = mockedResponse; }}; RequestContext requestContext = new RequestContext(); requestContext.setBaseUrl("SomeBaseUrl"); // Set mock RequestContext against ChargeService ChargeService chargeService = new ChargeService(requestContext); Charge chargeRequest = new Charge(); Capture captureChargeRequest = new Capture.Builder() .amount(expectedCharge.getAmount()) .context(expectedCharge.getContext()) .build(); Charge actualCharge = chargeService.capture("SomeChargeId", captureChargeRequest); Assert.assertEquals(expectedCharge.getAmount(), actualCharge.getAmount()); Assert.assertEquals(expectedCharge.getContext().getMobile(), actualCharge.getContext().getMobile()); Assert.assertEquals(expectedCharge.getContext().getIsEcommerce(), actualCharge.getContext().getIsEcommerce()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testCaptureChargeInvalidChargeId() throws BaseException { Charge expectedCharge = new Charge.Builder() .amount(new BigDecimal(1234)) .context(new PaymentContext.Builder().mobile("false").isEcommerce("true").build()) .build(); RequestContext requestContext = new RequestContext(); requestContext.setBaseUrl("SomeBaseUrl"); // Set mock RequestContext against ChargeService ChargeService chargeService = new ChargeService(requestContext); Capture captureChargeRequest = new Capture.Builder() .amount(expectedCharge.getAmount()) .context(expectedCharge.getContext()) .build(); // Pass in null ChargeId Charge actualCharge = chargeService.capture(null, captureChargeRequest); } @Test public void testRefundCharge() throws BaseException { // Build response object Refund expectedRefund = new Refund.Builder() .amount(new BigDecimal(1234)) .description("SomeDescription") .context( new PaymentContext.Builder() .tax(new BigDecimal(5678)) .recurring(true) .deviceInfo( new DeviceInfo.Builder() .macAddress("SomeMacAddress") .ipAddress("SomeIpAddress") .longitude("SomeLongitude") .latitude("SomeLatitude") .phoneNumber("1800-FAKE-FAKE") .type("mobile") .build()) .build()) .id("ThisIsAGeneratedRefundId") .created(new Date(System.currentTimeMillis())) .build(); // Serialize response object as JSON string final String serializedResponseString = JsonUtil.serialize(expectedRefund); final Response mockedResponse = new Response(200, serializedResponseString, "some_intuit_tid"); mockedResponse.setResponseObject(expectedRefund); new Expectations() {{ serviceBase.sendRequest((Request) any); result = mockedResponse; }}; RequestContext requestContext = new RequestContext(); requestContext.setBaseUrl("SomeBaseUrl"); // Set mock RequestContext against ChargeService ChargeService chargeService = new ChargeService(requestContext); Refund refundRequest = new Refund.Builder() .amount(expectedRefund.getAmount()) .description(expectedRefund.getDescription()) .context(expectedRefund.getContext()) .build(); Refund actualRefund = chargeService.refund("SomeChargeId", refundRequest); Assert.assertEquals(expectedRefund.getId(), actualRefund.getId()); Assert.assertEquals(expectedRefund.getAmount(), actualRefund.getAmount()); Assert.assertEquals(expectedRefund.getDescription(), actualRefund.getDescription()); Assert.assertEquals(expectedRefund.getContext().getTax(), actualRefund.getContext().getTax()); Assert.assertEquals(expectedRefund.getContext().getRecurring(), actualRefund.getContext().getRecurring()); Assert.assertEquals(expectedRefund.getCreated(), actualRefund.getCreated()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testRefundChargeInvalidChargeId() throws BaseException { Charge expectedCharge = new Charge.Builder() .amount(new BigDecimal(1234)) .context(new PaymentContext.Builder().mobile("false").isEcommerce("true").build()) .build(); RequestContext requestContext = new RequestContext(); requestContext.setBaseUrl("SomeBaseUrl"); // Set mock RequestContext against ChargeService ChargeService chargeService = new ChargeService(requestContext); Capture captureChargeRequest = new Capture.Builder() .amount(expectedCharge.getAmount()) .context(expectedCharge.getContext()) .build(); // Pass in null ChargeId Refund actualRefund = chargeService.refund(null, null); } @Test public void testGetRefund() throws BaseException { // Build response object Refund expectedRefund = new Refund.Builder() .amount(new BigDecimal(1234)) .description("SomeDescription") .context( new PaymentContext.Builder() .tax(new BigDecimal(5678)) .recurring(true) .deviceInfo( new DeviceInfo.Builder() .macAddress("SomeMacAddress") .ipAddress("SomeIpAddress") .longitude("SomeLongitude") .latitude("SomeLatitude") .phoneNumber("1800-FAKE-FAKE") .type("mobile") .build()) .build()) .id("ThisIsAGeneratedRefundId") .created(new Date(System.currentTimeMillis())) .build(); // Serialize response object as JSON string final String serializedResponseString = JsonUtil.serialize(expectedRefund); final Response mockedResponse = new Response(200, serializedResponseString, "some_intuit_tid"); mockedResponse.setResponseObject(expectedRefund); new Expectations() {{ serviceBase.sendRequest((Request) any); result = mockedResponse; }}; RequestContext requestContext = new RequestContext(); requestContext.setBaseUrl("SomeBaseUrl"); // Set mock RequestContext against ChargeService ChargeService chargeService = new ChargeService(requestContext); Refund actualRefund = chargeService.getRefund("SomeChargeId", "SomeRefundId"); Assert.assertEquals(expectedRefund.getId(), actualRefund.getId()); Assert.assertEquals(expectedRefund.getAmount(), actualRefund.getAmount()); Assert.assertEquals(expectedRefund.getDescription(), actualRefund.getDescription()); Assert.assertEquals(expectedRefund.getContext().getTax(), actualRefund.getContext().getTax()); Assert.assertEquals(expectedRefund.getContext().getRecurring(), actualRefund.getContext().getRecurring()); Assert.assertEquals(expectedRefund.getCreated(), actualRefund.getCreated()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testGetRefundInvalidChargeId() throws BaseException { RequestContext requestContext = new RequestContext(); requestContext.setBaseUrl("SomeBaseUrl"); // Set mock RequestContext against ChargeService ChargeService chargeService = new ChargeService(requestContext); // Pass in null ChargeId Refund actualRefund = chargeService.getRefund(null, "SomeRefundId"); } @Test(expectedExceptions = IllegalArgumentException.class) public void testGetRefundInvalidRefundId() throws BaseException { RequestContext requestContext = new RequestContext(); requestContext.setBaseUrl("SomeBaseUrl"); // Set mock RequestContext against ChargeService ChargeService chargeService = new ChargeService(requestContext); // Pass in null RefundId Refund actualRefund = chargeService.getRefund("SomeChargeId", null); } @Test public void testVoidTransaction() throws BaseException { // Build response object Refund expectedRefund = new Refund.Builder() .amount(new BigDecimal(1234)) .description("SomeDescription") .context( new PaymentContext.Builder() .tax(new BigDecimal(5678)) .recurring(true) .deviceInfo( new DeviceInfo.Builder() .macAddress("SomeMacAddress") .ipAddress("SomeIpAddress") .longitude("SomeLongitude") .latitude("SomeLatitude") .phoneNumber("1800-FAKE-FAKE") .type("mobile") .build()) .build()) .id("ThisIsAGeneratedRefundId") .created(new Date(System.currentTimeMillis())) .build(); // Serialize response object as JSON string final String serializedResponseString = JsonUtil.serialize(expectedRefund); final Response mockedResponse = new Response(200, serializedResponseString, "some_intuit_tid"); mockedResponse.setResponseObject(expectedRefund); new Expectations() {{ serviceBase.sendRequest((Request) any); result = mockedResponse; }}; RequestContext requestContext = new RequestContext(); requestContext.setBaseUrl("SomeBaseUrl"); // Set mock RequestContext against ChargeService ChargeService chargeService = new ChargeService(requestContext); Refund actualRefund = chargeService.voidTransaction("SomeChargeRequestId"); Assert.assertEquals(expectedRefund.getId(), actualRefund.getId()); Assert.assertEquals(expectedRefund.getAmount(), actualRefund.getAmount()); Assert.assertEquals(expectedRefund.getDescription(), actualRefund.getDescription()); Assert.assertEquals(expectedRefund.getContext().getTax(), actualRefund.getContext().getTax()); Assert.assertEquals(expectedRefund.getContext().getRecurring(), actualRefund.getContext().getRecurring()); Assert.assertEquals(expectedRefund.getCreated(), actualRefund.getCreated()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testVoidTransactionInvalidChargeId() throws BaseException { RequestContext requestContext = new RequestContext(); requestContext.setBaseUrl("SomeBaseUrl"); // Set mock RequestContext against ChargeService ChargeService chargeService = new ChargeService(requestContext); // Pass in null RefundId Refund actualRefund = chargeService.voidTransaction(null); } }
apache-2.0
pfrank13/spring-cloud-contract
samples/standalone/pact/pact-http-server/src/main/java/com/example/fraud/FraudDetectionController.java
1348
package com.example.fraud; import static org.springframework.web.bind.annotation.RequestMethod.PUT; import java.math.BigDecimal; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.fraud.model.FraudCheck; import com.example.fraud.model.FraudCheckResult; import com.example.fraud.model.FraudCheckStatus; @RestController public class FraudDetectionController { private static final String FRAUD_SERVICE_JSON_VERSION_1 = "application/vnd.fraud.v1+json"; private static final String NO_REASON = null; private static final String AMOUNT_TOO_HIGH = "Amount too high"; private static final BigDecimal MAX_AMOUNT = new BigDecimal("5000"); @RequestMapping( value = "/fraudcheck", method = PUT, consumes = FRAUD_SERVICE_JSON_VERSION_1, produces = FRAUD_SERVICE_JSON_VERSION_1) public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) { if (amountGreaterThanThreshold(fraudCheck)) { return new FraudCheckResult(FraudCheckStatus.FRAUD, AMOUNT_TOO_HIGH); } return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON); } private boolean amountGreaterThanThreshold(FraudCheck fraudCheck) { return MAX_AMOUNT.compareTo(fraudCheck.getLoanAmount()) < 0; } }
apache-2.0
pony-boy/AdamBradleyThesis
Metatation files/src/annotationInteraction/QueryGenerator.java
29678
package annotationInteraction; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; public class QueryGenerator { private long worksheet_id; private Poem poem_content; public QueryGenerator(long worksheet_id, Poem worksheet_content){ this.worksheet_id = worksheet_id; poem_content = worksheet_content; } public List<QueryDetails> generateQueriesAtTheEndOfPenStroke(ClusterGenerator pen_stroke_cluster_generator, List<PenStroke> all_pen_strokes_in_worksheet, PenStroke pen_stroke_generating_clusters){ List<Map<PenStroke, List<String>>> annotator_pen_strokes_in_clusters = new ArrayList<Map<PenStroke, List<String>>>(); List<Map<PenStroke, List<List<PenStroke>>>> connector_pen_strokes_in_clusters = new ArrayList<Map<PenStroke, List<List<PenStroke>>>>(); List<Cluster> clusters = pen_stroke_cluster_generator.getClusterIterationAtStopIterationIndex().getClusters(); System.out.println("clusters on last pen stroke: " + clusters.size()); for(int i = 0; i < clusters.size(); i++){ Cluster cluster = clusters.get(i); List<PenStroke> pen_strokes_in_cluster = cluster.getPenStrokes(); Map<PenStroke, List<String>> annotator_pen_strokes_in_cluster = new HashMap<PenStroke, List<String>>(); Map<PenStroke, List<List<PenStroke>>> connector_pen_strokes_in_cluster = new HashMap<PenStroke, List<List<PenStroke>>>(); System.out.println("pen strokes in cluster " + i + ": " + pen_strokes_in_cluster.size()); for(int j = 0; j < pen_strokes_in_cluster.size(); j++){ List<String> words_annotated_by_penstroke = new ArrayList<String>(); PenStroke pen_stroke = pen_strokes_in_cluster.get(j); //TODO check for space where cluster is made if not on text space then ignore ShapeRecognizer.penStrokeTypes pen_stroke_type = pen_stroke.getPenStrokeType(); if(pen_stroke_type == ShapeRecognizer.penStrokeTypes.Ellipse){ //System.out.println("cluster: " + i + " pen stroke " + j + " is ellipse"); words_annotated_by_penstroke = words_marked_by_ellipse(pen_stroke); if(!words_annotated_by_penstroke.isEmpty()){ annotator_pen_strokes_in_cluster.put(pen_stroke, words_annotated_by_penstroke); } } else if(pen_stroke_type == ShapeRecognizer.penStrokeTypes.Underline){ //System.out.println("cluster: " + i + " pen stroke " + j + " is underline"); words_annotated_by_penstroke = words_marked_by_underline(pen_stroke); if(!words_annotated_by_penstroke.isEmpty()){ annotator_pen_strokes_in_cluster.put(pen_stroke, words_annotated_by_penstroke); } } else if(pen_stroke_type == ShapeRecognizer.penStrokeTypes.Connector){ //System.out.println("cluster: " + i + " pen stroke " + j + " is connector"); List<List<PenStroke>> pen_strokes_connected = words_marked_by_connector(clusters, pen_stroke, all_pen_strokes_in_worksheet); if(!pen_strokes_connected.isEmpty()){ System.out.println("found connector in cluster to add"); connector_pen_strokes_in_cluster.put(pen_stroke, pen_strokes_connected); } } else{ continue; } } if(!annotator_pen_strokes_in_cluster.isEmpty()){ annotator_pen_strokes_in_clusters.add(annotator_pen_strokes_in_cluster); } //System.out.println(connector_pen_strokes_in_cluster.isEmpty()); if(!connector_pen_strokes_in_cluster.isEmpty()){ //System.out.println("found connector in cluster to add"); connector_pen_strokes_in_clusters.add(connector_pen_strokes_in_cluster); } } List<QueryDetails> all_queries = new ArrayList<QueryDetails>(); List<Long> annotator_pen_strokes_to_be_ignored_ids = new ArrayList<Long>(); // resolve all connectors first List<Map<PenStroke, List<QueryDetails>>> connector_queries_in_clusters = new ArrayList<Map<PenStroke, List<QueryDetails>>>(); for(int i = 0; i < connector_pen_strokes_in_clusters.size(); i++){ //System.out.println("cluster " + i); Map<PenStroke, List<QueryDetails>> connector_queries_in_cluster = new HashMap<PenStroke, List<QueryDetails>>(); Map<PenStroke, List<List<PenStroke>>> connector_pen_strokes_in_cluster = connector_pen_strokes_in_clusters.get(i); Iterator<Entry<PenStroke, List<List<PenStroke>>>> connector_pen_strokes_iterator = connector_pen_strokes_in_cluster.entrySet().iterator(); while(connector_pen_strokes_iterator.hasNext()){ Map.Entry<PenStroke, List<List<PenStroke>>> connector_pen_stroke_entry = (Map.Entry<PenStroke, List<List<PenStroke>>>) connector_pen_strokes_iterator.next(); PenStroke connector_pen_stroke = connector_pen_stroke_entry.getKey(); //System.out.println("storke " + connector_pen_stroke.getStrokeId()); List<List<PenStroke>> connected_pen_strokes = connector_pen_stroke_entry.getValue(); List<QueryDetails> connector_pen_stroke_queries = generate_connector_queries(worksheet_id, pen_stroke_generating_clusters.getStrokeId(),connector_pen_stroke, connected_pen_strokes, annotator_pen_strokes_in_clusters); //System.out.println(connector_pen_stroke_queries.isEmpty()); if(!connector_pen_stroke_queries.isEmpty()){ connector_queries_in_cluster.put(connector_pen_stroke, connector_pen_stroke_queries); for(int m = 0; m < connector_pen_stroke_queries.size(); m++){ QueryDetails connector_pen_stroke_query = connector_pen_stroke_queries.get(m); annotator_pen_strokes_to_be_ignored_ids.addAll(connector_pen_stroke_query.get_annotator_pen_strokes()); all_queries.add(connector_pen_stroke_query); } } } if(!connector_queries_in_cluster.isEmpty()){ connector_queries_in_clusters.add(connector_queries_in_cluster); } } // then resolve ellipses and underlines List<List<QueryDetails>> annotator_queries_in_clusters = new ArrayList<List<QueryDetails>>(); //System.out.println("before ellipse resolve"); for(int i = 0 ; i < annotator_pen_strokes_in_clusters.size(); i++){ List<QueryDetails> annotator_queries_in_cluster = new ArrayList<QueryDetails>(); Map<PenStroke, List<String>> ellipse_pen_strokes_in_cluster = new HashMap<PenStroke, List<String>>(); Map<PenStroke, List<String>> underline_pen_strokes_in_cluster = new HashMap<PenStroke, List<String>>(); Map<PenStroke, List<String>> annotator_pen_strokes_in_cluster = annotator_pen_strokes_in_clusters.get(i); Iterator<Entry<PenStroke, List<String>>> annotator_pen_strokes_in_cluster_iterator = annotator_pen_strokes_in_cluster.entrySet().iterator(); while(annotator_pen_strokes_in_cluster_iterator.hasNext()){ Map.Entry<PenStroke, List<String>> annotator_stroke_entry = (Map.Entry<PenStroke, List<String>>) annotator_pen_strokes_in_cluster_iterator.next(); PenStroke annotator_pen_stroke = annotator_stroke_entry.getKey(); long annotator_pen_stroke_id = annotator_pen_stroke.getStrokeId(); boolean ignore_annotator_pen_stroke = false; for(int j = 0; j < annotator_pen_strokes_to_be_ignored_ids.size(); j++){ if(annotator_pen_strokes_to_be_ignored_ids.get(j).longValue() == annotator_pen_stroke_id){ ignore_annotator_pen_stroke = true; break; } } if(!ignore_annotator_pen_stroke){ if(annotator_pen_stroke.getPenStrokeType() == ShapeRecognizer.penStrokeTypes.Ellipse){ ellipse_pen_strokes_in_cluster.put(annotator_pen_stroke, annotator_stroke_entry.getValue()); } else{ underline_pen_strokes_in_cluster.put(annotator_pen_stroke, annotator_stroke_entry.getValue()); } } } if(!ellipse_pen_strokes_in_cluster.isEmpty()){ QueryDetails annotator_query = new QueryDetails(worksheet_id, pen_stroke_generating_clusters.getStrokeId(), ellipse_pen_strokes_in_cluster); annotator_queries_in_cluster.add(annotator_query); all_queries.add(annotator_query); } if(!underline_pen_strokes_in_cluster.isEmpty()){ QueryDetails annotator_query = new QueryDetails(worksheet_id, pen_stroke_generating_clusters.getStrokeId(), underline_pen_strokes_in_cluster); annotator_queries_in_cluster.add(annotator_query); all_queries.add(annotator_query); } if(!annotator_queries_in_cluster.isEmpty()){ annotator_queries_in_clusters.add(annotator_queries_in_cluster); } } return all_queries; } private List<QueryDetails> generate_connector_queries(long worksheet_id, long pen_stroke_generating_clusters_id, PenStroke connector_pen_stroke, List<List<PenStroke>> all_connected_pen_strokes, List<Map<PenStroke, List<String>>> annotator_pen_strokes_in_clusters){ //System.out.println("called generate connector"); List<QueryDetails> connector_queries = new ArrayList<QueryDetails>(); // all sets of pen strokes connected by this connector pen stroke for(int i = 0; i < all_connected_pen_strokes.size(); i++){ // one set of pen strokes connected by this connector pen stroke List<PenStroke> connected_pen_strokes = all_connected_pen_strokes.get(i); long connected_1_stroke_id = connected_pen_strokes.get(0).getStrokeId(), connected_2_stroke_id = connected_pen_strokes.get(1).getStrokeId(); //System.out.println("looking for " + connected_1_stroke_id + ", " + connected_2_stroke_id + " in annotators"); Map<PenStroke, List<String>> connected_pen_strokes_all_info = new HashMap<PenStroke, List<String>>(); for(int j = 0; j < annotator_pen_strokes_in_clusters.size(); j++){ Map<PenStroke, List<String>> annotator_pen_strokes_in_cluster = annotator_pen_strokes_in_clusters.get(j); Iterator<Entry<PenStroke, List<String>>> annotator_pen_strokes_iterator = annotator_pen_strokes_in_cluster.entrySet().iterator(); while(annotator_pen_strokes_iterator.hasNext()){ Map.Entry<PenStroke, List<String>> annotator_pen_stroke_entry = (Map.Entry<PenStroke, List<String>>) annotator_pen_strokes_iterator.next(); PenStroke annotator_pen_stroke = annotator_pen_stroke_entry.getKey(); List<String> annotated_words = annotator_pen_stroke_entry.getValue(); long annotator_pen_stroke_id = annotator_pen_stroke.getStrokeId(); //System.out.println(annotator_pen_stroke_id); if(annotator_pen_stroke_id == connected_1_stroke_id || annotator_pen_stroke_id == connected_2_stroke_id){ //System.out.println("found match"); connected_pen_strokes_all_info.put(annotator_pen_stroke, annotated_words); } } /*if(connected_pen_strokes_all_info.size() == 2){ break; }*/ } if(connected_pen_strokes_all_info.size() == 2){ //System.out.println("Connector query"); QueryDetails connector_query = new QueryDetails(worksheet_id, pen_stroke_generating_clusters_id, connected_pen_strokes_all_info, connector_pen_stroke); connector_queries.add(connector_query); } } return connector_queries; } private List<String> words_marked_by_ellipse(PenStroke pen_stroke){ //System.out.println(pen_stroke.getStrokeId()); List<String> words_annotated = new ArrayList<String>(); Rectangle2D pen_stroke_bounds = pen_stroke.getStrokeBounds(); double pen_stroke_area = pen_stroke_bounds.getWidth() * pen_stroke_bounds.getHeight(); List<Stanza> poem_stanzas = poem_content.getPoemStanzas().getStanzas(); for(int i = 0; i < poem_stanzas.size(); i++){ Stanza poem_stanza = poem_stanzas.get(i); Rectangle2D poem_stanza_bounds = poem_stanza.getRawPixelBounds(); if(poem_stanza_bounds.intersects(pen_stroke_bounds)){ List<Line> stanza_lines = poem_stanza.getLines(); for(int j = 0; j < stanza_lines.size(); j++){ boolean has_annotated_word = false; Line stanza_line = stanza_lines.get(j); Rectangle2D stanza_line_bounds = stanza_line.getRawPixelBounds(); if(stanza_line_bounds.intersects(pen_stroke_bounds)){ Rectangle2D intersection = stanza_line_bounds.createIntersection(pen_stroke_bounds); double intersection_area = intersection.getWidth() * intersection.getHeight(); if(intersection_area / pen_stroke_area > 0.4){ has_annotated_word = true; //System.out.println("intersects line '" + j + "' with greater than 0.4"); List<Word> line_words = stanza_line.getWords(); for(int k = 0; k < line_words.size(); k++){ Word line_word = line_words.get(k); Rectangle2D line_word_bounds = line_word.getRawPixelBounds(); if(line_word_bounds.intersects(pen_stroke_bounds)){ intersection = line_word_bounds.createIntersection(pen_stroke_bounds); intersection_area = intersection.getWidth() * intersection.getHeight(); double word_area = line_word_bounds.getWidth() * line_word_bounds.getHeight(); //System.out.println("word area: " + word_area + " , intersection area: " + intersection_area + ", ratio: " + (intersection_area / pen_stroke_area)); if(intersection_area / word_area > 0.5){ words_annotated.add(i + "|" + j + "|" + k + "|" + line_word.getWord().trim().toLowerCase() + "|+|+|" + (intersection_area / pen_stroke_area)); //System.out.println("intersects word '" + line_word.getWord() + "' with greater than 0.5"); } else{ words_annotated.add(i + "|" + j + "|" + k + "|" + line_word.getWord().trim().toLowerCase() + "|+|-|" + (intersection_area / pen_stroke_area)); //System.out.println("intersects word '" + line_word.getWord() + "' with less than 0.5"); } } } } else{ if(words_annotated.isEmpty() || !has_annotated_word){ //System.out.println("intersects line '" + j + "' with less than 0.4"); List<Word> line_words = stanza_line.getWords(); for(int k = 0; k < line_words.size(); k++){ Word line_word = line_words.get(k); Rectangle2D line_word_bounds = line_word.getRawPixelBounds(); if(line_word_bounds.intersects(pen_stroke_bounds)){ intersection = line_word_bounds.createIntersection(pen_stroke_bounds); intersection_area = intersection.getWidth() * intersection.getHeight(); double word_area = line_word_bounds.getWidth() * line_word_bounds.getHeight(); //System.out.println("word area: " + word_area + " , intersection area: " + intersection_area + ", ratio: " + (intersection_area / pen_stroke_area)); if(intersection_area / word_area > 0.5){ words_annotated.add(i + "|" + j + "|" + k + "|" + line_word.getWord().trim().toLowerCase() + "|-|+|" + (intersection_area / pen_stroke_area)); //System.out.println("intersects word '" + line_word.getWord() + "' with greater than 0.5"); //System.out.println(i + "|" + j + "|" + k + "|" + line_word.getWord().trim().toLowerCase() + "|-|+|" + (intersection_area / pen_stroke_area)); } else{ words_annotated.add(i + "|" + j + "|" + k + "|" + line_word.getWord().trim().toLowerCase() + "|-|-|" + (intersection_area / pen_stroke_area)); //System.out.println("intersects word '" + line_word.getWord() + "' with less than 0.5"); } } } } } } } break; } } List<String> words_annotated_filtered = resolve_ellipse_plus_plus_words(words_annotated); if(!words_annotated_filtered.isEmpty()){ return words_annotated_filtered; } else{ words_annotated_filtered = resolve_ellipse_plus_minus_words(words_annotated); if(!words_annotated_filtered.isEmpty()){ return get_max_area_word(words_annotated_filtered); } else{ words_annotated_filtered = resolve_ellipse_minus_plus_words(words_annotated); if(!words_annotated_filtered.isEmpty()){ return get_max_area_word(words_annotated_filtered); } else{ words_annotated_filtered = resolve_ellipse_minus_minus_words(words_annotated); if(!words_annotated_filtered.isEmpty()){ return get_max_area_word(words_annotated_filtered); } else{ return words_annotated_filtered; } } } } } private List<String> resolve_ellipse_plus_plus_words(List<String> words_in_pen_stroke){ List<String> words = new ArrayList<String>(); for(int i = 0; i < words_in_pen_stroke.size(); i++){ String word_in_pen_stroke = words_in_pen_stroke.get(i); String[] word_split = word_in_pen_stroke.split("\\|"); if(word_split[4].equals("+") && word_split[5].equals("+")){ words.add(word_split[0] + "|" + word_split[1] + "|" + word_split[2] + "|" + word_split[3]); } } return words; } private List<String> resolve_ellipse_plus_minus_words(List<String> words_in_pen_stroke){ List<String> words = new ArrayList<String>(); for(int i = 0; i < words_in_pen_stroke.size(); i++){ String word_in_pen_stroke = words_in_pen_stroke.get(i); String[] word_split = word_in_pen_stroke.split("\\|"); if(word_split[4].equals("+") && word_split[5].equals("-")){ words.add(word_in_pen_stroke); } } return words; } private List<String> resolve_ellipse_minus_plus_words(List<String> words_in_pen_stroke){ List<String> words = new ArrayList<String>(); for(int i = 0; i < words_in_pen_stroke.size(); i++){ String word_in_pen_stroke = words_in_pen_stroke.get(i); String[] word_split = word_in_pen_stroke.split("\\|"); if(word_split[4].equals("-") && word_split[5].equals("+")){ words.add(word_in_pen_stroke); } } return words; } private List<String> resolve_ellipse_minus_minus_words(List<String> words_in_pen_stroke){ List<String> words = new ArrayList<String>(); for(int i = 0; i < words_in_pen_stroke.size(); i++){ String word_in_pen_stroke = words_in_pen_stroke.get(i); String[] word_split = word_in_pen_stroke.split("\\|"); if(word_split[4].equals("-") && word_split[5].equals("-")){ words.add(word_in_pen_stroke); } } return words; } private List<String> get_max_area_word(List<String> words){ List<String> max_area_words = new ArrayList<String>(); double max_area = Double.NEGATIVE_INFINITY; String max_area_word = null; for(int i = 0 ; i < words.size(); i++){ //System.out.println(words.get(i)); String[] word_split = words.get(i).split("\\|"); //System.out.println(word_split[0] + " " + word_split[1] + " " + word_split[2] + " " + word_split[3] + " " + word_split[4] + " " + word_split[5] + " " + word_split[6]); double word_area = Double.parseDouble(word_split[6]); if(word_area >= max_area){ max_area = word_area; max_area_word = word_split[0] + "|" + word_split[1] + "|" + word_split[2] + "|" + word_split[3]; } } if(max_area_word != null){ max_area_words.add(max_area_word); } return max_area_words; } private List<String> words_marked_by_underline(PenStroke pen_stroke){ List<String> words_annotated = new ArrayList<String>(); Rectangle2D pen_stroke_bounds = pen_stroke.getStrokeBounds(); //double pen_stroke_area = pen_stroke_bounds.getWidth() * pen_stroke_bounds.getHeight(); double pen_start_x = pen_stroke_bounds.getX(), pen_end_x = pen_stroke_bounds.getWidth() + pen_stroke_bounds.getX(); List<Stanza> poem_stanzas = poem_content.getPoemStanzas().getStanzas(); for(int i = 0; i < poem_stanzas.size(); i++){ Stanza poem_stanza = poem_stanzas.get(i); Rectangle2D poem_stanza_bounds = poem_stanza.getRawPixelBounds(); poem_stanza_bounds = new Rectangle2D.Double(poem_stanza_bounds.getX(), poem_stanza_bounds.getY(), poem_stanza_bounds.getWidth(), poem_stanza_bounds.getHeight() + CompositeGenerator.line_break_space); if(poem_stanza_bounds.intersects(pen_stroke_bounds)){ List<Line> lines_in_stanza = poem_stanza.getLines(); for(int j = 0; j < lines_in_stanza.size(); j++){ Line line_in_stanza = lines_in_stanza.get(j); Rectangle2D line_bounds = line_in_stanza.getRawPixelBounds(); if(j == lines_in_stanza.size() - 1){ line_bounds = new Rectangle2D.Double(line_bounds.getX(), line_bounds.getY(), line_bounds.getWidth(), line_bounds.getHeight() + CompositeGenerator.line_break_space); } else{ double next_line_start_y = lines_in_stanza.get(j + 1).getRawPixelBounds().getY(); double new_height = line_bounds.getHeight() + (next_line_start_y - (line_bounds.getY() + line_bounds.getHeight())); line_bounds = new Rectangle2D.Double(line_bounds.getX(), line_bounds.getY(), line_bounds.getWidth(), new_height); } if(line_bounds.intersects(pen_stroke_bounds)){ //System.out.println("Intersects line " + j); List<Word> words_in_line = line_in_stanza.getWords(); for(int k = 0 ; k < words_in_line.size(); k++){ Word word_in_line = words_in_line.get(k); Rectangle2D word_bounds = word_in_line.getRawPixelBounds(); double word_start_x = word_bounds.getX(), word_end_x = word_bounds.getWidth() + word_bounds.getX(); if(check_if_overlap_for_underline(word_start_x, word_end_x, pen_start_x, pen_end_x)){ //System.out.println("Overlaps word '" + word_in_line.getWord() + "'"); words_annotated.add(i + "|" + j + "|" + k + "|" + word_in_line.getWord().trim().toLowerCase()); } } } } break; } } return words_annotated; } private boolean check_if_overlap_for_underline(double word_start_x, double word_end_x, double pen_start_x, double pen_end_x){ Map<Double, String> end_points_sorted = new TreeMap<Double, String>(); end_points_sorted.put(word_start_x, "word_start"); end_points_sorted.put(word_end_x, "word_end"); end_points_sorted.put(pen_start_x, "pen_start"); end_points_sorted.put(pen_end_x, "pen_end"); boolean overlap = false; String previous_end_point = null; int end_points_compared = 0; for (Map.Entry<Double, String> entry : end_points_sorted.entrySet()) { if(end_points_compared < 2){ if(previous_end_point != null){ if(!entry.getValue().split("_")[0].equals(previous_end_point)){ overlap = true; } } else{ previous_end_point = entry.getValue().split("_")[0]; } } else{ break; } end_points_compared++; } return overlap; } private List<List<PenStroke>> words_marked_by_connector(List<Cluster> pen_stroke_clusters, PenStroke connector_pen_stroke, List<PenStroke> all_pen_strokes_in_worksheet){ long connector_pen_stroke_id = connector_pen_stroke.getStrokeId(); List<List<PenStroke>> preceding_marks_to_look_up = find_marks_preceding_connector(connector_pen_stroke_id, all_pen_strokes_in_worksheet, connector_pen_stroke); /* for(int i = 0; i < preceding_marks_to_look_up.size(); i++){ List<PenStroke> set_of_pen_strokes = preceding_marks_to_look_up.get(i); System.out.println("Connects stroke: "); for(int j = 0; j < set_of_pen_strokes.size(); j++){ System.out.println(set_of_pen_strokes.get(j).getStrokeId()); } }*/ return preceding_marks_to_look_up; } private List<List<PenStroke>> find_marks_preceding_connector(long connector_pen_stroke_id, List<PenStroke> all_pen_strokes_in_worksheet, PenStroke connector){ List<List<PenStroke>> pen_strokes_to_look_up = new ArrayList<List<PenStroke>>(); PenStroke connected_1, connected_2; List<PenStroke> pair_of_pen_strokes = new ArrayList<PenStroke>(); if(connector_pen_stroke_id == 0){ /* connected_1 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id + 1); connected_2 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id + 2); pair_of_pen_strokes = one_set_of_pen_strokes_to_check(connected_1, connected_2, connector); if(!pair_of_pen_strokes.isEmpty()){ pen_strokes_to_look_up.add(pair_of_pen_strokes); } */ } else if(connector_pen_stroke_id == 1){ /* connected_1 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id - 1); connected_2 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id + 1); pair_of_pen_strokes = one_set_of_pen_strokes_to_check(connected_1, connected_2, connector); if(!pair_of_pen_strokes.isEmpty()){ pen_strokes_to_look_up.add(pair_of_pen_strokes); } connected_1 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id + 1); connected_2 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id + 2); pair_of_pen_strokes = one_set_of_pen_strokes_to_check(connected_1, connected_2, connector); if(!pair_of_pen_strokes.isEmpty()){ pen_strokes_to_look_up.add(pair_of_pen_strokes); } */ } else{ /* connected_1 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id + 1); connected_2 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id + 2); pair_of_pen_strokes = one_set_of_pen_strokes_to_check(connected_1, connected_2, connector); if(!pair_of_pen_strokes.isEmpty()){ pen_strokes_to_look_up.add(pair_of_pen_strokes); } connected_1 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id - 1); connected_2 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id + 1); pair_of_pen_strokes = one_set_of_pen_strokes_to_check(connected_1, connected_2, connector); if(!pair_of_pen_strokes.isEmpty()){ pen_strokes_to_look_up.add(pair_of_pen_strokes); } */ connected_1 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id - 1); connected_2 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id - 2); pair_of_pen_strokes = one_set_of_pen_strokes_to_check(connected_1, connected_2, connector); if(!pair_of_pen_strokes.isEmpty()){ pen_strokes_to_look_up.add(pair_of_pen_strokes); } } return pen_strokes_to_look_up; } private PenStroke get_pen_stroke_by_stroke_id(List<PenStroke> all_pen_strokes_in_worksheet, long pen_stroke_id){ PenStroke pen_stroke_found = null; for(int i = 0 ; i < all_pen_strokes_in_worksheet.size(); i++){ PenStroke pen_stroke = all_pen_strokes_in_worksheet.get(i); if(pen_stroke_id == pen_stroke.getStrokeId()){ pen_stroke_found = pen_stroke; break; } } return pen_stroke_found; } private List<PenStroke> one_set_of_pen_strokes_to_check(PenStroke connected_1, PenStroke connected_2, PenStroke connector){ List<PenStroke> connected_pen_strokes = new ArrayList<PenStroke>(); if(connected_1 != null && connected_2 != null){ ShapeRecognizer.penStrokeTypes connected_1_stroke_type = connected_1.getPenStrokeType(); ShapeRecognizer.penStrokeTypes connected_2_stroke_type = connected_2.getPenStrokeType(); if((connected_1_stroke_type != ShapeRecognizer.penStrokeTypes.Undefined) && (connected_2_stroke_type != ShapeRecognizer.penStrokeTypes.Undefined)){ Rectangle2D connector_bounds = connector.getStrokeBounds(); if(connector_bounds.intersects(connected_1.getStrokeBounds()) && connector_bounds.intersects(connected_2.getStrokeBounds())){ connected_pen_strokes.add(connected_1); connected_pen_strokes.add(connected_2); } } } return connected_pen_strokes; } }
apache-2.0
SVADemoAPP/Server
model/com/sva/model/LocationModel.java
1944
package com.sva.model; import java.math.BigDecimal; public class LocationModel { private String idType; private BigDecimal timestamp; private String dataType; private BigDecimal x; private BigDecimal y; private BigDecimal z; private String userID; private String path; private String xo; private String yo; private String scale; public String getXo() { return xo; } public void setXo(String xo) { this.xo = xo; } public String getYo() { return yo; } public void setYo(String yo) { this.yo = yo; } public String getScale() { return scale; } public void setScale(String scale) { this.scale = scale; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getIdType() { return idType; } public void setIdType(String idType) { this.idType = idType; } public BigDecimal getTimestamp() { return timestamp; } public void setTimestamp(BigDecimal timestamp) { this.timestamp = timestamp; } public String getDataType() { return dataType; } public void setDataType(String dataType) { this.dataType = dataType; } public BigDecimal getX() { return x; } public void setX(BigDecimal x) { this.x = x; } public BigDecimal getY() { return y; } public void setY(BigDecimal y) { this.y = y; } public BigDecimal getZ() { return z; } public void setZ(BigDecimal z) { this.z = z; } public String getUserID() { return userID; } public void setUserID(String userID) { this.userID = userID; } }
apache-2.0
RobAltena/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ops/impl/transforms/custom/FakeQuantWithMinMaxVars.java
3062
package org.nd4j.linalg.api.ops.impl.transforms.custom; import org.nd4j.autodiff.samediff.SDVariable; import org.nd4j.autodiff.samediff.SameDiff; import org.nd4j.base.Preconditions; import org.nd4j.linalg.api.buffer.DataType; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.api.ops.DynamicCustomOp; import org.tensorflow.framework.AttrValue; import org.tensorflow.framework.GraphDef; import org.tensorflow.framework.NodeDef; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; /** * Fake quantization operation. * Quantized into range [0, 2^numBits - 1] when narrowRange is false, or [1, 2^numBits - 1] when narrowRange is true. * Note that numBits must be in range 2 to 16 (inclusive). * @author Alex Black */ public class FakeQuantWithMinMaxVars extends DynamicCustomOp { protected boolean narrowRange; protected int numBits; public FakeQuantWithMinMaxVars(SameDiff sd, SDVariable input, SDVariable min, SDVariable max, boolean narrowRange, int numBits){ super(sd, new SDVariable[]{input, min, max}); Preconditions.checkState(numBits >= 2 && numBits <= 16, "NumBits arg must be in range 2 to 16 inclusive, got %s", numBits); this.narrowRange = narrowRange; this.numBits = numBits; addArgs(); } public FakeQuantWithMinMaxVars(INDArray x, INDArray min, INDArray max, int num_bits, boolean narrow) { Preconditions.checkArgument(min.isVector() && max.isVector() && min.length() == max.length(), "FakeQuantWithMinMaxVars: min and max should be 1D tensors with the same length"); addInputArgument(x,min,max); addIArgument(num_bits); addBArgument(narrow); } public FakeQuantWithMinMaxVars(){ } protected void addArgs(){ iArguments.clear(); bArguments.clear(); addIArgument(numBits); addBArgument(narrowRange); } @Override public String opName(){ return "fake_quant_with_min_max_vars"; } @Override public String tensorflowName(){ return "FakeQuantWithMinMaxVars"; } @Override public void initFromTensorFlow(NodeDef nodeDef, SameDiff initWith, Map<String, AttrValue> attributesForNode, GraphDef graph) { if(attributesForNode.containsKey("narrow_range")){ this.narrowRange = attributesForNode.get("narrow_range").getB(); } this.numBits = (int)attributesForNode.get("num_bits").getI(); addArgs(); } @Override public List<DataType> calculateOutputDataTypes(List<DataType> inputDataTypes){ Preconditions.checkState(inputDataTypes != null && inputDataTypes.size() == 3, "Expected exactly 3 inputs, got %s", inputDataTypes); return Collections.singletonList(inputDataTypes.get(0)); } @Override public List<SDVariable> doDiff(List<SDVariable> gradients){ return Arrays.asList(sameDiff.zerosLike(arg(0)), sameDiff.zerosLike(arg(1)), sameDiff.zerosLike(arg(2))); } }
apache-2.0
ChetnaChaudhari/hadoop
hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientSpi.java
3772
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdds.scm; import com.google.common.annotations.VisibleForTesting; import org.apache.hadoop.hdds.scm.container.common.helpers.Pipeline; import org.apache.hadoop.hdds.protocol.DatanodeDetails; import org.apache.hadoop.hdds.protocol.proto.ContainerProtos .ContainerCommandRequestProto; import org.apache.hadoop.hdds.protocol.proto.ContainerProtos .ContainerCommandResponseProto; import org.apache.hadoop.hdds.protocol.proto.HddsProtos; import java.io.Closeable; import java.io.IOException; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; /** * A Client for the storageContainer protocol. */ public abstract class XceiverClientSpi implements Closeable { final private AtomicInteger referenceCount; private boolean isEvicted; XceiverClientSpi() { this.referenceCount = new AtomicInteger(0); this.isEvicted = false; } void incrementReference() { this.referenceCount.incrementAndGet(); } void decrementReference() { this.referenceCount.decrementAndGet(); cleanup(); } void setEvicted() { isEvicted = true; cleanup(); } // close the xceiverClient only if, // 1) there is no refcount on the client // 2) it has been evicted from the cache. private void cleanup() { if (referenceCount.get() == 0 && isEvicted) { close(); } } @VisibleForTesting public int getRefcount() { return referenceCount.get(); } /** * Connects to the leader in the pipeline. */ public abstract void connect() throws Exception; @Override public abstract void close(); /** * Returns the pipeline of machines that host the container used by this * client. * * @return pipeline of machines that host the container */ public abstract Pipeline getPipeline(); /** * Sends a given command to server and gets the reply back. * @param request Request * @return Response to the command * @throws IOException */ public abstract ContainerCommandResponseProto sendCommand( ContainerCommandRequestProto request) throws IOException; /** * Sends a given command to server gets a waitable future back. * * @param request Request * @return Response to the command * @throws IOException */ public abstract CompletableFuture<ContainerCommandResponseProto> sendCommandAsync(ContainerCommandRequestProto request) throws IOException, ExecutionException, InterruptedException; /** * Create a pipeline. * * @param pipelineID - Name of the pipeline. * @param datanodes - Datanodes */ public abstract void createPipeline(String pipelineID, List<DatanodeDetails> datanodes) throws IOException; /** * Returns pipeline Type. * * @return - {Stand_Alone, Ratis or Chained} */ public abstract HddsProtos.ReplicationType getPipelineType(); }
apache-2.0
richard-strauss-werke/glyphpicker
src/main/java/de/badw/strauss/glyphpicker/model/DataSourceList.java
3199
/** * Copyright 2015 Alexander Erhard * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.badw.strauss.glyphpicker.model; import javax.swing.*; import javax.xml.bind.annotation.*; import java.util.ArrayList; import java.util.List; /** * The data source combo box model. */ @XmlRootElement(name = "glyphTables") @XmlAccessorType(XmlAccessType.FIELD) public class DataSourceList extends AbstractListModel<String> implements ComboBoxModel<String> { private static final long serialVersionUID = 1L; /** * The maximum number of items in the list. */ private static final int ITEM_MAX = 20; /** * The selected item. */ @XmlTransient private Object selectedItem; /** * The data sources. */ @XmlElement(name = "glyphTable") private List<DataSource> data = new ArrayList<DataSource>(); /** * Instantiates a new DataSourceList. */ public DataSourceList() { } /** * Initializes the model. */ public void init() { if (data != null && data.size() > 0) { selectedItem = data.get(0).getLabel(); } } /** * Sets the first index. * * @param index the new first index */ public void setFirstIndex(int index) { DataSource item = getDataSourceAt(index); data.add(0, item); for (int i = data.size() - 1; i > 0; i--) { if (item.equals(data.get(i)) || i > ITEM_MAX) { data.remove(i); } } fireContentsChanged(item, -1, -1); } /* (non-Javadoc) * @see javax.swing.ComboBoxModel#getSelectedItem() */ public Object getSelectedItem() { return selectedItem; } /* (non-Javadoc) * @see javax.swing.ComboBoxModel#setSelectedItem(java.lang.Object) */ public void setSelectedItem(Object newValue) { selectedItem = newValue; fireContentsChanged(newValue, -1, -1); } /* (non-Javadoc) * @see javax.swing.ListModel#getSize() */ public int getSize() { return data.size(); } /** * Gets the data source's label at the specified index. * * @param i the index * @return the label */ public String getElementAt(int i) { return data.get(i).getLabel(); } /** * Gets the data source at the specified index. * * @param i the index * @return the data source */ public DataSource getDataSourceAt(int i) { return data.get(i); } /** * Gets the data. * * @return the data */ public List<DataSource> getData() { return data; } }
apache-2.0
Olegas/YandexAPI
src/ru/elifantiev/yandex/oauth/OAuthActivity.java
4910
/* * Copyright 2011 Oleg Elifantiev * * 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 ru.elifantiev.yandex.oauth; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.net.Uri; import ru.elifantiev.yandex.oauth.tokenstorage.AccessTokenStorage; abstract public class OAuthActivity extends Activity { /** * Intent's Extra holding auth result */ public static final String EXTRA_AUTH_RESULT = "ru.elifantiev.yandex.oauth.AUTH_RESULT_EXTRA"; /** * Intent's Extra holding error message (in case of error) */ public static final String EXTRA_AUTH_RESULT_ERROR = "ru.elifantiev.yandex.oauth.AUTH_RESULT_ERROR_EXTRA"; /** * An action, which will be used to start activity, which must handle an authentication result. * Must not be the same, as OAuthActivity. * Intent's data field contains Uri 'oauth://{appId}' where appId is application Id returned with getAppId method. */ public static final String ACTION_AUTH_RESULT = "ru.elifantiev.yandex.oauth.AUTH_RESULT"; public static final int AUTH_RESULT_OK = 0; public static final int AUTH_RESULT_ERROR = 1; @Override protected void onResume() { authorize(); super.onResume(); //To change body of overridden methods use File | Settings | File Templates. } protected void authorize() { Uri data = getIntent().getData(); if (data != null) { AuthSequence .newInstance(getServer(), getAppId()) .continueSequence(data, getContinuationHandler()); } else AuthSequence .newInstance(getServer(), getAppId()) .start(getClientId(), getRequiredPermissions(), this); } /** * This method must return PermissionsScope object declaring permission, required to current application * @return PermissionsScope instance */ abstract protected PermissionsScope getRequiredPermissions(); /** * Client ID by OAuth specification * @return OAuth client ID */ abstract protected String getClientId(); /** * This method must return an unique string ID of an application * It is usually an application's package name * This will be used to separate different application OAuth calls and token storage * @return Unique ID of calling application */ abstract protected String getAppId(); /** * Method to declare a server, which will handle OAuth calls * @return URL of target server */ abstract protected Uri getServer(); /** * Implementation of AccessTokenStorage to use for store application's access token * Now implemented: * - SharedPreferencesStorage - uses shared preferences to store token * - EncryptedSharedPreferencesStorage - uses shared preferences but token is encrypted with 3DES and user-supplied key * @return Token storage to use */ abstract protected AccessTokenStorage getTokenStorage(); protected AsyncContinuationHandler getContinuationHandler() { return new AsyncContinuationHandler(getClientId(), getDefaultStatusHandler()); } protected AuthStatusHandler getDefaultStatusHandler() { return new AuthStatusHandler() { public void onResult(AuthResult result) { Intent callHome = new Intent(ACTION_AUTH_RESULT); callHome.setData(Uri.parse(AuthSequence.OAUTH_SCHEME + "://" + getAppId())); if(result.isSuccess()) { getTokenStorage().storeToken(result.getToken(), getAppId()); callHome.putExtra(EXTRA_AUTH_RESULT, AUTH_RESULT_OK); } else { callHome .putExtra(EXTRA_AUTH_RESULT, AUTH_RESULT_ERROR) .putExtra(EXTRA_AUTH_RESULT_ERROR, result.getError()); } try { startActivity(callHome); } catch (ActivityNotFoundException e) { // ignore } finish(); } }; } }
apache-2.0
shs96c/buck
test/com/facebook/buck/android/MultipleResourcePackageIntegrationTest.java
2897
/* * Copyright 2014-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.android; import static org.junit.Assert.assertFalse; import com.facebook.buck.core.model.BuildTargetFactory; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.io.filesystem.TestProjectFilesystems; import com.facebook.buck.testutil.TemporaryPaths; import com.facebook.buck.testutil.integration.ProjectWorkspace; import com.facebook.buck.testutil.integration.TestDataHelper; import java.io.IOException; import java.nio.file.Path; import org.junit.Before; import org.junit.Rule; import org.junit.Test; public class MultipleResourcePackageIntegrationTest { @Rule public TemporaryPaths tmpFolder = new TemporaryPaths(); private ProjectWorkspace workspace; private ProjectFilesystem filesystem; @Before public void setUp() throws InterruptedException, IOException { workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "android_project", tmpFolder); workspace.setUp(); filesystem = TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath()); } @Test public void testRDotJavaFilesPerPackage() throws InterruptedException, IOException { AssumeAndroidPlatform.assumeSdkIsAvailable(); workspace.runBuckBuild("//apps/sample:app_with_multiple_rdot_java_packages").assertSuccess(); Path uberRDotJavaDir = GenerateRDotJava.getPathToGeneratedRDotJavaSrcFiles( BuildTargetFactory.newInstance("//apps/sample:app_with_multiple_rdot_java_packages") .withFlavors(AndroidBinaryResourcesGraphEnhancer.GENERATE_RDOT_JAVA_FLAVOR), filesystem); String sampleRJava = workspace.getFileContents(uberRDotJavaDir.resolve("com/sample/R.java").toString()); String sample2RJava = workspace.getFileContents(uberRDotJavaDir.resolve("com/sample2/R.java").toString()); assertFalse(sampleRJava.contains("sample2_string")); assertFalse(sample2RJava.contains("app_icon")); assertFalse(sample2RJava.contains("tiny_black")); assertFalse(sample2RJava.contains("tiny_something")); assertFalse(sample2RJava.contains("tiny_white")); assertFalse(sample2RJava.contains("top_layout")); assertFalse(sample2RJava.contains("app_name")); assertFalse(sample2RJava.contains("base_button")); } }
apache-2.0
Gigaspaces/xap-openspaces
src/main/java/org/openspaces/admin/gsa/ElasticServiceManagerOptions.java
3376
/* * Copyright 2006-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openspaces.admin.gsa; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.gigaspaces.grid.gsa.GSProcessOptions; /** * {@link org.openspaces.admin.esm.ElasticServiceManager} process options to be started by the * {@link org.openspaces.admin.gsa.GridServiceAgent}. * * @author Moran Avigdor * @see org.openspaces.admin.gsa.GridServiceAgent#startGridService(ElasticServiceManagerOptions) */ public class ElasticServiceManagerOptions { private final List<String> vmInputArguments = new ArrayList<String>(); private boolean overrideVmInputArguments = false; private boolean useScript = false; private final Map<String, String> environmentVariables = new HashMap<String, String>(); /** * Constructs a new elastic service manager options. By default will use JVM process execution. */ public ElasticServiceManagerOptions() { } /** * Will cause the {@link org.openspaces.admin.esm.ElasticServiceManager} to be started using a script * and not a pure Java process. */ public ElasticServiceManagerOptions useScript() { this.useScript = true; return this; } /** * Will cause JVM options added using {@link #vmInputArgument(String)} to override all the vm arguments * that the JVM will start by default with. */ public ElasticServiceManagerOptions overrideVmInputArguments() { overrideVmInputArguments = true; return this; } /** * Will add a JVM level argument when the process is executed using pure JVM. For example, the memory * can be controlled using <code>-Xmx512m</code>. */ public ElasticServiceManagerOptions vmInputArgument(String vmInputArgument) { vmInputArguments.add(vmInputArgument); return this; } /** * Sets an environment variable that will be passed to forked process. */ public ElasticServiceManagerOptions environmentVariable(String name, String value) { environmentVariables.put(name, value); return this; } /** * Returns the agent process options that represents what was set on this ESM options. */ public GSProcessOptions getOptions() { GSProcessOptions options = new GSProcessOptions("esm"); options.setUseScript(useScript); if (overrideVmInputArguments) { options.setVmInputArguments(vmInputArguments.toArray(new String[vmInputArguments.size()])); } else { options.setVmAppendableInputArguments(vmInputArguments.toArray(new String[vmInputArguments.size()])); } options.setEnvironmentVariables(environmentVariables); return options; } }
apache-2.0
wsv-accidis/tmeit-android
app/src/main/java/se/tmeit/app/model/ExternalEventAttendee.java
2147
package se.tmeit.app.model; import com.google.auto.value.AutoValue; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Model object for attendees of an external event. */ @AutoValue public abstract class ExternalEventAttendee { public static ExternalEventAttendee fromJson(JSONObject json) throws JSONException { return builder() .setDateOfBirth(json.optString(Keys.DOB, "")) .setDrinkPreferences(json.optString(Keys.DRINK_PREFS, "")) .setFoodPreferences(json.optString(Keys.FOOD_PREFS, "")) .setName(json.optString(Keys.NAME, "")) .setNotes(json.optString(Keys.NOTES, "")) .setId(json.optInt(Keys.ID)) .build(); } public static List<ExternalEventAttendee> fromJsonArray(JSONArray json) throws JSONException { ArrayList<ExternalEventAttendee> result = new ArrayList<>(json.length()); for (int i = 0; i < json.length(); i++) { result.add(fromJson(json.getJSONObject(i))); } return result; } public static Builder builder() { return new AutoValue_ExternalEventAttendee.Builder() .setId(0) .setName(""); } public abstract String dateOfBirth(); public abstract String drinkPreferences(); public abstract String foodPreferences(); public abstract String name(); public abstract String notes(); public abstract int id(); @AutoValue.Builder public abstract static class Builder { public abstract Builder setDateOfBirth(String value); public abstract Builder setDrinkPreferences(String value); public abstract Builder setFoodPreferences(String value); abstract Builder setName(String value); public abstract Builder setNotes(String value); abstract Builder setId(int id); public abstract ExternalEventAttendee build(); } public static class Keys { public static final String DOB = "dob"; public static final String DRINK_PREFS = "drink_prefs"; public static final String FOOD_PREFS = "food_prefs"; public static final String ID = "id"; public static final String NAME = "user_name"; public static final String NOTES = "notes"; private Keys() { } } }
apache-2.0
codeabovelab/haven-platform
cluster-manager/src/main/java/com/codeabovelab/dm/cluman/cluster/docker/model/swarm/DispatcherConfig.java
854
/* * Copyright 2016 Code Above Lab LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.codeabovelab.dm.cluman.cluster.docker.model.swarm; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; @Data public class DispatcherConfig { @JsonProperty("HeartbeatPeriod") private Long heartbeatPeriod; }
apache-2.0
hortonworks/cloudbreak
integration-test/src/main/java/com/sequenceiq/it/cloudbreak/dto/AzureInstanceTemplateParametersV4TestDto.java
644
package com.sequenceiq.it.cloudbreak.dto; import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.base.parameter.template.AzureInstanceTemplateV4Parameters; import com.sequenceiq.it.cloudbreak.Prototype; import com.sequenceiq.it.cloudbreak.context.TestContext; @Prototype public class AzureInstanceTemplateParametersV4TestDto extends AbstractCloudbreakTestDto<AzureInstanceTemplateV4Parameters, AzureInstanceTemplateV4Parameters, AzureInstanceTemplateParametersV4TestDto> { protected AzureInstanceTemplateParametersV4TestDto(TestContext testContext) { super(new AzureInstanceTemplateV4Parameters(), testContext); } }
apache-2.0
cbadenes/farolapi
src/main/java/es/upm/oeg/farolapi/model/LightAttribute.java
410
package es.upm.oeg.farolapi.model; import lombok.Data; import lombok.ToString; import java.util.Arrays; import java.util.List; /** * Created on 23/05/16: * * @author cbadenes */ @Data @ToString (callSuper = true) public class LightAttribute extends Attribute { @Override public List<String> getRange() { return Arrays.asList(new String[]{"P", "F", "E", "AA", "AC", "ER", "O"}); } }
apache-2.0
ThorbenLindhauer/graphical-models
inference-engine/src/test/java/com/github/thorbenlindhauer/inference/GaussianModelInferencerTest.java
5129
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.thorbenlindhauer.inference; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Before; import org.junit.Test; import com.github.thorbenlindhauer.cluster.Cluster; import com.github.thorbenlindhauer.cluster.ClusterGraph; import com.github.thorbenlindhauer.cluster.Edge; import com.github.thorbenlindhauer.cluster.messagepassing.BeliefUpdateContextFactory; import com.github.thorbenlindhauer.factor.GaussianFactor; import com.github.thorbenlindhauer.inference.loopy.MessageInstruction; import com.github.thorbenlindhauer.inference.loopy.StaticCalibrationContextFactory; import com.github.thorbenlindhauer.network.StandaloneGaussiaFactorBuilder; import com.github.thorbenlindhauer.test.util.LinearAlgebraUtil; import com.github.thorbenlindhauer.test.util.TestConstants; import com.github.thorbenlindhauer.variable.ContinuousVariable; /** * @author Thorben * */ public class GaussianModelInferencerTest { ClusterGraph<GaussianFactor> clusterGraph; Cluster<GaussianFactor> barometricCluster; Cluster<GaussianFactor> temperatureCluster; Cluster<GaussianFactor> rainCluster; Edge<GaussianFactor> tempRainEdge; Edge<GaussianFactor> baroRainEdge; @Before public void setUp() { StandaloneGaussiaFactorBuilder builder = StandaloneGaussiaFactorBuilder.withVariables( new ContinuousVariable("RainAmount"), new ContinuousVariable("Temperature"), new ContinuousVariable("BarometricPressure")); // the following factors make no sense meteorologically ;) GaussianFactor barometricFactor = builder .scope("BarometricPressure") .momentForm() .parameters(LinearAlgebraUtil.asVector(100.0d), LinearAlgebraUtil.asMatrix(10.0d)); GaussianFactor temperatureFactor = builder .scope("Temperature") .momentForm() .parameters(LinearAlgebraUtil.asVector(15.0d), LinearAlgebraUtil.asMatrix(12.0d)); GaussianFactor rainFactor = builder .scope("RainAmount", "BarometricPressure", "Temperature") .conditional() .conditioningScope("BarometricPressure", "Temperature") .parameters(LinearAlgebraUtil.asVector(900.0d), LinearAlgebraUtil.asMatrix(50.0d), LinearAlgebraUtil.asRowMatrix(0.1d, 2.0d)); barometricCluster = new Cluster<GaussianFactor>(Collections.singleton(barometricFactor)); temperatureCluster = new Cluster<GaussianFactor>(Collections.singleton(temperatureFactor)); rainCluster = new Cluster<GaussianFactor>(Collections.singleton(rainFactor)); Set<Cluster<GaussianFactor>> clusters = new HashSet<Cluster<GaussianFactor>>(); clusters.add(barometricCluster); clusters.add(temperatureCluster); clusters.add(rainCluster); clusterGraph = new ClusterGraph<GaussianFactor>(clusters); tempRainEdge = clusterGraph.connect(temperatureCluster, rainCluster); baroRainEdge = clusterGraph.connect(barometricCluster, rainCluster); } @Test public void testPointEstimate() { List<MessageInstruction> propagationOrder = new ArrayList<MessageInstruction>(); propagationOrder.add(new MessageInstruction(tempRainEdge, temperatureCluster)); propagationOrder.add(new MessageInstruction(baroRainEdge, rainCluster)); propagationOrder.add(new MessageInstruction(baroRainEdge, barometricCluster)); propagationOrder.add(new MessageInstruction(tempRainEdge, rainCluster)); GaussianModelInferencer inferencer = new GaussianClusterGraphInferencer(clusterGraph, new BeliefUpdateContextFactory(), new StaticCalibrationContextFactory(propagationOrder)); double[] marginalRainMean = inferencer.posteriorMean(clusterGraph.getScope().subScope("RainAmount")); assertThat(marginalRainMean).hasSize(1); assertThat(marginalRainMean[0]).isEqualTo(940.0d, TestConstants.DOUBLE_VALUE_TOLERANCE); double[][] marginalRainVariance = inferencer.posteriorCovariance(clusterGraph.getScope().subScope("RainAmount")); assertThat(marginalRainVariance).hasSize(1); assertThat(marginalRainVariance[0]).hasSize(1); assertThat(marginalRainVariance[0][0]).isEqualTo(98.1d, TestConstants.DOUBLE_VALUE_TOLERANCE); double marginalRainProbability = inferencer.jointProbability(clusterGraph.getScope().subScope("RainAmount"), new double[]{950.0d}); assertThat(marginalRainProbability).isEqualTo(0.0241948, TestConstants.DOUBLE_VALUE_TOLERANCE); } }
apache-2.0
googleapis/java-redis
proto-google-cloud-redis-v1/src/main/java/com/google/cloud/redis/v1/CreateInstanceRequestOrBuilder.java
3827
/* * Copyright 2020 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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/redis/v1/cloud_redis.proto package com.google.cloud.redis.v1; public interface CreateInstanceRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.redis.v1.CreateInstanceRequest) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Required. The resource name of the instance location using the form: * `projects/{project_id}/locations/{location_id}` * where `location_id` refers to a GCP region. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ java.lang.String getParent(); /** * * * <pre> * Required. The resource name of the instance location using the form: * `projects/{project_id}/locations/{location_id}` * where `location_id` refers to a GCP region. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ com.google.protobuf.ByteString getParentBytes(); /** * * * <pre> * Required. The logical name of the Redis instance in the customer project * with the following restrictions: * * Must contain only lowercase letters, numbers, and hyphens. * * Must start with a letter. * * Must be between 1-40 characters. * * Must end with a number or a letter. * * Must be unique within the customer project / location * </pre> * * <code>string instance_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The instanceId. */ java.lang.String getInstanceId(); /** * * * <pre> * Required. The logical name of the Redis instance in the customer project * with the following restrictions: * * Must contain only lowercase letters, numbers, and hyphens. * * Must start with a letter. * * Must be between 1-40 characters. * * Must end with a number or a letter. * * Must be unique within the customer project / location * </pre> * * <code>string instance_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for instanceId. */ com.google.protobuf.ByteString getInstanceIdBytes(); /** * * * <pre> * Required. A Redis [Instance] resource * </pre> * * <code>.google.cloud.redis.v1.Instance instance = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the instance field is set. */ boolean hasInstance(); /** * * * <pre> * Required. A Redis [Instance] resource * </pre> * * <code>.google.cloud.redis.v1.Instance instance = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The instance. */ com.google.cloud.redis.v1.Instance getInstance(); /** * * * <pre> * Required. A Redis [Instance] resource * </pre> * * <code>.google.cloud.redis.v1.Instance instance = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ com.google.cloud.redis.v1.InstanceOrBuilder getInstanceOrBuilder(); }
apache-2.0
data-integrations/delta
delta-app/src/main/java/io/cdap/delta/store/DBReplicationOffsetStore.java
4397
/* * Copyright © 2021 Cask Data, 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 io.cdap.delta.store; import com.google.gson.Gson; import io.cdap.cdap.spi.data.StructuredRow; import io.cdap.cdap.spi.data.StructuredTable; import io.cdap.cdap.spi.data.StructuredTableContext; import io.cdap.cdap.spi.data.TableNotFoundException; import io.cdap.cdap.spi.data.table.StructuredTableId; import io.cdap.cdap.spi.data.table.StructuredTableSpecification; import io.cdap.cdap.spi.data.table.field.Field; import io.cdap.cdap.spi.data.table.field.FieldType; import io.cdap.cdap.spi.data.table.field.Fields; import io.cdap.delta.app.DeltaWorkerId; import io.cdap.delta.app.OffsetAndSequence; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Optional; import javax.annotation.Nullable; /** * A StructuredTable based database table to store replication offset and sequence data. */ public class DBReplicationOffsetStore { private static final StructuredTableId TABLE_ID = new StructuredTableId("delta_offset_store"); private static final String NAMESPACE_COL = "namespace"; private static final String APP_GENERATION_COL = "app_generation"; private static final String APP_NAME_COL = "app_name"; private static final String INSTANCE_ID_COL = "instance_id"; private static final String OFFSET_COL = "offset_sequence"; private static final String UPDATED_COL = "last_updated"; public static final StructuredTableSpecification TABLE_SPEC = new StructuredTableSpecification.Builder() .withId(TABLE_ID) .withFields(new FieldType(NAMESPACE_COL, FieldType.Type.STRING), new FieldType(APP_GENERATION_COL, FieldType.Type.LONG), new FieldType(APP_NAME_COL, FieldType.Type.STRING), new FieldType(INSTANCE_ID_COL, FieldType.Type.INTEGER), new FieldType(OFFSET_COL, FieldType.Type.STRING), new FieldType(UPDATED_COL, FieldType.Type.LONG)) .withPrimaryKeys(NAMESPACE_COL, APP_NAME_COL, APP_GENERATION_COL, INSTANCE_ID_COL) .build(); private final StructuredTable table; private static final Gson GSON = new Gson(); private DBReplicationOffsetStore(StructuredTable table) { this.table = table; } static DBReplicationOffsetStore get(StructuredTableContext context) { try { StructuredTable table = context.getTable(TABLE_ID); return new DBReplicationOffsetStore(table); } catch (TableNotFoundException e) { throw new IllegalStateException(String.format( "System table '%s' does not exist. Please check your system environment.", TABLE_ID.getName()), e); } } @Nullable public OffsetAndSequence getOffsets(DeltaWorkerId id) throws IOException { List<Field<?>> keys = getKey(id); Optional<StructuredRow> row = table.read(keys); if (!row.isPresent() || row.get().getString(OFFSET_COL) == null) { return null; } String offsetStrJson = row.get().getString(OFFSET_COL); return GSON.fromJson(offsetStrJson, OffsetAndSequence.class); } public void writeOffset(DeltaWorkerId id, OffsetAndSequence data) throws IOException { Collection<Field<?>> fields = getKey(id); fields.add(Fields.stringField(OFFSET_COL, GSON.toJson(data))); fields.add(Fields.longField(UPDATED_COL, System.currentTimeMillis())); table.upsert(fields); } private List<Field<?>> getKey(DeltaWorkerId id) { List<Field<?>> keyFields = new ArrayList<>(4); keyFields.add(Fields.stringField(NAMESPACE_COL, id.getPipelineId().getNamespace())); keyFields.add(Fields.stringField(APP_NAME_COL, id.getPipelineId().getApp())); keyFields.add(Fields.longField(APP_GENERATION_COL, id.getPipelineId().getGeneration())); keyFields.add(Fields.intField(INSTANCE_ID_COL, id.getInstanceId())); return keyFields; } }
apache-2.0
qjafcunuas/jbromo
jbromo-lib/src/test/java/org/jbromo/common/test/common/EnumTestUtil.java
2245
/*- * Copyright (C) 2013-2014 The JBromo 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. */ package org.jbromo.common.test.common; import java.lang.reflect.Method; import org.jbromo.common.EnumUtil; import org.jbromo.common.invocation.InvocationException; import org.jbromo.common.invocation.InvocationUtil; import org.junit.Assert; import org.junit.Ignore; import lombok.AccessLevel; import lombok.NoArgsConstructor; /** * Enum test util class. * @author qjafcunuas */ @NoArgsConstructor(access = AccessLevel.PRIVATE) @Ignore public final class EnumTestUtil { /** * Tests valueOf method. * @param <E> the enum type. * @param enumClass the enum class. */ public static <E extends Enum<E>> void valueOf(final Class<E> enumClass) { E value; try { final Method method = InvocationUtil.getMethod(enumClass, "valueOf", String.class); for (final E one : EnumUtil.getValues(enumClass)) { value = InvocationUtil.invokeMethod(method, one, one.name()); Assert.assertEquals(one, value); } } catch (final InvocationException e) { Assert.fail(e.getMessage()); } } }
apache-2.0
evandor/skysail-framework
skysail.server.app.um.db/src/io/skysail/server/app/um/db/users/resources/UserResource.java
972
package io.skysail.server.app.um.db.users.resources; import io.skysail.api.links.Link; import io.skysail.api.responses.SkysailResponse; import io.skysail.server.app.um.db.UmApplication; import io.skysail.server.app.um.db.domain.User; import io.skysail.server.restlet.resources.EntityServerResource; import java.util.List; public class UserResource extends EntityServerResource<User> { private UmApplication app; protected void doInit() { app = (UmApplication) getApplication(); } public User getEntity() { return app.getUserRepository().findOne(getAttribute("id")); } public List<Link> getLinks() { return super.getLinks(PutUserResource.class); } public SkysailResponse<User> eraseEntity() { app.getUserRepository().delete(getAttribute("id")); return new SkysailResponse<>(); } @Override public String redirectTo() { return super.redirectTo(UsersResource.class); } }
apache-2.0
glassLake/MyVolleyPlus
app/src/main/java/com/hss01248/myvolleyplus/wrapper/CommonHelper.java
12163
package com.hss01248.myvolleyplus.wrapper; import android.text.TextUtils; import android.util.Log; import com.hss01248.myvolleyplus.config.BaseNetBean; import com.hss01248.myvolleyplus.config.ConfigInfo; import com.hss01248.myvolleyplus.config.NetConfig; import com.hss01248.myvolleyplus.retrofit.MyRetrofitUtil; import com.hss01248.myvolleyplus.retrofit.RetrofitAdapter; import com.hss01248.myvolleyplus.retrofit.RetrofitUtil2; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimerTask; /** * Created by Administrator on 2016/9/5 0005. */ public class CommonHelper { public static void addToken(Map map) { if (map != null){ map.put(NetConfig.TOKEN, NetConfig.getToken());//每一个请求都传递sessionid }else { map = new HashMap(); map.put(NetConfig.TOKEN, NetConfig.getToken());//每一个请求都传递sessionid } } public static String appendUrl(String urlTail,boolean isToAppend) { String url ; if (!isToAppend || urlTail.contains("http:")|| urlTail.contains("https:")){ url = urlTail; }else { url = NetConfig.baseUrl+ urlTail; } return url; } public static void parseStringResponseInTime(long time, final String response, final int method, final String url, final Map map, final ConfigInfo configInfo, final MyNetCallback myListener) { long time2 = System.currentTimeMillis(); long gap = time2 - time; if (configInfo.isForceMinTime && (gap < NetConfig.TIME_MINI)){ TimerUtil.doAfter(new TimerTask() { @Override public void run() { parseStringResponse(response,method,url,map,configInfo,myListener); } },(NetConfig.TIME_MINI - gap)); }else { parseStringResponse(response,method,url,map,configInfo,myListener); } } public static void parseErrorInTime(long time, final String error,final ConfigInfo configInfo, final MyNetCallback myListener) { long time2 = System.currentTimeMillis(); long gap = time2 - time; if (configInfo.isForceMinTime && (gap < NetConfig.TIME_MINI)){ TimerUtil.doAfter(new TimerTask() { @Override public void run() { myListener.onError(error); } },(NetConfig.TIME_MINI - gap)); }else { myListener.onError(error); } } private static void parseStringResponse(String response, int method, String urlTail, Map map, ConfigInfo configInfo, MyNetCallback myListener) { switch (configInfo.resonseType){ case ConfigInfo.TYPE_STRING: myListener.onSuccess(response,response); break; case ConfigInfo.TYPE_JSON:{ JSONObject jsonObject = null; try { jsonObject = new JSONObject(response); } catch (JSONException e) { e.printStackTrace(); myListener.onError("resonse is not a Json"); break; } myListener.onSuccess(jsonObject,response);} break; case ConfigInfo.TYPE_JSON_FORMATTED: JSONObject jsonObject = null; try { jsonObject = new JSONObject(response); } catch (JSONException e) { e.printStackTrace(); myListener.onError("resonse is not a Json"); break; } catch (NullPointerException e2){ e2.printStackTrace(); myListener.onError("resonse is null"); break; } String data = jsonObject.optString(NetConfig.KEY_DATA); String codeStr = jsonObject.optString(NetConfig.KEY_CODE); String msg = jsonObject.optString(NetConfig.KEY_MSG); int code = BaseNetBean.CODE_NONE; if (!TextUtils.isEmpty(codeStr) ){ try { code = Integer.parseInt(codeStr); }catch (Exception e){ } } parseStandardJsonResponse(jsonObject,response,data,code,msg, method, urlTail, map, configInfo, myListener); // myListener.onSuccess(jsonObject,response,data,code,msg); break; } } private static void parseStandardJsonResponse(JSONObject jsonObject, String response, String data, int code, String msg, final int method, final String urlTail, final Map map, final ConfigInfo configInfo, final MyNetCallback myListener) { switch (code){ case BaseNetBean.CODE_SUCCESS://请求成功 if (TextUtils.isEmpty(data) || "[]".equals(data) || "{}".equals(data) || "null".equals(data)) {//注意: 如果json里该字段返回null,那么optString拿到的就是字符化的"null" myListener.onEmpty(); } else { myListener.onSuccess(jsonObject,response,data,code,msg ); } break; case BaseNetBean.CODE_UN_FOUND://没有找到内容 myListener.onUnFound(); break; case BaseNetBean.CODE_UNLOGIN://未登录 //todo MyRetrofitUtil.autoLogin(new MyNetCallback() { @Override public void onSuccess(Object response, String resonseStr) { // todo sendRequest(method, urlTail, map, configInfo, myListener); RetrofitAdapter.getInstance().sendRequest(method,urlTail,map,configInfo,myListener); } @Override public void onError(String error) { super.onError(error); myListener.onUnlogin(); } }); break; default: myListener.onError(response.toString()); break; } } public static <E> void parseStandardJsonObj(BaseNetBean<E> baseBean, final String urlTail, final Map<String, String> params, final MyNetCallback<E> myListener, final RetrofitUtil2 retrofitUtil2){ switch (baseBean.code){ case BaseNetBean.CODE_SUCCESS://请求成功 /*{}: LinkedTreeMap, size = 0 会被解析成一个空对象 [] ArrayList sieze=0 会被解析成一个空的list * */ if (baseBean.data == null ) {//如果是{}或[]呢?data是否会为空? myListener.onEmpty(); } else { if (baseBean.data instanceof List){ List data = (List) baseBean.data; if (data.size() == 0){ myListener.onEmpty(); }else { myListener.onSuccess(baseBean.data,""); } }else { myListener.onSuccess(baseBean.data,"");//todo 空怎么搞? } } break; case BaseNetBean.CODE_UN_FOUND://没有找到内容 myListener.onUnFound(); break; case BaseNetBean.CODE_UNLOGIN://未登录 retrofitUtil2.autoLogin(new MyNetCallback() { @Override public void onSuccess(Object response, String resonseStr) { retrofitUtil2.postStandard(urlTail,params,myListener); } @Override public void onError(String error) { super.onError(error); myListener.onUnlogin(); } }); break; default: myListener.onError("code:"+baseBean.code + ", msg:"+baseBean.msg); break; } } public static boolean writeFile(final InputStream is, final String path,final MyNetCallback callback){ try { // todo change the file location/name according to your needs File futureStudioIconFile = new File(path); InputStream inputStream = null; OutputStream outputStream = null; try { byte[] fileReader = new byte[4096]; long fileSizeDownloaded = 0; inputStream = is; outputStream = new FileOutputStream(futureStudioIconFile); while (true) { int read = inputStream.read(fileReader); if (read == -1) { break; } outputStream.write(fileReader, 0, read); fileSizeDownloaded += read; Log.d("00", "file download: " + fileSizeDownloaded + " of " ); } outputStream.flush(); callback.onSuccess(path,path); return true; } catch (IOException e) { callback.onError(e.toString()); return false; } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } catch (IOException e) { callback.onError(e.toString()); return false; } /* SimpleTask task = new SimpleTask<String>() { @Override protected String doInBackground() { try { File file = new File(path); FileOutputStream fos = new FileOutputStream(file); BufferedInputStream bis = new BufferedInputStream(is); byte[] buffer = new byte[1024]; int len; while ((len = bis.read(buffer)) != -1) { fos.write(buffer, 0, len); fos.flush(); } fos.close(); bis.close(); is.close(); } catch (IOException e) { e.printStackTrace(); return e.toString(); } return path; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); if (!path.equals(s)){ callback.onError(s); }else { callback.onSuccess(path,path); } } }; task.execute();*/ } }
apache-2.0
dump247/aws-sdk-java
aws-java-sdk-devicefarm/src/main/java/com/amazonaws/services/devicefarm/model/transform/CreateUploadResultJsonUnmarshaller.java
2813
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.devicefarm.model.transform; import java.util.Map; import java.util.Map.Entry; import com.amazonaws.services.devicefarm.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * CreateUploadResult JSON Unmarshaller */ public class CreateUploadResultJsonUnmarshaller implements Unmarshaller<CreateUploadResult, JsonUnmarshallerContext> { public CreateUploadResult unmarshall(JsonUnmarshallerContext context) throws Exception { CreateUploadResult createUploadResult = new CreateUploadResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) return null; while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("upload", targetDepth)) { context.nextToken(); createUploadResult.setUpload(UploadJsonUnmarshaller .getInstance().unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals( currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return createUploadResult; } private static CreateUploadResultJsonUnmarshaller instance; public static CreateUploadResultJsonUnmarshaller getInstance() { if (instance == null) instance = new CreateUploadResultJsonUnmarshaller(); return instance; } }
apache-2.0
android-workloads/gcwfa
GC_workload_android/GCWA/build/generated/source/r/debug/com/intel/crtl/GCWA/R.java
9238
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.intel.crtl.GCWA; public final class R { public static final class attr { } public static final class color { public static final int result_color=0x7f070000; } public static final class dimen { public static final int activity_horizontal_margin=0x7f050000; public static final int activity_vertical_margin=0x7f050001; } public static final class drawable { public static final int ic_launcher=0x7f020000; } public static final class id { public static final int action_button=0x7f0a0039; public static final int activity_main=0x7f0a0000; public static final int activity_profile_config=0x7f0a000b; public static final int activity_result=0x7f0a0032; public static final int bucket_size_v=0x7f0a0010; public static final int button_confirm=0x7f0a000c; public static final int button_exe_time=0x7f0a0035; public static final int button_gc=0x7f0a0037; public static final int button_heap=0x7f0a0036; public static final int button_result=0x7f0a000a; public static final int button_set=0x7f0a0004; public static final int button_start=0x7f0a0005; public static final int buttons=0x7f0a0034; public static final int chart=0x7f0a0038; public static final int config_table=0x7f0a000e; public static final int exe_time_v=0x7f0a0031; public static final int execution_time=0x7f0a0009; public static final int lifetime_128_v=0x7f0a002b; public static final int lifetime_16_v=0x7f0a0028; public static final int lifetime_256_v=0x7f0a002c; public static final int lifetime_32_v=0x7f0a0029; public static final int lifetime_512_v=0x7f0a002d; public static final int lifetime_64_v=0x7f0a002a; public static final int lifetime_los_v=0x7f0a002e; public static final int los_dist_byte_v=0x7f0a0021; public static final int los_dist_char_v=0x7f0a0023; public static final int los_dist_desc_byte=0x7f0a0020; public static final int los_dist_desc_char=0x7f0a0022; public static final int los_dist_desc_int=0x7f0a0024; public static final int los_dist_desc_long=0x7f0a0026; public static final int los_dist_int_v=0x7f0a0025; public static final int los_dist_long_v=0x7f0a0027; public static final int los_threshold_v=0x7f0a0011; public static final int profile_list_view=0x7f0a0003; public static final int runtime_info=0x7f0a0008; public static final int scrollView1=0x7f0a000d; public static final int seek_bar=0x7f0a0001; public static final int single_thread=0x7f0a002f; public static final int size_desc_128=0x7f0a0018; public static final int size_desc_16=0x7f0a0012; public static final int size_desc_256=0x7f0a001a; public static final int size_desc_32=0x7f0a0014; public static final int size_desc_512=0x7f0a001c; public static final int size_desc_64=0x7f0a0016; public static final int size_desc_los=0x7f0a001e; public static final int size_dist_128_v=0x7f0a0019; public static final int size_dist_16_v=0x7f0a0013; public static final int size_dist_256_v=0x7f0a001b; public static final int size_dist_32_v=0x7f0a0015; public static final int size_dist_512_v=0x7f0a001d; public static final int size_dist_64_v=0x7f0a0017; public static final int size_dist_los_v=0x7f0a001f; public static final int thread_num=0x7f0a0030; public static final int total_size_v=0x7f0a000f; public static final int vm_type=0x7f0a0033; public static final int workload_result_layout=0x7f0a0007; public static final int workload_setting_layout=0x7f0a0002; public static final int workload_status=0x7f0a0006; } public static final class layout { public static final int activity_main=0x7f030000; public static final int activity_profile_config=0x7f030001; public static final int activity_result=0x7f030002; } public static final class menu { public static final int main=0x7f090000; } public static final class raw { public static final int profile=0x7f040000; } public static final class string { public static final int action_settings=0x7f080000; public static final int app_name=0x7f080001; public static final int bucket_size_default=0x7f080002; public static final int bucket_size_desc=0x7f080003; public static final int button_desc=0x7f080004; public static final int complete_time_desc=0x7f080005; public static final int exe_time_default=0x7f080006; public static final int exe_time_desc=0x7f080007; public static final int execution_time_desc=0x7f080008; public static final int fragment_default=0x7f080009; public static final int fragment_desc=0x7f08000a; public static final int gc_desc=0x7f08000b; public static final int heap_desc=0x7f08000c; public static final int lifetime_128_default=0x7f08000d; public static final int lifetime_16_default=0x7f08000e; public static final int lifetime_256_default=0x7f08000f; public static final int lifetime_32_default=0x7f080010; public static final int lifetime_512_default=0x7f080011; public static final int lifetime_64_default=0x7f080012; public static final int lifetime_desc=0x7f080013; public static final int lifetime_los_default=0x7f080014; public static final int lifetime_smallobject_default=0x7f080015; public static final int los_dist_byte_default=0x7f080016; public static final int los_dist_byte_desc=0x7f080017; public static final int los_dist_char_default=0x7f080018; public static final int los_dist_char_desc=0x7f080019; public static final int los_dist_desc=0x7f08001a; public static final int los_dist_int_default=0x7f08001b; public static final int los_dist_int_desc=0x7f08001c; public static final int los_dist_long_default=0x7f08001d; public static final int los_dist_long_desc=0x7f08001e; public static final int los_threshold_default=0x7f08001f; public static final int los_threshold_desc=0x7f080020; public static final int object_size_128_desc=0x7f080021; public static final int object_size_16_desc=0x7f080022; public static final int object_size_256_desc=0x7f080023; public static final int object_size_32_desc=0x7f080024; public static final int object_size_512_desc=0x7f080025; public static final int object_size_64_desc=0x7f080026; public static final int object_size_dist_desc=0x7f080027; public static final int object_size_los_desc=0x7f080028; public static final int object_size_smaollobject_desc=0x7f080029; public static final int outofmemory_desc=0x7f08002a; public static final int profile_list_dest=0x7f08002b; public static final int runtime_desc=0x7f08002c; public static final int set_profile_button_desc=0x7f08002d; public static final int setting_confirm_button_desc=0x7f08002e; public static final int show_result_button_desc=0x7f08002f; public static final int single_thread_desc=0x7f080030; public static final int size_dist_128_default=0x7f080031; public static final int size_dist_16_default=0x7f080032; public static final int size_dist_256_default=0x7f080033; public static final int size_dist_32_default=0x7f080034; public static final int size_dist_512_default=0x7f080035; public static final int size_dist_64_default=0x7f080036; public static final int size_dist_los_default=0x7f080037; public static final int start_button_desc=0x7f080038; public static final int thread_num_default=0x7f080039; public static final int thread_num_desc=0x7f08003a; public static final int total_size_default=0x7f08003b; public static final int total_size_desc=0x7f08003c; public static final int workload_status_desc=0x7f08003d; } public static final class style { /** API 11 theme customizations can go here. API 14 theme customizations can go here. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. */ public static final int AppBaseTheme=0x7f060000; /** All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f060001; } }
apache-2.0
mtendu/cosc603-tendulkar-project2
Monopoly/Monopoly/src/edu/towson/cis/cosc603/project2/monopoly/gui/UtilCellInfoFormatter.java
1011
package edu.towson.cis.cosc603.project2.monopoly.gui; import edu.towson.cis.cosc603.project2.monopoly.Cell; import edu.towson.cis.cosc603.project2.monopoly.Player; import edu.towson.cis.cosc603.project2.monopoly.UtilityCell; // TODO: Auto-generated Javadoc /** * The Class UtilCellInfoFormatter. */ public class UtilCellInfoFormatter extends OwnerName implements CellInfoFormatter { /* (non-Javadoc) * @see edu.towson.cis.cosc603.project2.monopoly.gui.CellInfoFormatter#format(edu.towson.cis.cosc603.project2.monopoly.Cell) */ public String format(Cell cell) { UtilityCell c = (UtilityCell)cell; StringBuffer buf = new StringBuffer(); String ownerName = getOwnerName(cell); buf.append("<html><b><font color='olive'>") .append(cell.getName()) .append("</font></b><br>") .append("$").append(c.getPrice()) .append("<br>Owner: ").append(ownerName) .append("</html>"); return buf.toString(); } }
apache-2.0
meNESS/EasyIntro
library/src/main/java/io/github/meness/easyintro/EasyIntro.java
9883
/* * Copyright 2016 Alireza Eskandarpour Shoferi * * 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.github.meness.easyintro; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.annotation.AnimRes; import android.support.annotation.CallSuper; import android.support.annotation.ColorInt; import android.support.annotation.DrawableRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RawRes; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.view.View; import io.github.meness.easyintro.enums.IndicatorContainer; import io.github.meness.easyintro.enums.PageIndicator; import io.github.meness.easyintro.enums.SlideTransformer; import io.github.meness.easyintro.enums.ToggleIndicator; import io.github.meness.easyintro.interfaces.IConfigMultiple; import io.github.meness.easyintro.interfaces.IConfigOnActivity; import io.github.meness.easyintro.listeners.EasyIntroInteractionsListener; public abstract class EasyIntro extends AppCompatActivity implements EasyIntroInteractionsListener, IConfigMultiple, IConfigOnActivity { public static final String TAG = EasyIntro.class.getSimpleName(); private EasyIntroCarouselFragment carouselFragment; @Override public void onPreviousSlide() { // empty } @Override public void onNextSlide() { // empty } @Override public void onDonePressed() { // empty } @Override public void onSkipPressed() { // empty } protected final EasyIntroCarouselFragment getCarouselFragment() { return carouselFragment; } /** * Only Activity has this special callback method * Fragment doesn't have any onBackPressed callback * <p/> * Logic: * Each time when the back button is pressed, this Activity will propagate the call to the * container Fragment and that Fragment will propagate the call to its each tab Fragment * those Fragments will propagate this method call to their child Fragments and * eventually all the propagated calls will get back to this initial method * <p/> * If the container Fragment or any of its Tab Fragments and/or Tab child Fragments couldn't * handle the onBackPressed propagated call then this Activity will handle the callback itself */ @Override @CallSuper public void onBackPressed() { if (!carouselFragment.onBackPressed()) { // container Fragment or its associates couldn't handle the back pressed task // delegating the task to super class super.onBackPressed(); } // else: carousel handled the back pressed task // do not call super } @Override @CallSuper public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_easyintro_main); initCarousel(savedInstanceState); } private void initCarousel(Bundle savedInstanceState) { if (savedInstanceState == null) { // withholding the previously created fragment from being created again // On orientation change, it will prevent fragment recreation // its necessary to reserve the fragment stack inside each tab // Creating the ViewPager container fragment once carouselFragment = (EasyIntroCarouselFragment) EasyIntroCarouselFragment.instantiate(getApplicationContext(), EasyIntroCarouselFragment.class.getName()); carouselFragment.setInteractionsListener(this); getSupportFragmentManager().beginTransaction() .replace(R.id.container, carouselFragment) .commit(); } else { // restoring the previously created fragment // and getting the reference carouselFragment = (EasyIntroCarouselFragment) getSupportFragmentManager().getFragments().get(0); } } @Override @CallSuper public void onCarouselViewCreated(View view, @Nullable Bundle savedInstanceState) { initIntro(); } protected abstract void initIntro(); @Override public void withTranslucentStatusBar(boolean b) { carouselFragment.withTranslucentStatusBar(b); } @Override public void withStatusBarColor(@ColorInt int statusBarColor) { carouselFragment.withStatusBarColor(statusBarColor); } @Override public void withOffScreenPageLimit(int limit) { carouselFragment.withOffScreenPageLimit(limit); } @Override public void withTransparentStatusBar(boolean b) { carouselFragment.withTransparentStatusBar(b); } @Override public void withTransparentNavigationBar(boolean b) { carouselFragment.withTransparentNavigationBar(b); } @Override public void withFullscreen(boolean b) { carouselFragment.withFullscreen(b); } @Override public void withTranslucentNavigationBar(boolean b) { carouselFragment.withTranslucentNavigationBar(b); } @Override public void withSlideTransformer(SlideTransformer transformer) { carouselFragment.withSlideTransformer(transformer); } @Override public void withToggleIndicator(ToggleIndicator indicators) { carouselFragment.withToggleIndicator(indicators); } @Override public void withVibrateOnSlide(int intensity) { carouselFragment.withVibrateOnSlide(intensity); } @Override public void withVibrateOnSlide() { carouselFragment.withVibrateOnSlide(); } @Override public void withRtlSupport() { carouselFragment.withRtlSupport(); } @Override public void withPageMargin(int marginPixels) { carouselFragment.withPageMargin(marginPixels); } @Override public void setPageMarginDrawable(Drawable d) { carouselFragment.setPageMarginDrawable(d); } @Override public void setPageMarginDrawable(@DrawableRes int resId) { carouselFragment.setPageMarginDrawable(resId); } @Override public void withToggleIndicatorSoundEffects(boolean b) { carouselFragment.withToggleIndicatorSoundEffects(b); } @Override public void withSlideSound(@RawRes int sound) { carouselFragment.withSlideSound(sound); } @Override public void withOverScrollMode(int mode) { carouselFragment.withOverScrollMode(mode); } @Override public void withPageIndicator(PageIndicator pageIndicator) { carouselFragment.withPageIndicator(pageIndicator); } @Override public void withIndicatorContainer(IndicatorContainer container) { carouselFragment.withIndicatorContainer(container); } @Override public void withIndicatorContainer(@LayoutRes int resId) { carouselFragment.withIndicatorContainer(resId); } @Override public void withRightIndicatorDisabled(boolean b) { carouselFragment.withRightIndicatorDisabled(b); } @Override public void withIndicatorContainerGravity(int gravity) { carouselFragment.withIndicatorContainerGravity(gravity); } @Override public void withSlide(Fragment slide) { carouselFragment.withSlide(slide); } @Override public void withLeftIndicatorDisabled(boolean b) { carouselFragment.withLeftIndicatorDisabled(b); } @Override public void withPageIndicator(@LayoutRes int resId) { carouselFragment.withPageIndicator(resId); } @Override public void withOverlaySlideAnimation(@AnimRes int enter, @AnimRes int exit, @AnimRes int popEnter, @AnimRes int popExit) { carouselFragment.withOverlaySlideAnimation(enter, exit, popEnter, popExit); } @Override public void withSlideBackPressSupport(boolean b) { carouselFragment.withSlideBackPressSupport(b); } @Override public void withPageIndicatorVisibility(boolean b) { carouselFragment.withPageIndicatorVisibility(b); } @Override public void withRightIndicatorDisabled(boolean b, @NonNull Class slide) { carouselFragment.withRightIndicatorDisabled(b, slide); } @Override public void withLeftIndicatorDisabled(boolean b, @NonNull Class slide) { carouselFragment.withLeftIndicatorDisabled(b, slide); } @Override public void withBothIndicatorsDisabled(boolean b, Class slide) { carouselFragment.withBothIndicatorsDisabled(b, slide); } @Override public void withNextSlide(boolean smoothScroll) { carouselFragment.withNextSlide(smoothScroll); } @Override public void withPreviousSlide(boolean smoothScroll) { carouselFragment.withPreviousSlide(smoothScroll); } @Override public void withSlideTo(int page, boolean smoothScroll) { carouselFragment.withSlideTo(page, smoothScroll); } @Override public Fragment getCurrentSlide() { return carouselFragment.getCurrentSlide(); } @Override public void withSlideTo(Class slideClass, boolean smoothScroll) { carouselFragment.withSlideTo(slideClass, smoothScroll); } }
apache-2.0
apacheignite/ignite
modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableMemoryAllocatorChunk.java
3228
/* * 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.portable.streams; import org.apache.ignite.internal.util.GridUnsafe; import org.apache.ignite.internal.util.typedef.internal.U; import sun.misc.Unsafe; import static org.apache.ignite.IgniteSystemProperties.IGNITE_MARSHAL_BUFFERS_RECHECK; /** * Memory allocator chunk. */ public class PortableMemoryAllocatorChunk { /** Unsafe instance. */ protected static final Unsafe UNSAFE = GridUnsafe.unsafe(); /** Array offset: byte. */ protected static final long BYTE_ARR_OFF = UNSAFE.arrayBaseOffset(byte[].class); /** Buffer size re-check frequency. */ private static final Long CHECK_FREQ = Long.getLong(IGNITE_MARSHAL_BUFFERS_RECHECK, 10000); /** Data array */ private byte[] data; /** Max message size detected between checks. */ private int maxMsgSize; /** Last time array size is checked. */ private long lastCheck = U.currentTimeMillis(); /** Whether the holder is acquired or not. */ private boolean acquired; /** * Allocate. * * @param size Desired size. * @return Data. */ public byte[] allocate(int size) { if (acquired) return new byte[size]; acquired = true; if (data == null || size > data.length) data = new byte[size]; return data; } /** * Reallocate. * * @param data Old data. * @param size Size. * @return New data. */ public byte[] reallocate(byte[] data, int size) { byte[] newData = new byte[size]; if (this.data == data) this.data = newData; UNSAFE.copyMemory(data, BYTE_ARR_OFF, newData, BYTE_ARR_OFF, data.length); return newData; } /** * Shrinks array size if needed. */ public void release(byte[] data, int maxMsgSize) { if (this.data != data) return; if (maxMsgSize > this.maxMsgSize) this.maxMsgSize = maxMsgSize; this.acquired = false; long now = U.currentTimeMillis(); if (now - this.lastCheck >= CHECK_FREQ) { int halfSize = data.length >> 1; if (this.maxMsgSize < halfSize) this.data = new byte[halfSize]; this.lastCheck = now; } } /** * @return {@code True} if acquired. */ public boolean isAcquired() { return acquired; } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/MqttContext.java
9309
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.iot.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Specifies the MQTT context to use for the test authorizer request * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class MqttContext implements Serializable, Cloneable, StructuredPojo { /** * <p> * The value of the <code>username</code> key in an MQTT authorization request. * </p> */ private String username; /** * <p> * The value of the <code>password</code> key in an MQTT authorization request. * </p> */ private java.nio.ByteBuffer password; /** * <p> * The value of the <code>clientId</code> key in an MQTT authorization request. * </p> */ private String clientId; /** * <p> * The value of the <code>username</code> key in an MQTT authorization request. * </p> * * @param username * The value of the <code>username</code> key in an MQTT authorization request. */ public void setUsername(String username) { this.username = username; } /** * <p> * The value of the <code>username</code> key in an MQTT authorization request. * </p> * * @return The value of the <code>username</code> key in an MQTT authorization request. */ public String getUsername() { return this.username; } /** * <p> * The value of the <code>username</code> key in an MQTT authorization request. * </p> * * @param username * The value of the <code>username</code> key in an MQTT authorization request. * @return Returns a reference to this object so that method calls can be chained together. */ public MqttContext withUsername(String username) { setUsername(username); return this; } /** * <p> * The value of the <code>password</code> key in an MQTT authorization request. * </p> * <p> * The AWS SDK for Java performs a Base64 encoding on this field before sending this request to the AWS service. * Users of the SDK should not perform Base64 encoding on this field. * </p> * <p> * Warning: ByteBuffers returned by the SDK are mutable. Changes to the content or position of the byte buffer will * be seen by all objects that have a reference to this object. It is recommended to call ByteBuffer.duplicate() or * ByteBuffer.asReadOnlyBuffer() before using or reading from the buffer. This behavior will be changed in a future * major version of the SDK. * </p> * * @param password * The value of the <code>password</code> key in an MQTT authorization request. */ public void setPassword(java.nio.ByteBuffer password) { this.password = password; } /** * <p> * The value of the <code>password</code> key in an MQTT authorization request. * </p> * <p> * {@code ByteBuffer}s are stateful. Calling their {@code get} methods changes their {@code position}. We recommend * using {@link java.nio.ByteBuffer#asReadOnlyBuffer()} to create a read-only view of the buffer with an independent * {@code position}, and calling {@code get} methods on this rather than directly on the returned {@code ByteBuffer}. * Doing so will ensure that anyone else using the {@code ByteBuffer} will not be affected by changes to the * {@code position}. * </p> * * @return The value of the <code>password</code> key in an MQTT authorization request. */ public java.nio.ByteBuffer getPassword() { return this.password; } /** * <p> * The value of the <code>password</code> key in an MQTT authorization request. * </p> * <p> * The AWS SDK for Java performs a Base64 encoding on this field before sending this request to the AWS service. * Users of the SDK should not perform Base64 encoding on this field. * </p> * <p> * Warning: ByteBuffers returned by the SDK are mutable. Changes to the content or position of the byte buffer will * be seen by all objects that have a reference to this object. It is recommended to call ByteBuffer.duplicate() or * ByteBuffer.asReadOnlyBuffer() before using or reading from the buffer. This behavior will be changed in a future * major version of the SDK. * </p> * * @param password * The value of the <code>password</code> key in an MQTT authorization request. * @return Returns a reference to this object so that method calls can be chained together. */ public MqttContext withPassword(java.nio.ByteBuffer password) { setPassword(password); return this; } /** * <p> * The value of the <code>clientId</code> key in an MQTT authorization request. * </p> * * @param clientId * The value of the <code>clientId</code> key in an MQTT authorization request. */ public void setClientId(String clientId) { this.clientId = clientId; } /** * <p> * The value of the <code>clientId</code> key in an MQTT authorization request. * </p> * * @return The value of the <code>clientId</code> key in an MQTT authorization request. */ public String getClientId() { return this.clientId; } /** * <p> * The value of the <code>clientId</code> key in an MQTT authorization request. * </p> * * @param clientId * The value of the <code>clientId</code> key in an MQTT authorization request. * @return Returns a reference to this object so that method calls can be chained together. */ public MqttContext withClientId(String clientId) { setClientId(clientId); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getUsername() != null) sb.append("Username: ").append(getUsername()).append(","); if (getPassword() != null) sb.append("Password: ").append(getPassword()).append(","); if (getClientId() != null) sb.append("ClientId: ").append(getClientId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof MqttContext == false) return false; MqttContext other = (MqttContext) obj; if (other.getUsername() == null ^ this.getUsername() == null) return false; if (other.getUsername() != null && other.getUsername().equals(this.getUsername()) == false) return false; if (other.getPassword() == null ^ this.getPassword() == null) return false; if (other.getPassword() != null && other.getPassword().equals(this.getPassword()) == false) return false; if (other.getClientId() == null ^ this.getClientId() == null) return false; if (other.getClientId() != null && other.getClientId().equals(this.getClientId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getUsername() == null) ? 0 : getUsername().hashCode()); hashCode = prime * hashCode + ((getPassword() == null) ? 0 : getPassword().hashCode()); hashCode = prime * hashCode + ((getClientId() == null) ? 0 : getClientId().hashCode()); return hashCode; } @Override public MqttContext clone() { try { return (MqttContext) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.iot.model.transform.MqttContextMarshaller.getInstance().marshall(this, protocolMarshaller); } }
apache-2.0
COBUAnalytics/libRandom
src/test/java/org/cobu/randomsamplers/KMeansSamplerTest.java
5663
package org.cobu.randomsamplers; import org.apache.commons.math3.ml.clustering.CentroidCluster; import org.apache.commons.math3.ml.clustering.DoublePoint; import org.apache.commons.math3.ml.distance.EuclideanDistance; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.List; import java.util.Random; public class KMeansSamplerTest { @Test public void testGetCentroidOneCluster() { int numberOfCentroids = 1; double[] randsToSelectSecond = {0.25, 0.5}; DoublePoint first = new DoublePoint(new double[]{.1, .2, .3}); DoublePoint second = new DoublePoint(new double[]{.1, .5, .3}); int sampleSize = 0; long populationSize = 2; KMeansSampler<DoublePoint> sampler = new KMeansSampler<DoublePoint>(new ArrayRandom(randsToSelectSecond), numberOfCentroids, sampleSize, Arrays.asList(first, second), populationSize, new EuclideanDistance()); final List<CentroidCluster<DoublePoint>> centroids = sampler.getCentroids(); Assert.assertEquals(1, centroids.size()); assertEquals(second.getPoint(), centroids.get(0).getCenter().getPoint()); } @Test public void testGetTwoCentroidsCluster() { int numberOfCentroids = 2; int sampleSize = 0; long populationSize = 3; double[] randsToSelectSecond = {0.00001, 0.99999, .0001, .99, .99, .99, 0.1, 0.1, 0.1}; DoublePoint secondCentroid = new DoublePoint(new double[]{.1, .2, .3}); DoublePoint fistCentroidPicked = new DoublePoint(new double[]{100, 300, 300}); DoublePoint closeToFirstCentroid = createVectorCloseBy(fistCentroidPicked); KMeansSampler<DoublePoint> sampler = new KMeansSampler<DoublePoint>(new ArrayRandom(randsToSelectSecond), numberOfCentroids, sampleSize, Arrays.asList(secondCentroid, fistCentroidPicked, closeToFirstCentroid), populationSize, new EuclideanDistance()); List<CentroidCluster<DoublePoint>> centroids = sampler.getCentroids(); Assert.assertEquals(2, centroids.size()); assertEquals(fistCentroidPicked.getPoint(), centroids.get(0).getCenter().getPoint()); assertEquals(secondCentroid.getPoint(), centroids.get(1).getCenter().getPoint()); } @Test public void testGetTwoCentroidsAndSample() { int numberOfCentroids = 2; int sizeOfSample = 2; double[] randsToSelectSecond = {0.25, 0.5, .001, .001, .001, 1e-16, 1.0, 0.5, 1e-16, 1e-16, 1e-8, 1e-16, .99, .99, .99, .99, .99, .99, .99, .99, .99, .99, .99, .99, .99, .99, .99, .99, .99, .99, .99, .99}; DoublePoint secondCentroid = new DoublePoint(new double[]{.1, .2, .3}); DoublePoint fistCentroidPicked = new DoublePoint(new double[]{.5, .5, .5}); DoublePoint closeToFirstCentroid = createVectorCloseBy(secondCentroid); DoublePoint closeToSecondCentroid = createVectorCloseBy(secondCentroid); DoublePoint farAway = new DoublePoint(new double[]{4, 5, 6}); DoublePoint fartherAway = new DoublePoint(new double[]{1, 1, 1}); long populationSize = 6; KMeansSampler<DoublePoint> sampler = new KMeansSampler<DoublePoint>(new ArrayRandom(randsToSelectSecond), numberOfCentroids, sizeOfSample, Arrays.asList(secondCentroid, fistCentroidPicked, closeToFirstCentroid, closeToSecondCentroid, farAway, fartherAway), populationSize, new EuclideanDistance()); List<CentroidCluster<DoublePoint>> centroids = sampler.getCentroids(); Assert.assertEquals(2, centroids.size()); assertEquals(fistCentroidPicked.getPoint(), centroids.get(0).getCenter().getPoint()); assertEquals(secondCentroid.getPoint(), centroids.get(1).getCenter().getPoint()); List<DoublePoint> samples1 = sampler.samples(); DoublePoint[] samples = samples1.toArray(new DoublePoint[samples1.size()]); Assert.assertEquals(2, samples.length); assertEquals(samples[0].getPoint(), farAway.getPoint()); assertEquals(samples[1].getPoint(), fartherAway.getPoint()); } @Test(expected = IllegalStateException.class) public void failsIfNotEnoughPointsForSample() { int numberOfCentroids = 1; double[] randsToSelectSecond = {0.25, 0.5}; DoublePoint first = new DoublePoint(new double[]{.1, .2, .3}); DoublePoint second = new DoublePoint(new double[]{.1, .5, .3}); long populationSize =2; new KMeansSampler<DoublePoint>(new ArrayRandom(randsToSelectSecond), numberOfCentroids, Integer.MAX_VALUE, Arrays.asList(first, second), populationSize, new EuclideanDistance()); } private DoublePoint createVectorCloseBy(DoublePoint vector) { double[] closeToVector = vector.getPoint(); double[] smallPerturbation = {.01, .02, .03}; for (int i = 0; i < closeToVector.length; i++) { closeToVector[i] += smallPerturbation[i]; } return new DoublePoint(closeToVector); } private void assertEquals(double[] a, double[] b) { Assert.assertEquals(a.length, b.length); for (int i = 0; i < a.length; i++) { Assert.assertEquals(a[i], b[i], 1.0E-9); } } private class ArrayRandom extends Random { private static final long serialVersionUID = 7161839673348881306L; private final double[] values; private int i; public ArrayRandom(double[] values) { this.values = values; } @Override public double nextDouble() { return values[i++]; } } }
apache-2.0
ihmcrobotics/ihmc-ros-control
src/main/java/us/ihmc/rosControl/wholeRobot/ForceTorqueSensorHandle.java
228
package us.ihmc.rosControl.wholeRobot; public interface ForceTorqueSensorHandle { double getTz(); double getTy(); double getTx(); double getFz(); double getFy(); double getFx(); String getName(); }
apache-2.0
sanlingdd/personalLinkedProfilesIn
linkedin-java/src/main/java/com/linkedin/automation/PeopleYouMayKnow.java
2429
package com.linkedin.automation; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class PeopleYouMayKnow { public void scrollThePage(WebDriver webDriver) { int sleepTime = 100; JavascriptExecutor js = (JavascriptExecutor) webDriver; js.executeScript("window.scrollTo(0, (document.body.scrollHeight)/2)"); sleep(sleepTime); js.executeScript("window.scrollTo(0, (document.body.scrollHeight)/6)"); sleep(sleepTime); } public void sleep(int time) { try { Thread.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) throws InterruptedException { PeopleYouMayKnow obj = new PeopleYouMayKnow(); WebDriver driver; System.setProperty("webdriver.chrome.driver", "/temp/chromedriver_win32/chromedriver.exe"); driver = new ChromeDriver(); driver.get("https://www.linkedin.com"); driver.manage().window().maximize(); WebElement account = driver.findElements(By.xpath(".//input[@id='login-email']")).get(0); account.sendKeys("17091275816"); driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS); WebElement pass = driver.findElement(By.xpath(".//input[@id='login-password']")); pass.sendKeys("hiro12345"); driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS); WebElement button = driver.findElement(By.xpath(".//input[@id='login-submit']")); button.click(); driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS); for (int i = 0; i < 50; i++) { driver.get("http://www.linkedin.com/mynetwork/"); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); int count = 0; while (true) { try { driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS); List<WebElement> elements = driver .findElements(By.xpath(".//button[@class='button-secondary-small']/span[text()='加为好友']")); if (!elements.isEmpty()) { elements.get(0).click(); driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS); Thread.sleep(10000); count++; } else { break; } } catch (Exception e) { break; } if (count % 6 == 0) { obj.scrollThePage(driver); } } } } }
apache-2.0
sismics/play-nativedb
app/helpers/db/filter/column/OrStringFilterColumn.java
1101
package helpers.db.filter.column; import org.apache.commons.lang.StringUtils; import java.util.ArrayList; import java.util.List; /** * Filter on a disjunction of string matches. * Instead of filtering on "column ~= filter", filters on (columns[0] ~= filter or ... or columns[n - 1] ~= filter). * * @author jtremeaux */ public class OrStringFilterColumn extends StringFilterColumn { private String[] columns; public OrStringFilterColumn(String column, String filter, String... columns) { super(column, filter); this.columns = columns; } @Override public String getPredicate() { List<String> predicates = new ArrayList<>(); for (String c : columns) { StringFilterColumn f = new StringFilterColumn(c, filter) { @Override public String getParamName() { return "filtercolumn_" + OrStringFilterColumn.this.hashCode(); } }; predicates.add(f.getPredicate()); } return "(" + StringUtils.join(predicates, " or ") + ")"; } }
apache-2.0
kamransaleem/waltz
waltz-data/src/main/java/com/khartec/waltz/data/complexity/ConnectionComplexityDao.java
5062
/* * Waltz - Enterprise Architecture * Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project * See README.md for more information * * 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 * */ package com.khartec.waltz.data.complexity; import com.khartec.waltz.model.EntityKind; import com.khartec.waltz.model.tally.ImmutableTally; import com.khartec.waltz.model.tally.Tally; import org.jooq.*; import org.jooq.impl.DSL; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.math.BigDecimal; import java.util.List; import static com.khartec.waltz.common.Checks.checkNotNull; import static com.khartec.waltz.data.logical_flow.LogicalFlowDao.LOGICAL_NOT_REMOVED; import static com.khartec.waltz.schema.tables.LogicalFlow.LOGICAL_FLOW; @Deprecated @Repository public class ConnectionComplexityDao { private static final Field<Integer> CONNECTION_COUNT_ALIAS = DSL.field("connection_count", Integer.class); private static final Field<Long> APP_ID_ALIAS = DSL.field("app_id", Long.class); private static final Field<Integer> TOTAL_CONNECTIONS_FIELD = DSL.field("total_connections", Integer.class); private static final Field<Long> SOURCE_APP_FIELD = LOGICAL_FLOW.SOURCE_ENTITY_ID.as(APP_ID_ALIAS); private static final Field<Long> TARGET_APP_FIELD = LOGICAL_FLOW.TARGET_ENTITY_ID.as(APP_ID_ALIAS); private static final Field<Integer> TARGET_COUNT_FIELD = DSL.countDistinct(LOGICAL_FLOW.TARGET_ENTITY_ID).as(CONNECTION_COUNT_ALIAS); private static final Field<Integer> SOURCE_COUNT_FIELD = DSL.countDistinct(LOGICAL_FLOW.SOURCE_ENTITY_ID).as(CONNECTION_COUNT_ALIAS); private static final String APPLICATION_KIND = EntityKind.APPLICATION.name(); private static final Condition BOTH_ARE_APPLICATIONS_AND_NOT_REMOVED = LOGICAL_FLOW.SOURCE_ENTITY_KIND .eq(APPLICATION_KIND) .and(LOGICAL_FLOW.TARGET_ENTITY_KIND .eq(APPLICATION_KIND)) .and(LOGICAL_NOT_REMOVED); private static final SelectHavingStep<Record2<Long, Integer>> OUTBOUND_FLOWS = DSL.select(SOURCE_APP_FIELD, TARGET_COUNT_FIELD) .from(LOGICAL_FLOW) .where(BOTH_ARE_APPLICATIONS_AND_NOT_REMOVED) .groupBy(LOGICAL_FLOW.SOURCE_ENTITY_ID); private static final SelectHavingStep<Record2<Long, Integer>> INBOUND_FLOWS = DSL.select(TARGET_APP_FIELD, SOURCE_COUNT_FIELD) .from(LOGICAL_FLOW) .where(BOTH_ARE_APPLICATIONS_AND_NOT_REMOVED) .groupBy(LOGICAL_FLOW.TARGET_ENTITY_ID); private static final SelectHavingStep<Record2<Long, BigDecimal>> TOTAL_FLOW_COUNTS = DSL.select(APP_ID_ALIAS, DSL.sum(CONNECTION_COUNT_ALIAS).as(TOTAL_CONNECTIONS_FIELD)) .from(OUTBOUND_FLOWS.unionAll(INBOUND_FLOWS)) .groupBy(APP_ID_ALIAS); private DSLContext dsl; @Autowired public ConnectionComplexityDao(DSLContext dsl) { this.dsl = dsl; checkNotNull(dsl, "DSL cannot be null"); } // ---- convenience functions public int calculateBaseline() { return calculateBaseline(DSL.trueCondition()); } public int calculateBaseline(Select<Record1<Long>> appIdProvider) { return calculateBaseline(APP_ID_ALIAS.in(appIdProvider)); } public int calculateBaseline(Long appIds) { return calculateBaseline(APP_ID_ALIAS.in(appIds)); } public List<Tally<Long>> findCounts() { return findCounts(DSL.trueCondition()); } public List<Tally<Long>> findCounts(Select<Record1<Long>> appIdProvider) { return findCounts(APP_ID_ALIAS.in(appIdProvider)); } public List<Tally<Long>> findCounts(Long... appIds) { return findCounts(APP_ID_ALIAS.in(appIds)); } // ---- base queries private int calculateBaseline(Condition condition) { return dsl.select(DSL.max(TOTAL_CONNECTIONS_FIELD)) .from(TOTAL_FLOW_COUNTS) .where(condition) .fetchOptional(0, Integer.class) .orElse(0); } private List<Tally<Long>> findCounts(Condition condition) { return dsl.select(APP_ID_ALIAS, TOTAL_CONNECTIONS_FIELD) .from(TOTAL_FLOW_COUNTS) .where(condition) .fetch(r -> ImmutableTally.<Long>builder() .id(r.value1()) .count(r.value2()) .build()); } }
apache-2.0
Cervator/DestinationSol
main/src/com/miloshpetrov/sol2/common/SolColorUtil.java
3119
package com.miloshpetrov.sol2.common; import com.badlogic.gdx.graphics.Color; public class SolColorUtil { public static void fromHSB(float hue, float saturation, float brightness, float a, Color dest) { float r = 0, g = 0, b = 0; if (saturation == 0) { r = g = b = brightness; } else { float h = (hue - (float)Math.floor(hue)) * 6.0f; float f = h - (float) Math.floor(h); float p = brightness * (1.0f - saturation); float q = brightness * (1.0f - saturation * f); float t = brightness * (1.0f - (saturation * (1.0f - f))); switch ((int) h) { case 0: r = brightness; g = t; b = p; break; case 1: r = q; g = brightness; b = p; break; case 2: r = p; g = brightness; b = t; break; case 3: r = p; g = q; b = brightness; break; case 4: r = t; g = p; b = brightness; break; case 5: r = brightness; g = p; b = q; break; } } dest.r = r; dest.g = g; dest.b = b; dest.a = a; } public static float[] toHSB(Color src) { int r = (int)(src.r * 255 + .5f); int g = (int)(src.g * 255 + .5f); int b = (int)(src.b * 255 + .5f); float hue, saturation, brightness; int cmax = (r > g) ? r : g; if (b > cmax) cmax = b; int cmin = (r < g) ? r : g; if (b < cmin) cmin = b; brightness = ((float) cmax) / 255.0f; if (cmax != 0) saturation = ((float) (cmax - cmin)) / ((float) cmax); else saturation = 0; if (saturation == 0) hue = 0; else { float redc = ((float) (cmax - r)) / ((float) (cmax - cmin)); float greenc = ((float) (cmax - g)) / ((float) (cmax - cmin)); float bluec = ((float) (cmax - b)) / ((float) (cmax - cmin)); if (r == cmax) hue = bluec - greenc; else if (g == cmax) hue = 2.0f + redc - bluec; else hue = 4.0f + greenc - redc; hue = hue / 6.0f; if (hue < 0) hue = hue + 1.0f; } float[] hsba = new float[4]; hsba[0] = hue; hsba[1] = saturation; hsba[2] = brightness; hsba[3] = src.a; return hsba; } public static Color load(String s) { String[] parts = s.split(" "); boolean hsb = "hsb".equals(parts[0]); int idx = hsb ? 1 : 0; int v1 = Integer.parseInt(parts[idx++]); int v2 = Integer.parseInt(parts[idx++]); int v3 = Integer.parseInt(parts[idx++]); float a = 1; if (parts.length > idx) a = Integer.parseInt(parts[idx]) / 255f; Color res = new Color(); if (hsb) { fromHSB(v1/360f, v2/100f, v3/100f, a, res); } else { res.set(v1/255f, v2/255f, v3/255f, a); } return res; } public static void changeBrightness(Color c, float b) { if (b > 0) { float bi = 1 - b; c.r = 1 - bi * (1 - c.r); c.g = 1 - bi * (1 - c.g); c.b = 1 - bi * (1 - c.b); return; } float bi = 1 + b; c.r *= bi; c.g *= bi; c.b *= bi; } }
apache-2.0
clarenceV1/MyApp
app/src/main/java/com/wodejia/myapp/data/contacts/ContactsMenuDO.java
634
package com.wodejia.myapp.data.contacts; import java.io.Serializable; /** * Created by clarence on 16/9/2. */ public class ContactsMenuDO implements Serializable { private int key; private String value; private String title; public int getKey() { return key; } public void setKey(int key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
apache-2.0
rycaon/isis-base
amap_base/src/main/java/org/wicketstuff/gmap/geocoder/pojos/GeocoderAddress.java
2587
/* * * ============================================================================== * 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.wicketstuff.gmap.geocoder.pojos; import com.fasterxml.jackson.annotation.JsonProperty; /** * POJO for an entity in Google geocoders address_components Array <br/> * * <p> * See also: <a href="https://developers.google.com/maps/documentation/geocoding/?hl=en#Results"> * Google Geocoder Result Documentation</a><br/> * * <b>Note:</b><br/> * The most documentation in this class a have been adopted by Google documentation.<br/> * Say thank you to Google! * </p> * * @author Mathias Born - Contact: www.mathiasborn.de */ public class GeocoderAddress { /** full text description or name of the address component */ @JsonProperty("long_name") private String longName; /** an abbreviated textual name for the address component */ @JsonProperty("short_name") private String shortName; /** array indicating the type of the address component. */ private String[] types; /** * @return the longName */ public String getLongName() { return longName; } /** * Set the full text description or name of the address component * * @param longName * the longName to set */ public void setLongName(String longName) { this.longName = longName; } /** * Get the full text description or name of the address component * * @return the shortName */ public String getShortName() { return shortName; } /** * Set an abbreviated textual name for the address component * * @param shortName * the shortName to set */ public void setShortName(String shortName) { this.shortName = shortName; } /** * Get an array that indicating the type of the address component. * * @return the types */ public String[] getTypes() { return types; } /** * Set an array that indicating the type of the address component. * * @param types * the types to set */ public void setTypes(String[] types) { this.types = types; } }
apache-2.0
echopfcom/ECHO-Android-SDK
src/com/echopf/ECHODate.java
2110
/******* Copyright 2015 NeuroBASE,Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **********/ package com.echopf; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** * An ECHODate is the extended Date object for the SDK. */ public class ECHODate extends Date { private static final long serialVersionUID = 1L; /** * {@.en Constructs a new ECHODate.} * {@.ja 日時オブジェクトを現在時刻で生成します。} */ public ECHODate() { super(); } /** * {@.en Constructs a new ECHODate with an acceptable date string for the API.} * {@.ja APIの仕様に準拠した文字列形式の日時から、日時オブジェクトを生成します。} * @param s an acceptable date string for the API (e.g. "2015-02-20 00:00:00") */ public ECHODate(String s) throws ParseException { super(); DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); try { setTime(sdf.parse(s).getTime()); } catch (ParseException e) { throw e; } } /** * {@.en Converts this object to an acceptable date string for the API.} * {@.ja APIの仕様に準拠した文字列形式の日時へ変換します。} * @return the formatted date string for the ECHO API. */ public String toStringForECHO() { DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); return sdf.format(this); } }
apache-2.0
DSolyom/AndroidDSFramework
FrameworkV4/frameworkv4/src/main/java/ds/framework/v4/widget/LaizyImageFlipAnimationLayout.java
6588
/* Copyright 2014 Dániel Sólyom 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 ds.framework.v4.widget; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import ds.framework.v4.R; import ds.framework.v4.widget.LaizyImageView.LaizyImageViewInfo; import ds.framework.v4.widget.LaizyImageView.OnImageSetListener; public class LaizyImageFlipAnimationLayout extends FlipAnimationLayout { private LaizyImageViewInfo mImageInfo; private int mDirection = TOP_TO_BOTTOM; private int mNextImagePosition = 0; private int mNextLoadingPosition = 0; private LaizyImageView mNextImageView; private boolean mFirstImage = true; private boolean mShowingLoading = false; private boolean mNeedToShowLoading = false; private boolean mFlipFirst; private OnImageSetListener mOnImageSetListener = new OnImageSetListener() { @Override public void onDefaultSet(LaizyImageView view) { if (!view.getInfo().info.equals(mImageInfo.info)) { return; } onFinishedLoading(); } @Override public void onLoadingSet(LaizyImageView view) { if (!view.getInfo().info.equals(mImageInfo.info)) { return; } mShowingLoading = true; if (mNextImagePosition == mNextLoadingPosition) { // only happens when we are loading the first image and no need to flip ((LaizyImageView) getChildAt(0)).showLoading(mImageInfo); return; } // just animate in the loading image mNeedToShowLoading = true; showLoading(); } @Override public void onErrorSet(LaizyImageView view) { if (!view.getInfo().info.equals(mImageInfo.info)) { return; } onFinishedLoading(); } @Override public void onImageSet(LaizyImageView view) { if (!view.getInfo().info.equals(mImageInfo.info)) { return; } onFinishedLoading(); } }; public LaizyImageFlipAnimationLayout(Context context) { this(context, null); } public LaizyImageFlipAnimationLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public LaizyImageFlipAnimationLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DsView, defStyle, 0); mFlipFirst = a.getBoolean(R.styleable.DsView_flip_first, true); a.recycle(); } /** * create third image view which will be used to lazy-load the images * * @param context * @return */ protected LaizyImageView createThirdImageView(Context context) { return new LaizyImageView(context); } public void reset() { stop(); setCurrentChild(0); mFirstImage = true; } /** * * @param always */ public void flipAlways(boolean always) { mFlipFirst = always; } /** * * @param info */ public void loadImage(LaizyImageViewInfo info) { if (mImageInfo != null && (info == null || info.info.equals(mImageInfo.info))) { // already loading / loaded this image return; } stop(); if (getChildCount() < 3) { for(int i = getChildCount(); i < 3; ++i) { final LaizyImageView thirdView = createThirdImageView(getContext()); addView(thirdView); } } mNeedToShowLoading = false; mImageInfo = info; info.needFading = false; // load the image if (mFirstImage) { // first image to load mNextLoadingPosition = mNextImagePosition = 1; // act like we are showing loading so we could do the flip even for the first image mShowingLoading = mFlipFirst; mFirstImage = false; } else { // load to the next empty position mNextImagePosition = advancePosition(getCurrentChildPosition()); // the current third position which is not showing and not used to // load into it will be the only empty position we can have mNextLoadingPosition = advancePosition(mNextImagePosition); } mNextImageView = (LaizyImageView) getChildAt(mNextImagePosition); mNextImageView.setOnImageSetListener(mOnImageSetListener); mNextImageView.reset(); mNextImageView.load(mImageInfo); } /** * */ public void stop() { mNeedToShowLoading = false; mShowingLoading = false; if (mNextImageView != null) { mNextImageView.stopLoading(); mNextImageView.setOnImageSetListener(null); } mNextImageView = null; mImageInfo = null; super.cancel(); } /** * * @param direction */ public void setDirection(int direction) { assert(direction >= 0 && direction < DIRECTIONS.length); mDirection = direction; } @Override void setState(int state) { super.setState(state); if (mNeedToShowLoading && state == STATE_CALM) { // still loading the image and the previous flip is finished // show loading showLoading(); } } /** * */ private void showLoading() { if (!mNeedToShowLoading) { return; } if (getState() == STATE_ANIMATING) { // wait for the previous animation to finish when loading return; } mNeedToShowLoading = false; ((LaizyImageView) getChildAt(mNextLoadingPosition)).showLoading(mImageInfo); start(mDirection, mNextLoadingPosition); } /** * */ private void onFinishedLoading() { if (getCurrentChildPosition() == mNextImagePosition) { // we are showing the image that just finished loading so nothing to do // except we cancel the animation if there was any // this would look messy if animating but mostly it is not the case cancel(); return; } if (!mShowingLoading) { // there was no need to show loading - image was right there // just switch without animation setCurrentChild(mNextImagePosition); } else { // flip to the loaded image start(mDirection, mNextImagePosition); } mNextImageView.setOnImageSetListener(null); } /** * * @param resource */ public void setCurrentTo(int resId) { stop(); ((LaizyImageView) getCurrentChild()).setImageResource(resId); } /** * */ private int advancePosition(int position) { position++; if (position > 2) { position = 0; } return position; } }
apache-2.0