hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
2691c1f9c5b4bf6f56effd67f4c9678e11e571de
1,240
/* * Copyright 2010-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * @author max */ package org.napile.idea.plugin; import org.jetbrains.annotations.NotNull; import org.napile.compiler.NXmlFileType; import org.napile.compiler.NapileFileType; import com.intellij.ide.highlighter.ZipArchiveFileType; import com.intellij.openapi.fileTypes.FileTypeConsumer; import com.intellij.openapi.fileTypes.FileTypeFactory; public class NapileFileFactory extends FileTypeFactory { @Override public void createFileTypes(@NotNull FileTypeConsumer consumer) { consumer.consume(NapileFileType.INSTANCE); consumer.consume(NXmlFileType.INSTANCE); consumer.consume(ZipArchiveFileType.INSTANCE, "nzip"); } }
29.52381
75
0.778226
90bfcb573f4264a6ac110ec1e4cabd35e3f713ca
1,632
/* * 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. */ /* INSERT HP DISCLAIMER HERE Dynamic intersection, May 2002, hedgehog */ package org.apache.jena.graph.compose; import org.apache.jena.graph.* ; import org.apache.jena.util.iterator.* ; /** The dynamic intersection of two graphs L and R. <code>add()</code> affects both L and R, whereas <code>delete()</code> affects L only. */ public class Intersection extends Dyadic implements Graph { public Intersection( Graph L, Graph R ) { super( L, R ); } @Override public void performAdd( Triple t ) { L.add( t ); R.add( t ); } @Override public void performDelete( Triple t ) { if (this.contains( t )) L.delete( t ); } @Override protected ExtendedIterator<Triple> _graphBaseFind( Triple s ) { return L.find( s ) .filterKeep( ifIn( R ) ); } }
28.631579
138
0.691789
2b94ae869a0dae6b22b7b2d620fc1f1bfb7d9341
629
package Exercicios; import java.util.ArrayList; import java.util.List; public class Ex6 { public static void main(String[] args) { List<Integer> numeros = new ArrayList<>(); List<Integer> numerosPares = new ArrayList<>(); numeros.add(2); numeros.add(3); numeros.add(5); numeros.add(8); numeros.add(9); numeros.add(11); for (int i = 0; i < numeros.size(); i++){ if ( numeros.get(i)%2 == 0){ numerosPares.add(numeros.get(i)); } } System.out.println(" Array de PAres é " + numerosPares); } }
24.192308
64
0.535771
676b09c9c502b7881464816157b1b799aa8b194e
305
package com.rexx.rra; import com.rexx.rra.registry.ModItems; import net.fabricmc.api.ModInitializer; public class rra implements ModInitializer { public static final String MOD_ID = "rra81206"; @Override public void onInitialize() { ModItems.registerItems(); } }
20.333333
52
0.685246
c2d57716d3038fffde1c1dafb23dd5e40c35a886
2,583
/** * Copyright (C) 2016-2019 Expedia 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.hotels.road.schema.gdpr; import static java.util.stream.Collectors.toList; import static org.apache.avro.Schema.Type.BYTES; import static org.apache.avro.Schema.Type.NULL; import static org.apache.avro.Schema.Type.STRING; import static org.apache.avro.Schema.Type.UNION; import java.util.Collection; import java.util.List; import org.apache.avro.Schema; import org.apache.avro.Schema.Field; import org.apache.avro.Schema.Type; import com.hotels.road.schema.SchemaTraverser.Visitor; public class PiiVisitor<T> implements Visitor<T> { public static final String SENSITIVITY = "sensitivity"; public static final String PII = "PII"; @Override public void onVisit(Schema schema, Collection<String> breadcrumb) { if (PII.equalsIgnoreCase(schema.getProp(SENSITIVITY))) { throw new InvalidPiiAnnotationException(breadcrumb); } } @Override public void onVisit(Field field, Collection<String> breadcrumb) { if (PII.equalsIgnoreCase(field.getProp(SENSITIVITY))) { Schema schema = field.schema(); if (!isStringOrBytes(schema) && !isNullableStringOrBytes(schema)) { throw new InvalidPiiAnnotationException(breadcrumb); } onPiiField(field, breadcrumb); } } @Override public T getResult() { return null; } /** * Override this for additional functionality when a PII field is found. */ protected void onPiiField(Field field, Collection<String> breadcrumb) {} private static boolean isStringOrBytes(Schema schema) { Type type = schema.getType(); return type == STRING || type == BYTES; } private static boolean isNullableStringOrBytes(Schema schema) { Type type = schema.getType(); if (type == UNION) { List<Type> types = schema.getTypes().stream().map(Schema::getType).collect(toList()); if (types.size() == 2 && types.contains(NULL) && (types.contains(STRING) || types.contains(BYTES))) { return true; } } return false; } }
31.5
107
0.716221
a91c7459558a40d518d7ab1f982fca749138b780
288
package net.sadovnikov.marvinbot.core.service.chat; import net.sadovnikov.marvinbot.core.domain.Channel; public abstract class AbstractChat { public boolean isGroupChat() { return false; } public abstract String chatId(); public abstract Channel channel(); }
19.2
52
0.725694
5592ad7c72529eb57d981f9f0b14468fc49f916e
3,382
/* * Copyright (C) 2015 Square, 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 keywhiz.cli.commands; import com.google.common.base.Throwables; import java.io.IOException; import java.util.List; import keywhiz.api.model.Client; import keywhiz.api.model.Group; import keywhiz.api.model.SanitizedSecret; import keywhiz.cli.Printing; import keywhiz.cli.configs.DescribeActionConfig; import keywhiz.client.KeywhizClient; import keywhiz.client.KeywhizClient.NotFoundException; import static java.lang.String.format; import static keywhiz.cli.Utilities.VALID_NAME_PATTERN; import static keywhiz.cli.Utilities.validName; public class DescribeAction implements Runnable { private final DescribeActionConfig describeActionConfig; private final KeywhizClient keywhizClient; private final Printing printing; public DescribeAction(DescribeActionConfig describeActionConfig, KeywhizClient client, Printing printing) { this.describeActionConfig = describeActionConfig; this.keywhizClient = client; this.printing = printing; } @Override public void run() { List<String> describeType = describeActionConfig.describeType; if (describeType == null || describeType.isEmpty()) { throw new IllegalArgumentException("Must specify a single type to describe."); } if (describeActionConfig.name == null || !validName(describeActionConfig.name)) { throw new IllegalArgumentException(format("Invalid name, must match %s", VALID_NAME_PATTERN)); } String firstType = describeType.get(0).toLowerCase().trim(); String name = describeActionConfig.name; switch (firstType) { case "group": try { Group group = keywhizClient.getGroupByName(name); printing.printGroupWithDetails(group); } catch (NotFoundException e) { throw new AssertionError("Group not found."); } catch (IOException e) { throw Throwables.propagate(e); } break; case "client": try { Client client = keywhizClient.getClientByName(name); printing.printClientWithDetails(client); } catch (NotFoundException e) { throw new AssertionError("Client not found."); } catch (IOException e) { throw Throwables.propagate(e); } break; case "secret": SanitizedSecret sanitizedSecret; try { sanitizedSecret = keywhizClient.getSanitizedSecretByName(name); printing.printSanitizedSecretWithDetails(sanitizedSecret); } catch (NotFoundException e) { throw new AssertionError("Secret not found."); } catch (IOException e) { throw Throwables.propagate(e); } break; default: throw new IllegalArgumentException("Invalid describe type specified: " + firstType); } } }
32.834951
100
0.703134
ced5c727cc78051997a0a1af353a1d48ed8787eb
3,632
package myy803.model.version; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import myy803.DocumentManager; import myy803.commons.Files; import myy803.model.Document; public class StableVersionStrategy implements VersionStrategy { private static final long serialVersionUID = -5795326622847220821L; private static final Pattern VERSION_FILES_PATTERN = Pattern.compile("version(\\d*)"); public StableVersionStrategy() { } @Override public void rollbackToPreviousVersion(Document document) throws NoPreviousVersionException { if (document.getVersionId() == 1) { throw new NoPreviousVersionException("Document " + document.getName() + " has no previous versions."); } File documentFolder = getDocumentVersionsFolder(document); File[] documents = documentFolder.listFiles(f -> f.getName().matches(VERSION_FILES_PATTERN.pattern())); if (documents.length == 0) { throw new NoPreviousVersionException("Document's previous versions cannot be found in disk."); } document.setVersionId(document.getVersionId() - 1); List<File> documentsList = Arrays.asList(documents); documentsList.sort((f1, f2) -> f1.getName().compareTo(f2.getName())); File lastVersion = documentsList.stream() .filter(f -> f.getName().toLowerCase().endsWith(String.valueOf(document.getVersionId()))).findFirst() .orElse(null); try { Document previousDocument = DocumentManager.INSTANCE.loadDocument(lastVersion); document.copyPropertiesFrom(previousDocument); } catch (ClassNotFoundException | IOException e) { System.out.println("Cannot load document from previous version."); e.printStackTrace(); } } @Override public List<Document> getPreviousVersions(Document document) { if (document.getVersionId() == 1) { return Collections.emptyList(); } File documentFolder = getDocumentVersionsFolder(document); File[] documents = documentFolder.listFiles(f -> isVersionFileWithIdSmallerThan(f, document.getVersionId())); if (documents.length == 0) { return Collections.emptyList(); } List<File> docFileList = Arrays.asList(documents); return docFileList.stream().map(t -> { try { return DocumentManager.INSTANCE.loadDocument(t); } catch (ClassNotFoundException | IOException e) { System.err.println("Cannot load document in order to get previous versions."); e.printStackTrace(); } return null; }).collect(Collectors.toList()); } private boolean isVersionFileWithIdSmallerThan(File file, int id) { Matcher m = VERSION_FILES_PATTERN.matcher(file.getName()); if (m.matches()) { String group1 = m.group(1); int vId = Integer.parseInt(group1); return vId < id; } return false; } @Override public void saveVersion(Document doc) { Document version = doc.clone(); version.setPath(new File(getDocumentVersionsFolder(doc), "version" + version.getVersionId())); try { DocumentManager.INSTANCE.saveDocument(version); } catch (IOException e) { System.out.println("Cannot save version for document: " + doc.getPath() + " in path:" + version.getPath()); e.printStackTrace(); } doc.setVersionId(doc.getVersionId() + 1); } private File getDocumentVersionsFolder(Document doc) { File documentFolder = new File(Files.VERSIONS_FOLDER, String.valueOf(doc.hashCode())); if (!documentFolder.exists()) documentFolder.mkdirs(); return documentFolder; } @Override public VersionStrategyType type() { return VersionStrategyType.STABLE; } }
33.321101
111
0.741189
d287b4804982c4310f84efbf385cd9dfe3add9c2
1,129
package com.robocon.leonardchin.capstone3.fragments; public class DoubleParkReport { public String latitude; public String longitude; public String car_plate; public String time; public String photoUrl; public DoubleParkReport(String latitude, String longitude, String car_plate, String time, String photoUrl) { this.latitude = latitude; this.longitude = longitude; this.car_plate = car_plate; this.time = time; this.photoUrl = photoUrl; } public DoubleParkReport() { } public String getLatitude() { return latitude; } public String getLongitude() { return longitude; } public void setcarPlate(String car_plate) { this.car_plate = car_plate; } public String getCar_plate() { return car_plate; } public void setTime(String time) { this.time = time; } public String getTime() { return time; } public String getPhotoUrl() { return photoUrl; } public void setPhotoUrl(String photoUrl) { this.photoUrl = photoUrl; } }
20.907407
112
0.630647
78d793cae636e6200f566b9c30c1d9e8bf79d5a0
925
package cn.lliiooll.opq.core.managers.event.data; import cn.lliiooll.opq.core.data.group.Group; import cn.lliiooll.opq.core.managers.event.Event; import cn.lliiooll.opq.core.managers.event.HandlerList; import lombok.Getter; /** * 好友请求事件 */ public class FriendRequestEvent extends Event { private static HandlerList handlers = new HandlerList(); @Getter public final long id; @Getter public final String question; @Getter public final boolean isFromGroup; @Getter public final Group fromGroup; public FriendRequestEvent(long id, String question, boolean isFromGroup, Group fromGroup) { this.id = id; this.question = question; this.isFromGroup = isFromGroup; this.fromGroup = fromGroup; } public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } }
23.125
95
0.694054
f863e38216364ddfb4625322d1b658ca6a6d9985
38,499
/* * 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.thrift; import static org.apache.hadoop.hbase.thrift.Constants.COALESCE_INC_KEY; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.net.InetAddress; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.CompatibilityFactory; import org.apache.hadoop.hbase.HBaseClassTestRule; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor; import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.RegionInfo; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.client.TableDescriptor; import org.apache.hadoop.hbase.client.TableDescriptorBuilder; import org.apache.hadoop.hbase.filter.ParseFilter; import org.apache.hadoop.hbase.security.UserProvider; import org.apache.hadoop.hbase.test.MetricsAssertHelper; import org.apache.hadoop.hbase.testclassification.ClientTests; import org.apache.hadoop.hbase.testclassification.LargeTests; import org.apache.hadoop.hbase.thrift.ThriftMetrics.ThriftServerType; import org.apache.hadoop.hbase.thrift.generated.BatchMutation; import org.apache.hadoop.hbase.thrift.generated.ColumnDescriptor; import org.apache.hadoop.hbase.thrift.generated.Hbase; import org.apache.hadoop.hbase.thrift.generated.IOError; import org.apache.hadoop.hbase.thrift.generated.Mutation; import org.apache.hadoop.hbase.thrift.generated.TAppend; import org.apache.hadoop.hbase.thrift.generated.TCell; import org.apache.hadoop.hbase.thrift.generated.TIncrement; import org.apache.hadoop.hbase.thrift.generated.TRegionInfo; import org.apache.hadoop.hbase.thrift.generated.TRowResult; import org.apache.hadoop.hbase.thrift.generated.TScan; import org.apache.hadoop.hbase.thrift.generated.TThriftServerType; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.TableDescriptorChecker; import org.apache.hadoop.hbase.util.Threads; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.TestName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Unit testing for ThriftServerRunner.HBaseServiceHandler, a part of the * org.apache.hadoop.hbase.thrift package. */ @Category({ClientTests.class, LargeTests.class}) public class TestThriftServer { @ClassRule public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestThriftServer.class); private static final HBaseTestingUtility UTIL = new HBaseTestingUtility(); private static final Logger LOG = LoggerFactory.getLogger(TestThriftServer.class); private static final MetricsAssertHelper metricsHelper = CompatibilityFactory .getInstance(MetricsAssertHelper.class); protected static final int MAXVERSIONS = 3; private static ByteBuffer asByteBuffer(String i) { return ByteBuffer.wrap(Bytes.toBytes(i)); } private static ByteBuffer asByteBuffer(long l) { return ByteBuffer.wrap(Bytes.toBytes(l)); } // Static names for tables, columns, rows, and values private static ByteBuffer tableAname = asByteBuffer("tableA"); private static ByteBuffer tableBname = asByteBuffer("tableB"); private static ByteBuffer columnAname = asByteBuffer("columnA:"); private static ByteBuffer columnAAname = asByteBuffer("columnA:A"); private static ByteBuffer columnBname = asByteBuffer("columnB:"); private static ByteBuffer rowAname = asByteBuffer("rowA"); private static ByteBuffer rowBname = asByteBuffer("rowB"); private static ByteBuffer valueAname = asByteBuffer("valueA"); private static ByteBuffer valueBname = asByteBuffer("valueB"); private static ByteBuffer valueCname = asByteBuffer("valueC"); private static ByteBuffer valueDname = asByteBuffer("valueD"); private static ByteBuffer valueEname = asByteBuffer(100L); @Rule public TestName name = new TestName(); @BeforeClass public static void beforeClass() throws Exception { UTIL.getConfiguration().setBoolean(COALESCE_INC_KEY, true); UTIL.getConfiguration().setBoolean(TableDescriptorChecker.TABLE_SANITY_CHECKS, false); UTIL.getConfiguration().setInt("hbase.client.retries.number", 3); UTIL.startMiniCluster(); } @AfterClass public static void afterClass() throws Exception { UTIL.shutdownMiniCluster(); } /** * Runs all of the tests under a single JUnit test method. We * consolidate all testing to one method because HBaseClusterTestCase * is prone to OutOfMemoryExceptions when there are three or more * JUnit test methods. */ @Test public void testAll() throws Exception { // Run all tests doTestTableCreateDrop(); doTestThriftMetrics(); doTestTableMutations(); doTestTableTimestampsAndColumns(); doTestTableScanners(); doTestGetTableRegions(); doTestFilterRegistration(); doTestGetRegionInfo(); doTestIncrements(); doTestAppend(); doTestCheckAndPut(); } /** * Tests for creating, enabling, disabling, and deleting tables. Also * tests that creating a table with an invalid column name yields an * IllegalArgument exception. */ public void doTestTableCreateDrop() throws Exception { ThriftHBaseServiceHandler handler = new ThriftHBaseServiceHandler(UTIL.getConfiguration(), UserProvider.instantiate(UTIL.getConfiguration())); doTestTableCreateDrop(handler); } public static void doTestTableCreateDrop(Hbase.Iface handler) throws Exception { createTestTables(handler); dropTestTables(handler); } public static final class MySlowHBaseHandler extends ThriftHBaseServiceHandler implements Hbase.Iface { protected MySlowHBaseHandler(Configuration c) throws IOException { super(c, UserProvider.instantiate(c)); } @Override public List<ByteBuffer> getTableNames() throws IOError { Threads.sleepWithoutInterrupt(3000); return super.getTableNames(); } } /** * TODO: These counts are supposed to be zero but sometimes they are not, they are equal to the * passed in maybe. Investigate why. My guess is they are set by the test that runs just * previous to this one. Sometimes they are cleared. Sometimes not. */ private int getCurrentCount(final String name, final int maybe, final ThriftMetrics metrics) { int currentCount = 0; try { metricsHelper.assertCounter(name, maybe, metrics.getSource()); LOG.info("Shouldn't this be null? name=" + name + ", equals=" + maybe); currentCount = maybe; } catch (AssertionError e) { // Ignore } return currentCount; } /** * Tests if the metrics for thrift handler work correctly */ public void doTestThriftMetrics() throws Exception { LOG.info("START doTestThriftMetrics"); Configuration conf = UTIL.getConfiguration(); ThriftMetrics metrics = getMetrics(conf); Hbase.Iface handler = getHandlerForMetricsTest(metrics, conf); int currentCountCreateTable = getCurrentCount("createTable_num_ops", 2, metrics); int currentCountDeleteTable = getCurrentCount("deleteTable_num_ops", 2, metrics); int currentCountDisableTable = getCurrentCount("disableTable_num_ops", 2, metrics); createTestTables(handler); dropTestTables(handler); metricsHelper.assertCounter("createTable_num_ops", currentCountCreateTable + 2, metrics.getSource()); metricsHelper.assertCounter("deleteTable_num_ops", currentCountDeleteTable + 2, metrics.getSource()); metricsHelper.assertCounter("disableTable_num_ops", currentCountDisableTable + 2, metrics.getSource()); handler.getTableNames(); // This will have an artificial delay. // 3 to 6 seconds (to account for potential slowness), measured in nanoseconds try { metricsHelper.assertGaugeGt("getTableNames_avg_time", 3L * 1000 * 1000 * 1000, metrics.getSource()); metricsHelper.assertGaugeLt("getTableNames_avg_time",6L * 1000 * 1000 * 1000, metrics.getSource()); } catch (AssertionError e) { LOG.info("Fix me! Why does this happen? A concurrent cluster running?", e); } } private static Hbase.Iface getHandlerForMetricsTest(ThriftMetrics metrics, Configuration conf) throws Exception { Hbase.Iface handler = new MySlowHBaseHandler(conf); return HbaseHandlerMetricsProxy.newInstance((ThriftHBaseServiceHandler)handler, metrics, conf); } private static ThriftMetrics getMetrics(Configuration conf) throws Exception { return new ThriftMetrics(conf, ThriftMetrics.ThriftServerType.ONE); } public static void createTestTables(Hbase.Iface handler) throws Exception { // Create/enable/disable/delete tables, ensure methods act correctly List<java.nio.ByteBuffer> bbs = handler.getTableNames(); assertEquals(bbs.stream().map(b -> Bytes.toString(b.array())). collect(Collectors.joining(",")), 0, bbs.size()); handler.createTable(tableAname, getColumnDescriptors()); assertEquals(1, handler.getTableNames().size()); assertEquals(2, handler.getColumnDescriptors(tableAname).size()); assertTrue(handler.isTableEnabled(tableAname)); handler.createTable(tableBname, getColumnDescriptors()); assertEquals(2, handler.getTableNames().size()); } public static void checkTableList(Hbase.Iface handler) throws Exception { assertTrue(handler.getTableNames().contains(tableAname)); } public static void dropTestTables(Hbase.Iface handler) throws Exception { handler.disableTable(tableBname); assertFalse(handler.isTableEnabled(tableBname)); handler.deleteTable(tableBname); assertEquals(1, handler.getTableNames().size()); handler.disableTable(tableAname); assertFalse(handler.isTableEnabled(tableAname)); /* TODO Reenable. assertFalse(handler.isTableEnabled(tableAname)); handler.enableTable(tableAname); assertTrue(handler.isTableEnabled(tableAname)); handler.disableTable(tableAname);*/ handler.deleteTable(tableAname); assertEquals(0, handler.getTableNames().size()); } public void doTestIncrements() throws Exception { ThriftHBaseServiceHandler handler = new ThriftHBaseServiceHandler(UTIL.getConfiguration(), UserProvider.instantiate(UTIL.getConfiguration())); createTestTables(handler); doTestIncrements(handler); dropTestTables(handler); } public static void doTestIncrements(ThriftHBaseServiceHandler handler) throws Exception { List<Mutation> mutations = new ArrayList<>(1); mutations.add(new Mutation(false, columnAAname, valueEname, true)); mutations.add(new Mutation(false, columnAname, valueEname, true)); handler.mutateRow(tableAname, rowAname, mutations, null); handler.mutateRow(tableAname, rowBname, mutations, null); List<TIncrement> increments = new ArrayList<>(3); increments.add(new TIncrement(tableAname, rowBname, columnAAname, 7)); increments.add(new TIncrement(tableAname, rowBname, columnAAname, 7)); increments.add(new TIncrement(tableAname, rowBname, columnAAname, 7)); int numIncrements = 60000; for (int i = 0; i < numIncrements; i++) { handler.increment(new TIncrement(tableAname, rowAname, columnAname, 2)); handler.incrementRows(increments); } Thread.sleep(1000); long lv = handler.get(tableAname, rowAname, columnAname, null).get(0).value.getLong(); // Wait on all increments being flushed while (handler.coalescer.getQueueSize() != 0) { Threads.sleep(10); } assertEquals((100 + (2 * numIncrements)), lv); lv = handler.get(tableAname, rowBname, columnAAname, null).get(0).value.getLong(); assertEquals((100 + (3 * 7 * numIncrements)), lv); assertTrue(handler.coalescer.getSuccessfulCoalescings() > 0); } /** * Tests adding a series of Mutations and BatchMutations, including a * delete mutation. Also tests data retrieval, and getting back multiple * versions. */ public void doTestTableMutations() throws Exception { ThriftHBaseServiceHandler handler = new ThriftHBaseServiceHandler(UTIL.getConfiguration(), UserProvider.instantiate(UTIL.getConfiguration())); doTestTableMutations(handler); } public static void doTestTableMutations(Hbase.Iface handler) throws Exception { // Setup handler.createTable(tableAname, getColumnDescriptors()); // Apply a few Mutations to rowA // mutations.add(new Mutation(false, columnAname, valueAname)); // mutations.add(new Mutation(false, columnBname, valueBname)); handler.mutateRow(tableAname, rowAname, getMutations(), null); // Assert that the changes were made assertEquals(valueAname, handler.get(tableAname, rowAname, columnAname, null).get(0).value); TRowResult rowResult1 = handler.getRow(tableAname, rowAname, null).get(0); assertEquals(rowAname, rowResult1.row); assertEquals(valueBname, rowResult1.columns.get(columnBname).value); // Apply a few BatchMutations for rowA and rowB // rowAmutations.add(new Mutation(true, columnAname, null)); // rowAmutations.add(new Mutation(false, columnBname, valueCname)); // batchMutations.add(new BatchMutation(rowAname, rowAmutations)); // Mutations to rowB // rowBmutations.add(new Mutation(false, columnAname, valueCname)); // rowBmutations.add(new Mutation(false, columnBname, valueDname)); // batchMutations.add(new BatchMutation(rowBname, rowBmutations)); handler.mutateRows(tableAname, getBatchMutations(), null); // Assert that changes were made to rowA List<TCell> cells = handler.get(tableAname, rowAname, columnAname, null); assertFalse(cells.size() > 0); assertEquals(valueCname, handler.get(tableAname, rowAname, columnBname, null).get(0).value); List<TCell> versions = handler.getVer(tableAname, rowAname, columnBname, MAXVERSIONS, null); assertEquals(valueCname, versions.get(0).value); assertEquals(valueBname, versions.get(1).value); // Assert that changes were made to rowB TRowResult rowResult2 = handler.getRow(tableAname, rowBname, null).get(0); assertEquals(rowBname, rowResult2.row); assertEquals(valueCname, rowResult2.columns.get(columnAname).value); assertEquals(valueDname, rowResult2.columns.get(columnBname).value); // Apply some deletes handler.deleteAll(tableAname, rowAname, columnBname, null); handler.deleteAllRow(tableAname, rowBname, null); // Assert that the deletes were applied int size = handler.get(tableAname, rowAname, columnBname, null).size(); assertEquals(0, size); size = handler.getRow(tableAname, rowBname, null).size(); assertEquals(0, size); // Try null mutation List<Mutation> mutations = new ArrayList<>(1); mutations.add(new Mutation(false, columnAname, null, true)); handler.mutateRow(tableAname, rowAname, mutations, null); TRowResult rowResult3 = handler.getRow(tableAname, rowAname, null).get(0); assertEquals(rowAname, rowResult3.row); assertEquals(0, rowResult3.columns.get(columnAname).value.remaining()); // Teardown handler.disableTable(tableAname); handler.deleteTable(tableAname); } /** * Similar to testTableMutations(), except Mutations are applied with * specific timestamps and data retrieval uses these timestamps to * extract specific versions of data. */ public void doTestTableTimestampsAndColumns() throws Exception { // Setup ThriftHBaseServiceHandler handler = new ThriftHBaseServiceHandler(UTIL.getConfiguration(), UserProvider.instantiate(UTIL.getConfiguration())); handler.createTable(tableAname, getColumnDescriptors()); // Apply timestamped Mutations to rowA long time1 = System.currentTimeMillis(); handler.mutateRowTs(tableAname, rowAname, getMutations(), time1, null); Thread.sleep(1000); // Apply timestamped BatchMutations for rowA and rowB long time2 = System.currentTimeMillis(); handler.mutateRowsTs(tableAname, getBatchMutations(), time2, null); // Apply an overlapping timestamped mutation to rowB handler.mutateRowTs(tableAname, rowBname, getMutations(), time2, null); // the getVerTs is [inf, ts) so you need to increment one. time1 += 1; time2 += 2; // Assert that the timestamp-related methods retrieve the correct data assertEquals(2, handler.getVerTs(tableAname, rowAname, columnBname, time2, MAXVERSIONS, null).size()); assertEquals(1, handler.getVerTs(tableAname, rowAname, columnBname, time1, MAXVERSIONS, null).size()); TRowResult rowResult1 = handler.getRowTs(tableAname, rowAname, time1, null).get(0); TRowResult rowResult2 = handler.getRowTs(tableAname, rowAname, time2, null).get(0); // columnA was completely deleted //assertTrue(Bytes.equals(rowResult1.columns.get(columnAname).value, valueAname)); assertEquals(rowResult1.columns.get(columnBname).value, valueBname); assertEquals(rowResult2.columns.get(columnBname).value, valueCname); // ColumnAname has been deleted, and will never be visible even with a getRowTs() assertFalse(rowResult2.columns.containsKey(columnAname)); List<ByteBuffer> columns = new ArrayList<>(1); columns.add(columnBname); rowResult1 = handler.getRowWithColumns(tableAname, rowAname, columns, null).get(0); assertEquals(rowResult1.columns.get(columnBname).value, valueCname); assertFalse(rowResult1.columns.containsKey(columnAname)); rowResult1 = handler.getRowWithColumnsTs(tableAname, rowAname, columns, time1, null).get(0); assertEquals(rowResult1.columns.get(columnBname).value, valueBname); assertFalse(rowResult1.columns.containsKey(columnAname)); // Apply some timestamped deletes // this actually deletes _everything_. // nukes everything in columnB: forever. handler.deleteAllTs(tableAname, rowAname, columnBname, time1, null); handler.deleteAllRowTs(tableAname, rowBname, time2, null); // Assert that the timestamp-related methods retrieve the correct data int size = handler.getVerTs(tableAname, rowAname, columnBname, time1, MAXVERSIONS, null).size(); assertEquals(0, size); size = handler.getVerTs(tableAname, rowAname, columnBname, time2, MAXVERSIONS, null).size(); assertEquals(1, size); // should be available.... assertEquals(handler.get(tableAname, rowAname, columnBname, null).get(0).value, valueCname); assertEquals(0, handler.getRow(tableAname, rowBname, null).size()); // Teardown handler.disableTable(tableAname); handler.deleteTable(tableAname); } /** * Tests the four different scanner-opening methods (with and without * a stoprow, with and without a timestamp). */ public void doTestTableScanners() throws Exception { // Setup ThriftHBaseServiceHandler handler = new ThriftHBaseServiceHandler(UTIL.getConfiguration(), UserProvider.instantiate(UTIL.getConfiguration())); handler.createTable(tableAname, getColumnDescriptors()); // Apply timestamped Mutations to rowA long time1 = System.currentTimeMillis(); handler.mutateRowTs(tableAname, rowAname, getMutations(), time1, null); // Sleep to assure that 'time1' and 'time2' will be different even with a // coarse grained system timer. Thread.sleep(1000); // Apply timestamped BatchMutations for rowA and rowB long time2 = System.currentTimeMillis(); handler.mutateRowsTs(tableAname, getBatchMutations(), time2, null); time1 += 1; // Test a scanner on all rows and all columns, no timestamp int scanner1 = handler.scannerOpen(tableAname, rowAname, getColumnList(true, true), null); TRowResult rowResult1a = handler.scannerGet(scanner1).get(0); assertEquals(rowResult1a.row, rowAname); // This used to be '1'. I don't know why when we are asking for two columns // and when the mutations above would seem to add two columns to the row. // -- St.Ack 05/12/2009 assertEquals(1, rowResult1a.columns.size()); assertEquals(rowResult1a.columns.get(columnBname).value, valueCname); TRowResult rowResult1b = handler.scannerGet(scanner1).get(0); assertEquals(rowResult1b.row, rowBname); assertEquals(2, rowResult1b.columns.size()); assertEquals(rowResult1b.columns.get(columnAname).value, valueCname); assertEquals(rowResult1b.columns.get(columnBname).value, valueDname); closeScanner(scanner1, handler); // Test a scanner on all rows and all columns, with timestamp int scanner2 = handler.scannerOpenTs(tableAname, rowAname, getColumnList(true, true), time1, null); TRowResult rowResult2a = handler.scannerGet(scanner2).get(0); assertEquals(1, rowResult2a.columns.size()); // column A deleted, does not exist. //assertTrue(Bytes.equals(rowResult2a.columns.get(columnAname).value, valueAname)); assertEquals(rowResult2a.columns.get(columnBname).value, valueBname); closeScanner(scanner2, handler); // Test a scanner on the first row and first column only, no timestamp int scanner3 = handler.scannerOpenWithStop(tableAname, rowAname, rowBname, getColumnList(true, false), null); closeScanner(scanner3, handler); // Test a scanner on the first row and second column only, with timestamp int scanner4 = handler.scannerOpenWithStopTs(tableAname, rowAname, rowBname, getColumnList(false, true), time1, null); TRowResult rowResult4a = handler.scannerGet(scanner4).get(0); assertEquals(1, rowResult4a.columns.size()); assertEquals(rowResult4a.columns.get(columnBname).value, valueBname); // Test scanner using a TScan object once with sortColumns False and once with sortColumns true TScan scanNoSortColumns = new TScan(); scanNoSortColumns.setStartRow(rowAname); scanNoSortColumns.setStopRow(rowBname); int scanner5 = handler.scannerOpenWithScan(tableAname , scanNoSortColumns, null); TRowResult rowResult5 = handler.scannerGet(scanner5).get(0); assertEquals(1, rowResult5.columns.size()); assertEquals(rowResult5.columns.get(columnBname).value, valueCname); TScan scanSortColumns = new TScan(); scanSortColumns.setStartRow(rowAname); scanSortColumns.setStopRow(rowBname); scanSortColumns = scanSortColumns.setSortColumns(true); int scanner6 = handler.scannerOpenWithScan(tableAname ,scanSortColumns, null); TRowResult rowResult6 = handler.scannerGet(scanner6).get(0); assertEquals(1, rowResult6.sortedColumns.size()); assertEquals(rowResult6.sortedColumns.get(0).getCell().value, valueCname); List<Mutation> rowBmutations = new ArrayList<>(20); for (int i = 0; i < 20; i++) { rowBmutations.add(new Mutation(false, asByteBuffer("columnA:" + i), valueCname, true)); } ByteBuffer rowC = asByteBuffer("rowC"); handler.mutateRow(tableAname, rowC, rowBmutations, null); TScan scanSortMultiColumns = new TScan(); scanSortMultiColumns.setStartRow(rowC); scanSortMultiColumns = scanSortMultiColumns.setSortColumns(true); int scanner7 = handler.scannerOpenWithScan(tableAname, scanSortMultiColumns, null); TRowResult rowResult7 = handler.scannerGet(scanner7).get(0); ByteBuffer smallerColumn = asByteBuffer("columnA:"); for (int i = 0; i < 20; i++) { ByteBuffer currentColumn = rowResult7.sortedColumns.get(i).columnName; assertTrue(Bytes.compareTo(smallerColumn.array(), currentColumn.array()) < 0); smallerColumn = currentColumn; } TScan reversedScan = new TScan(); reversedScan.setReversed(true); reversedScan.setStartRow(rowBname); reversedScan.setStopRow(rowAname); int scanner8 = handler.scannerOpenWithScan(tableAname , reversedScan, null); List<TRowResult> results = handler.scannerGet(scanner8); handler.scannerClose(scanner8); assertEquals(1, results.size()); assertEquals(ByteBuffer.wrap(results.get(0).getRow()), rowBname); // Teardown handler.disableTable(tableAname); handler.deleteTable(tableAname); } /** * For HBASE-2556 * Tests for GetTableRegions */ public void doTestGetTableRegions() throws Exception { ThriftHBaseServiceHandler handler = new ThriftHBaseServiceHandler(UTIL.getConfiguration(), UserProvider.instantiate(UTIL.getConfiguration())); doTestGetTableRegions(handler); } public static void doTestGetTableRegions(Hbase.Iface handler) throws Exception { assertEquals(0, handler.getTableNames().size()); handler.createTable(tableAname, getColumnDescriptors()); assertEquals(1, handler.getTableNames().size()); List<TRegionInfo> regions = handler.getTableRegions(tableAname); int regionCount = regions.size(); assertEquals("empty table should have only 1 region, " + "but found " + regionCount, 1, regionCount); LOG.info("Region found:" + regions.get(0)); handler.disableTable(tableAname); handler.deleteTable(tableAname); regionCount = handler.getTableRegions(tableAname).size(); assertEquals("non-existing table should have 0 region, " + "but found " + regionCount, 0, regionCount); } public void doTestFilterRegistration() throws Exception { Configuration conf = UTIL.getConfiguration(); conf.set("hbase.thrift.filters", "MyFilter:filterclass"); ThriftServer.registerFilters(conf); Map<String, String> registeredFilters = ParseFilter.getAllFilters(); assertEquals("filterclass", registeredFilters.get("MyFilter")); } public void doTestGetRegionInfo() throws Exception { ThriftHBaseServiceHandler handler = new ThriftHBaseServiceHandler(UTIL.getConfiguration(), UserProvider.instantiate(UTIL.getConfiguration())); doTestGetRegionInfo(handler); } public static void doTestGetRegionInfo(Hbase.Iface handler) throws Exception { // Create tableA and add two columns to rowA handler.createTable(tableAname, getColumnDescriptors()); try { handler.mutateRow(tableAname, rowAname, getMutations(), null); byte[] searchRow = RegionInfo.createRegionName( TableName.valueOf(tableAname.array()), rowAname.array(), HConstants.NINES, false); TRegionInfo regionInfo = handler.getRegionInfo(ByteBuffer.wrap(searchRow)); assertTrue(Bytes.toStringBinary(regionInfo.getName()).startsWith( Bytes.toStringBinary(tableAname))); } finally { handler.disableTable(tableAname); handler.deleteTable(tableAname); } } /** * Appends the value to a cell and checks that the cell value is updated properly. */ public static void doTestAppend() throws Exception { ThriftHBaseServiceHandler handler = new ThriftHBaseServiceHandler(UTIL.getConfiguration(), UserProvider.instantiate(UTIL.getConfiguration())); handler.createTable(tableAname, getColumnDescriptors()); try { List<Mutation> mutations = new ArrayList<>(1); mutations.add(new Mutation(false, columnAname, valueAname, true)); handler.mutateRow(tableAname, rowAname, mutations, null); List<ByteBuffer> columnList = new ArrayList<>(1); columnList.add(columnAname); List<ByteBuffer> valueList = new ArrayList<>(1); valueList.add(valueBname); TAppend append = new TAppend(tableAname, rowAname, columnList, valueList); handler.append(append); TRowResult rowResult = handler.getRow(tableAname, rowAname, null).get(0); assertEquals(rowAname, rowResult.row); assertArrayEquals(Bytes.add(valueAname.array(), valueBname.array()), rowResult.columns.get(columnAname).value.array()); } finally { handler.disableTable(tableAname); handler.deleteTable(tableAname); } } /** * Check that checkAndPut fails if the cell does not exist, then put in the cell, then check that * the checkAndPut succeeds. */ public static void doTestCheckAndPut() throws Exception { ThriftHBaseServiceHandler handler = new ThriftHBaseServiceHandler(UTIL.getConfiguration(), UserProvider.instantiate(UTIL.getConfiguration())); handler.createTable(tableAname, getColumnDescriptors()); try { List<Mutation> mutations = new ArrayList<>(1); mutations.add(new Mutation(false, columnAname, valueAname, true)); Mutation putB = (new Mutation(false, columnBname, valueBname, true)); assertFalse(handler.checkAndPut(tableAname, rowAname, columnAname, valueAname, putB, null)); handler.mutateRow(tableAname, rowAname, mutations, null); assertTrue(handler.checkAndPut(tableAname, rowAname, columnAname, valueAname, putB, null)); TRowResult rowResult = handler.getRow(tableAname, rowAname, null).get(0); assertEquals(rowAname, rowResult.row); assertEquals(valueBname, rowResult.columns.get(columnBname).value); } finally { handler.disableTable(tableAname); handler.deleteTable(tableAname); } } @Test public void testMetricsWithException() throws Exception { String rowkey = "row1"; String family = "f"; String col = "c"; // create a table which will throw exceptions for requests final TableName tableName = TableName.valueOf(name.getMethodName()); ColumnFamilyDescriptor columnFamilyDescriptor = ColumnFamilyDescriptorBuilder .newBuilder(Bytes.toBytes(family)) .build(); TableDescriptor tableDescriptor = TableDescriptorBuilder.newBuilder(tableName) .setCoprocessor(ErrorThrowingGetObserver.class.getName()) .setColumnFamily(columnFamilyDescriptor) .build(); Table table = UTIL.createTable(tableDescriptor, null); long now = System.currentTimeMillis(); table.put(new Put(Bytes.toBytes(rowkey)) .addColumn(Bytes.toBytes(family), Bytes.toBytes(col), now, Bytes.toBytes("val1"))); Configuration conf = UTIL.getConfiguration(); ThriftMetrics metrics = getMetrics(conf); ThriftHBaseServiceHandler hbaseHandler = new ThriftHBaseServiceHandler(UTIL.getConfiguration(), UserProvider.instantiate(UTIL.getConfiguration())); Hbase.Iface handler = HbaseHandlerMetricsProxy.newInstance(hbaseHandler, metrics, conf); ByteBuffer tTableName = asByteBuffer(tableName.getNameAsString()); // check metrics increment with a successful get long preGetCounter = metricsHelper.checkCounterExists("getRow_num_ops", metrics.getSource()) ? metricsHelper.getCounter("getRow_num_ops", metrics.getSource()) : 0; List<TRowResult> tRowResult = handler.getRow(tTableName, asByteBuffer(rowkey), null); assertEquals(1, tRowResult.size()); TRowResult tResult = tRowResult.get(0); TCell expectedColumnValue = new TCell(asByteBuffer("val1"), now); assertArrayEquals(Bytes.toBytes(rowkey), tResult.getRow()); Collection<TCell> returnedColumnValues = tResult.getColumns().values(); assertEquals(1, returnedColumnValues.size()); assertEquals(expectedColumnValue, returnedColumnValues.iterator().next()); metricsHelper.assertCounter("getRow_num_ops", preGetCounter + 1, metrics.getSource()); // check metrics increment when the get throws each exception type for (ErrorThrowingGetObserver.ErrorType type : ErrorThrowingGetObserver.ErrorType.values()) { testExceptionType(handler, metrics, tTableName, rowkey, type); } } private void testExceptionType(Hbase.Iface handler, ThriftMetrics metrics, ByteBuffer tTableName, String rowkey, ErrorThrowingGetObserver.ErrorType errorType) throws Exception { long preGetCounter = metricsHelper.getCounter("getRow_num_ops", metrics.getSource()); String exceptionKey = errorType.getMetricName(); long preExceptionCounter = metricsHelper.checkCounterExists(exceptionKey, metrics.getSource()) ? metricsHelper.getCounter(exceptionKey, metrics.getSource()) : 0; Map<ByteBuffer, ByteBuffer> attributes = new HashMap<>(); attributes.put(asByteBuffer(ErrorThrowingGetObserver.SHOULD_ERROR_ATTRIBUTE), asByteBuffer(errorType.name())); try { List<TRowResult> tRowResult = handler.getRow(tTableName, asByteBuffer(rowkey), attributes); fail("Get with error attribute should have thrown an exception"); } catch (IOError e) { LOG.info("Received exception: ", e); metricsHelper.assertCounter("getRow_num_ops", preGetCounter + 1, metrics.getSource()); metricsHelper.assertCounter(exceptionKey, preExceptionCounter + 1, metrics.getSource()); } } /** * @return a List of ColumnDescriptors for use in creating a table. Has one * default ColumnDescriptor and one ColumnDescriptor with fewer versions */ private static List<ColumnDescriptor> getColumnDescriptors() { ArrayList<ColumnDescriptor> cDescriptors = new ArrayList<>(2); // A default ColumnDescriptor ColumnDescriptor cDescA = new ColumnDescriptor(); cDescA.name = columnAname; cDescriptors.add(cDescA); // A slightly customized ColumnDescriptor (only 2 versions) ColumnDescriptor cDescB = new ColumnDescriptor(columnBname, 2, "NONE", false, "NONE", 0, 0, false, -1); cDescriptors.add(cDescB); return cDescriptors; } /** * * @param includeA whether or not to include columnA * @param includeB whether or not to include columnB * @return a List of column names for use in retrieving a scanner */ private List<ByteBuffer> getColumnList(boolean includeA, boolean includeB) { List<ByteBuffer> columnList = new ArrayList<>(); if (includeA) { columnList.add(columnAname); } if (includeB) { columnList.add(columnBname); } return columnList; } /** * @return a List of Mutations for a row, with columnA having valueA * and columnB having valueB */ private static List<Mutation> getMutations() { List<Mutation> mutations = new ArrayList<>(2); mutations.add(new Mutation(false, columnAname, valueAname, true)); mutations.add(new Mutation(false, columnBname, valueBname, true)); return mutations; } /** * @return a List of BatchMutations with the following effects: * (rowA, columnA): delete * (rowA, columnB): place valueC * (rowB, columnA): place valueC * (rowB, columnB): place valueD */ private static List<BatchMutation> getBatchMutations() { List<BatchMutation> batchMutations = new ArrayList<>(3); // Mutations to rowA. You can't mix delete and put anymore. List<Mutation> rowAmutations = new ArrayList<>(1); rowAmutations.add(new Mutation(true, columnAname, null, true)); batchMutations.add(new BatchMutation(rowAname, rowAmutations)); rowAmutations = new ArrayList<>(1); rowAmutations.add(new Mutation(false, columnBname, valueCname, true)); batchMutations.add(new BatchMutation(rowAname, rowAmutations)); // Mutations to rowB List<Mutation> rowBmutations = new ArrayList<>(2); rowBmutations.add(new Mutation(false, columnAname, valueCname, true)); rowBmutations.add(new Mutation(false, columnBname, valueDname, true)); batchMutations.add(new BatchMutation(rowBname, rowBmutations)); return batchMutations; } /** * Asserts that the passed scanner is exhausted, and then closes * the scanner. * * @param scannerId the scanner to close * @param handler the HBaseServiceHandler interfacing to HBase */ private void closeScanner( int scannerId, ThriftHBaseServiceHandler handler) throws Exception { handler.scannerGet(scannerId); handler.scannerClose(scannerId); } @Test public void testGetThriftServerType() throws Exception { ThriftHBaseServiceHandler handler = new ThriftHBaseServiceHandler(UTIL.getConfiguration(), UserProvider.instantiate(UTIL.getConfiguration())); assertEquals(TThriftServerType.ONE, handler.getThriftServerType()); } /** * Verify that thrift client calling thrift2 server can get the thrift2 server type correctly. */ @Test public void testGetThriftServerOneType() throws Exception { // start a thrift2 server HBaseThriftTestingUtility THRIFT_TEST_UTIL = new HBaseThriftTestingUtility(); LOG.info("Starting HBase Thrift Server Two"); THRIFT_TEST_UTIL.startThriftServer(UTIL.getConfiguration(), ThriftServerType.TWO); try (TTransport transport = new TSocket(InetAddress.getLocalHost().getHostName(), THRIFT_TEST_UTIL.getServerPort())){ TProtocol protocol = new TBinaryProtocol(transport); // This is our thrift client. Hbase.Client client = new Hbase.Client(protocol); // open the transport transport.open(); assertEquals(TThriftServerType.TWO.name(), client.getThriftServerType().name()); } finally { THRIFT_TEST_UTIL.stopThriftServer(); } } }
41.665584
100
0.734409
9b0012d26333561195209593701d415c4b8f0d84
1,960
package cl.usach.ingesoft.agendator.business.service; import cl.usach.ingesoft.agendator.entity.CareSessionEntity; import cl.usach.ingesoft.agendator.entity.OngEntity; import java.util.Date; import java.util.List; public interface IAdministrationService { /** * Operation 5. * * @param careSession Creates a new CareSession for the given parameters. * @return just created CareSession. */ CareSessionEntity createCareSession(CareSessionEntity careSession); /** * Operation 6. * * Cancels a CareSession (this does not deletes it). * * @param idCareSession Id for the CareSession to be canceled. * @return whether the CareSession could be canceled or not (true means canceled, otherwise false). */ boolean cancelCareSession(int idCareSession); /** * Operation 7. * * @param careSession CareSession to be updated. * @return CareSession just updated. */ CareSessionEntity updateCareSession(CareSessionEntity careSession); /** * * @param ongId Id for the Ong to retrieve. * @return Ong for the id provided, or null if none was found. */ OngEntity findCurrentOng(int ongId); OngEntity findCurrentOng(); /** * * @param ong Ong for which the CareSession is to be retrieved. * @param currentTime Date and time for which the CareSession is to be retrieved. * @return CareSession for the supplied parameters (or null if none was found). */ CareSessionEntity findCurrentCareSession(OngEntity ong, Date currentTime); List<CareSessionEntity> findAllCareSessions(int ongId); List<CareSessionEntity> findPendingCareSessions(int ongId, Date currentDate); /** * * @param idCareSession If for the CareSession to be retrieved. * @return CareSession for the provided id, or null if none was found. */ CareSessionEntity findCareSessionById(int idCareSession); }
31.111111
103
0.698469
83615a4b445dd057852480a321f3bb6de91028b1
183
package com.example.retrofit.downlaod; /** * 下载状态 * Created by WZG on 2016/10/21. */ public enum DownState { START, DOWN, PAUSE, STOP, ERROR, FINISH, }
10.764706
38
0.584699
edcb7c13debf7b43ccc0039eaf4e13e603e66085
2,727
package com.puresoltechnologies.javafx.reactive.flux; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.puresoltechnologies.javafx.reactive.MessageBroker; public class FluxTest { @BeforeEach public void initialize() { assertFalse(Flux.isInitialized()); MessageBroker.initialize(); Flux.initialize(); assertTrue(Flux.isInitialized()); } @AfterEach public void shutdown() { assertTrue(Flux.isInitialized()); Flux.shutdown(); MessageBroker.shutdown(); assertFalse(Flux.isInitialized()); } @Test public void testWithoutStores() { // Simple smoke test. Intentionally left blank. } /** * A double initialization is meant to throw an {@link IllegalStateException}. * But, the status is still initialized. */ @Test public void testMultiInitialize() { assertThrows(IllegalStateException.class, () -> Flux.initialize()); assertTrue(Flux.isInitialized()); } /** * A double shut down is meant to throw an {@link IllegalStateException}. But, * the status is still uninitialized. */ @Test public void testMultiShutdown() { assertTrue(Flux.isInitialized()); Flux.shutdown(); assertFalse(Flux.isInitialized()); assertThrows(IllegalStateException.class, () -> Flux.shutdown()); assertFalse(Flux.isInitialized()); /* * We need to initialize again, to satisfy @AfterAll shutdown method. */ Flux.initialize(); assertTrue(Flux.isInitialized()); } private enum Actions { ACTION_1; } private static class TestStore extends Store<Actions, String> { @Override protected void handle(Payload payload) { // TODO Auto-generated method stub } } @Test public void testRegisterStore() { TestStore store = new TestStore(); Flux.registerStore(store); Store<Actions, String> foundStore = Flux.getStore(TestStore.class); assertSame(store, foundStore); } @Test public void testRegisteredStoreIsGoneAfterReInitialization() { TestStore store = new TestStore(); Flux.registerStore(store); Store<Actions, String> foundStore = Flux.getStore(TestStore.class); assertSame(store, foundStore); Flux.shutdown(); Flux.initialize(); foundStore = Flux.getStore(TestStore.class); assertNull(foundStore); } }
27.545455
83
0.700403
8087251bce7e30a740679ce08389ce9b172c3d4b
1,386
package data; import java.util.*; import static data.WarehouseRepository.getAllItems; public class Warehouse { // Fields private int id; List<Item> stock; // Constructor public Warehouse(int warehouseId) { this.id = warehouseId; this.stock = new ArrayList<>(); } public int getId() { return id; } public int occupancy() { return getStock().size(); } public void addItem(Item item) { getStock().add(item); } public boolean search(String searchTerm) { for (Item item : getStock()) { if (item.toString().equalsIgnoreCase(searchTerm)) { return true; } } return false; } public List<Item> getItemsInStock(String itemName) { List<Item> allItemsInThisWarehouse = new ArrayList<Item>(); for (Item item : getStock()) { if (item.toString().equalsIgnoreCase(itemName)){ allItemsInThisWarehouse.add(item); } } return allItemsInThisWarehouse; } public List<Item> getStock() { return stock; } public Set<String> getCategories() { Set<String> categoryList = new TreeSet<>(); for (Item item : getStock()) { categoryList.add(item.getCategory()); } return categoryList; } }
19.25
67
0.561328
2e4111afe6ceba72ffd72349a51e4c9e4e3f6c15
11,194
/* * This file is part of plugin-meta, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.plugin.metadata.parser; import com.google.common.base.Preconditions; import com.google.gson.Gson; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import org.spongepowered.plugin.metadata.PluginContributor; import org.spongepowered.plugin.metadata.PluginDependency; import org.spongepowered.plugin.metadata.PluginLinks; import org.spongepowered.plugin.metadata.PluginMetadata; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; public final class PluginMetadataAdapter extends TypeAdapter<PluginMetadata> { private final Gson gson; public PluginMetadataAdapter(final Gson gson) { this.gson = Preconditions.checkNotNull(gson); } @Override public void write(final JsonWriter out, final PluginMetadata value) throws IOException { out.beginObject(); out.name("id").value(value.getId()); this.writeStringIfPresent(out, "name", value.getName()); out.name("version").value(value.getVersion()); out.name("main-class").value(value.getMainClass()); this.writeStringIfPresent(out, "description", value.getDescription()); this.writeLinks(out, value.getLinks()); this.writeContributors(out, value.getContributors()); this.writeDependencies(out, value.getDependencies()); this.writeExtraMetadata(out, value.getExtraMetadata()); out.endObject(); } @Override public PluginMetadata read(final JsonReader in) throws IOException { in.beginObject(); final Set<String> processedKeys = new HashSet<>(); final PluginMetadata.Builder builder = PluginMetadata.builder(); while (in.hasNext()) { final String key = in.nextName(); if (!processedKeys.add(key)) { throw new JsonParseException("Duplicate key '" + key + "' in " + in); } switch (key) { case "id": builder.setId(in.nextString()); break; case "name": builder.setName(in.nextString()); break; case "version": builder.setVersion(in.nextString()); break; case "main-class": builder.setMainClass(in.nextString()); break; case "description": builder.setDescription(in.nextString()); break; case "links": this.readLinks(in, builder); break; case "contributors": this.readContributors(in, builder); break; case "dependencies": this.readDependencies(in, builder); break; case "extra": in.beginObject(); final Map<String, String> extraMetadata = new HashMap<>(); while (in.hasNext()) { final String eKey = in.nextName(); final String eValue = in.nextString(); extraMetadata.put(eKey, eValue); } in.endObject(); // TODO Move Extra Metadata to String -> String builder.setExtraMetadata((Map<String, Object>) (Object) extraMetadata); } } in.endObject(); return builder.build(); } private void readLinks(final JsonReader in, final PluginMetadata.Builder builder) throws IOException { in.beginObject(); final Set<String> processedKeys = new HashSet<>(); final PluginLinks.Builder linksBuilder = PluginLinks.builder(); while (in.hasNext()) { final String key = in.nextName(); if (!processedKeys.add(key)) { throw new JsonParseException("Duplicate key '" + key + "' in " + in); } switch (key) { case "homepage": linksBuilder.setHomepage(new URL(in.nextString())); break; case "source": linksBuilder.setSource(new URL(in.nextString())); break; case "issues": linksBuilder.setIssues(new URL(in.nextString())); break; } } builder.setLinks(linksBuilder.build()); in.endObject(); } private void readContributors(final JsonReader in, final PluginMetadata.Builder builder) throws IOException { in.beginArray(); while (in.hasNext()) { builder.contributor(this.readContributor(in)); } in.endArray(); } private PluginContributor readContributor(final JsonReader in) throws IOException { in.beginObject(); final Set<String> processedKeys = new HashSet<>(); final PluginContributor.Builder builder = PluginContributor.builder(); while (in.hasNext()) { final String key = in.nextName(); if (!processedKeys.add(key)) { throw new JsonParseException("Duplicate key '" + key + "' in " + in); } switch (key) { case "name": builder.setName(in.nextString()); break; case "description": builder.setDescription(in.nextString()); break; } } in.endObject(); return builder.build(); } private void readDependencies(final JsonReader in, final PluginMetadata.Builder builder) throws IOException { in.beginArray(); while (in.hasNext()) { builder.dependency(this.readDependency(in)); } in.endArray(); } private PluginDependency readDependency(final JsonReader in) throws IOException { in.beginObject(); final Set<String> processedKeys = new HashSet<>(); final PluginDependency.Builder builder = PluginDependency.builder(); while (in.hasNext()) { final String key = in.nextName(); if (!processedKeys.add(key)) { throw new JsonParseException("Duplicate key '" + key + "' in " + in); } switch (key) { case "id": builder.setId(in.nextString()); break; case "version": builder.setVersion(in.nextString()); break; case "optional": builder.setOptional(in.nextBoolean()); break; case "load-order": try { builder.setLoadOrder(PluginDependency.LoadOrder.valueOf(in.nextString().toUpperCase())); } catch (final Exception ex) { throw new JsonParseException("Invalid load order found in " + in, ex); } break; } } in.endObject(); return builder.build(); } private void writeLinks(final JsonWriter out, final PluginLinks links) throws IOException { if (!links.getHomepage().isPresent() && !links.getSource().isPresent() && !links.getIssues().isPresent()) { return; } out.name("links").beginObject(); this.writeURLIfPresent(out, "homepage", links.getHomepage()); this.writeURLIfPresent(out, "source", links.getSource()); this.writeURLIfPresent(out, "issues", links.getIssues()); out.endObject(); } private void writeContributors(final JsonWriter out, final List<PluginContributor> contributors) throws IOException { if (contributors.isEmpty()) { return; } out.name("contributors").beginArray(); for (final PluginContributor contributor : contributors) { out.name("name").value(contributor.getName()); this.writeStringIfPresent(out, "description", contributor.getDescription()); } out.endArray(); } private void writeDependencies(final JsonWriter out, final List<PluginDependency> dependencies) throws IOException { if (dependencies.isEmpty()) { return; } out.name("dependencies").beginArray(); for (final PluginDependency dependency : dependencies) { out.name("id").value(dependency.getId()); out.name("version").value(dependency.getVersion()); out.name("load-order").value(dependency.getLoadOrder().name()); out.name("optional").value(dependency.isOptional()); } out.endArray(); } private void writeExtraMetadata(final JsonWriter out, final Map<String, Object> extraMetadata) throws IOException { if (extraMetadata.isEmpty()) { return; } out.name("extra").beginObject(); for (final Map.Entry<String, Object> entry : extraMetadata.entrySet()) { // TODO Figure out how to serialize properly out.name(entry.getKey()).value(entry.getValue().toString()); } out.endObject(); } private void writeStringIfPresent(final JsonWriter out, final String name, final Optional<String> value) throws IOException { if (value.isPresent()) { out.name(name).value(value.get()); } } private void writeURLIfPresent(final JsonWriter out, final String name, final Optional<URL> value) throws IOException { if (value.isPresent()) { out.name(name).value(value.get().toString()); } } }
39.695035
129
0.588619
981526a8ef3f0320102f955b76713e7ff0c58858
370
package com.github.apachefoundation.jerrymouse.enumeration; /** * @Author: xiantang * @Date: 2019/4/17 14:45 */ public enum HttpStatus { OK(200),NOT_FOUND(404),INTERNAL_SERVER_ERROR(500),BAD_REQUEST(400),MOVED_TEMPORARILY(302); private int code; HttpStatus(int code){ this.code = code; } public int getCode(){ return code; } }
23.125
94
0.664865
12ec87d1b045a3a7593cd817319e306640263103
520
package com.pnu.spring.smartfactory.Mapper; import java.util.List; import java.util.Map; import com.pnu.spring.smartfactory.DAO.InspectDAO; import com.pnu.spring.smartfactory.DAO.RepairDAO; public interface RepairMapper { public void insRepair(Map<String, Object> param); public void delRepair(Map<String, Object> param); public List<RepairDAO> getRepairList(); public List<RepairDAO> getRepairDetail(Map<String, Object> param); public List<RepairDAO> getRepairDetailByRepairNo(Map<String, Object> param); }
26
77
0.792308
5ff495cc1b4a827eba19c17df0fb16ada5239df9
249
/** * Original: https://en.wikipedia.org/wiki/Interpreter_pattern#Java */ package pattern.behavioral.interpreter.calculator; import java.util.Map; public interface Expression { public int interpret(final Map<String,Expression> variables); }
22.636364
67
0.771084
25c6eb8067bbc039be3f2fdfab8aca688dfefc06
1,869
package ch.uzh.ifi.group26.scrumblebee.security.utils; import io.jsonwebtoken.*; import io.jsonwebtoken.security.Keys; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; import javax.crypto.SecretKey; import java.util.Date; import java.util.function.Function; @Component public class JwtUtils { private SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS256); private Long refreshTokenDurationsMS; public void setRefreshTokenDuration(Long duration) { this.refreshTokenDurationsMS = duration; } public String generateJwtToken(UserDetails userDetails) { return Jwts.builder() .setSubject(userDetails.getUsername()) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + refreshTokenDurationsMS)) .signWith(key, SignatureAlgorithm.HS256).compact(); } public String extractUsername(String token) { return extractClaim(token, Claims::getSubject); } public Date extractExpiration(String token) { return extractClaim(token, Claims::getExpiration); } public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) { final Claims claims = extractAllClaims(token); return claimsResolver.apply(claims); } private Claims extractAllClaims(String token) { return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody(); } private Boolean isTokenExpired(String token) { return extractExpiration(token).before(new Date()); } public Boolean validateToken(String token, UserDetails userDetails) { final String username = extractUsername(token); return (username.equals(userDetails.getUsername()) && !isTokenExpired(token)); } }
31.677966
95
0.712681
699ce841084940ef539a0ccae4bae98de7956df6
18,357
package org.hisp.dhis.common; /* * Copyright (c) 2004-2013, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hisp.dhis.common.IdentifiableObject.IdentifiableProperty; import org.hisp.dhis.common.NameableObject.NameableProperty; import org.hisp.dhis.common.comparator.IdentifiableObjectNameComparator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * @author Lars Helge Overland */ @Transactional public class DefaultIdentifiableObjectManager implements IdentifiableObjectManager { private static final Log log = LogFactory.getLog( DefaultIdentifiableObjectManager.class ); @Autowired private Set<GenericIdentifiableObjectStore<IdentifiableObject>> identifiableObjectStores; @Autowired private Set<GenericNameableObjectStore<NameableObject>> nameableObjectStores; private Map<Class<IdentifiableObject>, GenericIdentifiableObjectStore<IdentifiableObject>> identifiableObjectStoreMap; private Map<Class<NameableObject>, GenericNameableObjectStore<NameableObject>> nameableObjectStoreMap; @PostConstruct public void init() { identifiableObjectStoreMap = new HashMap<Class<IdentifiableObject>, GenericIdentifiableObjectStore<IdentifiableObject>>(); for ( GenericIdentifiableObjectStore<IdentifiableObject> store : identifiableObjectStores ) { identifiableObjectStoreMap.put( store.getClazz(), store ); } nameableObjectStoreMap = new HashMap<Class<NameableObject>, GenericNameableObjectStore<NameableObject>>(); for ( GenericNameableObjectStore<NameableObject> store : nameableObjectStores ) { nameableObjectStoreMap.put( store.getClazz(), store ); } } //-------------------------------------------------------------------------- // IdentifiableObjectManager implementation //-------------------------------------------------------------------------- @Override public void save( IdentifiableObject object ) { GenericIdentifiableObjectStore<IdentifiableObject> store = getIdentifiableObjectStore( object.getClass() ); if ( store != null ) { store.save( object ); } } @Override public void update( IdentifiableObject object ) { GenericIdentifiableObjectStore<IdentifiableObject> store = getIdentifiableObjectStore( object.getClass() ); if ( store != null ) { store.update( object ); } } @Override public void delete( IdentifiableObject object ) { GenericIdentifiableObjectStore<IdentifiableObject> store = getIdentifiableObjectStore( object.getClass() ); if ( store != null ) { store.delete( object ); } } @Override @SuppressWarnings("unchecked") public <T extends IdentifiableObject> T get( String uid ) { for ( GenericIdentifiableObjectStore<IdentifiableObject> store : identifiableObjectStores ) { T object = (T) store.getByUid( uid ); if ( object != null ) { return object; } } return null; } @Override @SuppressWarnings("unchecked") public <T extends IdentifiableObject> T get( Class<T> clazz, int id ) { GenericIdentifiableObjectStore<IdentifiableObject> store = getIdentifiableObjectStore( clazz ); if ( store == null ) { return null; } return (T) store.get( id ); } @Override @SuppressWarnings("unchecked") public <T extends IdentifiableObject> T get( Class<T> clazz, String uid ) { GenericIdentifiableObjectStore<IdentifiableObject> store = getIdentifiableObjectStore( clazz ); if ( store == null ) { return null; } return (T) store.getByUid( uid ); } @Override public <T extends IdentifiableObject> boolean exists( Class<T> clazz, String uid ) { return get( clazz, uid ) != null; } @Override @SuppressWarnings("unchecked") public <T extends IdentifiableObject> T getByCode( Class<T> clazz, String code ) { GenericIdentifiableObjectStore<IdentifiableObject> store = getIdentifiableObjectStore( clazz ); if ( store == null ) { return null; } return (T) store.getByCode( code ); } @Override @SuppressWarnings("unchecked") public <T extends IdentifiableObject> T getByName( Class<T> clazz, String name ) { GenericIdentifiableObjectStore<IdentifiableObject> store = getIdentifiableObjectStore( clazz ); if ( store == null ) { return null; } return (T) store.getByName( name ); } @Override public <T extends IdentifiableObject> T search( Class<T> clazz, String query ) { T object = get( clazz, query ); if ( object == null ) { object = getByCode( clazz, query ); } if ( object == null ) { object = getByName( clazz, query ); } return object; } @Override public <T extends IdentifiableObject> Collection<T> filter( Class<T> clazz, String query ) { Set<T> uniqueObjects = new HashSet<T>(); T uidObject = get( clazz, query ); if ( uidObject != null ) { uniqueObjects.add( uidObject ); } T codeObject = getByCode( clazz, query ); if ( codeObject != null ) { uniqueObjects.add( codeObject ); } uniqueObjects.addAll( getLikeName( clazz, query ) ); uniqueObjects.addAll( getLikeShortName( clazz, query ) ); List<T> objects = new ArrayList<T>( uniqueObjects ); Collections.sort( objects, IdentifiableObjectNameComparator.INSTANCE ); return objects; } @Override @SuppressWarnings("unchecked") public <T extends IdentifiableObject> Collection<T> getAll( Class<T> clazz ) { GenericIdentifiableObjectStore<IdentifiableObject> store = getIdentifiableObjectStore( clazz ); if ( store == null ) { return new ArrayList<T>(); } return (Collection<T>) store.getAll(); } @Override @SuppressWarnings("unchecked") public <T extends IdentifiableObject> Collection<T> getAllSorted( Class<T> clazz ) { GenericIdentifiableObjectStore<IdentifiableObject> store = getIdentifiableObjectStore( clazz ); if ( store == null ) { return new ArrayList<T>(); } return (Collection<T>) store.getAllOrderedName(); } @Override @SuppressWarnings("unchecked") public <T extends IdentifiableObject> List<T> getByUid( Class<T> clazz, Collection<String> uids ) { GenericIdentifiableObjectStore<IdentifiableObject> store = getIdentifiableObjectStore( clazz ); if ( store == null ) { return new ArrayList<T>(); } return (List<T>) store.getByUid( uids ); } @Override @SuppressWarnings("unchecked") public <T extends IdentifiableObject> Collection<T> getLikeName( Class<T> clazz, String name ) { GenericIdentifiableObjectStore<IdentifiableObject> store = getIdentifiableObjectStore( clazz ); if ( store == null ) { return new ArrayList<T>(); } return (Collection<T>) store.getAllLikeName( name ); } @Override @SuppressWarnings("unchecked") public <T extends IdentifiableObject> Collection<T> getLikeShortName( Class<T> clazz, String shortName ) { GenericIdentifiableObjectStore<IdentifiableObject> store = getIdentifiableObjectStore( clazz ); if ( store == null ) { return new ArrayList<T>(); } return (Collection<T>) store.getAllLikeShortName( shortName ); } @Override @SuppressWarnings("unchecked") public <T extends IdentifiableObject> List<T> getBetween( Class<T> clazz, int first, int max ) { GenericIdentifiableObjectStore<IdentifiableObject> store = getIdentifiableObjectStore( clazz ); if ( store == null ) { return new ArrayList<T>(); } return (List<T>) store.getAllOrderedName( first, max ); } @Override @SuppressWarnings("unchecked") public <T extends IdentifiableObject> List<T> getBetweenByName( Class<T> clazz, String name, int first, int max ) { GenericIdentifiableObjectStore<IdentifiableObject> store = getIdentifiableObjectStore( clazz ); if ( store == null ) { return new ArrayList<T>(); } return (List<T>) store.getAllLikeNameOrderedName( name, first, max ); } @Override @SuppressWarnings("unchecked") public <T extends IdentifiableObject> Collection<T> getByLastUpdated( Class<T> clazz, Date lastUpdated ) { GenericIdentifiableObjectStore<IdentifiableObject> store = getIdentifiableObjectStore( clazz ); if ( store == null ) { return new ArrayList<T>(); } return (Collection<T>) store.getAllGeLastUpdated( lastUpdated ); } @Override @SuppressWarnings("unchecked") public <T extends IdentifiableObject> Collection<T> getByLastUpdatedSorted( Class<T> clazz, Date lastUpdated ) { GenericIdentifiableObjectStore<IdentifiableObject> store = getIdentifiableObjectStore( clazz ); if ( store == null ) { return new ArrayList<T>(); } return (Collection<T>) store.getAllGeLastUpdatedOrderedName( lastUpdated ); } @Override public <T extends IdentifiableObject> Set<Integer> convertToId( Class<T> clazz, Collection<String> uids ) { GenericIdentifiableObjectStore<IdentifiableObject> store = getIdentifiableObjectStore( clazz ); Set<Integer> ids = new HashSet<Integer>(); for ( String uid : uids ) { IdentifiableObject object = store.getByUid( uid ); if ( object != null ) { ids.add( object.getId() ); } } return ids; } @Override @SuppressWarnings("unchecked") public <T extends IdentifiableObject> Map<String, T> getIdMap( Class<T> clazz, IdentifiableProperty property ) { Map<String, T> map = new HashMap<String, T>(); GenericIdentifiableObjectStore<T> store = (GenericIdentifiableObjectStore<T>) getIdentifiableObjectStore( clazz ); if ( store == null ) { return map; } Collection<T> objects = store.getAll(); for ( T object : objects ) { if ( IdentifiableProperty.ID.equals( property ) ) { if ( object.getId() > 0 ) { map.put( String.valueOf( object.getId() ), object ); } } else if ( IdentifiableProperty.UID.equals( property ) ) { if ( object.getUid() != null ) { map.put( object.getUid(), object ); } } else if ( IdentifiableProperty.CODE.equals( property ) ) { if ( object.getCode() != null ) { map.put( object.getCode(), object ); } } else if ( IdentifiableProperty.NAME.equals( property ) ) { if ( object.getName() != null ) { map.put( object.getName(), object ); } } } return map; } @Override @SuppressWarnings("unchecked") public <T extends NameableObject> Map<String, T> getIdMap( Class<T> clazz, NameableProperty property ) { Map<String, T> map = new HashMap<String, T>(); GenericNameableObjectStore<T> store = (GenericNameableObjectStore<T>) getNameableObjectStore( clazz ); Collection<T> objects = store.getAll(); for ( T object : objects ) { if ( property == NameableProperty.SHORT_NAME ) { if ( object.getShortName() != null ) { map.put( object.getShortName(), object ); } } } return map; } @Override @SuppressWarnings("unchecked") public <T extends IdentifiableObject> T getObject( Class<T> clazz, IdentifiableProperty property, String id ) { GenericIdentifiableObjectStore<T> store = (GenericIdentifiableObjectStore<T>) getIdentifiableObjectStore( clazz ); if ( id != null ) { if ( IdentifiableProperty.ID.equals( property ) ) { if ( Integer.valueOf( id ) > 0 ) { return store.get( Integer.valueOf( id ) ); } } else if ( IdentifiableProperty.UID.equals( property ) ) { return store.getByUid( id ); } else if ( IdentifiableProperty.CODE.equals( property ) ) { return store.getByCode( id ); } else if ( IdentifiableProperty.NAME.equals( property ) ) { return store.getByName( id ); } } throw new IllegalArgumentException( String.valueOf( property ) ); } @Override public IdentifiableObject getObject( String uid, String simpleClassName ) { for ( GenericIdentifiableObjectStore<IdentifiableObject> objectStore : identifiableObjectStores ) { if ( simpleClassName.equals( objectStore.getClass().getSimpleName() ) ) { return objectStore.getByUid( uid ); } } return null; } @Override public IdentifiableObject getObject( int id, String simpleClassName ) { for ( GenericIdentifiableObjectStore<IdentifiableObject> objectStore : identifiableObjectStores ) { if ( simpleClassName.equals( objectStore.getClazz().getSimpleName() ) ) { return objectStore.get( id ); } } return null; } @Override public <T extends IdentifiableObject> int getCount( Class<T> clazz ) { GenericIdentifiableObjectStore<IdentifiableObject> store = getIdentifiableObjectStore( clazz ); if ( store != null ) { return store.getCount(); } return 0; } @Override @SuppressWarnings("unchecked") public <T extends IdentifiableObject> T getNoAcl( Class<T> clazz, String uid ) { GenericIdentifiableObjectStore<IdentifiableObject> store = getIdentifiableObjectStore( clazz ); if ( store == null ) { return null; } return (T) store.getByUidNoAcl( uid ); } @Override public <T extends IdentifiableObject> void updateNoAcl( T object ) { GenericIdentifiableObjectStore<IdentifiableObject> store = getIdentifiableObjectStore( object.getClass() ); if ( store != null ) { store.updateNoAcl( object ); } } private <T extends IdentifiableObject> GenericIdentifiableObjectStore<IdentifiableObject> getIdentifiableObjectStore( Class<T> clazz ) { GenericIdentifiableObjectStore<IdentifiableObject> store = identifiableObjectStoreMap.get( clazz ); if ( store == null ) { store = identifiableObjectStoreMap.get( clazz.getSuperclass() ); if ( store == null ) { log.warn( "No IdentifiableObjectStore found for class: " + clazz ); } } return store; } private <T extends NameableObject> GenericNameableObjectStore<NameableObject> getNameableObjectStore( Class<T> clazz ) { GenericNameableObjectStore<NameableObject> store = nameableObjectStoreMap.get( clazz ); if ( store == null ) { store = nameableObjectStoreMap.get( clazz.getSuperclass() ); if ( store == null ) { log.warn( "No NameableObjectStore found for class: " + clazz ); } } return store; } }
30.493355
138
0.612464
2545d7b017cd247365b81f8243c2fc45abfb213f
1,367
package dev.unethicalite.api.query.entities; import dev.unethicalite.api.Interactable; import net.runelite.api.Actor; import org.apache.commons.lang3.ArrayUtils; import java.util.List; import java.util.function.Supplier; public abstract class ActorQuery<T extends Actor, Q extends ActorQuery<T, Q>> extends SceneEntityQuery<T, Q> { private int[] levels = null; private int[] animations = null; private Interactable[] targeting = null; private Boolean moving = null; protected ActorQuery(Supplier<List<T>> supplier) { super(supplier); } public Q levels(int... levels) { this.levels = levels; return (Q) this; } public Q animations(int... animations) { this.animations = animations; return (Q) this; } public Q targeting(Interactable... targets) { this.targeting = targets; return (Q) this; } public Q moving(Boolean moving) { this.moving = moving; return (Q) this; } @Override public boolean test(T t) { if (levels != null && ArrayUtils.contains(levels, t.getCombatLevel())) { return false; } if (animations != null && ArrayUtils.contains(animations, t.getAnimation())) { return false; } if (moving != null && moving != t.isMoving()) { return false; } if (targeting != null && !ArrayUtils.contains(targeting, t.getInteracting())) { return false; } return super.test(t); } }
18.726027
79
0.684711
8adbeebc7fbdac1689705269b0bbe89728a787b6
4,990
package org.acme.dvdstore.controller; import java.io.File; import java.io.IOException; import java.io.Reader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDateTime; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; import org.acme.dvdstore.base.CommandPattern; import org.acme.dvdstore.base.StructurePattern; import org.acme.dvdstore.model.Language; import org.acme.dvdstore.service.LanguageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import com.google.gson.JsonSyntaxException; import lombok.extern.slf4j.Slf4j; import static org.acme.dvdstore.base.FilePattern.LANGUAGE; @Component @Slf4j public class LanguageController extends BaseController { @Autowired LanguageService languageService; @Scheduled(cron = "0/15 * * * * *") private void poll() { final Path languagePath = getRoot().resolve(StructurePattern.ENTITIES.getName()).resolve( LANGUAGE.getSuffix()); log.trace("Looking for {} related commands in {}.", LANGUAGE.getSuffix(), languagePath); try (final Stream<Path> languageFilesPath = Files.find(languagePath, 1, (path, basicFileAttributes) -> String.valueOf(path) .endsWith(LANGUAGE .getSuffix() + "." + fileFormat))) { final List<File> commandFiles = languageFilesPath.map(Path::toFile).collect(Collectors.toList()); if (commandFiles.size() == 0) { log.trace("Found no commands."); } else { log.debug("Found {} command(s).", commandFiles.size()); processCommands(commandFiles); } } catch (final IOException e) { log.error("Error while reading files in {}.", languagePath); e.printStackTrace(); } } private void processCommands(final List<File> commands) { for (final File file : commands) { log.trace("Processing create command in file {}.", file); final String generatedId = dateTimeFormatter.format(LocalDateTime.now()); try (final Reader reader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) { final String command = file.getName().split(separator)[0]; switch (Objects.requireNonNull(CommandPattern.get(command))) { case CREATE: final List<Language> languages = createLanguage(reader); if (!CollectionUtils.isEmpty(languages)) { generateResponse(constructResponseFile(file, generatedId), languages); } break; case UPDATE: updateLanguage(reader); generateResponse(constructResponseFile(file, generatedId), "{status:\"OK\"}"); break; case DELETE: deleteLanguage(reader); generateResponse(constructResponseFile(file, generatedId), "{status:\"OK\"}"); break; case READ: final Language languageFound = getLanguage(reader); generateResponse(constructResponseFile(file, generatedId), languageFound); } archiveCommand(file, generatedId); } catch (final NullPointerException ex) { log.warn("Command could not be recognised."); try { archiveCommand(file, generatedId); } catch (final IOException e) { e.printStackTrace(); } } catch (final JsonSyntaxException ex) { log.error("Corrupted file {}.", file); } catch (final IOException e) { log.error("File {} cannot be accessed.", file); e.printStackTrace(); } } } private List<Language> createLanguage(final Reader reader) { final Language[] languages = gson.fromJson(reader, Language[].class); if (!CollectionUtils.isEmpty(Arrays.asList(languages))) { final List<Language> newLanguages = languageService.createAll(languages); log.debug("{} language(s) loaded.", languages.length); return newLanguages; } else { log.debug("No languages loaded from file."); return Collections.emptyList(); } } private void updateLanguage(final Reader reader) { final Language language = gson.fromJson(reader, Language.class); if (language != null) { languageService.update(language); log.debug("1 language updated."); } else { log.debug("No languages loaded from file."); } } private void deleteLanguage(final Reader reader) { final Language language = gson.fromJson(reader, Language.class); if (language != null) { languageService.delete(language); log.debug("1 language deleted."); } else { log.debug("No languages loaded from file."); } } private Language getLanguage(final Reader reader) { final Long languageId = gson.fromJson(reader, Long.class); final Language languageFound = languageService.get(languageId); log.debug("Language ({}) found and retrieved.", languageId); return languageFound; } }
33.945578
100
0.704409
8e9a5e5913221977b03fe5ba249b260e5289671a
7,705
package com.esotericsoftware.kryo.serializers; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.KryoException; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.reflectasm.MethodAccess; import static com.esotericsoftware.minlog.Log.*; /** Serializes Java beans using bean accessor methods. Only bean properties with both a getter and setter are serialized. This * class is not as fast as {@link FieldSerializer} but is much faster and more efficient than Java serialization. Bytecode * generation is used to invoke the bean propert methods, if possible. * <p> * BeanSerializer does not write header data, only the object data is stored. If the type of a bean property is not final (note * primitives are final) then an extra byte is written for that property. * @see Serializer * @see Kryo#register(Class, Serializer) * @author Nathan Sweet <[email protected]> */ public class BeanSerializer<T> extends Serializer<T> { static final Object[] noArgs = {}; private final Kryo kryo; private CachedProperty[] properties; Object access; public BeanSerializer (Kryo kryo, Class type) { this.kryo = kryo; BeanInfo info; try { info = Introspector.getBeanInfo(type); } catch (IntrospectionException ex) { throw new KryoException("Error getting bean info.", ex); } // Methods are sorted by alpha so the order of the data is known. PropertyDescriptor[] descriptors = info.getPropertyDescriptors(); Arrays.sort(descriptors, new Comparator<PropertyDescriptor>() { public int compare (PropertyDescriptor o1, PropertyDescriptor o2) { return o1.getName().compareTo(o2.getName()); } }); ArrayList<CachedProperty> cachedProperties = new ArrayList(descriptors.length); for (int i = 0, n = descriptors.length; i < n; i++) { PropertyDescriptor property = descriptors[i]; String name = property.getName(); if (name.equals("class")) continue; Method getMethod = property.getReadMethod(); Method setMethod = property.getWriteMethod(); if (getMethod == null || setMethod == null) continue; // Require both a getter and setter. // Always use the same serializer for this property if the properties' class is final. Serializer serializer = null; Class returnType = getMethod.getReturnType(); if (kryo.isFinal(returnType)) serializer = kryo.getRegistration(returnType).getSerializer(); CachedProperty cachedProperty = new CachedProperty(); cachedProperty.name = name; cachedProperty.getMethod = getMethod; cachedProperty.setMethod = setMethod; cachedProperty.serializer = serializer; cachedProperty.setMethodType = setMethod.getParameterTypes()[0]; cachedProperties.add(cachedProperty); } properties = cachedProperties.toArray(new CachedProperty[cachedProperties.size()]); try { access = MethodAccess.get(type); for (int i = 0, n = properties.length; i < n; i++) { CachedProperty property = properties[i]; property.getterAccessIndex = ((MethodAccess)access).getIndex(property.getMethod.getName(), property.getMethod.getParameterTypes()); property.setterAccessIndex = ((MethodAccess)access).getIndex(property.setMethod.getName(), property.setMethod.getParameterTypes()); } } catch (Throwable ignored) { // ReflectASM is not available on Android. } } public void write (Kryo kryo, Output output, T object) { Class type = object.getClass(); for (int i = 0, n = properties.length; i < n; i++) { CachedProperty property = properties[i]; try { if (TRACE) trace("kryo", "Write property: " + property + " (" + type.getName() + ")"); Object value = property.get(object); Serializer serializer = property.serializer; if (serializer != null) kryo.writeObjectOrNull(output, value, serializer); else kryo.writeClassAndObject(output, value); } catch (IllegalAccessException ex) { throw new KryoException("Error accessing getter method: " + property + " (" + type.getName() + ")", ex); } catch (InvocationTargetException ex) { throw new KryoException("Error invoking getter method: " + property + " (" + type.getName() + ")", ex); } catch (KryoException ex) { ex.addTrace(property + " (" + type.getName() + ")"); throw ex; } catch (RuntimeException runtimeEx) { KryoException ex = new KryoException(runtimeEx); ex.addTrace(property + " (" + type.getName() + ")"); throw ex; } } } public T read (Kryo kryo, Input input, Class<T> type) { T object = kryo.newInstance(type); kryo.reference(object); for (int i = 0, n = properties.length; i < n; i++) { CachedProperty property = properties[i]; try { if (TRACE) trace("kryo", "Read property: " + property + " (" + object.getClass() + ")"); Object value; Serializer serializer = property.serializer; if (serializer != null) value = kryo.readObjectOrNull(input, property.setMethodType, serializer); else value = kryo.readClassAndObject(input); property.set(object, value); } catch (IllegalAccessException ex) { throw new KryoException("Error accessing setter method: " + property + " (" + object.getClass().getName() + ")", ex); } catch (InvocationTargetException ex) { throw new KryoException("Error invoking setter method: " + property + " (" + object.getClass().getName() + ")", ex); } catch (KryoException ex) { ex.addTrace(property + " (" + object.getClass().getName() + ")"); throw ex; } catch (RuntimeException runtimeEx) { KryoException ex = new KryoException(runtimeEx); ex.addTrace(property + " (" + object.getClass().getName() + ")"); throw ex; } } return object; } public T copy (Kryo kryo, T original) { T copy = (T)kryo.newInstance(original.getClass()); for (int i = 0, n = properties.length; i < n; i++) { CachedProperty property = properties[i]; try { Object value = property.get(original); property.set(copy, value); } catch (KryoException ex) { ex.addTrace(property + " (" + copy.getClass().getName() + ")"); throw ex; } catch (RuntimeException runtimeEx) { KryoException ex = new KryoException(runtimeEx); ex.addTrace(property + " (" + copy.getClass().getName() + ")"); throw ex; } catch (Exception ex) { throw new KryoException("Error copying bean property: " + property + " (" + copy.getClass().getName() + ")", ex); } } return copy; } class CachedProperty<X> { String name; Method getMethod, setMethod; Class setMethodType; Serializer serializer; int getterAccessIndex, setterAccessIndex; public String toString () { return name; } Object get (Object object) throws IllegalAccessException, InvocationTargetException { if (access != null) return ((MethodAccess)access).invoke(object, getterAccessIndex); return getMethod.invoke(object, noArgs); } void set (Object object, Object value) throws IllegalAccessException, InvocationTargetException { if (access != null) { ((MethodAccess)access).invoke(object, setterAccessIndex, value); return; } setMethod.invoke(object, new Object[] {value}); } } }
39.111675
128
0.684231
6ccb604c9a91b354e86b85f57a5f7851548a24f2
2,255
/* * Copyright 2019 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 com.netflix.spinnaker.front50.migrations; import com.netflix.spinnaker.front50.model.application.Application; import com.netflix.spinnaker.front50.model.application.ApplicationDAO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.time.Clock; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; @Component public class CloudProvidersStringMigration implements Migration { private static final Logger log = LoggerFactory.getLogger(CloudProvidersStringMigration.class); // Only valid until June 1st, 2020 private static final Date VALID_UNTIL = new GregorianCalendar(2020, 6, 1).getTime(); @Autowired private ApplicationDAO applicationDAO; private Clock clock = Clock.systemDefaultZone(); @Override public boolean isValid() { return clock.instant().toEpochMilli() < VALID_UNTIL.getTime(); } @Override public void run() { log.info("Starting cloud provider string migration"); for (Application a : applicationDAO.all()) { if (a.details().get("cloudProviders") instanceof List) { migrate(a); } } } private void migrate(Application application) { log.info("Converting cloudProviders ({}) for application {} from a List to a String for {}", application.details().get("cloudProviders").toString(), application.getName()); application.set("cloudProviders", String.join(",", (List<String>) application.details().get("cloudProviders"))); application.update(application); } }
33.656716
116
0.746341
4f60515a59ea107ef6d352e1338efdbcaa288b74
4,212
package br.edu.ufcspa.tc6m.dao; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.support.annotation.NonNull; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import br.edu.ufcspa.tc6m.modelo.Paciente; /** * Created by edupooch on 17/02/16. */ public class PacienteDAO extends SQLiteOpenHelper { public PacienteDAO(Context context) { super(context, "Agenda", null, 3); } @Override public void onCreate(SQLiteDatabase db) { String sql = "CREATE TABLE Pacientes (id INTEGER PRIMARY KEY, " + "nome TEXT NOT NULL, " + "data TEXT NOT NULL, " + "peso FLOAT NOT NULL, " + "altura TEXT NOT NULL, " + "telefone TEXT, " + "email TEXT, " + "obs TEXT," + "genero INTEGER," + "caminhoFoto TEXT);"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { //Esquema para controle de versões do banco: String sql; switch (oldVersion) { case 1: sql = "ALTER TABLE Pacientes ADD COLUMN genero INTEGER;"; db.execSQL(sql); case 2: sql = "ALTER TABLE Pacientes ADD COLUMN genero INTEGER;"; db.execSQL(sql); } } public void insere(Paciente paciente) { SQLiteDatabase db = getWritableDatabase(); ContentValues dados = getContentValuesPaciente(paciente); db.insert("Pacientes", null, dados); } @NonNull private ContentValues getContentValuesPaciente(Paciente paciente) { ContentValues dados = new ContentValues(); dados.put("nome", paciente.getNome()); SimpleDateFormat dtFormat = new SimpleDateFormat("yyyy-MM-dd"); dados.put("data", dtFormat.format(paciente.getDataNascimento())); dados.put("peso", paciente.getMassa()); dados.put("altura", paciente.getEstatura()); dados.put("telefone", paciente.getTelefone()); dados.put("email", paciente.getEmail()); dados.put("obs", paciente.getObs()); dados.put("genero", paciente.getGenero()); dados.put("caminhoFoto", paciente.getCaminhoFoto()); return dados; } public List<Paciente> buscaPacientes() { String sql = "SELECT * FROM Pacientes;"; SQLiteDatabase db = getReadableDatabase(); Cursor c = db.rawQuery(sql, null); List<Paciente> pacientes = new ArrayList<Paciente>(); while (c.moveToNext()) { Paciente paciente = new Paciente(); paciente.setId(c.getLong(c.getColumnIndex("id"))); paciente.setNome(c.getString(c.getColumnIndex("nome"))); paciente.setDataNascimento(java.sql.Date.valueOf(c.getString(c.getColumnIndex("data")))); paciente.setMassa(c.getDouble(c.getColumnIndex("peso"))); paciente.setEstatura(c.getDouble(c.getColumnIndex("altura"))); paciente.setTelefone(c.getString(c.getColumnIndex("telefone"))); paciente.setEmail(c.getString(c.getColumnIndex("email"))); paciente.setObs(c.getString(c.getColumnIndex("obs"))); paciente.setGenero(c.getInt(c.getColumnIndex("genero"))); paciente.setCaminhoFoto(c.getString(c.getColumnIndex("caminhoFoto"))); pacientes.add(paciente); } c.close(); return pacientes; } public void deleta(Paciente paciente) { SQLiteDatabase db = getWritableDatabase(); String[] parametros = {paciente.getId().toString()}; db.delete("Pacientes", "id = ?", parametros); } public void altera(Paciente paciente) { SQLiteDatabase db = getWritableDatabase(); ContentValues dados2 = getContentValuesPaciente(paciente); String[] param = {paciente.getId().toString()}; db.update("Pacientes", dados2, "id = ?", param); } }
33.967742
101
0.619183
b83c49170a23c1a625a5e8a1eb08d47d3cb48d32
216
@javax.xml.bind.annotation.XmlSchema(namespace = "urn:wco:datamodel:WCO:DocumentMetaData-DMS:2", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package wco.datamodel.wco.documentmetadata_dms._2;
72
164
0.833333
853c3e8fc0080e3223ad0032eeea9931274f36ca
495
package com.mt.demo.upload.swagger.config; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; /** * ResultStateEnum * * @author mt.luo * @description: */ @AllArgsConstructor @NoArgsConstructor public enum ResultStateEnum { /** * success */ SUCCESS(1000, "success"), /** * error */ ERROR(1001, "error"); @Getter private Integer code; @Getter private String message; }
16.5
43
0.612121
a3418e0d2cd25e6be1e22608f3fb4b85afbdbe0a
1,905
package com.github.kwoin.kgate.test; import com.github.kwoin.kgate.core.configuration.KGateConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ServerSocketFactory; import javax.net.ssl.SSLServerSocketFactory; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; /** * @author P. WILLEMET */ public class DummyServer { private final Logger logger = LoggerFactory.getLogger(DummyServer.class); private ServerSocket serverSocket; private boolean started; public void start(Callback callback, boolean tls) throws IOException { try { ServerSocketFactory factory = tls ? SSLServerSocketFactory.getDefault() : ServerSocketFactory.getDefault(); serverSocket = factory.createServerSocket( KGateConfig.getConfig().getInt("kgate.core.client.port"), 1, InetAddress.getByName(KGateConfig.getConfig().getString("kgate.core.client.host"))); } catch (IOException e) { throw new RuntimeException(e); } started = true; Thread t = new Thread(new Runnable() { @Override public void run() { try { while (started) callback.execute(serverSocket.accept()); } catch (SocketException e) { logger.debug("Server accept() interrupted"); } catch (IOException e) { logger.error("Unexpected error while listening to new connection", e); } } }); t.start(); } public void stop() throws IOException { started = false; serverSocket.close(); } public interface Callback { void execute(Socket socket); } }
26.830986
119
0.610499
39ea2d9724578e5f69f4a76ec69ed619dc51ee98
2,486
package com.scoreboard.app.utils; import com.scoreboard.app.comment.dto.CommentDto; import com.scoreboard.app.comment.repository.Comment; import com.scoreboard.app.game.repository.Game; import com.scoreboard.app.game.repository.PlayerStat; import java.time.ZonedDateTime; import java.util.UUID; public class EntityCreator { public static class CommentCreator { private static final String COMMENT_ID = UUID.randomUUID().toString(); private static final String COMMENT_TEXT = "Testing comment"; private static final Long GAME_ID = 1L; private static final ZonedDateTime MODIFIED_DATE = ZonedDateTime.now(); public static Comment createComment() { return Comment.builder() .gameId(GAME_ID) .text(COMMENT_TEXT) .id(COMMENT_ID) .modifiedDate(MODIFIED_DATE) .build(); } public static CommentDto createCommentDto() { CommentDto commentDto = new CommentDto(); commentDto.setId(COMMENT_ID); commentDto.setText(COMMENT_TEXT); commentDto.setGameId(GAME_ID); commentDto.setModifiedDate(MODIFIED_DATE); return commentDto; } } public static class GameCreator { private static final Long GAME_ID = 1L; private static final String VISITOR_TEAM_NAME = "VISITOR"; private static final Integer VISITOR_TEAM_SCORE = 10; private static final String HOME_TEAM_NAME = "HOME"; private static final Integer HOME_TEAM_SCORE = 10; private static final String DATE = "2019-02-09 00:00:00 UTC"; public static Game createGame() { return Game.builder() .id(GAME_ID) .homeTeamName(HOME_TEAM_NAME) .homeTeamScore(HOME_TEAM_SCORE) .visitorTeamName(VISITOR_TEAM_NAME) .visitorTeamScore(VISITOR_TEAM_SCORE) .date(DATE) .build(); } } public static class GameStatsCreator { private static final String PLAYER_NAME = "PLAYER"; private static final Integer PLAYER_SCORE = 10; public static PlayerStat createPlayerStat() { return PlayerStat.builder() .playerName(PLAYER_NAME) .playerScore(PLAYER_SCORE) .build(); } } }
33.146667
79
0.609815
19bfa119ec16c0b582f010c75fe3f71927ea5f5e
3,159
/* * Copyright © 2015 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 co.cask.cdap.api.workflow; import co.cask.cdap.api.customaction.CustomActionSpecification; import co.cask.cdap.api.schedule.SchedulableProgramType; import javax.annotation.Nullable; /** * Represents the ACTION node in the {@link Workflow}. */ public class WorkflowActionNode extends WorkflowNode { private final ScheduleProgramInfo program; @Deprecated private final WorkflowActionSpecification actionSpecification; private final CustomActionSpecification customActionSpecification; public WorkflowActionNode(String nodeId, ScheduleProgramInfo program) { super(nodeId, WorkflowNodeType.ACTION); this.program = program; this.actionSpecification = null; this.customActionSpecification = null; } @Deprecated public WorkflowActionNode(String nodeId, WorkflowActionSpecification actionSpecification) { super(nodeId, WorkflowNodeType.ACTION); this.program = new ScheduleProgramInfo(SchedulableProgramType.CUSTOM_ACTION, actionSpecification.getName()); this.actionSpecification = actionSpecification; this.customActionSpecification = null; } public WorkflowActionNode(String nodeId, CustomActionSpecification customActionSpecification) { super(nodeId, WorkflowNodeType.ACTION); this.program = new ScheduleProgramInfo(SchedulableProgramType.CUSTOM_ACTION, customActionSpecification.getName()); this.customActionSpecification = customActionSpecification; this.actionSpecification = null; } /** * * @return the program information associated with the {@link WorkflowNode} */ public ScheduleProgramInfo getProgram() { return program; } /** * * @return the {@link WorkflowActionSpecification} for the custom action represented by this {@link WorkflowNode} */ @Deprecated @Nullable public WorkflowActionSpecification getActionSpecification() { return actionSpecification; } /** * @return the {@link CustomActionSpecification} if this {@link WorkflowNode} represents the custom action, * otherwise null is returned */ @Nullable public CustomActionSpecification getCustomActionSpecification() { return customActionSpecification; } @Override public String toString() { StringBuilder sb = new StringBuilder("WorkflowActionNode{"); sb.append("nodeId=").append(nodeId); sb.append("program=").append(program); sb.append(", actionSpecification=").append(actionSpecification); sb.append(", customActionSpecification=").append(customActionSpecification); sb.append('}'); return sb.toString(); } }
33.967742
118
0.759418
c7aac5ff443d715c1e99c2784c8ee6ccfee1259a
899
/* COLA DE PRIORIDADES EN UN MONTÍCULO A continuación se escribe su implementación utilizando las operaciones básicas del montículo. Naturalmente, los elementos son referencias a Tarea que implementa la interfaz Comparador. */ package PriorityQueues1; public class AplicacionCP { //Creo un Monticulo/Binary heap protected Monticulo cp;//Creo un Monticulo/Binary heap //Construcutor public AplicacionCP() { //Inciializo mi monticulo: cp = new Monticulo(); } //Añade una tarea a la cola public void insertarEnPrioridad(Tarea t) { cp.insertar((Comparable) t); } public Tarea elementoMin() throws Exception { return (Tarea) cp.buscarMinimo(); } public Tarea quitarMin() throws Exception { return (Tarea) cp.eliminarMinimo(); } public boolean colaPrioridadVacia() { return cp.esVacio(); } }
24.297297
93
0.682981
9de54a0549b30f6446ec2fcc37d63891b4dc4d23
1,475
package com.twu.biblioteca; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; public class ReturnBookTest { PrintStream console = null; ByteArrayOutputStream bytes = null; BookRepository bookRepository; @Before public void setUp() { bytes = new ByteArrayOutputStream(); console = System.out; System.setOut(new PrintStream(bytes)); bookRepository = new BookRepository(); bookRepository.createMockList(); bookRepository.getBookList().get("To Kill a MockingBird").setCheckedOut(true); } @After public void tearDown() { System.setOut(console); } @Test public void shouldSetCheckOutToFalseAfterReturn() { bookRepository.returnBook("To Kill a MockingBird"); assertFalse(bookRepository.getBookList().get("To Kill a MockingBird").isCheckedOut()); } @Test public void shouldPrintMessageWhenReturnSuccessfully() { bookRepository.returnBook("To Kill a MockingBird"); assertEquals("Thank you for returning the book\n", bytes.toString()); } @Test public void shouldPrintNoticeMessageWhenReturnInvalid() { bookRepository.returnBook("Animal Farm"); assertEquals("That is not a valid book to return\n", bytes.toString()); } }
27.314815
94
0.696949
df6dbb19dc30cbce4dd1881f0437034509970a3f
294
package edu.psu.presenations.simple; import edu.psu.presenations.defaultabstract.Orientable; public class OrientableWithDefaults implements Orientable { public static void main(String[] args) { OrientableWithDefaults twd = new OrientableWithDefaults(); twd.rotate(); } }
18.375
62
0.755102
1bf3dc585f7deabb92777621d94106e0de11858a
2,637
package my.pkg.name; import java.net.URI; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import microsoft.exchange.webservices.data.core.ExchangeService; import microsoft.exchange.webservices.data.core.PropertySet; import microsoft.exchange.webservices.data.core.enumeration.property.BasePropertySet; import microsoft.exchange.webservices.data.core.enumeration.property.WellKnownFolderName; import microsoft.exchange.webservices.data.core.enumeration.search.LogicalOperator; import microsoft.exchange.webservices.data.core.enumeration.search.SortDirection; import microsoft.exchange.webservices.data.core.service.item.Item; import microsoft.exchange.webservices.data.core.service.schema.ItemSchema; import microsoft.exchange.webservices.data.search.FindItemsResults; import microsoft.exchange.webservices.data.search.ItemView; import microsoft.exchange.webservices.data.search.filter.SearchFilter; @RestController public class EWSController { /** * * Outlook client. * * Demonstrates a filtered fetch of items from your inbox * * @return * @throws Exception */ @RequestMapping("/getMessageCount") public String getMessageCount() throws Exception { String email = "your gov email here"; String passwd ="your idir password here"; ExchangeService service = EWSAutodiscoverAPI.connectViaExchangeAutodiscover(email, passwd); // current (DEV) API Gateway endpoint for EWS service.setUrl(new URI("https://wsgw.dev.jag.gov.bc.ca/dps/bcgov/ews/services/Exchange.asmx")); FindItemsResults<Item> findResults = findItems(service); return Integer.toString(findResults.getTotalCount()) + " Messages found in you Inbox"; } private FindItemsResults<Item> findItems(ExchangeService service) throws Exception { ItemView view = new ItemView(10); view.getOrderBy().add(ItemSchema.DateTimeReceived, SortDirection.Ascending); view.setPropertySet(new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived)); FindItemsResults<Item> findResults = service.findItems(WellKnownFolderName.Inbox, new SearchFilter.SearchFilterCollection( LogicalOperator.Or, new SearchFilter.ContainsSubstring(ItemSchema.Subject, "EWS"), new SearchFilter.ContainsSubstring(ItemSchema.Subject, "API")), view); //MOOOOOOST IMPORTANT: load items properties, before service.loadPropertiesForItems(findResults, PropertySet.FirstClassProperties); System.out.println("Total number of items found: " + findResults.getTotalCount()); return findResults; } }
39.358209
112
0.79105
3deff4a652cd39249f4006cc943901dc2a9b560c
434
package lists.chap14.list14_03; import java.util.Calendar; import java.util.Date; public class Main { public static void main(String[] args) { // 現在の年を表示する Date now = new Date(); Calendar c = Calendar.getInstance(); c.setTime(now); int y = c.get(Calendar.YEAR); System.out.println("今年は" + y + "年です"); // 指定した日のDate型の値を得る c.set(2010, 8, 22, 1, 23, 45); c.set(Calendar.YEAR, 2011); Date past = c.getTime(); } }
20.666667
41
0.656682
662d2bf5b08a709627761e36793a9aaa00940a0a
1,897
package com.skjanyou.desktop.swt; import java.util.Queue; import java.util.concurrent.LinkedBlockingDeque; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; public class SwtResourcesManager { private static Display defaultDisplay = Display.getDefault(); private static Shell defaultShell = new Shell(defaultDisplay); private static Queue<Shell> shellQueue = new LinkedBlockingDeque<>(); private static boolean isRunning = true; private static class SubWindowCreateEvent extends Event { private Shell shell; public void setShell( Shell shell ){ this.shell = shell; } public Shell getShell(){ return this.shell; } } static { defaultShell.addListener(SWT.None, new Listener() { @Override public void handleEvent(Event event) { if( event instanceof SubWindowCreateEvent ){ SubWindowCreateEvent e = (SubWindowCreateEvent) event; Shell subShell = new Shell(); e.setShell(subShell); } } }); } public static Display getDefaultDisplay(){ return defaultDisplay; } public static Shell getDefaultShell(){ return defaultShell; } public static Shell createSubWindow(){ SubWindowCreateEvent event = new SubWindowCreateEvent(); defaultShell.getListeners(SWT.None)[0].handleEvent(event); Shell shell = event.getShell(); shellQueue.add(shell); return shell; } public static void keep(){ while (!defaultShell.isDisposed() && isRunning ) { if (!defaultDisplay.readAndDispatch()) { defaultDisplay.sleep(); } } } public static void exit(){ Shell shell = null; // 将所有创建的shell都关闭 while( ( shell = shellQueue.poll() ) != null ){ shell.dispose(); } // 再终止主线程 isRunning = false; } }
25.293333
71
0.691618
acf373a7de5fe74f86a96f7669ad66646175e587
3,001
/* * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.io; /** * Signals that an attempt to open the file denoted by a specified pathname * has failed. * * <p> This exception will be thrown by the {@link FileInputStream}, {@link * FileOutputStream}, and {@link RandomAccessFile} constructors when a file * with the specified pathname does not exist. It will also be thrown by these * constructors if the file does exist but for some reason is inaccessible, for * example when an attempt is made to open a read-only file for writing. * * @author unascribed * @since JDK1.0 */ public class FileNotFoundException extends IOException { private static final long serialVersionUID = -897856973823710492L; /** * Constructs a <code>FileNotFoundException</code> with * <code>null</code> as its error detail message. */ public FileNotFoundException() { super(); } /** * Constructs a <code>FileNotFoundException</code> with the * specified detail message. The string <code>s</code> can be * retrieved later by the * <code>{@link java.lang.Throwable#getMessage}</code> * method of class <code>java.lang.Throwable</code>. * * @param s the detail message. */ public FileNotFoundException(String s) { super(s); } /** * Constructs a <code>FileNotFoundException</code> with a detail message * consisting of the given pathname string followed by the given reason * string. If the <code>reason</code> argument is <code>null</code> then * it will be omitted. This private constructor is invoked only by native * I/O methods. * * @since 1.2 */ private FileNotFoundException(String path, String reason) { super(path + ((reason == null) ? "" : " (" + reason + ")")); } }
37.049383
79
0.699434
7020cb87de4b57d894ac161388783a5aeb5bbd34
7,991
/** */ package org.jboss.drools.util; import java.util.List; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.jboss.drools.DocumentRoot; import org.jboss.drools.DroolsPackage; import org.jboss.drools.GlobalType; import org.jboss.drools.ImportType; import org.jboss.drools.MetaDataType; import org.jboss.drools.OnEntryScriptType; import org.jboss.drools.OnExitScriptType; /** * <!-- begin-user-doc --> * The <b>Switch</b> for the model's inheritance hierarchy. * It supports the call {@link #doSwitch(EObject) doSwitch(object)} * to invoke the <code>caseXXX</code> method for each class of the model, * starting with the actual class of the object * and proceeding up the inheritance hierarchy * until a non-null result is returned, * which is the result of the switch. * <!-- end-user-doc --> * @see org.jboss.drools.DroolsPackage * @generated */ public class DroolsSwitch<T> { /** * The cached model package * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static DroolsPackage modelPackage; /** * Creates an instance of the switch. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DroolsSwitch() { if (modelPackage == null) { modelPackage = DroolsPackage.eINSTANCE; } } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ public T doSwitch(EObject theEObject) { return doSwitch(theEObject.eClass(), theEObject); } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ protected T doSwitch(EClass theEClass, EObject theEObject) { if (theEClass.eContainer() == modelPackage) { return doSwitch(theEClass.getClassifierID(), theEObject); } else { List<EClass> eSuperTypes = theEClass.getESuperTypes(); return eSuperTypes.isEmpty() ? defaultCase(theEObject) : doSwitch(eSuperTypes.get(0), theEObject); } } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case DroolsPackage.DOCUMENT_ROOT: { DocumentRoot documentRoot = (DocumentRoot)theEObject; T result = caseDocumentRoot(documentRoot); if (result == null) result = defaultCase(theEObject); return result; } case DroolsPackage.GLOBAL_TYPE: { GlobalType globalType = (GlobalType)theEObject; T result = caseGlobalType(globalType); if (result == null) result = defaultCase(theEObject); return result; } case DroolsPackage.IMPORT_TYPE: { ImportType importType = (ImportType)theEObject; T result = caseImportType(importType); if (result == null) result = defaultCase(theEObject); return result; } case DroolsPackage.META_DATA_TYPE: { MetaDataType metaDataType = (MetaDataType)theEObject; T result = caseMetaDataType(metaDataType); if (result == null) result = defaultCase(theEObject); return result; } case DroolsPackage.ON_ENTRY_SCRIPT_TYPE: { OnEntryScriptType onEntryScriptType = (OnEntryScriptType)theEObject; T result = caseOnEntryScriptType(onEntryScriptType); if (result == null) result = defaultCase(theEObject); return result; } case DroolsPackage.ON_EXIT_SCRIPT_TYPE: { OnExitScriptType onExitScriptType = (OnExitScriptType)theEObject; T result = caseOnExitScriptType(onExitScriptType); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } } /** * Returns the result of interpreting the object as an instance of '<em>Document Root</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Document Root</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseDocumentRoot(DocumentRoot object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Global Type</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Global Type</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseGlobalType(GlobalType object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Import Type</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Import Type</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseImportType(ImportType object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Meta Data Type</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Meta Data Type</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseMetaDataType(MetaDataType object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>On Entry Script Type</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>On Entry Script Type</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseOnEntryScriptType(OnEntryScriptType object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>On Exit Script Type</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>On Exit Script Type</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseOnExitScriptType(OnExitScriptType object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>EObject</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch, but this is the last case anyway. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>EObject</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */ public T defaultCase(EObject object) { return null; } } //DroolsSwitch
33.7173
118
0.692654
72f363caf151085b5f18b9ebabf9a08a7d5f13f2
2,331
package org.batfish.specifier; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.util.regex.Pattern; import org.batfish.datamodel.IpWildcard; import org.batfish.datamodel.questions.InterfacesSpecifier; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class FlexibleInterfaceSpecifierFactoryTest { @Rule public final ExpectedException exception = ExpectedException.none(); @Test public void testConnectedTo() { assertThat( new FlexibleInterfaceSpecifierFactory().buildInterfaceSpecifier("connectedTo(1.2.3.4)"), equalTo(new InterfaceWithConnectedIpsSpecifier(new IpWildcard("1.2.3.4").toIpSpace()))); } @Test public void testGarbageIn() { exception.expect(IllegalArgumentException.class); new FlexibleInterfaceSpecifierFactory().buildInterfaceSpecifier("fofoao:klklk:opopo:oo"); } @Test public void testLoad() { assertTrue( InterfaceSpecifierFactory.load(FlexibleInterfaceSpecifierFactory.NAME) instanceof FlexibleInterfaceSpecifierFactory); } @Test public void testNull() { assertThat( new FlexibleInterfaceSpecifierFactory().buildInterfaceSpecifier(null), equalTo(new ShorthandInterfaceSpecifier(InterfacesSpecifier.ALL))); } @Test public void testReferenceInterfaceGroup() { assertThat( new FlexibleInterfaceSpecifierFactory().buildInterfaceSpecifier("ref.interfaceGroup(a, b)"), equalTo(new ReferenceInterfaceGroupInterfaceSpecifier("a", "b"))); } @Test public void testShorthand() { assertThat( new FlexibleInterfaceSpecifierFactory().buildInterfaceSpecifier("name:.*"), equalTo(new ShorthandInterfaceSpecifier(new InterfacesSpecifier("name:.*")))); } @Test public void testType() { assertThat( new FlexibleInterfaceSpecifierFactory().buildInterfaceSpecifier("type(.*)"), equalTo( new TypeNameRegexInterfaceSpecifier(Pattern.compile(".*", Pattern.CASE_INSENSITIVE)))); } @Test public void testVrf() { assertThat( new FlexibleInterfaceSpecifierFactory().buildInterfaceSpecifier("vrf(.*)"), equalTo(new VrfNameRegexInterfaceSpecifier(Pattern.compile(".*")))); } }
31.5
100
0.739168
48c0db95a17de36ec1ce9b37be820c60b099b244
1,796
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.thespheres.betula.services.implementation.ui.build; import java.util.function.BiConsumer; import java.util.function.Consumer; import org.openide.util.EditableProperties; import org.thespheres.betula.adminconfig.ConfigurationBuilder; import org.thespheres.betula.adminconfig.layerxml.LayerFileSystem; import org.thespheres.betula.services.implementation.ui.impl.SyncedProviderInstance; import org.thespheres.betula.adminconfig.ConfigurationBuildTask; /** * * @author boris.heithecker */ class ConfigurationBuilderImpl implements ConfigurationBuilder { private final SyncedProviderInstance instance; ConfigurationBuilderImpl(SyncedProviderInstance instance) { this.instance = instance; } @Override public void buildLayer(BiConsumer<ConfigurationBuildTask, LayerFileSystem> agent) { final LayerUpdater lu = new LayerUpdater(instance, agent); instance.submit(lu); } @Override public void buildLocalProperties(BiConsumer<ConfigurationBuildTask, EditableProperties> agent) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void buildResources(String resources, Consumer<ConfigurationBuildTask> agent) { buildResources(resources, agent, null); } @Override public void buildResources(String resources, Consumer<ConfigurationBuildTask> agent, String providedLock) { final ResourceUpdater ru = new ResourceUpdater(instance, resources, agent, providedLock); instance.submit(ru); } }
35.215686
135
0.767261
187e17b5357e69620a9c86aaa570d783e7e21187
498
package org.ansj.recognition.impl; import org.ansj.domain.Result; import org.ansj.splitWord.analysis.ToAnalysis; import org.junit.Assert; import org.junit.Test; public class EmailRecognitionTest { @Test public void recognition() throws Exception { Result recognition = null ; recognition = ToAnalysis.parse("[email protected]是一个好网址").recognition(new EmailRecognition()); System.out.println(recognition); Assert.assertEquals(recognition.get(0).getName(), ("[email protected]")); } }
22.636364
95
0.761044
744ea07da9a06f90ce4a3924dfac6f20d1e984c4
4,992
package de.tarent.mica.maze.bot.strategy.navigation; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeUnit; import de.tarent.mica.maze.model.Coord; import de.tarent.mica.maze.model.Direction; import de.tarent.mica.maze.model.Field; import de.tarent.mica.maze.model.Maze; /** * This class is responsible for finding a route from a start position to a * destination. * * @author rainu */ public class RecursiveFinder { private List<List<Coord>> routes = new LinkedList<>(); private final Maze maze; private final Coord start; private final Coord dest; private final long maxDuration; private final long startTime; public RecursiveFinder(Maze maze, Coord start, Coord dest, TimeUnit unit, long maxDuration) { this.maze = maze; this.start = start; this.dest = dest; this.maxDuration = TimeUnit.MILLISECONDS.convert(maxDuration, unit); this.startTime = System.currentTimeMillis(); walk(new LinkedList<Coord>(), start, dest); Collections.sort(routes, new Comparator<List<Coord>>() { @Override public int compare(List<Coord> o1, List<Coord> o2) { return Integer.compare(o1.size(), o2.size()); } }); } public RecursiveFinder(Maze maze, Coord start, Coord dest) { this(maze, start, dest, TimeUnit.SECONDS, 5); } private void walk(List<Coord> walkedWay, Coord curCoord, final Coord dest) { if (timeIsOver()) { return; } if (visited(walkedWay, curCoord)) { return; } walkedWay.add(curCoord); if (destinationReached(curCoord, dest)) { saveWay(walkedWay); return; } if (worseThanBest(walkedWay)) { return; } Collection<Coord> neighbors = getNeighbors(curCoord, dest); for (Coord n : neighbors) { walk(copyWay(walkedWay), n, dest); } } private boolean timeIsOver() { return (startTime + maxDuration) <= System.currentTimeMillis(); } private boolean visited(List<Coord> walkedWay, Coord curCoord) { return walkedWay.contains(curCoord); } private boolean destinationReached(Coord curCoord, Coord dest) { return curCoord.equals(dest); } private boolean worseThanBest(List<Coord> walkedWay) { int longest = getLongestWay(); return walkedWay.size() >= longest; } private int getLongestWay() { int longest = Integer.MAX_VALUE; for (List<Coord> r : routes) { if (r.size() > longest) { longest = r.size(); } } return longest; } private void saveWay(List<Coord> walkedWay) { List<Coord> copy = copyWay(walkedWay); routes.add(Collections.unmodifiableList(copy)); } private List<Coord> copyWay(List<Coord> walkedWay) { List<Coord> copy = new LinkedList<>(); for (Coord c : walkedWay) { copy.add(c.clone()); } return copy; } private List<Coord> getNeighbors(Coord curCoord, Coord dest) { List<Coord> neighbors = new LinkedList<>(); List<Direction> directions = getShortestDirections(curCoord, dest); for (Direction dir : directions) { switch (dir) { case NORTH: neighbors.add(curCoord.north()); break; case EAST: neighbors.add(curCoord.east()); break; case SOUTH: neighbors.add(curCoord.south()); break; case WEST: neighbors.add(curCoord.west()); break; } } Iterator<Coord> iter = neighbors.iterator(); while (iter.hasNext()) { Field f = maze.getField(iter.next()); if (f == null || f.isWall()) { iter.remove(); } } return neighbors; } // TODO: Vorher das Labyrinth analysieren... je nach "bauart" ist eine // "rekursionsrichtung" besser geeignet private List<Direction> getShortestDirections(Coord curCord, Coord dest) { List<Direction> result = new ArrayList<Direction>(4); int horizontalDist = Math.max(curCord.getX(), dest.getX()) - Math.min(curCord.getX(), dest.getX()); int verticalDist = Math.max(curCord.getY(), dest.getY()) - Math.min(curCord.getY(), dest.getY()); if (horizontalDist > verticalDist) { if (curCord.getX() < dest.getX()) { result.add(Direction.EAST); } else if (curCord.getX() > dest.getX()) { result.add(Direction.WEST); } } if (horizontalDist < verticalDist) { if (curCord.getY() < dest.getY()) { result.add(Direction.NORTH); } else if (curCord.getY() > dest.getY()) { result.add(Direction.SOUTH); } } if (!result.contains(Direction.NORTH)) result.add(Direction.NORTH); if (!result.contains(Direction.EAST)) result.add(Direction.EAST); if (!result.contains(Direction.SOUTH)) result.add(Direction.SOUTH); if (!result.contains(Direction.WEST)) result.add(Direction.WEST); return result; } public List<List<Coord>> getRoutes() { Collections.sort(routes, new Comparator<List<Coord>>() { @Override public int compare(List<Coord> o1, List<Coord> o2) { return Integer.compare(o1.size(), o2.size()); } }); return Collections.unmodifiableList(routes); } }
24.835821
77
0.686498
60ccabfba5f2b1042e2629a309e47af06ac5ec54
4,280
/* * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.vm.ci.hotspot; import java.lang.reflect.Modifier; import jdk.vm.ci.meta.JavaMethod; import jdk.vm.ci.meta.ResolvedJavaMethod; import jdk.vm.ci.meta.ResolvedJavaType; /** * Implementation of {@link JavaMethod} for resolved HotSpot methods. */ public interface HotSpotResolvedJavaMethod extends ResolvedJavaMethod { /** * Returns true if this method has a {@code CallerSensitive} annotation. * * @return true if CallerSensitive annotation present, false otherwise */ boolean isCallerSensitive(); HotSpotResolvedObjectType getDeclaringClass(); /** * Returns true if this method has a {@code ForceInline} annotation. * * @return true if ForceInline annotation present, false otherwise */ boolean isForceInline(); /** * Returns true if this method has a {@code ReservedStackAccess} annotation. * * @return true if ReservedStackAccess annotation present, false otherwise */ boolean hasReservedStackAccess(); /** * Sets flags on {@code method} indicating that it should never be inlined or compiled by the VM. */ void setNotInlinableOrCompilable(); /** * Returns true if this method is one of the special methods that is ignored by security stack * walks. * * @return true if special method ignored by security stack walks, false otherwise */ boolean ignoredBySecurityStackWalk(); ResolvedJavaMethod uniqueConcreteMethod(HotSpotResolvedObjectType receiver); /** * Returns whether this method has compiled code. * * @return true if this method has compiled code, false otherwise */ boolean hasCompiledCode(); /** * @param level * @return true if the currently installed code was generated at {@code level}. */ boolean hasCompiledCodeAtLevel(int level); default boolean isDefault() { if (isConstructor()) { return false; } // Copied from java.lang.Method.isDefault() int mask = Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC; return ((getModifiers() & mask) == Modifier.PUBLIC) && getDeclaringClass().isInterface(); } /** * Returns the offset of this method into the v-table. The method must have a v-table entry as * indicated by {@link #isInVirtualMethodTable(ResolvedJavaType)}, otherwise an exception is * thrown. * * @return the offset of this method into the v-table */ int vtableEntryOffset(ResolvedJavaType resolved); int intrinsicId(); /** * Determines if this method denotes itself as a candidate for intrinsification. As of JDK 9, * this is denoted by the {@code HotSpotIntrinsicCandidate} annotation. In earlier JDK versions, * this method returns true. * * @see <a href="https://bugs.openjdk.java.net/browse/JDK-8076112">JDK-8076112</a> */ boolean isIntrinsicCandidate(); /** * Allocates a compile id for this method by asking the VM for one. * * @param entryBCI entry bci * @return compile id */ int allocateCompileId(int entryBCI); boolean hasCodeAtLevel(int entryBCI, int level); int methodIdnum(); }
33.4375
101
0.692523
5cbc2d979e1587a7c229d3fafe20a0fc334346a8
2,959
/** * CopyRight by Chinamobile * * Util.java */ package com.chinamobile.bcbsp.deploy; import java.io.BufferedWriter; public class Util { public static class SystemConf { public static String MASTER_NAME_HEADER = "three-master-name"; public static String SYSTEM_CHECK_FILE = "profile"; public static String JDK_HOME_CHECK_HEADER = "JAVA_HOME="; public static String BCBSP_HOME_PATH_HEADER = "BCBSP_HOME="; public static String HADOOP_HOME_PATH_HEADER = "HADOOP_HOME="; public static String DEPLOY_CACHE_DIR = "cache"; public static String DEPLOY_CACHE_File = "cache.info"; public static String DEPLOY_TEMP_DIR = "tmp"; } public static class BCBSPConf { public static String BCBSP_CONF_DIR = "conf"; public static String BCBSP_CONF_ENV_FILE = "bcbsp-env.sh"; public static String BCBSP_CONF_SITE_FILE = "bcbsp-site.xml"; public static String BCBSP_CONF_WORKERS_FILE = "workermanager"; } public static class HadoopConf { public static String HADOOP_CONF_DIR = "conf"; public static String HADOOP_CONF_ENV_FILE = "hadoop-env.sh"; public static String HADOOP_CONF_CORE_FILE = "core-site.xml"; public static String HADOOP_CONF_HDFS_FILE = "hdfs-site.xml"; public static String HADOOP_CONF_MAPRED_FILE = "mapred-site.xml"; public static String HADOOP_CONF_SLAVES_FILE = "slaves"; } public static class XML { public static String VERSION_INFO = "<?xml version=\"1.0\"?>"; public static String TYPE_INFO = "<?xml-stylesheet type=\"text/xsl\" href=\"configuration.xsl\"?>"; public static String CONTENT_START = "<configuration>"; public static String CONTENT_END = "</configuration>"; public static String PROPERTY_START = "<property>"; public static String PROPERTY_END = "</property>"; public static String PROPERTY_NAME_START = "<name>"; public static String PROPERTY_NAME_END = "</name>"; public static String PROPERTY_VALUE_START = "<value>"; public static String PROPERTY_VALUE_END = "</value>"; public static String filter(String content, String startFlag, String endFlag) { String result = null; int start = -1, end = -1; start = content.indexOf(startFlag); end = content.indexOf(endFlag); if (start != -1 && end != -1) { result = content.substring(start + startFlag.length(), end); } return result; } public static void writeHeader(BufferedWriter bw) throws Exception { bw.write(VERSION_INFO); bw.newLine(); bw.write(TYPE_INFO); bw.newLine(); bw.write(CONTENT_START); } public static void writeEnd(BufferedWriter bw) throws Exception { bw.write(CONTENT_END); } public static void writeRecord(BufferedWriter bw, String name, String value) throws Exception { bw.newLine(); bw.write(PROPERTY_START); bw.newLine(); bw.write(PROPERTY_NAME_START + name + PROPERTY_NAME_END); bw.newLine(); bw.write(PROPERTY_VALUE_START + value + PROPERTY_VALUE_END); bw.newLine(); bw.write(PROPERTY_END); } } }
35.22619
101
0.726935
97944605184523d6014323b03b56f8ed2380e725
61,355
/* * roombajssc * * MIT License * * Copyright (c) 2016 Geoffrey Mastenbroek, [email protected] * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * */ package com.maschel.roomba; import com.maschel.roomba.song.RoombaSongNote; import org.apache.log4j.Logger; /** * RoombaJSSC - Library for controlling a roomba using the JSSC serial library. * * This library implements (basically) all the commands and sensors specified * in the iRobot Create 2 Open Interface Specification based on Roomba 600 * http://www.irobot.com/~/media/MainSite/PDFs/About/STEM/Create/create_2_Open_Interface_Spec.pdf * * This abstract class contains all the (serial)implementation independent * methods/commands that can be send to or read from the Roomba. * The main reason to split the roomba commands from the serial implementation * is to give future support for multiple serial libraries and/or library API changes. * * Standard library lifecycle: * * // Setup * RoombaJSSC roomba = new RoombaJSSCSerial(); * String[] ports = roomba.portList(); * roomba.connect("a-serial-port"); // Use portList(); to get available ports. * * // Send commands * roomba.startup(); * roomba.clean(); * // ...etc * * // Read sensor values * while (condition) { * roomba.updateSensors(); * roomba.sleep(50); // Sleep for (min!) 50ms * // Read sensor values * System.out.println(roomba.batteryVoltage()); * // ..etc * } * * // Close connection * roomba.stop(); * roomba.disconnect(); * */ public abstract class RoombaJSSC { final static Logger log = Logger.getLogger(RoombaJSSC.class); boolean connected = false; byte[] currentSensorData = new byte[SENSOR_PACKET_ALL_SIZE]; byte[] sensorDataBuffer = new byte[SENSOR_PACKET_ALL_SIZE]; int sensorDataBufferIndex = 0; private long lastSensorUpdate = 0; public RoombaJSSC() {} public abstract String[] portList(); public abstract boolean connect(String portId); public abstract void disconnect(); public abstract boolean send(byte[] bytes); public abstract boolean send(int b); //region Roomba basic power commands /** * This command starts the OI. You must always send the Start command * before sending any other commands to the OI. */ public void start() { log.info("Sending 'start' command to roomba."); send(OPC_START); } /** * This command starts the OI of the roomba and puts it in Safe mode * which enables user control. Safe mode turns off all LEDs. * This will run the 'start' and 'safe' commands. * <p>Note: Wait at least 500ms before sending any commands.</p> */ public void startup() { log.info("Sending 'startup' and 'safeMode' command to roomba."); byte cmd[] = { (byte)OPC_START, (byte)OPC_SAFE }; send(cmd); } /** * This command stops the OI. All streams will stop and the robot will no longer * respond to commands. Use this command when you are finished working with the robot. */ public void stop() { log.info("Sending 'stop' command to roomba."); send(OPC_STOP); } /** * This command powers down Roomba. The OI can be in Passive, * Safe, or Full mode to accept this command. */ public void powerOff() { log.info("Sending 'powerOff' command to roomba."); send(OPC_POWER); } /** * Reset the Roomba after error, this will also run the 'start' and 'safe' commands. */ public void reset() { log.info("Sending 'reset' command to roomba."); startup(); } /** * This command resets the Roomba, as if you had removed and reinserted the battery. * <p>Note: Wait at least 5000ms before sending any commands.</p> */ public void hardReset() { log.info("Sending 'hardReset' command to roomba."); send(OPC_RESET); } //endregion //region Roomba mode commands /** * This command puts the OI into Safe mode, enabling user control of Roomba. * It turns off all LEDs. The OI can be in Passive, Safe, or Full mode to accept this command. * If a safety condition occurs Roomba reverts automatically to Passive mode. */ public void safeMode() { log.info("Sending 'safe' command to roomba."); send(OPC_SAFE); } /** * This command gives you complete control over Roomba by putting the OI into Full mode, * and turning off the cliff, wheel-drop and internal charger safety features. That is, in Full mode, * Roomba executes any command that you send it, even if the internal charger is plugged in, or command * triggers a cliff or wheel drop condition. */ public void fullMode() { log.info("Sending 'full' command to roomba."); send(OPC_FULL); } //endregion //region Roomba cleaning commands /** * This command starts the default cleaning mode. This is the same as pressing Roomba’s Clean button, * and will pause a cleaning cycle if one is already in progress. */ public void clean() { log.info("Sending 'clean' command to roomba."); send(OPC_CLEAN); } /** * This command starts the Max cleaning mode, which will clean until the battery is dead. * This command will pause a cleaning cycle if one is already in progress. */ public void cleanMax() { log.info("Sending 'cleanMax' command to roomba."); send(OPC_MAX_CLEAN); } /** * This command starts the Spot cleaning mode. This is the same as pressing Roomba’s Spot button, * and will pause a cleaning cycle if one is already in progress. */ public void cleanSpot() { log.info("Sending 'cleanSpot' command to roomba."); send(OPC_SPOT); } /** * This command directs Roomba to drive onto the dock the next time it encounters the docking beams. * This is the same as pressing Roomba’s Dock button, and will pause a cleaning cycle if one is already * in progress. */ public void seekDock() { log.info("Sending 'seekDock' command to roomba."); send(OPC_FORCE_SEEKING_DOCK); } /** * This command sends Roomba a new schedule. To disable scheduled cleaning, send all false and 0s. * @param sun Enable Sunday scheduling * @param mon Enable Monday scheduling * @param tue Enable Tuesday scheduling * @param wed Enable Wednesday scheduling * @param thu Enable Thursday scheduling * @param fri Enable Friday scheduling * @param sat Enable Saturday scheduling * @param sun_hour Sunday scheduled hour * @param sun_min Sunday scheduled minute * @param mon_hour Monday scheduled hour * @param mon_min Monday scheduled minute * @param tue_hour Tuesday scheduled hour * @param tue_min Tuesday scheduled minute * @param wed_hour Wednesday scheduled hour * @param wed_min Wednesday scheduled minute * @param thu_hour Thursday scheduled hour * @param thu_min Thursday scheduled minute * @param fri_hour Friday scheduled hour * @param fri_min Friday scheduled minute * @param sat_hour Saturday scheduled hour * @param sat_min Saturday scheduled minute * @throws IllegalArgumentException One of the arguments is out of bounds. */ public void schedule(boolean sun, boolean mon, boolean tue, boolean wed, boolean thu, boolean fri, boolean sat, int sun_hour, int sun_min, int mon_hour, int mon_min, int tue_hour, int tue_min, int wed_hour, int wed_min, int thu_hour, int thu_min, int fri_hour, int fri_min, int sat_hour, int sat_min) throws IllegalArgumentException { // Validate argument values if ((sun_hour < 0 || sun_hour > 23) || (mon_hour < 0 || mon_hour > 23) || (tue_hour < 0 || tue_hour > 23) || (wed_hour < 0 || wed_hour > 23) || (thu_hour < 0 || thu_hour > 23) || (fri_hour < 0 || fri_hour > 23) || (sat_hour < 0 || sat_hour > 23)) { throw new IllegalArgumentException("Scheduled hours should be between 0 and 23"); } if ((sun_min < 0 || sun_min > 59) || (mon_min < 0 || mon_min > 59) || (tue_min < 0 || tue_min > 59) || (wed_min < 0 || wed_min > 59) || (thu_min < 0 || thu_min > 59) || (fri_min < 0 || fri_min > 59) || (sat_min < 0 || sat_min > 59)) { throw new IllegalArgumentException("Scheduled minutes should be between 0 and 59"); } log.info("Sending new schedule to roomba."); // Create Days byte byte days = (byte)((sun?SCHEDULE_SUNDAY_MASK:0) | (mon?SCHEDULE_MONDAY_MASK:0) | (tue?SCHEDULE_TUESDAY_MASK:0) | (wed?SCHEDULE_WEDNESDAY_MASK:0) | (thu?SCHEDULE_THURSDAY_MASK:0) |(fri?SCHEDULE_FRIDAY_MASK:0) | (sat?SCHEDULE_SATURDAY_MASK:0)); send(new byte[] { (byte)OPC_SCHEDULE, days, (byte)sun_hour, (byte)sun_min, (byte)mon_hour, (byte)mon_min, (byte)tue_hour, (byte)tue_min, (byte)wed_hour, (byte)wed_min, (byte)thu_hour, (byte)thu_min, (byte)fri_hour, (byte)fri_min, (byte)sat_hour, (byte)sat_min }); } /** * This command sets Roomba’s clock. * @param day Day number: 0 = Sunday, 1 = Monday ... 6 = Saturday * @param hour Hour in 24hour format 0-23 * @param minute Minute 0-59 * @throws IllegalArgumentException One of the arguments is out of bounds. */ public void setDayTime(int day, int hour, int minute) throws IllegalArgumentException { // Validate argument values if (day < 0 || day > 6) throw new IllegalArgumentException("Day should be between 0 (sun) and 6 (sat)"); if (hour < 0 || hour > 23) throw new IllegalArgumentException("Hour should be between 0 and 23"); if (minute < 0 || minute > 59) throw new IllegalArgumentException("Minute should be between 0 and 59"); log.info("Setting time of roomba to: day='" + day + "', time='" + hour + ":" + minute + "'."); send(new byte[] { (byte)OPC_SET_DAYTIME, (byte)day, (byte)hour, (byte)minute }); } //endregion //region Roomba Actuator commands /** * This command controls Roomba’s drive wheels. * @param velocity The average velocity of the drive wheels in millimeters per second (mm/s) * A positive velocity makes the roomba drive forward, a negative velocity * makes it drive backwards. * min: -500mm/s max: 500mm/s * @param radius The radius in millimeters at which Roomba will turn * The longer radii make Roomba drive straighter, while the shorter radii make Roomba turn more. * The radius is measured from the center of the turning circle to the center of Roomba. * <p>min: -2000mm max: 2000mm</p> * Special cases: * <ul> * <li>Straight = 32767 or 32768</li> * <li>Turn in place clockwise = -1</li> * <li>Turn in place counter-clockwise = 1</li> * </ul> * @throws IllegalArgumentException One of the arguments is out of bounds. */ public void drive(int velocity, int radius) throws IllegalArgumentException { // Validate argument values if (velocity < -500 || velocity > 500) throw new IllegalArgumentException("Velocity should be between -500 and 500"); if ((radius < -2000 || radius > 2000) && (radius != 32768 && radius != 32767)) throw new IllegalArgumentException("Radius should be between -2000 and 2000 or 32767-32768"); log.info("Sending 'drive' command (velocity:" + velocity + ", radius:" + radius + ") to roomba."); byte[] cmd = { (byte)OPC_DRIVE, (byte)(velocity >>> 8), (byte)velocity, (byte)(radius >>> 8), (byte)radius }; send(cmd); } /** * This command lets you control the forward and backward motion of Roomba’s drive wheels independently. * A positive velocity makes that wheel drive forward, while a negative velocity makes it drive backward. * @param rightVelocity Right wheel velocity min: -500 mm/s, max: 500 mm/s * @param leftVelocity Left wheel velocity min: -500 mm/s, max: 500 mm/s * @throws IllegalArgumentException One of the arguments is out of bounds. */ public void driveDirect(int rightVelocity, int leftVelocity) throws IllegalArgumentException { // Validate argument values if (rightVelocity < -500 || rightVelocity > 500 || leftVelocity < -500 || leftVelocity > 500) throw new IllegalArgumentException("Velocity should be between -500 and 500"); log.info("Sending 'driveDirect' command (velocity right: " + rightVelocity + ", " + "velocity left: " + leftVelocity + ") to roomba."); byte[] cmd = { (byte)OPC_DRIVE_WHEELS, (byte)(rightVelocity >>> 8), (byte)rightVelocity, (byte)(leftVelocity >>> 8), (byte)leftVelocity }; send(cmd); } /** * This command lets you control the raw forward and backward motion of Roomba’s drive wheels independently. * A positive PWM makes that wheel drive forward, while a negative PWM makes it drive backward. * The PWM values are percentages: 100% is full power forward, -100% is full power reverse. * @param rightPWM Right wheel PWM (min: -100%, max: 100%) * @param leftPWM Left wheel PWM (min: -100%, max: 100%) * @throws IllegalArgumentException One of the arguments is out of bounds. */ public void drivePWM(int rightPWM, int leftPWM) throws IllegalArgumentException { // Validate argument values if (rightPWM < -100 || rightPWM > 100 || leftPWM < -100 || leftPWM > 100) throw new IllegalArgumentException("PWM should be between -100% and 100%"); log.info("Sending 'drivePWM' command (right PWM: " + rightPWM + "%, left PWM: " + leftPWM + "%) to roomba."); int relRightPWM = DRIVE_WHEEL_MAX_POWER * rightPWM / 100; int relLeftPWM = DRIVE_WHEEL_MAX_POWER * leftPWM / 100; byte[] cmd = { (byte)OPC_DRIVE_PWM, (byte)(relRightPWM >>> 8), (byte)relRightPWM, (byte)(relLeftPWM >>> 8), (byte)relLeftPWM }; send(cmd); } /** * This command lets you control the forward and backward motion of Roomba’s main brush, side brush, * and vacuum independently. Motor velocity cannot be controlled with this command, all motors will run at * maximum speed when enabled. The main brush and side brush can be run in either direction. * The vacuum only runs forward. * @param sideBrush Turns on side brush * @param vacuum Turns on vacuum * @param mainBrush Turns on main brush * @param sideBrushClockwise if true the side brush will turn clockwise (default: counterclockwise) * @param mainBrushOutward if true the side brush will turn outward (default: inward) */ public void motors(boolean sideBrush, boolean vacuum, boolean mainBrush, boolean sideBrushClockwise, boolean mainBrushOutward) { log.info("Sending 'motors' command (sideBrush: " + sideBrush + "(clockwise: " + sideBrushClockwise + "), " + "vacuum: " + vacuum + ", mainBrush: " + mainBrush + "(outward: " + mainBrushOutward + ")) to roomba."); // Create motor byte byte motors = (byte)((sideBrush?MOTORS_SIDE_BRUSH_MASK:0) | (vacuum?MOTORS_VACUUM_MASK:0) | (mainBrush?MOTORS_MAIN_BRUSH_MASK:0) | (sideBrushClockwise?MOTORS_SIDE_BRUSH_CW_MASK:0) | (mainBrushOutward?MOTORS_MAIN_BRUSH_OW_MASK:0)); byte[] cmd = { (byte)OPC_MOTORS, motors }; send(cmd); } /** * This command lets you control the speed of Roomba’s main brush, side brush, and vacuum independently. * The main brush and side brush can be run in either direction. The vacuum only runs forward. * Positive speeds turn the motor in its default (cleaning) direction. Default direction for the side brush is * counterclockwise. Default direction for the main brush/flapper is inward. * The PWM values are percentages: 100% is full power forward, -100% is full power reverse. * @param mainBrushPWM Main brush PWM (min: -100%, max: 100%) * @param sideBrushPWM Side brush PWM (min: -100%, max: 100%) * @param vacuumPWM Vacuum PWM (min: 0%, max: 100%) * @throws IllegalArgumentException One of the arguments is out of bounds. */ public void motorsPWM(int mainBrushPWM, int sideBrushPWM, int vacuumPWM) throws IllegalArgumentException { // Validate argument values if (mainBrushPWM < -100 || mainBrushPWM > 100 || sideBrushPWM < -100 || sideBrushPWM > 100) throw new IllegalArgumentException("Main- and side- brush PWM should be between -100% and 100%"); if (vacuumPWM < 0 || vacuumPWM > 100) throw new IllegalArgumentException("Vacuum PWM should be between 0% and 100%"); log.info("Sending 'motorsPWM' command (mainBrushPWM: " + mainBrushPWM + "%, sideBrushPWM: " + sideBrushPWM + "%, vacuumPWM: " + vacuumPWM + "%) to roomba."); int relMainBrushPWM = MOTORS_MAX_POWER * mainBrushPWM / 100; int relSideBrushPWM = MOTORS_MAX_POWER * sideBrushPWM / 100; int relVacuumPWM = MOTORS_MAX_POWER * vacuumPWM / 100; byte[] cmd = { (byte)OPC_PWM_MOTORS, (byte)relMainBrushPWM, (byte)relSideBrushPWM, (byte)relVacuumPWM }; send(cmd); } /** * This command controls the LEDs common to all models of Roomba 600. * @param debris Turns on the debris LED * @param spot Turns on the spot LED * @param dock Turns on the dock LED * @param check_robot Turns on the check robot LED * @param powerColor Controls the power LED red color relative to green: 0% = green, 100% = red. * Intermediate values are intermediate colors (orange, yellow, etc). * @param powerIntensity Controls the intensity of the power led. 0% = off, 100% = full intensity. * Intermediate values are intermediate intensities. * @throws IllegalArgumentException One of the arguments is out of bounds. */ public void relativeLeds(boolean debris, boolean spot, boolean dock, boolean check_robot, int powerColor, int powerIntensity) throws IllegalArgumentException { // Validate argument values if (powerColor < 0 || powerColor > 100 || powerIntensity < 0 || powerIntensity > 100) throw new IllegalArgumentException("Color and/or Intensity should be between 0% and 100%"); log.info("Sending 'LEDs' command (debris: " + debris + ", spot: " + spot + ", dock: " + dock + ", checkRobot: " + check_robot + ", powerRedColor: " + powerColor + ", powerIntensity: " + powerIntensity + ") to roomba."); // Create LEDs byte byte LEDs = (byte)((debris?LEDS_DEBRIS_MASK:0) | (spot?LEDS_SPOT_MASK:0) | (dock?LEDS_DOCK_MASK:0) | (check_robot?LEDS_CHECK_ROBOT_MASK:0)); int relPowerRedColor = LEDS_POWER_RED_COLOR * powerColor / 100; int relPowerIntensity = LEDS_POWER_MAX_INTENSITY * powerIntensity / 100; byte[] cmd = { (byte)OPC_LEDS, LEDs, (byte)relPowerRedColor, (byte)relPowerIntensity }; send(cmd); } /** * This command controls the LEDs common to all models of Roomba 600. * @param debris Turns on the debris LED * @param spot Turns on the spot LED * @param dock Turns on the dock LED * @param check_robot Turns on the check robot LED * @param powerColor Controls the power LED color: 0 = green, 255 = red. * Intermediate values are intermediate colors (orange, yellow, etc). * @param powerIntensity Controls the intensity of the power led. 0 = off, 255 = full intensity. * Intermediate values are intermediate intensities. * @throws IllegalArgumentException One of the arguments is out of bounds. */ public void leds(boolean debris, boolean spot, boolean dock, boolean check_robot, int powerColor, int powerIntensity) throws IllegalArgumentException { // Validate argument values if (powerColor < 0 || powerColor > 255 || powerIntensity < 0 || powerIntensity > 255) throw new IllegalArgumentException("Color and/or Intensity should be between 0 and 255"); log.info("Sending 'LEDs' command (debris: " + debris + ", spot: " + spot + ", dock: " + dock + ", checkRobot: " + check_robot + ", powerRedColor: " + powerColor + ", powerIntensity: " + powerIntensity + ") to roomba."); // Create LEDs byte byte LEDs = (byte)((debris?LEDS_DEBRIS_MASK:0) | (spot?LEDS_SPOT_MASK:0) | (dock?LEDS_DOCK_MASK:0) | (check_robot?LEDS_CHECK_ROBOT_MASK:0)); byte[] cmd = { (byte)OPC_LEDS, LEDs, (byte)powerColor, (byte)powerIntensity }; send(cmd); } /** * This command controls the state of the scheduling LEDs present on the Roomba 560 and 570. * @param sun Turn on scheduling Sunday LED * @param mon Turn on scheduling Monday LED * @param tue Turn on scheduling Tuesday LED * @param wed Turn on scheduling Wednesday LED * @param thu Turn on scheduling Thursday LED * @param fri Turn on scheduling Friday LED * @param sat Turn on scheduling Saturday LED * @param colon Turn on scheduling Colon LED * @param pm Turn on scheduling PM LED * @param am Turn on scheduling AM LED * @param clock Turn on scheduling clock LED * @param schedule Turn on scheduling schedule LED */ public void schedulingLeds(boolean sun, boolean mon, boolean tue, boolean wed, boolean thu, boolean fri, boolean sat, boolean colon, boolean pm, boolean am, boolean clock, boolean schedule) { log.info("Sending 'schedulingLEDs' command (sun:" + sun + ", mon:" + mon + ", tue:" + tue + ", wed:" + wed + ", thu:" + thu + ", fri:" + fri + ", sat:" + sat + ", colon:" + colon + ", pm:" + pm + ", am:" + am + ", clock:" + clock + ", schedule:" + schedule + ") to roomba."); // Create weekday LEDs byte byte weekdayLEDs = (byte)((sun?SCHEDULE_SUNDAY_MASK:0) | (mon?SCHEDULE_MONDAY_MASK:0) | (tue?SCHEDULE_TUESDAY_MASK:0) | (wed?SCHEDULE_WEDNESDAY_MASK:0) | (thu?SCHEDULE_THURSDAY_MASK:0) | (fri?SCHEDULE_FRIDAY_MASK:0) | (sat?SCHEDULE_SATURDAY_MASK:0)); // Create Scheduling LEDs byte byte schedulingLEDs = (byte)((colon?LEDS_SCHEDULE_COLON_MASK:0) | (pm?LEDS_SCHEDULE_PM_MASK:0) | (am?LEDS_SCHEDULE_AM_MASK:0) | (clock?LEDS_SCHEDULE_CLOCK_MASK:0) | (schedule?LEDS_SCHEDULE_SCHEDULE_MASK:0)); byte[] cmd = { (byte)OPC_SCHEDULING_LEDS, weekdayLEDs, schedulingLEDs }; send(cmd); } /** * This command controls the four 7 segment displays on the Roomba 560 and 570 using ASCII character codes. * Because a 7 segment display is not sufficient to display alphabetic characters properly, all characters are * an approximation, and not all ASCII codes are implemented. * Note: Use a space for an empty character * @param char0 First character * @param char1 Second character * @param char2 Third character * @param char3 Fourth character * @throws IllegalArgumentException One of the arguments is out of bounds. */ public void digitLedsAscii(char char0, char char1, char char2, char char3) throws IllegalArgumentException { // Validate argument values if (!isAllowedASCIIChar(char0)) throw new IllegalArgumentException("Character '" + char0 + "' is not allowed"); if (!isAllowedASCIIChar(char1)) throw new IllegalArgumentException("Character '" + char1 + "' is not allowed"); if (!isAllowedASCIIChar(char2)) throw new IllegalArgumentException("Character '" + char2 + "' is not allowed"); if (!isAllowedASCIIChar(char3)) throw new IllegalArgumentException("Character '" + char3 + "' is not allowed"); log.info("Sending 'digitLedsAscii' command with chars: " + char0 + ", " + char1 + ", " + char2 + ", " + char3 + " to roomba."); byte[] cmd = { (byte)OPC_DIGIT_LEDS_ASCII, (byte)char0, (byte)char1, (byte)char2, (byte)char3 }; send(cmd); } /** * This command lets you push Roomba’s buttons. The buttons will automatically release after 1/6th of a second. * @param clean Presses the clean button * @param spot Presses the spot button * @param dock Presses the dock button * @param minute Presses the minute button * @param hour Presses the hour button * @param day Presses the day button * @param schedule Presses the schedule button * @param clock Presses the clock button */ public void buttons(boolean clean, boolean spot, boolean dock, boolean minute, boolean hour, boolean day, boolean schedule, boolean clock) { log.info("Sending 'buttons' command with pushed clean:" + clean + ", spot:" + spot + ", dock:" + dock + ", minute:" + minute + ", hour:" + hour + ", day:" + day + ", schedule:" + schedule + ", clock:" + clock + " to roomba."); // Create buttons byte byte buttons = (byte)((clean?BUTTONS_CLEAN_MASK:0) | (spot?BUTTONS_SPOT_MASK:0) | (dock?BUTTONS_DOCK_MASK:0) | (minute?BUTTONS_MINUTE_MASK:0) | (hour?BUTTONS_HOUR_MASK:0) | (day?BUTTONS_DAY_MASK:0) | (schedule?BUTTONS_SCHEDULE_MASK:0) | (clock?BUTTONS_CLOCK_MASK:0)); byte[] cmd = { (byte)OPC_BUTTONS, buttons }; send(cmd); } /** * This command lets you specify up to four songs to the OI that you can play at a later time. * Each song is associated with a song number. The Play command uses the song number to identify your * song selection. Each song can contain up to sixteen notes. * @param songNumber Song number (0-15) * @param notes Array of RoombaSongNote (max. 16) * @param tempo Tempo in BPM (min. 60 BPM, max. 800 BPM) * @throws IllegalArgumentException One of the arguments is out of bounds. */ public void song(int songNumber, RoombaSongNote[] notes, int tempo) throws IllegalArgumentException { // Validate argument values if (songNumber < 0 || songNumber > 15) throw new IllegalArgumentException("Song number should be between 0 and 15"); if (notes.length > 16) throw new IllegalArgumentException("Songs have a maximum of 16 notes"); if (tempo < 60 || tempo > 800) throw new IllegalArgumentException("Song Tempo should be between 60 and 800 BPM"); log.info("Sending 'song' command, saving song number: " + songNumber + " to roomba."); final int notes_offset = 3; byte[] cmd = new byte[notes.length*2 + notes_offset]; cmd[0] = (byte)OPC_SONG; cmd[1] = (byte)songNumber; cmd[2] = (byte)notes.length; System.arraycopy(RoombaSongNote.songNotesToBytes(notes, tempo), 0, cmd, notes_offset, notes.length*2); send(cmd); } /** * This command lets you select a song to play from the songs added to Roomba using the Song command. * You must add one or more songs to Roomba using the Song command in order for the Play command to work. * @param songNumber Song number (0-15) * @throws IllegalArgumentException One of the arguments is out of bounds. */ public void play(int songNumber) throws IllegalArgumentException { // Validate argument values if (songNumber < 0 || songNumber > 15) throw new IllegalArgumentException("Song number should be between 0 and 15"); log.info("Sending 'play' command, song number: " + songNumber + " to roomba."); byte[] cmd = { (byte)OPC_PLAY, (byte)songNumber }; send(cmd); } //endregion //region Roomba Sensor commands /** * This command requests new sensor data from the roomba. * <p>Note: Don't invoke this method more than once per 50ms, this will possibly corrupt the sensor data received * from the roomba.</p> * @throws RuntimeException If sensor data updates are requested more than once per 50ms. */ public void updateSensors() throws RuntimeException { final long now = System.currentTimeMillis(); if (lastSensorUpdate != 0 && (now - lastSensorUpdate) < 50) { throw new RuntimeException("Too many updateSensor() invocations, this should be limited to max " + "one invocation per 50ms."); } lastSensorUpdate = now; // Ensure we reset the buffer to starting position sensorDataBufferIndex = 0; log.debug("Requesting new sensor data."); byte[] cmd = { (byte)OPC_QUERY, (byte)SENSOR_PACKET_ALL }; send(cmd); } //endregion //region Roomba sensor value getters /** * Check if a safety fault has occurred, this will put the roomba into passive mode. * @return True if a safety fault has occurred */ public boolean safetyFault() { return bumpRight() || bumpLeft() || wheelDropRight() || wheelDropLeft() || cliffLeft() || cliffFrontLeft() || cliffFrontRight() || cliffRight(); } /** * Get value of right bumper sensor. * @return True if bumped right */ public boolean bumpRight() { return (currentSensorData[SENSOR_BUMPS_WHEELDROPS_OFFSET] & SENSOR_BUMP_RIGHT_MASK) != 0; } /** * Get value of left bumper sensor. * @return True if bumped left */ public boolean bumpLeft() { return (currentSensorData[SENSOR_BUMPS_WHEELDROPS_OFFSET] & SENSOR_BUMP_LEFT_MASK) != 0; } /** * Get value of right wheel drop sensor. * @return True if wheel drops right */ public boolean wheelDropRight() { return (currentSensorData[SENSOR_BUMPS_WHEELDROPS_OFFSET] & SENSOR_WHEELDROP_RIGHT_MASK) != 0; } /** * Get value of left wheel drop sensor. * @return True if wheel drops left */ public boolean wheelDropLeft() { return (currentSensorData[SENSOR_BUMPS_WHEELDROPS_OFFSET] & SENSOR_WHEELDROP_LEFT_MASK) != 0; } /** * Get value of wall sensor. * @return True if wall is seen */ public boolean wall() { return currentSensorData[SENSOR_WALL_OFFSET] != 0; } /** * Get value of cliff left sensor. * @return True if cliff is seen on left side */ public boolean cliffLeft() { return currentSensorData[SENSOR_CLIFF_LEFT_OFFSET] != 0; } /** * Get value of cliff front left sensor. * @return True if cliff is seen on front left */ public boolean cliffFrontLeft() { return currentSensorData[SENSOR_CLIFF_FRONT_LEFT_OFFSET] != 0; } /** * Get value of cliff front right sensor. * @return True if cliff is seen on front right */ public boolean cliffFrontRight() { return currentSensorData[SENSOR_CLIFF_FRONT_RIGHT_OFFSET] != 0; } /** * Get value of cliff right sensor. * @return True if cliff is seen on right side */ public boolean cliffRight() { return currentSensorData[SENSOR_CLIFF_RIGHT_OFFSET] != 0; } /** * Get value of virtual wall sensor. * @return True if a virtual wall is detected */ public boolean virtualWall() { return currentSensorData[SENSOR_VIRTUAL_WALL_OFFSET] != 0; } /** * Get value of side brush overcurrent sensor. * @return True if side brush overcurrent */ public boolean sideBrushOvercurrent() { return (currentSensorData[SENSOR_WHEEL_OVERCURRENT_OFFSET] & SENSOR_OVERCURRENT_SIDE_BRUSH_MASK) != 0; } /** * Get value of main brush overcurrent sensor. * @return True if main brush overcurrent */ public boolean mainBrushOvercurrent() { return (currentSensorData[SENSOR_WHEEL_OVERCURRENT_OFFSET] & SENSOR_OVERCURRENT_MAIN_BRUSH_MASK) != 0; } /** * Get value of right wheel overcurrent sensor. * @return True if right wheel overcurrent */ public boolean wheelOvercurrentRight() { return (currentSensorData[SENSOR_WHEEL_OVERCURRENT_OFFSET] & SENSOR_OVERCURRENT_RIGHT_WHEEL_MASK) != 0; } /** * Get value of left wheel overcurrent sensor. * @return True if left wheel overcurrent */ public boolean wheelOvercurrentLeft() { return (currentSensorData[SENSOR_WHEEL_OVERCURRENT_OFFSET] & SENSOR_OVERCURRENT_LEFT_WHEEL_MASK) != 0; } /** * Get the level of the dirt detect sensor. * @return Dirt level (0-255) */ public int dirtDetectLevel() { return currentSensorData[SENSOR_DIRT_DETECT_OFFSET] & 0xff; } /** * Get the character currently received by the omnidirectional receiver. * @return Received character (0-255) */ public int infraredCharacterOmni() { return currentSensorData[SENSOR_INFRARED_CHAR_OMNI_OFFSET] & 0xff; } /** * Get the character currently received by the left receiver. * @return Received character (0-255) */ public int infraredCharacterLeft() { return currentSensorData[SENSOR_INFRARED_CHAR_LEFT_OFFSET] & 0xff; } /** * Get the character currently received by the right receiver. * @return Received character (0-225) */ public int infraredCharacterRight() { return currentSensorData[SENSOR_INFRARED_CHAR_RIGHT_OFFSET] & 0xff; } /** * Check if the clean button is pressed. * @return True if pressed */ public boolean buttonCleanPressed() { return (currentSensorData[SENSOR_BUTTONS_OFFSET] & BUTTONS_CLEAN_MASK) != 0; } /** * Check if the spot button is pressed. * @return True if pressed */ public boolean buttonSpotPressed() { return (currentSensorData[SENSOR_BUTTONS_OFFSET] & BUTTONS_SPOT_MASK) != 0; } /** * Check if the dock button is pressed. * @return True if pressed */ public boolean buttonDockPressed() { return (currentSensorData[SENSOR_BUTTONS_OFFSET] & BUTTONS_DOCK_MASK) != 0; } /** * Check if the minute button is pressed. * @return True if pressed */ public boolean buttonMinutePressed() { return (currentSensorData[SENSOR_BUTTONS_OFFSET] & BUTTONS_MINUTE_MASK) != 0; } /** * Check if the hour button is pressed. * @return True if pressed */ public boolean buttonHourPressed() { return (currentSensorData[SENSOR_BUTTONS_OFFSET] & BUTTONS_HOUR_MASK) != 0; } /** * Check if the day button is pressed. * @return True if pressed */ public boolean buttonDayPressed() { return (currentSensorData[SENSOR_BUTTONS_OFFSET] & BUTTONS_DAY_MASK) != 0; } /** * Check if the schedule button is pressed. * @return True if pressed */ public boolean buttonSchedulePressed() { return (currentSensorData[SENSOR_BUTTONS_OFFSET] & BUTTONS_SCHEDULE_MASK) != 0; } /** * Check if the clock button is pressed. * @return True if pressed */ public boolean buttonClockPressed() { return (currentSensorData[SENSOR_BUTTONS_OFFSET] & BUTTONS_CLOCK_MASK) != 0; } /** * Get distance travelled in mm since the last sensor data request. * <p>Note: if the sensor data is not polled frequently enough this value is capped at its * minimum or maximum (-32768, 32767)</p> * @return Distance travelled in mm since last sensor data request */ public int distanceTraveled() { return signed16BitToInt(currentSensorData[SENSOR_DISTANCE_OFFSET], currentSensorData[SENSOR_DISTANCE_OFFSET+1]); } /** * Get the angle turned in degrees since the last sensor data request. * Counter-clockwise angles are positive, clockwise angles are negative. * <p>Note: if the sonsor data is not polled requently enough this value is capped at its * minimum or maximum (-32768, 32767)</p> * @return Angle turned in degrees since last sensor data request */ public int angleTurned() { return signed16BitToInt(currentSensorData[SENSOR_ANGLE_OFFSET], currentSensorData[SENSOR_ANGLE_OFFSET+1]); } /** * Get current charging state * <p>States:</p> * <ul> * <li>0 = Not charging</li> * <li>1 = Reconditioning charging</li> * <li>2 = Full charging</li> * <li>3 = Trickle Charging</li> * <li>4 = Waiting</li> * <li>5 = Charging Fault condition</li> * </ul> * @return Charging state (0-5) */ public int chargingState() { return currentSensorData[SENSOR_CHARGING_STATE_OFFSET]; } /** * Get the voltage of the battery in millivolt (mV) * @return battery voltage (0 - 65535 mV) */ public int batteryVoltage() { return unsigned16BitToInt(currentSensorData[SENSOR_VOLTAGE_OFFSET], currentSensorData[SENSOR_VOLTAGE_OFFSET+1]); } /** * Get the current in milliamps (mA) flowing into or out of roomba's battery. Negative currents indicate that the * current is flowing out of the battery, as during normal running. Positive currents indicate that the current * is flowing into the battery, as during charging. * @return Current in milliamps (-32768, 32768 mA) */ public int batteryCurrent() { return signed16BitToInt(currentSensorData[SENSOR_CURRENT_OFFSET], currentSensorData[SENSOR_CURRENT_OFFSET+1]); } /** * Get the temperature of Roomba's battery in degrees Celsius. * @return Battery temperature in degrees Celsius (-128, 127) */ public int batteryTemperature() { return currentSensorData[SENSOR_TEMPERATURE_OFFSET]; } /** * Get the estimated charge of the roomba's battery in milliamp-hours (mAh). * @return Estimated battery charge (0 - 65535 mAh) */ public int batteryCharge() { return unsigned16BitToInt(currentSensorData[SENSOR_BATTERY_CHARGE_OFFSET], currentSensorData[SENSOR_BATTERY_CHARGE_OFFSET+1]); } /** * Get the estimated charge capacity of roomba's battery in milliamp-hours (mAh) * @return Estimated charge capacity (0 - 65535 mAh) */ public int batteryCapacity() { return unsigned16BitToInt(currentSensorData[SENSOR_BATTERY_CAPACITY_OFFSET], currentSensorData[SENSOR_BATTERY_CAPACITY_OFFSET+1]); } /** * Get the strength of the wall signal. * @return Strength of wall signal (0-1023) */ public int wallSignal() { return unsigned16BitToInt(currentSensorData[SENSOR_WALL_SIGNAL_OFFSET], currentSensorData[SENSOR_WALL_SIGNAL_OFFSET+1]); } /** * Get the strength of the cliff left signal. * @return Strength of cliff left signal(0-4095) */ public int cliffSignalLeft() { return unsigned16BitToInt(currentSensorData[SENSOR_CLIFF_LEFT_SIGNAL_OFFSET], currentSensorData[SENSOR_CLIFF_LEFT_SIGNAL_OFFSET+1]); } /** * Get the strength of the cliff front left signal. * @return Strength of cliff front left signal(0-4095) */ public int cliffSignalFrontLeft() { return unsigned16BitToInt(currentSensorData[SENSOR_CLIFF_FRONT_LEFT_SIGNAL_OFFSET], currentSensorData[SENSOR_CLIFF_FRONT_LEFT_SIGNAL_OFFSET+1]); } /** * Get the strength of the cliff front right signal. * @return Strength of cliff front left signal(0-4095) */ public int cliffSignalFrontRight() { return unsigned16BitToInt(currentSensorData[SENSOR_CLIFF_FRONT_RIGHT_SIGNAL_OFFSET], currentSensorData[SENSOR_CLIFF_FRONT_RIGHT_SIGNAL_OFFSET+1]); } /** * Get the strength of the cliff right signal. * @return Strength of cliff right signal(0-4095) */ public int cliffSignalRight() { return unsigned16BitToInt(currentSensorData[SENSOR_CLIFF_RIGHT_SIGNAL_OFFSET], currentSensorData[SENSOR_CLIFF_RIGHT_SIGNAL_OFFSET+1]); } /** * Check if the internal charger is present and powered. * @return True if present and powered. */ public boolean internalChargerAvailable() { return (currentSensorData[SENSOR_CHARGING_SOURCES_OFFSET] & SENSOR_CHARGER_INTERNAL_MASK) != 0; } /** * Check if the homebase charger is present and powered. * @return True if present and powered. */ public boolean homebaseChargerAvailable() { return (currentSensorData[SENSOR_CHARGING_SOURCES_OFFSET] & SENSOR_CHARGER_HOMEBASE_MASK) != 0; } /** * Get the current OI mode. * <p>OI modes:</p> * <ul> * <li>0 = Off</li> * <li>1 = Passive</li> * <li>2 = Safe</li> * <li>3 = Full</li> * </ul> * @return Current OI mode (0-3) */ public int mode() { return currentSensorData[SENSOR_OI_MODE_OFFSET]; } /** * Get the currently selected song. * @return Selected song number (0-15) */ public int songNumber() { return currentSensorData[SENSOR_SONG_NUMBER_OFFSET]; } /** * Check if a song is playing. * @return True if a song is playing. */ public boolean songPlaying() { return currentSensorData[SENSOR_SONG_PLAYING_OFFSET] != 0; } /** * Get the velocity most recently requested with a Drive command. * @return Requested velocity (-500 - 500mm/s) */ public int requestedVelocity() { return signed16BitToInt(currentSensorData[SENSOR_REQUESTED_VELOCITY_OFFSET], currentSensorData[SENSOR_REQUESTED_VELOCITY_OFFSET+1]); } /** * Get the radius most recently requested with a Drive command. * @return Requested radius (-32768 - 32767mm) */ public int requestedRadius() { return signed16BitToInt(currentSensorData[SENSOR_REQUESTED_RADIUS_OFFSET], currentSensorData[SENSOR_REQUESTED_RADIUS_OFFSET+1]); } /** * Get the right wheel velocity most recently requested with a Drive Direct command. * @return Requested right wheel velocity (-500 - 500mm/s) */ public int requestedVelocityRight() { return signed16BitToInt(currentSensorData[SENSOR_REQUESTED_RIGHT_VELOCITY_OFFSET], currentSensorData[SENSOR_REQUESTED_RIGHT_VELOCITY_OFFSET+1]); } /** * Get the left wheel velocity most recently requested with a Drive Direct command. * @return Requested left wheel velocity (-500 - 500mm/s) */ public int requestedVelocityLeft() { return signed16BitToInt(currentSensorData[SENSOR_REQUESTED_LEFT_VELOCITY_OFFSET], currentSensorData[SENSOR_REQUESTED_LEFT_VELOCITY_OFFSET+1]); } /** * Get the (cumulative) number of raw left encoder counts. * <p>Note: This number will roll over to 0 after it passes 65535.</p> * @return Cumulative left encoder counts (0-65535) */ public int encoderCountsLeft() { return unsigned16BitToInt(currentSensorData[SENSOR_LEFT_ENCODER_COUNTS_OFFSET], currentSensorData[SENSOR_LEFT_ENCODER_COUNTS_OFFSET+1]); } /** * Get the (cumulative) number of raw right encoder counts. * <p>Note: This number will roll over to 0 after it passes 65535.</p> * @return Cumulative right encoder counts (0-65535) */ public int encoderCountsRight() { return unsigned16BitToInt(currentSensorData[SENSOR_RIGHT_ENCODER_COUNTS_OFFSET], currentSensorData[SENSOR_RIGHT_ENCODER_COUNTS_OFFSET+1]); } /** * Check if the left light bumper detects an obstacle. * @return True on obstacle */ public boolean lightBumperLeft() { return (currentSensorData[SENSOR_LIGHT_BUMPER_OFFSET] & SENSOR_LIGHT_BUMPER_LEFT_MASK) != 0; } /** * Check if the front left light bumper detects an obstacle. * @return True on obstacle */ public boolean lightBumperFrontLeft() { return (currentSensorData[SENSOR_LIGHT_BUMPER_OFFSET] & SENSOR_LIGHT_BUMPER_FRONT_LEFT_MASK) != 0; } /** * Check if the center left light bumper detects an obstacle. * @return True on obstacle */ public boolean lightBumperCenterLeft() { return (currentSensorData[SENSOR_LIGHT_BUMPER_OFFSET] & SENSOR_LIGHT_BUMPER_CENTER_LEFT_MASK) != 0; } /** * Check if the center right light bumper detects an obstacle. * @return True on obstacle */ public boolean lightBumperCenterRight() { return (currentSensorData[SENSOR_LIGHT_BUMPER_OFFSET] & SENSOR_LIGHT_BUMPER_CENTER_RIGHT_MASK) != 0; } /** * Check if the front right light bumper detects an obstacle. * @return True on obstacle */ public boolean lightBumperFrontRight() { return (currentSensorData[SENSOR_LIGHT_BUMPER_OFFSET] & SENSOR_LIGHT_BUMPER_FRONT_RIGHT_MASK) != 0; } /** * Check if the right light bumper detects an obstacle. * @return True on obstacle */ public boolean lightBumperRight() { return (currentSensorData[SENSOR_LIGHT_BUMPER_OFFSET] & SENSOR_LIGHT_BUMPER_RIGHT_MASK) != 0; } /** * Get the strength of the light bumper left signal. * @return Signal strength (0-4095) */ public int lightBumperSignalLeft() { return unsigned16BitToInt(currentSensorData[SENSOR_LIGHT_BUMPER_LEFT_SIGNAL_OFFSET], currentSensorData[SENSOR_LIGHT_BUMPER_LEFT_SIGNAL_OFFSET+1]); } /** * Get the strength of the light bumper front left signal. * @return Signal strength (0-4095) */ public int lightBumperSignalFrontLeft() { return unsigned16BitToInt(currentSensorData[SENSOR_LIGHT_BUMPER_FRONT_LEFT_SIGNAL_OFFSET], currentSensorData[SENSOR_LIGHT_BUMPER_FRONT_LEFT_SIGNAL_OFFSET+1]); } /** * Get the strength of the light bumper center left signal. * @return Signal strength (0-4095) */ public int lightBumperSignalCenterLeft() { return unsigned16BitToInt(currentSensorData[SENSOR_LIGHT_BUMPER_CENTER_LEFT_SIGNAL_OFFSET], currentSensorData[SENSOR_LIGHT_BUMPER_CENTER_LEFT_SIGNAL_OFFSET+1]); } /** * Get the strength of the light bumper center right signal. * @return Signal strength (0-4095) */ public int lightBumperSignalCenterRight() { return unsigned16BitToInt(currentSensorData[SENSOR_LIGHT_BUMPER_CENTER_RIGHT_SIGNAL_OFFSET], currentSensorData[SENSOR_LIGHT_BUMPER_CENTER_RIGHT_SIGNAL_OFFSET+1]); } /** * Get the strength of the light bumper front right signal. * @return Signal strength (0-4095) */ public int lightBumperSignalFrontRight() { return unsigned16BitToInt(currentSensorData[SENSOR_LIGHT_BUMPER_FRONT_RIGHT_SIGNAL_OFFSET], currentSensorData[SENSOR_LIGHT_BUMPER_FRONT_RIGHT_SIGNAL_OFFSET+1]); } /** * Get the strength of the light bumper right signal. * @return Signal strength (0-4095) */ public int lightBumperSignalRight() { return unsigned16BitToInt(currentSensorData[SENSOR_LIGHT_BUMPER_RIGHT_SIGNAL_OFFSET], currentSensorData[SENSOR_LIGHT_BUMPER_RIGHT_SIGNAL_OFFSET+1]); } /** * Get the current being drawn by the left wheel motor in milli Ampere (mA). * @return Motor current in mA (-32768 - 32767 mA) */ public int motorCurrentLeft() { return signed16BitToInt(currentSensorData[SENSOR_LEFT_MOTOR_CURRENT], currentSensorData[SENSOR_LEFT_MOTOR_CURRENT+1]); } /** * Get the current being drawn by the right wheel motor in milli Ampere (mA). * @return Motor current in mA (-32768 - 32767 mA) */ public int motorCurrentRight() { return signed16BitToInt(currentSensorData[SENSOR_RIGHT_MOTOR_CURRENT], currentSensorData[SENSOR_RIGHT_MOTOR_CURRENT+1]); } /** * Get the current being drawn by the main brush motor in milli Ampere (mA). * @return Motor current in mA (-32768 - 32767 mA) */ public int motorCurrentMainBrush() { return signed16BitToInt(currentSensorData[SENSOR_MAIN_BRUSH_CURRENT], currentSensorData[SENSOR_MAIN_BRUSH_CURRENT+1]); } /** * Get the current being drawn by the side brush motor in milli Ampere (mA). * @return Motor current in mA (-32768 - 32767 mA) */ public int motorCurrentSideBrush() { return signed16BitToInt(currentSensorData[SENSOR_SIDE_BRUSH_CURRENT], currentSensorData[SENSOR_SIDE_BRUSH_CURRENT+1]); } /** * Check if the roomba is making forward progress. * <p>Note: this method returns false when the roomba is turning, driving backward, * or is not driving.</p> * @return True if making forward progress */ public boolean stasis() { return currentSensorData[SENSOR_STASIS] != 0; } //endregion //region Class helpers /** * General sleep function that gives commands that use this function some time to instantiate. * @param millis Time in milliseconds that the current Thread should sleep. */ public void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) {} } /** * Checks if the given char is a charter that can be shown on the roomba. * @param c The char to check. * @return True if the character is printable by the roomba. */ private boolean isAllowedASCIIChar(char c) { return c >= 32 && c <= 126 // Printable ASCII characters && c != 42 // Not * && c != 43 // Not + && c != 64; // Not @ } private int signed16BitToInt(byte highByte, byte lowByte) { return lowByte & 0xff | (short) (highByte << 8); } private int unsigned16BitToInt(byte highByte, byte lowByte) { return ((highByte & 0xff) << 8) | (lowByte & 0xff); } //endregion //region static class variables // roomba Open interface commands Opcodes private static final int OPC_RESET = 7; private static final int OPC_START = 128; private static final int OPC_SAFE = 131; private static final int OPC_FULL = 132; private static final int OPC_POWER = 133; private static final int OPC_SPOT = 134; private static final int OPC_CLEAN = 135; private static final int OPC_MAX_CLEAN = 136; private static final int OPC_DRIVE = 137; private static final int OPC_MOTORS = 138; private static final int OPC_LEDS = 139; private static final int OPC_SONG = 140; private static final int OPC_PLAY = 141; private static final int OPC_QUERY = 142; private static final int OPC_FORCE_SEEKING_DOCK = 143; private static final int OPC_PWM_MOTORS = 144; private static final int OPC_DRIVE_WHEELS = 145; private static final int OPC_DRIVE_PWM = 146; private static final int OPC_SCHEDULING_LEDS = 162; private static final int OPC_DIGIT_LEDS_ASCII = 164; private static final int OPC_BUTTONS = 165; private static final int OPC_SCHEDULE = 167; private static final int OPC_SET_DAYTIME = 168; private static final int OPC_STOP = 173; // Sensor packets Group packet ID private static final int SENSOR_PACKET_ALL = 100; static final int SENSOR_PACKET_ALL_SIZE = 80; // Sensor bytes offset private static final int SENSOR_BUMPS_WHEELDROPS_OFFSET = 0; private static final int SENSOR_WALL_OFFSET = 1; private static final int SENSOR_CLIFF_LEFT_OFFSET = 2; private static final int SENSOR_CLIFF_FRONT_LEFT_OFFSET = 3; private static final int SENSOR_CLIFF_FRONT_RIGHT_OFFSET = 4; private static final int SENSOR_CLIFF_RIGHT_OFFSET = 5; private static final int SENSOR_VIRTUAL_WALL_OFFSET = 6; private static final int SENSOR_WHEEL_OVERCURRENT_OFFSET = 7; private static final int SENSOR_DIRT_DETECT_OFFSET = 8; private static final int SENSOR_INFRARED_CHAR_OMNI_OFFSET = 9; private static final int SENSOR_BUTTONS_OFFSET = 11; private static final int SENSOR_DISTANCE_OFFSET = 12; private static final int SENSOR_ANGLE_OFFSET = 14; private static final int SENSOR_CHARGING_STATE_OFFSET = 16; private static final int SENSOR_VOLTAGE_OFFSET = 17; private static final int SENSOR_CURRENT_OFFSET = 19; private static final int SENSOR_TEMPERATURE_OFFSET = 21; private static final int SENSOR_BATTERY_CHARGE_OFFSET = 22; private static final int SENSOR_BATTERY_CAPACITY_OFFSET = 24; private static final int SENSOR_WALL_SIGNAL_OFFSET = 26; private static final int SENSOR_CLIFF_LEFT_SIGNAL_OFFSET = 28; private static final int SENSOR_CLIFF_FRONT_LEFT_SIGNAL_OFFSET = 30; private static final int SENSOR_CLIFF_FRONT_RIGHT_SIGNAL_OFFSET = 32; private static final int SENSOR_CLIFF_RIGHT_SIGNAL_OFFSET = 34; private static final int SENSOR_CHARGING_SOURCES_OFFSET = 39; private static final int SENSOR_OI_MODE_OFFSET = 40; private static final int SENSOR_SONG_NUMBER_OFFSET = 41; private static final int SENSOR_SONG_PLAYING_OFFSET = 42; private static final int SENSOR_REQUESTED_VELOCITY_OFFSET = 44; private static final int SENSOR_REQUESTED_RADIUS_OFFSET = 46; private static final int SENSOR_REQUESTED_RIGHT_VELOCITY_OFFSET = 48; private static final int SENSOR_REQUESTED_LEFT_VELOCITY_OFFSET = 50; private static final int SENSOR_LEFT_ENCODER_COUNTS_OFFSET = 52; private static final int SENSOR_RIGHT_ENCODER_COUNTS_OFFSET = 54; private static final int SENSOR_LIGHT_BUMPER_OFFSET = 56; private static final int SENSOR_LIGHT_BUMPER_LEFT_SIGNAL_OFFSET = 57; private static final int SENSOR_LIGHT_BUMPER_FRONT_LEFT_SIGNAL_OFFSET = 59; private static final int SENSOR_LIGHT_BUMPER_CENTER_LEFT_SIGNAL_OFFSET = 61; private static final int SENSOR_LIGHT_BUMPER_CENTER_RIGHT_SIGNAL_OFFSET = 63; private static final int SENSOR_LIGHT_BUMPER_FRONT_RIGHT_SIGNAL_OFFSET = 65; private static final int SENSOR_LIGHT_BUMPER_RIGHT_SIGNAL_OFFSET = 67; private static final int SENSOR_INFRARED_CHAR_LEFT_OFFSET = 69; private static final int SENSOR_INFRARED_CHAR_RIGHT_OFFSET = 70; private static final int SENSOR_LEFT_MOTOR_CURRENT = 71; private static final int SENSOR_RIGHT_MOTOR_CURRENT = 73; private static final int SENSOR_MAIN_BRUSH_CURRENT = 75; private static final int SENSOR_SIDE_BRUSH_CURRENT = 77; private static final int SENSOR_STASIS = 79; // Sensor data bitmask private static final int SENSOR_BUMP_RIGHT_MASK = 0x1; private static final int SENSOR_BUMP_LEFT_MASK = 0x2; private static final int SENSOR_WHEELDROP_RIGHT_MASK = 0x4; private static final int SENSOR_WHEELDROP_LEFT_MASK = 0x8; private static final int SENSOR_OVERCURRENT_SIDE_BRUSH_MASK = 0x1; private static final int SENSOR_OVERCURRENT_MAIN_BRUSH_MASK = 0x4; private static final int SENSOR_OVERCURRENT_RIGHT_WHEEL_MASK = 0x8; private static final int SENSOR_OVERCURRENT_LEFT_WHEEL_MASK = 0x10; private static final int SENSOR_CHARGER_INTERNAL_MASK = 0x1; private static final int SENSOR_CHARGER_HOMEBASE_MASK = 0x2; private static final int SENSOR_LIGHT_BUMPER_LEFT_MASK = 0x1; private static final int SENSOR_LIGHT_BUMPER_FRONT_LEFT_MASK = 0x2; private static final int SENSOR_LIGHT_BUMPER_CENTER_LEFT_MASK = 0x4; private static final int SENSOR_LIGHT_BUMPER_CENTER_RIGHT_MASK = 0x8; private static final int SENSOR_LIGHT_BUMPER_FRONT_RIGHT_MASK = 0x10; private static final int SENSOR_LIGHT_BUMPER_RIGHT_MASK = 0x20; // Scheduling bitmask private static final int SCHEDULE_SUNDAY_MASK = 0x1; private static final int SCHEDULE_MONDAY_MASK = 0x2; private static final int SCHEDULE_TUESDAY_MASK = 0x4; private static final int SCHEDULE_WEDNESDAY_MASK = 0x8; private static final int SCHEDULE_THURSDAY_MASK = 0x10; private static final int SCHEDULE_FRIDAY_MASK = 0x20; private static final int SCHEDULE_SATURDAY_MASK = 0x40; // Motors bitmask private static final int MOTORS_SIDE_BRUSH_MASK = 0x1; private static final int MOTORS_VACUUM_MASK = 0x2; private static final int MOTORS_MAIN_BRUSH_MASK = 0x4; private static final int MOTORS_SIDE_BRUSH_CW_MASK = 0x8; private static final int MOTORS_MAIN_BRUSH_OW_MASK = 0x10; // LEDs bitmask private static final int LEDS_DEBRIS_MASK = 0x1; private static final int LEDS_SPOT_MASK = 0x2; private static final int LEDS_DOCK_MASK = 0x4; private static final int LEDS_CHECK_ROBOT_MASK = 0x8; // Schedule LEDs bitmask private static final int LEDS_SCHEDULE_COLON_MASK = 0x1; private static final int LEDS_SCHEDULE_PM_MASK = 0x2; private static final int LEDS_SCHEDULE_AM_MASK = 0x4; private static final int LEDS_SCHEDULE_CLOCK_MASK = 0x8; private static final int LEDS_SCHEDULE_SCHEDULE_MASK = 0x10; // Buttons bitmask private static final int BUTTONS_CLEAN_MASK = 0x1; private static final int BUTTONS_SPOT_MASK = 0x2; private static final int BUTTONS_DOCK_MASK = 0x4; private static final int BUTTONS_MINUTE_MASK = 0x8; private static final int BUTTONS_HOUR_MASK = 0x10; private static final int BUTTONS_DAY_MASK = 0x20; private static final int BUTTONS_SCHEDULE_MASK = 0x40; private static final int BUTTONS_CLOCK_MASK = 0x80; // Drive constants private static final int DRIVE_WHEEL_MAX_POWER = 0xFF; // Motors constants private static final int MOTORS_MAX_POWER = 0x7F; // LEDS constants private static final int LEDS_POWER_MAX_INTENSITY = 0xFF; private static final int LEDS_POWER_RED_COLOR = 0xFF; //endregion }
42.430844
152
0.648505
8821daa215a4f8640aa4a5cafecad74fe992daf7
13,360
package com.saltechsystems.couchbase_lite; import android.content.res.AssetManager; import com.couchbase.lite.Array; import com.couchbase.lite.Blob; import com.couchbase.lite.ConcurrencyControl; import com.couchbase.lite.CouchbaseLiteException; import com.couchbase.lite.Database; import com.couchbase.lite.DatabaseConfiguration; import com.couchbase.lite.Dictionary; import com.couchbase.lite.Document; import com.couchbase.lite.ListenerToken; import com.couchbase.lite.LogLevel; import com.couchbase.lite.MutableDocument; import com.couchbase.lite.Replicator; import com.couchbase.lite.Query; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; class CBManager { private HashMap<String, Database> mDatabase = new HashMap<>(); private HashMap<String, Query> mQueries = new HashMap<>(); private final static HashMap<String, Blob> mBlobs = new HashMap<>(); private HashMap<String, ListenerToken> mQueryListenerTokens = new HashMap<>(); private HashMap<String, Replicator> mReplicators = new HashMap<>(); private HashMap<String, ListenerToken[]> mReplicatorListenerTokens = new HashMap<>(); private HashMap<String, ListenerToken> mDatabaseListenerTokens = new HashMap<>(); private DatabaseConfiguration mDBConfig; private CBManagerDelegate mDelegate; CBManager(CBManagerDelegate delegate, LogLevel logLevel) { mDelegate = delegate; mDBConfig = new DatabaseConfiguration(); Database.log.getConsole().setLevel(logLevel); } Database getDatabase(String name) { if (mDatabase.containsKey(name)) { return mDatabase.get(name); } return null; } Map<String, Object> saveDocument(Database database, Map<String, Object> _map, ConcurrencyControl concurrencyControl) throws CouchbaseLiteException { MutableDocument mutableDoc = new MutableDocument(convertSETDictionary(_map)); boolean success = database.save(mutableDoc, concurrencyControl); HashMap<String, Object> resultMap = new HashMap<>(); resultMap.put("success", success); if (success) { resultMap.put("id", mutableDoc.getId()); resultMap.put("sequence", mutableDoc.getSequence()); resultMap.put("doc", _documentToMap(mutableDoc)); } return resultMap; } Map<String, Object> saveDocumentWithId(Database database, String _id, Map<String, Object> _map, ConcurrencyControl concurrencyControl) throws CouchbaseLiteException { HashMap<String, Object> resultMap = new HashMap<>(); MutableDocument mutableDoc = new MutableDocument(_id, convertSETDictionary(_map)); boolean success = database.save(mutableDoc, concurrencyControl); resultMap.put("success", success); if (success) { resultMap.put("id", mutableDoc.getId()); resultMap.put("sequence", mutableDoc.getSequence()); resultMap.put("doc", _documentToMap(mutableDoc)); } return resultMap; } Map<String, Object> saveDocumentWithId(Database database, String _id, long sequence, Map<String, Object> _map, ConcurrencyControl concurrencyControl) throws CouchbaseLiteException { HashMap<String, Object> resultMap = new HashMap<>(); Document document = database.getDocument(_id); if (document != null && document.getSequence() != sequence) { resultMap.put("success", false); return resultMap; } MutableDocument mutableDoc; if (document == null) { mutableDoc = new MutableDocument(_id); } else { mutableDoc = document.toMutable(); } mutableDoc.setData(convertSETDictionary(_map)); boolean success = database.save(mutableDoc, concurrencyControl); resultMap.put("success", success); if (success) { resultMap.put("id", mutableDoc.getId()); resultMap.put("sequence", mutableDoc.getSequence()); resultMap.put("doc", _documentToMap(mutableDoc)); } return resultMap; } static Blob getBlobWithDigest(String digest) { synchronized (mBlobs) { return mBlobs.get(digest); } } static void setBlobWithDigest(String digest, Blob blob) { synchronized (mBlobs) { mBlobs.put(digest, blob); } } static void clearBlobCache() { synchronized (mBlobs) { mBlobs.clear(); } } private Map<String, Object> _documentToMap(Document doc) { HashMap<String,Object> parsed = new HashMap<>(); for (String key: doc.getKeys()) { parsed.put(key, convertGETValue(doc.getValue(key))); } return parsed; } static Object convertSETValue(Object value) { if (value instanceof Map<?, ?>) { Map<String, Object> result = convertSETDictionary(getMapFromGenericMap(value)); if (Objects.equals(result.get("@type"), "blob")) { Object dataObject = result.get("data"); Object contentTypeObject = result.get("content_type"); if (!(result.get("digest") instanceof String) && dataObject instanceof byte[] && contentTypeObject instanceof String) { String contentType = (String) contentTypeObject; byte[] content = (byte[]) dataObject; return new Blob(contentType,content); } else { // Prevent blob from updating when it doesn't change return result; } } else { return result; } } else if (value instanceof List<?>) { return convertSETArray(getListFromGenericList(value)); } else { return value; } } static Map<String, Object> convertSETDictionary(Map<String, Object> _map) { if (_map == null) { return null; } HashMap<String,Object> result = new HashMap<>(); for (Map.Entry<String,Object> entry: _map.entrySet()) { result.put(entry.getKey(), convertSETValue(entry.getValue())); } return result; } static List<Object> convertSETArray(List<Object> array) { if (array == null) { return null; } List<Object> rtnList = new ArrayList<>(); for (Object value: array) { rtnList.add(convertSETValue(value)); } return rtnList; } static Map<String,Object> convertGETDictionary(Dictionary dict) { HashMap<String, Object> rtnMap = new HashMap<>(); for (String key: dict.getKeys()) { rtnMap.put(key, convertGETValue(dict.getValue(key))); } return rtnMap; } static List<Object> convertGETArray(Array array) { List<Object> rtnList = new ArrayList<>(); for (int idx = 0; idx < array.count(); idx++) { rtnList.add(convertGETValue(array.getValue(idx))); } return rtnList; } static Object convertGETValue(Object value) { if (value instanceof Blob) { Blob blob = (Blob) value; String digest = blob.digest(); if (digest != null) { // Store the blob for retrieving the content setBlobWithDigest(digest,blob); } // Don't return the data, JSONMessageCodec doesn't support it HashMap<String,Object> json = new HashMap<>(); json.put("content_type", blob.getContentType()); json.put("digest", digest); json.put("length", blob.length()); json.put("@type","blob"); return json; } else if (value instanceof Dictionary){ return convertGETDictionary((Dictionary) value); } else if (value instanceof Array){ return convertGETArray((Array) value); } else { return value; } } private static Map<String, Object> getMapFromGenericMap(Object objectMap) { Map<String, Object> resultMap = new HashMap<>(); if (objectMap instanceof Map<?, ?>) { Map<?,?> genericMap = (Map<?,?>) objectMap; for (Map.Entry<?, ?> entry : genericMap.entrySet()) { resultMap.put((String) entry.getKey(), entry.getValue()); } } return resultMap; } private static List<Object> getListFromGenericList(Object objectList) { List<Object> resultList = new ArrayList<>(); if (objectList instanceof List<?>) { List<?> genericList = (List<?>) objectList; resultList.addAll(genericList); } return resultList; } static List<Map<String, Object>> getListOfMapsFromGenericList(Object objectList) { List<Map<String, Object>> rtnList = new ArrayList<>(); if (objectList instanceof List<?>) { List<?> genericList = (List<?>) objectList; for (Object objectMap : genericList) { rtnList.add(getMapFromGenericMap(objectMap)); } } return rtnList; } Map<String, Object> getDocumentWithId(Database database, String _id) { HashMap<String, Object> resultMap = new HashMap<>(); Document document = database.getDocument(_id); if (document != null) { resultMap.put("doc", _documentToMap(document)); resultMap.put("id", document.getId()); resultMap.put("sequence", document.getSequence()); } else { resultMap.put("doc", null); resultMap.put("id", _id); } return resultMap; } void deleteDocumentWithId(Database database, String _id) throws CouchbaseLiteException { Document document = database.getDocument(_id); if (document != null) { database.delete(document); } } Database initDatabaseWithName(String _name) throws CouchbaseLiteException { if (!mDatabase.containsKey(_name)) { Database database = new Database(_name, mDBConfig); mDatabase.put(_name, database); return database; } return mDatabase.get(_name); } void deleteDatabaseWithName(String _name) throws CouchbaseLiteException { Database _db = mDatabase.remove(_name); if (_db != null) { _db.delete(); } else { Database.delete(_name, new File(mDBConfig.getDirectory())); } } void closeDatabaseWithName(String _name) throws CouchbaseLiteException { removeDatabaseListenerToken(_name); Database _db = mDatabase.remove(_name); if (_db != null) { _db.close(); } } ListenerToken getDatabaseListenerToken(String dbname) { return mDatabaseListenerTokens.get(dbname); } void addDatabaseListenerToken(String dbname, ListenerToken token) { mDatabaseListenerTokens.put(dbname, token); } void removeDatabaseListenerToken(String dbname) { Database _db = mDatabase.get(dbname); ListenerToken token = mDatabaseListenerTokens.remove(dbname); if (_db != null && token != null) { _db.removeChangeListener(token); } } void addQuery(String queryId, Query query, ListenerToken token) { mQueries.put(queryId,query); mQueryListenerTokens.put(queryId,token); } Query getQuery(String queryId) { return mQueries.get(queryId); } Query removeQuery(String queryId) { Query query = mQueries.remove(queryId); ListenerToken token = mQueryListenerTokens.remove(queryId); if (query != null && token != null) { query.removeChangeListener(token); } return query; } void addReplicator(String replicatorId, Replicator replicator, ListenerToken[] tokens) { mReplicators.put(replicatorId,replicator); mReplicatorListenerTokens.put(replicatorId,tokens); } Replicator getReplicator(String replicatorId) { return mReplicators.get(replicatorId); } Replicator removeReplicator(String replicatorId) { Replicator replicator = mReplicators.remove(replicatorId); ListenerToken[] tokens = mReplicatorListenerTokens.remove(replicatorId); if (replicator != null && tokens != null) { for (ListenerToken token : tokens) { replicator.removeChangeListener(token); } } return replicator; } byte[] getAssetByteArray(String assetKey) throws IOException { AssetManager assetManager = mDelegate.getAssets(); String fileKey = mDelegate.lookupKeyForAsset(assetKey); try (ByteArrayOutputStream buffer = new ByteArrayOutputStream(); InputStream is = assetManager.open(fileKey)) { int nRead; byte[] data = new byte[1024]; while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); return buffer.toByteArray(); } } }
34.521964
185
0.618488
82254c481894867ab7facb8f7ec848ed3500d083
324
package org.innovateuk.ifs.competition.domain; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import java.io.Serializable; @Entity @DiscriminatorValue("COMPETITION_INNOVATION_LEAD") public class InnovationLeadInvite extends CompetitionInvite<InnovationLeadInvite> implements Serializable { }
32.4
107
0.864198
4e82a84f48c854ef682776f9c20c46c114a7c2c1
1,338
package tr.havelsan.ueransim.ngap0.ies.sequence_ofs; import tr.havelsan.ueransim.ngap0.core.*; import tr.havelsan.ueransim.ngap0.pdu.*; import tr.havelsan.ueransim.utils.bits.*; import tr.havelsan.ueransim.utils.octets.*; import tr.havelsan.ueransim.ngap0.ies.bit_strings.*; import tr.havelsan.ueransim.ngap0.ies.octet_strings.*; import tr.havelsan.ueransim.ngap0.ies.printable_strings.*; import tr.havelsan.ueransim.ngap0.ies.sequences.*; import tr.havelsan.ueransim.ngap0.ies.sequence_ofs.*; import tr.havelsan.ueransim.ngap0.ies.choices.*; import tr.havelsan.ueransim.ngap0.ies.integers.*; import tr.havelsan.ueransim.ngap0.ies.enumerations.*; import java.util.List; public class NGAP_QosFlowSetupResponseListSURes extends NGAP_SequenceOf<NGAP_QosFlowSetupResponseItemSURes> { public NGAP_QosFlowSetupResponseListSURes() { super(); } public NGAP_QosFlowSetupResponseListSURes(List<NGAP_QosFlowSetupResponseItemSURes> value) { super(value); } @Override public String getAsnName() { return "QosFlowSetupResponseListSURes"; } @Override public String getXmlTagName() { return "QosFlowSetupResponseListSURes"; } @Override public Class<NGAP_QosFlowSetupResponseItemSURes> getItemType() { return NGAP_QosFlowSetupResponseItemSURes.class; } }
31.116279
109
0.763827
2ed32fee4eff6173435bf63cb90cd80cc1199a63
1,553
package br.com.zup.propostas.proposal; import javax.persistence.*; import java.math.BigDecimal; @Entity @Table(name = "proposals") public class CardProposal { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false) private String personalDocument; @Column(nullable = false) private String name; @Column(nullable = false) private String email; @Embedded private Address address; @Column(nullable = false) private BigDecimal salary; @Enumerated(EnumType.STRING) private CardProposalStatus status; private String approvedCardNumber; @Deprecated public CardProposal() { } public CardProposal(String personalDocument, String email, String name, Address address, BigDecimal salary) { this.personalDocument = personalDocument; this.email = email; this.name = name; this.address = address; this.salary = salary; } public Long getId() { return id; } public String getPersonalDocument() { return personalDocument; } public String getName() { return name; } public CardProposalStatus getStatus() { return status; } public String getApprovedCardNumber() { return approvedCardNumber; } public void updateStatus(CardProposalStatus cardProposalStatus) { status = cardProposalStatus; } public void setApprovedCardNumber(String cardNumber) { approvedCardNumber = cardNumber; } }
23.179104
113
0.670316
e9472a09abb30335876200f5fa52e8f519481ce1
5,831
/* * Copyright @ 2021 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.xmpp.extensions.colibri2; import org.jetbrains.annotations.*; import org.jitsi.utils.*; import org.jitsi.xmpp.extensions.*; import org.jitsi.xmpp.extensions.jingle.*; import org.jivesoftware.smack.packet.*; import org.jivesoftware.smack.parsing.*; import org.jivesoftware.smack.xml.*; import javax.xml.namespace.*; import java.io.*; import java.util.*; public class Media extends AbstractPacketExtension { /** * The XML element name of the Colibri2 Media element. */ public static final String ELEMENT = "media"; /** * The XML namespace of the Colibri2 Media element. */ public static final String NAMESPACE = ConferenceModifyIQ.NAMESPACE; /** * The qualified name of the element. */ public static final QName QNAME = new QName(NAMESPACE, ELEMENT); /** * The name of the <tt>type</tt> attribute. */ public static final String TYPE_ATTR_NAME = "type"; /** * Construct a Media. Needs to be public for DefaultPacketExtensionProvider to work. */ public Media() { super(NAMESPACE, ELEMENT); } /** * Construct a media from a builder - used by Builder#build(). */ private Media(Builder b) { super(NAMESPACE, ELEMENT); if (b.type == null) { throw new IllegalArgumentException("Media type must be set"); } setAttribute(TYPE_ATTR_NAME, b.type.toString()); for (PayloadTypePacketExtension pt: b.payloadTypes) { addChildExtension(pt); } for (RTPHdrExtPacketExtension ext: b.rtpHeaderExtensions) { addChildExtension(ext); } } /** * Get the media type of this media. */ public @NotNull MediaType getType() { return MediaType.parseString(getAttributeAsString(TYPE_ATTR_NAME)); } /** * Get the payload types of this media. */ public @NotNull List<PayloadTypePacketExtension> getPayloadTypes() { return getChildExtensionsOfType(PayloadTypePacketExtension.class); } /** * Get the RTP header extensions of this media. */ public @NotNull List<RTPHdrExtPacketExtension> getRtpHdrExts() { return getChildExtensionsOfType(RTPHdrExtPacketExtension.class); } /** * Get a builder for Media objects. */ public static Builder getBuilder() { return new Builder(); } /** * Builder for Media objects. */ public static final class Builder { /** * The media type of the media object being built. */ MediaType type = null; /** * The <tt>payload-type</tt> elements defined by XEP-0167: Jingle RTP * Sessions associated with this <tt>media</tt>. */ private final List<PayloadTypePacketExtension> payloadTypes = new ArrayList<>(); /** * The <tt>rtp-hdrext</tt> elements defined by XEP-0294: Jingle RTP * Header Extensions Negotiation associated with this media. */ private final List<RTPHdrExtPacketExtension> rtpHeaderExtensions = new ArrayList<>(); /** * Sets the media type for the media being built. */ public Builder setType(MediaType t) { type = t; return this; } /** * Adds a payload type to the media being built. */ public Builder addPayloadType(PayloadTypePacketExtension pt) { payloadTypes.add(pt); return this; } /** * Adds an RTP header extension to the media being built. */ public Builder addRtpHdrExt(RTPHdrExtPacketExtension ext) { rtpHeaderExtensions.add(ext); return this; } /* TODO: add something to set values from higher-level Jingle structures. */ private Builder() { } @Contract(" -> new") public @NotNull Media build() { return new Media(this); } } public static class Provider extends DefaultPacketExtensionProvider<Media> { /** * Creates a new packet provider for MediaSource packet extensions. */ public Provider() { super(Media.class); } @Override public Media parse(XmlPullParser parser, int depth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException { Media m = super.parse(parser, depth, xmlEnvironment); /* Validate parameters */ String type = m.getAttributeAsString(TYPE_ATTR_NAME); if (type == null) { throw new SmackParsingException.RequiredAttributeMissingException(TYPE_ATTR_NAME); } try { MediaType.parseString(type); } catch (IllegalArgumentException e) { throw new SmackParsingException(TYPE_ATTR_NAME + ":" + e.getMessage()); } return m; } } }
26.99537
98
0.598011
0d6c431df93efe278d29ddb687bb74d0c7de7152
7,917
/* * Copyright ConsenSys AG. * * 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. * * SPDX-License-Identifier: Apache-2.0 */ package org.hyperledger.besu.ethereum.api.jsonrpc.internal.privacy.methods.priv; import static org.apache.logging.log4j.LogManager.getLogger; import org.hyperledger.besu.enclave.EnclaveClientException; import org.hyperledger.besu.ethereum.api.jsonrpc.JsonRpcEnclaveErrorConverter; import org.hyperledger.besu.ethereum.api.jsonrpc.RpcMethod; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.JsonRpcMethod; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.privacy.methods.EnclavePublicKeyProvider; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.results.Quantity; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.results.privacy.PrivateTransactionReceiptResult; import org.hyperledger.besu.ethereum.core.Address; import org.hyperledger.besu.ethereum.core.Hash; import org.hyperledger.besu.ethereum.privacy.ExecutedPrivateTransaction; import org.hyperledger.besu.ethereum.privacy.PrivacyController; import org.hyperledger.besu.ethereum.privacy.PrivateTransaction; import org.hyperledger.besu.ethereum.privacy.PrivateTransactionReceipt; import org.hyperledger.besu.ethereum.privacy.storage.PrivateStateStorage; import org.hyperledger.besu.ethereum.rlp.RLP; import java.util.Optional; import org.apache.logging.log4j.Logger; import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes32; public class PrivGetTransactionReceipt implements JsonRpcMethod { private static final Logger LOG = getLogger(); private final PrivateStateStorage privateStateStorage; private final PrivacyController privacyController; private final EnclavePublicKeyProvider enclavePublicKeyProvider; public PrivGetTransactionReceipt( final PrivateStateStorage privateStateStorage, final PrivacyController privacyController, final EnclavePublicKeyProvider enclavePublicKeyProvider) { this.privateStateStorage = privateStateStorage; this.privacyController = privacyController; this.enclavePublicKeyProvider = enclavePublicKeyProvider; } @Override public String getName() { return RpcMethod.PRIV_GET_TRANSACTION_RECEIPT.getMethodName(); } @Override public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { LOG.trace("Executing {}", RpcMethod.PRIV_GET_TRANSACTION_RECEIPT.getMethodName()); final Hash pmtTransactionHash = requestContext.getRequiredParameter(0, Hash.class); final String enclaveKey = enclavePublicKeyProvider.getEnclaveKey(requestContext.getUser()); final ExecutedPrivateTransaction privateTransaction; try { privateTransaction = privacyController .findPrivateTransactionByPmtHash(pmtTransactionHash, enclaveKey) .orElse(null); } catch (final EnclaveClientException e) { return handleEnclaveException(requestContext, e); } if (privateTransaction == null) { return new JsonRpcSuccessResponse(requestContext.getRequest().getId(), null); } final String contractAddress = calculateContractAddress(privateTransaction); LOG.trace("Calculated contractAddress: {}", contractAddress); final Hash blockHash = privateTransaction.getBlockHash(); final PrivateTransactionReceipt privateTransactionReceipt = privateStateStorage .getTransactionReceipt(blockHash, pmtTransactionHash) // backwards compatibility - private receipts indexed by private transaction hash key .or( () -> findPrivateReceiptByPrivateTxHash( privateStateStorage, blockHash, privateTransaction)) .orElse(PrivateTransactionReceipt.FAILED); LOG.trace("Processed private transaction receipt"); final PrivateTransactionReceiptResult result = buildPrivateTransactionReceiptResult(privateTransaction, privateTransactionReceipt); LOG.trace( "Created Private Transaction Receipt Result from given Transaction Hash {}", privateTransaction.getPmtHash()); return new JsonRpcSuccessResponse(requestContext.getRequest().getId(), result); } private PrivateTransactionReceiptResult buildPrivateTransactionReceiptResult( final ExecutedPrivateTransaction privateTransaction, final PrivateTransactionReceipt privateTransactionReceipt) { return new PrivateTransactionReceiptResult( calculateContractAddress(privateTransaction), privateTransaction.getSender().toString(), privateTransaction.getTo().map(Address::toString).orElse(null), privateTransactionReceipt.getLogs(), privateTransactionReceipt.getOutput(), privateTransaction.getBlockHash(), privateTransaction.getBlockNumber(), privateTransaction.getPmtIndex(), privateTransaction.getPmtHash(), privateTransaction.getHash(), privateTransaction.getPrivateFrom(), privateTransaction.getPrivateFor().orElse(null), privateTransaction.getPrivacyGroupId().orElse(null), privateTransactionReceipt.getRevertReason().orElse(null), Quantity.create(privateTransactionReceipt.getStatus())); } private String calculateContractAddress(final ExecutedPrivateTransaction privateTransaction) { if (privateTransaction.getTo().isEmpty()) { final Address sender = privateTransaction.getSender(); final long nonce = privateTransaction.getNonce(); final Bytes privacyGroupId = privateTransaction .getPrivacyGroupId() .orElse(Bytes.fromBase64String(privateTransaction.getInternalPrivacyGroup())); final Address contractAddress = Address.privateContractAddress(sender, nonce, privacyGroupId); return contractAddress.toString(); } else { return null; } } private Optional<? extends PrivateTransactionReceipt> findPrivateReceiptByPrivateTxHash( final PrivateStateStorage privateStateStorage, final Hash blockHash, final PrivateTransaction privateTransaction) { final Bytes rlpEncoded = RLP.encode(privateTransaction::writeTo); final Bytes32 txHash = org.hyperledger.besu.crypto.Hash.keccak256(rlpEncoded); return privateStateStorage.getTransactionReceipt(blockHash, txHash); } private JsonRpcResponse handleEnclaveException( final JsonRpcRequestContext requestContext, final EnclaveClientException e) { final JsonRpcError jsonRpcError = JsonRpcEnclaveErrorConverter.convertEnclaveInvalidReason(e.getMessage()); switch (jsonRpcError) { case ENCLAVE_PAYLOAD_NOT_FOUND: { return new JsonRpcSuccessResponse(requestContext.getRequest().getId(), null); } case ENCLAVE_KEYS_CANNOT_DECRYPT_PAYLOAD: { LOG.warn( "Unable to decrypt payload with configured privacy node key. Check if your 'privacy-public-key-file' property matches your Enclave public key."); } // fall through default: throw e; } } }
43.5
159
0.765315
0715a2ad8b60f8441c80389ad16971e4f58eaf19
3,969
/* * Copyright (c) 2016 deltaDNA Ltd. 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.deltadna.android.sdk.notifications; import android.util.Log; import java.lang.reflect.InvocationTargetException; import java.util.LinkedList; import java.util.Queue; final class UnityForwarder { private static final String TAG = BuildConfig.LOG_TAG + ' ' + UnityForwarder.class.getSimpleName(); private static final Class<?> PLAYER_ACTIVITY; static { Class<?> playerActivity; try { playerActivity = Class.forName( "com.unity3d.player.UnityPlayerActivity"); } catch (ClassNotFoundException e) { playerActivity = null; } PLAYER_ACTIVITY = playerActivity; } private static final Class<?> PLAYER; static { Class<?> player; try { player = Class.forName("com.unity3d.player.UnityPlayer"); } catch (ClassNotFoundException e) { player = null; } PLAYER = player; } private static UnityForwarder instance; static boolean isPresent() { return PLAYER_ACTIVITY != null; } static synchronized UnityForwarder getInstance() { if (instance == null) { instance = new UnityForwarder(); } return instance; } private final Queue<Message> deferred = new LinkedList<>(); private boolean loaded; private UnityForwarder() {} void markLoaded() { Log.d(TAG, "Marked as loaded"); loaded = true; if (!deferred.isEmpty()) { final Message message = deferred.remove(); sendMessage( message.gameObject, message.methodName, message.message); } } void forward(String gameObject, String methodName, String message) { if (loaded) { sendMessage(gameObject, methodName, message); } else { Log.d(TAG, "Deferring message due to not loaded"); deferred.add(new Message(gameObject, methodName, message)); } } private static void sendMessage( String gameObject, String methodName, String message) { try { PLAYER.getDeclaredMethod( "UnitySendMessage", String.class, String.class, String.class) .invoke(PLAYER, gameObject, methodName, message); } catch (NoSuchMethodException e) { Log.e(TAG, "Failed sending message to Unity", e); } catch (InvocationTargetException e) { Log.e(TAG, "Failed sending message to Unity", e); } catch (IllegalAccessException e) { Log.e(TAG, "Failed sending message to Unity", e); } } private static final class Message { final String gameObject; final String methodName; final String message; Message(String gameObject, String methodName, String message) { this.gameObject = gameObject; this.methodName = methodName; this.message = message; } } }
29.4
75
0.566893
b08136f8e21d3aeed36b34920031656ae8f4643b
813
package me.ifydev.factionify.api.faction; import lombok.AllArgsConstructor; import lombok.Getter; import me.ifydev.factionify.api.structures.Chunk; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; /** * @author Innectic * @since 07/27/2018 */ @AllArgsConstructor @Getter public class Faction { private UUID uuid; private String name; private String description; private Map<UUID, Role> roles; private Map<UUID, UUID> players; private List<Chunk> claimedChunks; public Optional <Role> getRoleForPlayer(UUID uuid) { return getRoleByUUID(players.get(uuid)); } public Optional<Role> getRoleByUUID(UUID uuid) { return Optional.ofNullable(roles.getOrDefault(uuid, null)); } }
23.911765
68
0.694957
c95458726e891c3e12545548e3247b42b28ff872
6,405
/* * 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.protocol; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.Properties; import java.util.concurrent.TimeUnit; import org.awaitility.Awaitility; import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.RestoreSystemProperties; import org.junit.experimental.categories.Category; import org.apache.geode.cache.Cache; import org.apache.geode.cache.CacheFactory; import org.apache.geode.cache.server.CacheServer; import org.apache.geode.distributed.ConfigurationProperties; import org.apache.geode.internal.AvailablePortHelper; import org.apache.geode.internal.protocol.protobuf.AuthenticationAPI; import org.apache.geode.internal.protocol.protobuf.ClientProtocol; import org.apache.geode.internal.protocol.protobuf.RegionAPI; import org.apache.geode.internal.protocol.protobuf.serializer.ProtobufProtocolSerializer; import org.apache.geode.management.internal.security.ResourceConstants; import org.apache.geode.security.SecurityManager; import org.apache.geode.test.junit.categories.IntegrationTest; @Category(IntegrationTest.class) public class AuthenticationIntegrationTest { private static final String TEST_USERNAME = "bob"; private static final String TEST_PASSWORD = "bobspassword"; private Cache cache; @Rule public final RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties(); private OutputStream outputStream; private InputStream inputStream; private ProtobufProtocolSerializer protobufProtocolSerializer; public void setUp(String authenticationMode) throws IOException { Properties expectedAuthProperties = new Properties(); expectedAuthProperties.setProperty(ResourceConstants.USER_NAME, TEST_USERNAME); expectedAuthProperties.setProperty(ResourceConstants.PASSWORD, TEST_PASSWORD); Object securityPrincipal = new Object(); SecurityManager mockSecurityManager = mock(SecurityManager.class); when(mockSecurityManager.authenticate(expectedAuthProperties)).thenReturn(securityPrincipal); when(mockSecurityManager.authorize(same(securityPrincipal), any())).thenReturn(true); Properties properties = new Properties(); CacheFactory cacheFactory = new CacheFactory(properties); cacheFactory.set(ConfigurationProperties.MCAST_PORT, "0"); // sometimes it isn't due to other // tests. cacheFactory.set(ConfigurationProperties.USE_CLUSTER_CONFIGURATION, "false"); cacheFactory.set(ConfigurationProperties.ENABLE_CLUSTER_CONFIGURATION, "false"); cacheFactory.setSecurityManager(mockSecurityManager); cache = cacheFactory.create(); CacheServer cacheServer = cache.addCacheServer(); int cacheServerPort = AvailablePortHelper.getRandomAvailableTCPPort(); cacheServer.setPort(cacheServerPort); cacheServer.start(); System.setProperty("geode.feature-protobuf-protocol", "true"); System.setProperty("geode.protocol-authentication-mode", authenticationMode); Socket socket = new Socket("localhost", cacheServerPort); Awaitility.await().atMost(5, TimeUnit.SECONDS).until(socket::isConnected); outputStream = socket.getOutputStream(); inputStream = socket.getInputStream(); outputStream.write(110); protobufProtocolSerializer = new ProtobufProtocolSerializer(); } @After public void tearDown() { if (cache != null) { cache.close(); cache = null; } } @Test public void noopAuthenticationSucceeds() throws Exception { setUp("NOOP"); ClientProtocol.Message getRegionsMessage = ClientProtocol.Message.newBuilder().setRequest(ClientProtocol.Request.newBuilder() .setGetRegionNamesRequest(RegionAPI.GetRegionNamesRequest.newBuilder())).build(); protobufProtocolSerializer.serialize(getRegionsMessage, outputStream); ClientProtocol.Message regionsResponse = protobufProtocolSerializer.deserialize(inputStream); assertEquals(ClientProtocol.Response.ResponseAPICase.GETREGIONNAMESRESPONSE, regionsResponse.getResponse().getResponseAPICase()); } @Test public void simpleAuthenticationSucceeds() throws Exception { setUp("SIMPLE"); AuthenticationAPI.SimpleAuthenticationRequest authenticationRequest = AuthenticationAPI.SimpleAuthenticationRequest.newBuilder().setUsername(TEST_USERNAME) .setPassword(TEST_PASSWORD).build(); authenticationRequest.writeDelimitedTo(outputStream); AuthenticationAPI.SimpleAuthenticationResponse authenticationResponse = AuthenticationAPI.SimpleAuthenticationResponse.parseDelimitedFrom(inputStream); assertTrue(authenticationResponse.getAuthenticated()); ClientProtocol.Message getRegionsMessage = ClientProtocol.Message.newBuilder().setRequest(ClientProtocol.Request.newBuilder() .setGetRegionNamesRequest(RegionAPI.GetRegionNamesRequest.newBuilder())).build(); protobufProtocolSerializer.serialize(getRegionsMessage, outputStream); ClientProtocol.Message regionsResponse = protobufProtocolSerializer.deserialize(inputStream); assertEquals(ClientProtocol.Response.ResponseAPICase.GETREGIONNAMESRESPONSE, regionsResponse.getResponse().getResponseAPICase()); } }
43.571429
100
0.78829
5f1c2f5d3acd71461a933801cc83def40c94eb80
1,505
package com.beijunyi.parallelgit.filesystem; import java.io.IOException; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class GitPathHashCodeTest extends AbstractGitFileSystemTest { @Before public void setupFileSystem() throws IOException { initGitFileSystem(); } @Test public void hashCodesFromSameAbsolutePath() { GitPath p1 = gfs.getPath("/a/b/c"); GitPath p2 = gfs.getPath("/a/b/c"); assertEquals(p1.hashCode(), p2.hashCode()); } @Test public void hashCodesFromSameRelativePath() { GitPath p1 = gfs.getPath("a/b/c"); GitPath p2 = gfs.getPath("a/b/c"); assertEquals(p1.hashCode(), p2.hashCode()); } @Test public void hashCodesFromDifferentPaths() { GitPath path = gfs.getPath("/a/b/c"); int hashCode = path.hashCode(); assertNotEquals(hashCode, gfs.getPath("a/b/c").hashCode()); assertNotEquals(hashCode, gfs.getPath("/a/b").hashCode()); assertNotEquals(hashCode, gfs.getPath("/a/b/c/d").hashCode()); assertNotEquals(hashCode, gfs.getPath("abc").hashCode()); assertNotEquals(hashCode, gfs.getPath("/").hashCode()); assertNotEquals(hashCode, gfs.getPath("").hashCode()); } @Test public void hashCodesFromDifferentFileSystems() throws IOException { try(GitFileSystem otherGfs = Gfs.newFileSystem(repo)) { GitPath p1 = gfs.getPath("/a/b/c"); GitPath p2 = otherGfs.getPath("/a/b/c"); assertNotEquals(p1.hashCode(), p2.hashCode()); } } }
27.87037
70
0.683721
832a6e92447eb36d4ef3c80db9e7d74064cd14c8
1,217
package org.omg.hw.session; import org.omg.PortableServer.POA; /** * Generated from IDL interface "Session_I" * @author JacORB IDL compiler V 2.2.3, 10-Dec-2005 */ public class Session_IPOATie extends Session_IPOA { private Session_IOperations _delegate; private POA _poa; public Session_IPOATie(Session_IOperations delegate) { _delegate = delegate; } public Session_IPOATie(Session_IOperations delegate, POA poa) { _delegate = delegate; _poa = poa; } public org.omg.hw.session.Session_I _this() { return org.omg.hw.session.Session_IHelper.narrow(_this_object()); } public org.omg.hw.session.Session_I _this(org.omg.CORBA.ORB orb) { return org.omg.hw.session.Session_IHelper.narrow(_this_object(orb)); } public Session_IOperations _delegate() { return _delegate; } public void _delegate(Session_IOperations delegate) { _delegate = delegate; } public POA _default_POA() { if (_poa != null) { return _poa; } else { return super._default_POA(); } } public org.omg.hw.session.Session_I associatedSession() { return _delegate.associatedSession(); } public void ping() { _delegate.ping(); } public void endSession() { _delegate.endSession(); } }
17.897059
70
0.723911
31bc2a74111ca1077d1999ece0f69348b21a3138
1,316
package com.ys.yoosir.zzshow.mvp.presenter; import com.ys.yoosir.zzshow.mvp.apis.VideoModuleApiIml; import com.ys.yoosir.zzshow.mvp.apis.interfaces.VideoModuleApi; import com.ys.yoosir.zzshow.mvp.entity.videos.VideoChannel; import com.ys.yoosir.zzshow.mvp.presenter.interfaces.VideoPresenter; import com.ys.yoosir.zzshow.mvp.view.VideoView; import java.util.List; /** * @version 1.0 * @author yoosir * Created by Administrator on 2016/11/26. */ public class VideoPresenterImpl extends BasePresenterImpl<VideoView,List<VideoChannel>> implements VideoPresenter { private VideoModuleApi<List<VideoChannel>> videoModuleApi; public VideoPresenterImpl(){ videoModuleApi = new VideoModuleApiIml(); } @Override public void onCreate() { super.onCreate(); loadVideoChannel(); } @Override public void loadVideoChannel() { mSubscription = videoModuleApi.getVideoChannelList(this); } @Override public void success(List<VideoChannel> data) { super.success(data); mView.initViewPager(data); } @Override public void onError(String errorMsg) { super.onError(errorMsg); } @Override public void onDestroy() { super.onDestroy(); } }
25.307692
116
0.675532
59352e51fa89b487e05bc90c5883daf333b50119
488
package concurrency.ex03; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 会预先创建有限的线程集 * * @author wangzhichao * @since 2020/3/2 */ public class FixedThreadPool { public static void main(String[] args) { ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(5); for (int i = 0; i < 5; i++) { newFixedThreadPool.execute(new MyRunnable(i)); } newFixedThreadPool.shutdown(); } }
23.238095
77
0.668033
c5f94364edf9d0915f8c6aca217f6f56b1df8938
5,200
/* * Copyright © 2019 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.plugin.cloud.vision.transform.transformer; import com.google.cloud.vision.v1.AnnotateImageResponse; import com.google.cloud.vision.v1.Likelihood; import com.google.cloud.vision.v1.SafeSearchAnnotation; import io.cdap.cdap.api.data.format.StructuredRecord; import io.cdap.cdap.api.data.schema.Schema; import io.cdap.plugin.cloud.vision.transform.ImageFeature; import io.cdap.plugin.cloud.vision.transform.schema.SafeSearchAnnotationSchema; import org.junit.Assert; import org.junit.Test; /** * {@link SafeSearchAnnotationsToRecordTransformer} test. */ public class SafeSearchAnnotationsToRecordTransformerTest extends BaseAnnotationsToRecordTransformerTest { private static final SafeSearchAnnotation SAFE_SEARCH_ANNOTATION = SafeSearchAnnotation.newBuilder() .setAdult(Likelihood.UNLIKELY) .setSpoof(Likelihood.POSSIBLE) .setMedical(Likelihood.UNLIKELY) .setViolence(Likelihood.POSSIBLE) .setRacy(Likelihood.UNLIKELY) .build(); private static final AnnotateImageResponse RESPONSE = AnnotateImageResponse.newBuilder() .setSafeSearchAnnotation(SAFE_SEARCH_ANNOTATION) .build(); @Test @SuppressWarnings("ConstantConditions") public void testTransform() { String output = "extracted"; Schema schema = Schema.recordOf("transformed-record-schema", Schema.Field.of("path", Schema.of(Schema.Type.STRING)), Schema.Field.of(output, ImageFeature.EXPLICIT_CONTENT.getSchema())); SafeSearchAnnotationsToRecordTransformer transformer = new SafeSearchAnnotationsToRecordTransformer(schema, output); StructuredRecord transformed = transformer.transform(INPUT_RECORD, RESPONSE); Assert.assertNotNull(transformed); StructuredRecord actual = transformed.get(output); assertAnnotationEquals(SAFE_SEARCH_ANNOTATION, actual); } @Test @SuppressWarnings("ConstantConditions") public void testTransformEmptyAnnotation() { String output = "extracted"; Schema schema = Schema.recordOf("transformed-record-schema", Schema.Field.of("path", Schema.of(Schema.Type.STRING)), Schema.Field.of(output, ImageFeature.EXPLICIT_CONTENT.getSchema())); SafeSearchAnnotationsToRecordTransformer transformer = new SafeSearchAnnotationsToRecordTransformer(schema, output); SafeSearchAnnotation emptyAnnotation = SafeSearchAnnotation.newBuilder().build(); AnnotateImageResponse response = AnnotateImageResponse.newBuilder() .setSafeSearchAnnotation(emptyAnnotation) .build(); StructuredRecord transformed = transformer.transform(INPUT_RECORD, response); Assert.assertNotNull(transformed); StructuredRecord actual = transformed.get(output); assertAnnotationEquals(emptyAnnotation, actual); } @Test @SuppressWarnings("ConstantConditions") public void testTransformSingleField() { String output = "extracted"; Schema singleFieldSchema = Schema.recordOf("single-field", Schema.Field.of( SafeSearchAnnotationSchema.VIOLENCE_FIELD_NAME, Schema.of(Schema.Type.STRING))); Schema schema = Schema.recordOf("transformed-record-schema", Schema.Field.of("path", Schema.of(Schema.Type.STRING)), Schema.Field.of(output, singleFieldSchema)); SafeSearchAnnotationsToRecordTransformer transformer = new SafeSearchAnnotationsToRecordTransformer(schema, output); StructuredRecord transformed = transformer.transform(INPUT_RECORD, RESPONSE); Assert.assertNotNull(transformed); StructuredRecord actual = transformed.get(output); // actual record has single-field schema Assert.assertEquals(singleFieldSchema, actual.getSchema()); Assert.assertEquals(SAFE_SEARCH_ANNOTATION.getViolence().name(), actual.get(SafeSearchAnnotationSchema.VIOLENCE_FIELD_NAME)); } private void assertAnnotationEquals(SafeSearchAnnotation expected, StructuredRecord actual) { Assert.assertNotNull(actual); Likelihood adult = expected.getAdult(); Assert.assertEquals(adult.name(), actual.get(SafeSearchAnnotationSchema.ADULT_FIELD_NAME)); Likelihood violence = expected.getViolence(); Assert.assertEquals(violence.name(), actual.get(SafeSearchAnnotationSchema.VIOLENCE_FIELD_NAME)); Likelihood spoof = expected.getSpoof(); Assert.assertEquals(spoof.name(), actual.get(SafeSearchAnnotationSchema.SPOOF_FIELD_NAME)); Likelihood medical = expected.getMedical(); Assert.assertEquals(medical.name(), actual.get(SafeSearchAnnotationSchema.MEDICAL_FIELD_NAME)); Likelihood racy = expected.getRacy(); Assert.assertEquals(racy.name(), actual.get(SafeSearchAnnotationSchema.RACY_FIELD_NAME)); } }
43.333333
120
0.778654
f20aab9df5f2ddfc315ed782658ce9388b660c4a
4,199
package software.amazon.rds.dbsubnetgroup; import java.util.List; import software.amazon.awssdk.services.rds.RdsClient; import software.amazon.awssdk.services.rds.model.DBSubnetGroup; import software.amazon.cloudformation.proxy.AmazonWebServicesClientProxy; import software.amazon.cloudformation.proxy.Logger; import software.amazon.cloudformation.proxy.ProgressEvent; import software.amazon.cloudformation.proxy.ProxyClient; import software.amazon.cloudformation.proxy.ResourceHandlerRequest; import software.amazon.rds.common.handler.Commons; import software.amazon.rds.common.handler.HandlerConfig; import software.amazon.rds.common.handler.Tagging; public class ReadHandler extends BaseHandlerStd { public ReadHandler() { this(HandlerConfig.builder().build()); } public ReadHandler(final HandlerConfig config) { super(config); } protected ProgressEvent<ResourceModel, CallbackContext> handleRequest( final AmazonWebServicesClientProxy proxy, final ResourceHandlerRequest<ResourceModel> request, final CallbackContext callbackContext, final ProxyClient<RdsClient> proxyClient, final Logger logger ) { return ProgressEvent.progress(request.getDesiredResourceState(), callbackContext) .then(progress -> describeDbSubnetGroup(proxy, request, callbackContext, proxyClient)) .then(progress -> readTags(proxyClient, progress)); } private ProgressEvent<ResourceModel, CallbackContext> describeDbSubnetGroup(final AmazonWebServicesClientProxy proxy, final ResourceHandlerRequest<ResourceModel> request, final CallbackContext callbackContext, final ProxyClient<RdsClient> proxyClient ) { return proxy.initiate("rds::read-dbsubnet-group", proxyClient, request.getDesiredResourceState(), callbackContext) .translateToServiceRequest(Translator::describeDbSubnetGroupsRequest) .backoffDelay(config.getBackoff()) .makeServiceCall((describeDbSubnetGroupRequest, proxyInvocation) -> proxyInvocation.injectCredentialsAndInvokeV2(describeDbSubnetGroupRequest, proxyInvocation.client()::describeDBSubnetGroups)) .handleError((awsRequest, exception, client, resourceModel, context) -> Commons.handleException( ProgressEvent.progress(resourceModel, context), exception, DEFAULT_DB_SUBNET_GROUP_ERROR_RULE_SET)) .done((describeDbSubnetGroupsRequest, describeDbSubnetGroupsResponse, proxyInvocation, model, context) -> { final DBSubnetGroup dbSubnetGroup = describeDbSubnetGroupsResponse.dbSubnetGroups().stream().findFirst().get(); context.setDbSubnetGroupArn(dbSubnetGroup.dbSubnetGroupArn()); return ProgressEvent.progress(Translator.translateToModel(dbSubnetGroup), context); }); } protected ProgressEvent<ResourceModel, CallbackContext> readTags( final ProxyClient<RdsClient> proxyClient, final ProgressEvent<ResourceModel, CallbackContext> progress ) { ResourceModel model = progress.getResourceModel(); CallbackContext context = progress.getCallbackContext(); try { String arn = progress.getCallbackContext().getDbSubnetGroupArn(); List<software.amazon.rds.dbsubnetgroup.Tag> resourceTags = Translator .translateTags(Tagging.listTagsForResource(proxyClient, arn)); model.setTags(resourceTags); } catch (Exception exception) { return Commons.handleException( ProgressEvent.progress(model, context), exception, Tagging.SOFT_FAIL_TAG_ERROR_RULE_SET.orElse(DEFAULT_DB_SUBNET_GROUP_ERROR_RULE_SET) ); } return ProgressEvent.success(model, context); } }
53.151899
209
0.673256
36631b4bb14cd549980c22c69fba7a121e0b2cf3
3,264
package xyz.klenkiven.kmall.ware.controller; import java.util.Arrays; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import xyz.klenkiven.kmall.common.exception.ExceptionCodeEnum; import xyz.klenkiven.kmall.common.utils.Result; import xyz.klenkiven.kmall.ware.entity.WareSkuEntity; import xyz.klenkiven.kmall.common.exception.NoStockException; import xyz.klenkiven.kmall.ware.service.WareSkuService; import xyz.klenkiven.kmall.common.utils.PageUtils; import xyz.klenkiven.kmall.common.utils.R; import xyz.klenkiven.kmall.common.to.SkuHasStockTO; import xyz.klenkiven.kmall.ware.vo.FareResp; import xyz.klenkiven.kmall.ware.vo.WareSkuLockDTO; /** * 商品库存 * * @author klenkiven * @email [email protected] * @date 2021-10-06 19:38:05 */ @RestController @RequestMapping("ware/waresku") public class WareSkuController { @Autowired private WareSkuService wareSkuService; /** * [FEIGN] Ware Lock SKU for Order */ @PostMapping("/lock/order") public Result<Boolean> lockOrder(@RequestBody WareSkuLockDTO lock) { try { wareSkuService.orderLockStock(lock); return Result.ok(); } catch (NoStockException e) { return Result.error(ExceptionCodeEnum.NO_STOCK_ERROR.getCode(), ExceptionCodeEnum.NO_STOCK_ERROR.getMessage()); } } /** * [FEIGN] Query User Fare * /ware/waresku/fare */ @PostMapping("/fare") public Result<FareResp> getFare(@RequestParam Long addrId) { FareResp result = wareSkuService.getFare(addrId); return Result.ok(result); } /** * [RPC] Query SKU has Stock * /ware/waresku/has-stock */ @PostMapping("/has-stock") public Result<List<SkuHasStockTO>> getSkuHasStock(@RequestBody List<Long> skuIds) { List<SkuHasStockTO> result = wareSkuService.getSkuHasStock(skuIds); return Result.ok(result); } /** * 列表 */ @RequestMapping("/list") // @RequiresPermissions("ware:waresku:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = wareSkuService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") // @RequiresPermissions("ware:waresku:info") public R info(@PathVariable("id") Long id){ WareSkuEntity wareSku = wareSkuService.getById(id); return R.ok().put("wareSku", wareSku); } /** * 保存 */ @RequestMapping("/save") // @RequiresPermissions("ware:waresku:save") public R save(@RequestBody WareSkuEntity wareSku){ wareSkuService.save(wareSku); return R.ok(); } /** * 修改 */ @RequestMapping("/update") // @RequiresPermissions("ware:waresku:update") public R update(@RequestBody WareSkuEntity wareSku){ wareSkuService.updateById(wareSku); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") // @RequiresPermissions("ware:waresku:delete") public R delete(@RequestBody Long[] ids){ wareSkuService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
25.700787
87
0.660846
98e69f689bfcba8d38c4320c79e08f4bcf9ab9cd
13,776
package ru.betterend.entity; import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos.MutableBlockPos; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.util.Mth; import net.minecraft.world.DifficultyInstance; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.MobSpawnType; import net.minecraft.world.entity.SpawnGroupData; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.ai.control.MoveControl; import net.minecraft.world.entity.ai.goal.Goal; import net.minecraft.world.entity.ai.goal.target.NearestAttackableTargetGoal; import net.minecraft.world.entity.animal.IronGolem; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.entity.monster.Slime; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.item.enchantment.EnchantmentHelper; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.ServerLevelAccessor; import net.minecraft.world.level.block.Blocks; import ru.bclib.api.biomes.BiomeAPI; import ru.bclib.api.tag.CommonBlockTags; import ru.bclib.util.BlocksHelper; import ru.bclib.util.MHelper; import ru.bclib.world.biomes.BCLBiome; import ru.betterend.interfaces.ISlime; import ru.betterend.registry.EndBiomes; import ru.betterend.util.GlobalState; import java.util.EnumSet; import java.util.Random; public class EndSlimeEntity extends Slime { private static final EntityDataAccessor<Byte> VARIANT = SynchedEntityData.defineId( EndSlimeEntity.class, EntityDataSerializers.BYTE ); public EndSlimeEntity(EntityType<EndSlimeEntity> entityType, Level world) { super(entityType, world); this.moveControl = new EndSlimeMoveControl(this); } protected void registerGoals() { this.goalSelector.addGoal(1, new SwimmingGoal()); this.goalSelector.addGoal(2, new FaceTowardTargetGoal()); this.goalSelector.addGoal(3, new RandomLookGoal()); this.goalSelector.addGoal(5, new MoveGoal()); this.targetSelector.addGoal( 1, new NearestAttackableTargetGoal<Player>(this, Player.class, 10, true, false, (livingEntity) -> { return Math.abs(livingEntity.getY() - this.getY()) <= 4.0D; }) ); this.targetSelector.addGoal(3, new NearestAttackableTargetGoal<IronGolem>(this, IronGolem.class, true)); } public static AttributeSupplier.Builder createMobAttributes() { return LivingEntity .createLivingAttributes() .add(Attributes.MAX_HEALTH, 1.0D) .add(Attributes.ATTACK_DAMAGE, 1.0D) .add(Attributes.FOLLOW_RANGE, 16.0D) .add(Attributes.MOVEMENT_SPEED, 0.15D); } @Override public SpawnGroupData finalizeSpawn(ServerLevelAccessor world, DifficultyInstance difficulty, MobSpawnType spawnReason, SpawnGroupData entityData, CompoundTag entityTag) { SpawnGroupData data = super.finalizeSpawn(world, difficulty, spawnReason, entityData, entityTag); BCLBiome biome = BiomeAPI.getFromBiome(world.getBiome(blockPosition())); if (biome == EndBiomes.FOGGY_MUSHROOMLAND) { this.setMossy(); } else if (biome == EndBiomes.MEGALAKE || biome == EndBiomes.MEGALAKE_GROVE) { this.setLake(); } else if (biome == EndBiomes.AMBER_LAND) { this.setAmber(true); } this.refreshDimensions(); return data; } @Override protected void defineSynchedData() { super.defineSynchedData(); this.entityData.define(VARIANT, (byte) 0); } @Override public void addAdditionalSaveData(CompoundTag tag) { super.addAdditionalSaveData(tag); tag.putByte("Variant", (byte) getSlimeType()); } @Override public void readAdditionalSaveData(CompoundTag tag) { super.readAdditionalSaveData(tag); if (tag.contains("Variant")) { this.entityData.set(VARIANT, tag.getByte("Variant")); } } @Override protected ParticleOptions getParticleType() { return ParticleTypes.PORTAL; } @Override public void remove(RemovalReason reason) { int i = this.getSize(); if (!this.level.isClientSide && i > 1 && this.isDeadOrDying()) { Component text = this.getCustomName(); boolean bl = this.isNoAi(); float f = (float) i / 4.0F; int j = i / 2; int k = 2 + this.random.nextInt(3); int type = this.getSlimeType(); for (int l = 0; l < k; ++l) { float g = ((float) (l % 2) - 0.5F) * f; float h = ((float) (l / 2) - 0.5F) * f; EndSlimeEntity slimeEntity = (EndSlimeEntity) this.getType().create(this.level); if (this.isPersistenceRequired()) { slimeEntity.setPersistenceRequired(); } slimeEntity.setSlimeType(type); slimeEntity.setCustomName(text); slimeEntity.setNoAi(bl); slimeEntity.setInvulnerable(this.isInvulnerable()); ((ISlime) slimeEntity).be_setSlimeSize(j, true); slimeEntity.refreshDimensions(); slimeEntity.moveTo( this.getX() + (double) g, this.getY() + 0.5D, this.getZ() + (double) h, this.random.nextFloat() * 360.0F, 0.0F ); this.level.addFreshEntity(slimeEntity); } } ((ISlime) this).entityRemove(reason); } @Override protected void dropFromLootTable(DamageSource source, boolean causedByPlayer) { int maxCount = this.getSize(); int minCount = maxCount >> 1; if (minCount < 1) { minCount = 1; } if (causedByPlayer && this.lastHurtByPlayer != null) { int looting = EnchantmentHelper.getMobLooting(this.lastHurtByPlayer); minCount += looting; } int count = minCount < maxCount ? MHelper.randRange(minCount, maxCount, random) : maxCount; ItemEntity drop = new ItemEntity(level, getX(), getY(), getZ(), new ItemStack(Items.SLIME_BALL, count)); this.level.addFreshEntity(drop); } public int getSlimeType() { return this.entityData.get(VARIANT).intValue(); } public void setSlimeType(int value) { this.entityData.set(VARIANT, (byte) value); } protected void setMossy() { setSlimeType(1); } public boolean isMossy() { return getSlimeType() == 1; } protected void setLake() { setSlimeType(2); } public boolean isLake() { return getSlimeType() == 2; } protected void setAmber(boolean mossy) { this.entityData.set(VARIANT, (byte) 3); } public boolean isAmber() { return this.entityData.get(VARIANT) == 3; } public boolean isChorus() { return this.entityData.get(VARIANT) == 0; } public static boolean canSpawn(EntityType entityType, LevelAccessor world, MobSpawnType spawnType, BlockPos pos, Random random) { if (!world.getBlockState(pos.below()).is(CommonBlockTags.END_STONES)) { return false; } BCLBiome biome = BiomeAPI.getFromBiome(world.getBiome(pos)); if (biome == EndBiomes.CHORUS_FOREST || biome == EndBiomes.MEGALAKE) { return true; } if (biome == EndBiomes.MEGALAKE_GROVE && random.nextBoolean()) { return true; } return random.nextInt(4) == 0 && isWaterNear(world, pos); } private static boolean isWaterNear(LevelAccessor world, BlockPos pos) { final MutableBlockPos POS = GlobalState.stateForThread().POS; for (int x = pos.getX() - 32; x <= pos.getX() + 32; x++) { POS.setX(x); for (int z = pos.getZ() - 32; z <= pos.getZ() + 32; z++) { POS.setZ(z); for (int y = pos.getY() - 8; y <= pos.getY() + 8; y++) { POS.setY(y); if (world.getBlockState(POS).getBlock() == Blocks.WATER) { return true; } } } } return false; } class MoveGoal extends Goal { public MoveGoal() { this.setFlags(EnumSet.of(Goal.Flag.JUMP, Goal.Flag.MOVE)); } public boolean canUse() { if (EndSlimeEntity.this.isPassenger()) { return false; } float yaw = EndSlimeEntity.this.getYHeadRot(); float speed = EndSlimeEntity.this.getSpeed(); if (speed > 0.1) { float dx = Mth.sin(-yaw * 0.017453292F); float dz = Mth.cos(-yaw * 0.017453292F); BlockPos pos = EndSlimeEntity.this.blockPosition().offset(dx * speed * 4, 0, dz * speed * 4); int down = BlocksHelper.downRay(EndSlimeEntity.this.level, pos, 16); return down < 5; } return true; } public void tick() { ((EndSlimeMoveControl) EndSlimeEntity.this.getMoveControl()).move(1.0D); } } class SwimmingGoal extends Goal { public SwimmingGoal() { this.setFlags(EnumSet.of(Goal.Flag.JUMP, Goal.Flag.MOVE)); EndSlimeEntity.this.getNavigation().setCanFloat(true); } public boolean canUse() { return (EndSlimeEntity.this.isInWater() || EndSlimeEntity.this.isInLava()) && EndSlimeEntity.this.getMoveControl() instanceof EndSlimeMoveControl; } public void tick() { if (EndSlimeEntity.this.getRandom().nextFloat() < 0.8F) { EndSlimeEntity.this.getJumpControl().jump(); } ((EndSlimeMoveControl) EndSlimeEntity.this.getMoveControl()).move(1.2D); } } class RandomLookGoal extends Goal { private float targetYaw; private int timer; public RandomLookGoal() { this.setFlags(EnumSet.of(Goal.Flag.LOOK)); } public boolean canUse() { return EndSlimeEntity.this.getTarget() == null && (EndSlimeEntity.this.onGround || EndSlimeEntity.this.isInWater() || EndSlimeEntity.this .isInLava() || EndSlimeEntity.this.hasEffect(MobEffects.LEVITATION)) && EndSlimeEntity.this.getMoveControl() instanceof EndSlimeMoveControl; } public void tick() { if (--this.timer <= 0) { this.timer = 40 + EndSlimeEntity.this.getRandom().nextInt(60); this.targetYaw = (float) EndSlimeEntity.this.getRandom().nextInt(360); } ((EndSlimeMoveControl) EndSlimeEntity.this.getMoveControl()).look(this.targetYaw, false); } } class FaceTowardTargetGoal extends Goal { private int ticksLeft; public FaceTowardTargetGoal() { this.setFlags(EnumSet.of(Goal.Flag.LOOK)); } public boolean canUse() { LivingEntity livingEntity = EndSlimeEntity.this.getTarget(); if (livingEntity == null) { return false; } else if (!livingEntity.isAlive()) { return false; } else { return livingEntity instanceof Player && ((Player) livingEntity).getAbilities().invulnerable ? false : EndSlimeEntity.this .getMoveControl() instanceof EndSlimeMoveControl; } } public void start() { this.ticksLeft = 300; super.start(); } public boolean canContinueToUse() { LivingEntity livingEntity = EndSlimeEntity.this.getTarget(); if (livingEntity == null) { return false; } else if (!livingEntity.isAlive()) { return false; } else if (livingEntity instanceof Player && ((Player) livingEntity).getAbilities().invulnerable) { return false; } else { return --this.ticksLeft > 0; } } public void tick() { EndSlimeEntity.this.lookAt(EndSlimeEntity.this.getTarget(), 10.0F, 10.0F); ((EndSlimeMoveControl) EndSlimeEntity.this.getMoveControl()).look( EndSlimeEntity.this.getYRot(), EndSlimeEntity.this.isDealsDamage() ); } } class EndSlimeMoveControl extends MoveControl { private float targetYaw; private int ticksUntilJump; private boolean jumpOften; public EndSlimeMoveControl(EndSlimeEntity slime) { super(slime); this.targetYaw = 180.0F * slime.getYRot() / 3.1415927F; } public void look(float targetYaw, boolean jumpOften) { this.targetYaw = targetYaw; this.jumpOften = jumpOften; } public void move(double speed) { this.speedModifier = speed; this.operation = MoveControl.Operation.MOVE_TO; } public void tick() { this.mob.setYRot(this.rotlerp(this.mob.getYRot(), this.targetYaw, 90.0F)); this.mob.yHeadRot = this.mob.getYRot(); this.mob.yBodyRot = this.mob.getYRot(); if (this.operation != MoveControl.Operation.MOVE_TO) { this.mob.setZza(0.0F); } else { this.operation = MoveControl.Operation.WAIT; if (this.mob.isOnGround()) { this.mob.setSpeed((float) (this.speedModifier * this.mob.getAttributeValue(Attributes.MOVEMENT_SPEED))); if (this.ticksUntilJump-- <= 0) { this.ticksUntilJump = EndSlimeEntity.this.getJumpDelay(); if (this.jumpOften) { this.ticksUntilJump /= 3; } EndSlimeEntity.this.getJumpControl().jump(); if (EndSlimeEntity.this.doPlayJumpSound()) { EndSlimeEntity.this.playSound( EndSlimeEntity.this.getJumpSound(), EndSlimeEntity.this.getSoundVolume(), getJumpSoundPitch() ); } } else { EndSlimeEntity.this.xxa = 0.0F; EndSlimeEntity.this.zza = 0.0F; this.mob.setSpeed(0.0F); } } else { this.mob.setSpeed((float) (this.speedModifier * this.mob.getAttributeValue(Attributes.MOVEMENT_SPEED))); } } } private float getJumpSoundPitch() { float f = EndSlimeEntity.this.isTiny() ? 1.4F : 0.8F; return ((EndSlimeEntity.this.random.nextFloat() - EndSlimeEntity.this.random.nextFloat()) * 0.2F + 1.0F) * f; } } }
31.815242
173
0.684669
4264b146e793acb663ef29715b55c4377a9e244b
82
package interfaces; public interface OnResult { void onSuccess(String s); }
13.666667
30
0.731707
9404204d18af21715821c0b0601178dc799bfd37
3,060
package com.ecust.test; import com.ecust.utils.PageUtils; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import java.util.List; /** * 用来测试 Selenium */ public class TestSeleniumDemo { /** * 用来测试第一个代码,访问百度 */ @Test public void testHelloWordl() throws Exception { //开启个浏览器并且输入链接 WebDriver driver = PageUtils.getChromeDriver("https://igovsolution.net/fsbonline/Lookups/Individual.aspx"); driver.manage().window().maximize(); //得到浏览器的标题 System.out.println(driver.getTitle()); Thread.sleep(5000); //关闭浏览器 下面是关闭所有标签页,还有一个代码是 driver.close();, 关闭当前标签页 driver.quit(); } /** * 测试向input标签输入值 */ @Test public void testInputStrByJS(){ //开启个浏览器并且输入链接 WebDriver driver = PageUtils.getChromeDriver("https://www.baidu.com/"); //向input输入值 PageUtils.inputStrByJS(driver, "kw", "月之暗面 博客园"); } /** * 测试点击 */ @Test public void testScrollToElementAndClick() throws Exception { //1、开启个浏览器并且输入链接 WebDriver driver = PageUtils.getChromeDriver("https://www.baidu.com/"); //2、向百度输入框输入需要查询的值 PageUtils.inputStrByJS(driver, "kw", "月之暗面 博客园"); //3、得到百度一下的标签 WebElement submitElement = driver.findElement(By.cssSelector("input#su")); //4、点击百度一下 PageUtils.scrollToElementAndClick(submitElement, driver); //休息3秒,加载数据 Thread.sleep(3000); //5、首先找到 id 为 content_left 的 div 下面的所有 div List<WebElement> divElements = driver.findElements(By.cssSelector("div#content_left div")); //6、找到搜索的第一个链接 WebElement aElement = divElements.get(0).findElement(By.cssSelector("div.f13 a[href]")); //7、点击该链接 PageUtils.scrollToElementAndClick(aElement, driver); } /** * 测试切换到另一个标签页 */ @Test public void testGetAnotherPage() throws Exception { //1、开启个浏览器并且输入链接 WebDriver driver = PageUtils.getChromeDriver("https://www.baidu.com/"); //2、向百度输入框输入需要查询的值 PageUtils.inputStrByJS(driver, "kw", "月之暗面 博客园"); //3、得到百度一下的标签 WebElement submitElement = driver.findElement(By.cssSelector("input#su")); //4、点击百度一下 PageUtils.scrollToElementAndClick(submitElement, driver); //休息3秒,加载数据 Thread.sleep(3000); //5、首先找到 id 为 content_left 的 div 下面的所有 div List<WebElement> divElements = driver.findElements(By.cssSelector("div#content_left div")); //6、找到搜索的第一个链接 WebElement aElement = divElements.get(0).findElement(By.cssSelector("div.f13 a[href]")); //7、点击该链接 PageUtils.scrollToElementAndClick(aElement, driver); //8、当前页面时百度的页面 //将浏览器对象强制转为可以执行js的对象 System.out.println("现在的页面是:"+driver.getTitle()); //9、切换到博客园页面 PageUtils.getAnotherPage(driver); //将浏览器对象强制转为可以执行js的对象 System.out.println("现在的页面是:"+driver.getTitle()); } }
28.333333
115
0.635294
0cf645623f33c070c540eb0dd4c0cf9812511ad2
1,740
package problem.p1089duplicatezeros; import java.util.Arrays; /** * 1089. Duplicate Zeros * * https://leetcode-cn.com/problems/duplicate-zeros/ * * Given a fixed length array arr of integers, duplicate each occurrence of zero, * shifting the remaining elements to the right. * * Note that elements beyond the length of the original array are not written. * * Do the above modifications to the input array in place, do not return anything from your function. */ public class Solution { public void duplicateZeros(int[] arr) { int l = arr.length, c = 0, i = 0; while (c < l) c += arr[i++] == 0 ? 2 : 1; if (i == l) return; int j = arr.length - 1; if (arr[--i] == 0 && c > l) { arr[j--] = 0; i--; } for (; i >= 0; i--) { if (arr[i] == 0) { arr[j--] = 0; arr[j--] = 0; } else { arr[j--] = arr[i]; } } } public static void main(String[] args) { int[] v2 = new int[]{1,5,2,0,6,8,0,6,0}; new Solution().duplicateZeros(v2); System.out.println(Arrays.toString(v2)); int[] v1 = new int[]{8,4,5,0,0,0,0,7}; new Solution().duplicateZeros(v1); System.out.println(Arrays.toString(v1)); int[] v0 = new int[]{0,0,0,0,0,0,0}; new Solution().duplicateZeros(v0); System.out.println(Arrays.toString(v0)); int[] p0 = new int[]{1,0,2,3,0,4,5,0}; new Solution().duplicateZeros(p0); System.out.println(Arrays.toString(p0)); int[] p1 = new int[]{1,2,3}; new Solution().duplicateZeros(p1); System.out.println(Arrays.toString(p1)); } }
27.1875
101
0.531609
1cf1bb06b008b3bc46d0d29b273c44fdb104617a
1,372
package exceptions.ex24; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; class NeedsCleanup { public void dispose() { System.out.println("NeedsCleanup " + " disposed"); } } class FailingConstructor { private BufferedReader in; NeedsCleanup nc; public FailingConstructor(String fileName) throws Exception { try { in = new BufferedReader(new FileReader(fileName)); } catch (FileNotFoundException e) { throw e; } catch (Exception e) { try { in.close(); } catch (IOException ex) { ex.printStackTrace(); } throw e; } nc = new NeedsCleanup(); } public void dispose() { System.out.println("FailingConstructor dispose"); } } public class Ex24 { public static void main(String[] args) { try { FailingConstructor fc = new FailingConstructor("G:\\AndroidWorkspaces\\Think4JavaExamples\\app\\src\\main\\java\\holding\\SetOperations.java"); try { } finally { fc.nc.dispose(); fc.dispose(); } } catch (Exception e) { System.out.println("FailingConstructor construction failed"); } } }
24.945455
155
0.572157
8eb9d4c711d2e781227af261c1d29c27cb8cb81e
1,004
package io.quarkus.agroal.test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import javax.enterprise.inject.spi.DeploymentException; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import io.quarkus.test.QuarkusUnitTest; public class XaRequiresXaDatasourceTest { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class) .addAsResource("application-wrongdriverkind-datasource.properties", "application.properties")) .assertException(t -> { assertEquals(DeploymentException.class, t.getClass()); }); @Test public void xaRequiresJta() { //Should not be reached: verify assertTrue(false); } }
31.375
114
0.726096
5de81c899c73315a59bd092cab43f4b3df9e5592
235
package com.binder.database.datasearch; import android.content.Context; import com.binder.database.DatabaseAccess; public class LoginCheck { private DatabaseAccess instance; public LoginCheck (Context context){ } }
14.6875
42
0.757447
ad803180eb25921601c2d12d5cfb229797b24722
643
package org.woehlke.twitterwall.oodm.repositories.custom; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.woehlke.twitterwall.oodm.model.HashTag; import org.woehlke.twitterwall.oodm.model.transients.HashTagCounted; import org.woehlke.twitterwall.oodm.repositories.common.DomainObjectEntityRepository; public interface HashTagRepositoryCustom extends DomainObjectEntityRepository<HashTag> { HashTag findByUniqueId(HashTag domainObject); Page<HashTagCounted> countAllUser2HashTag(Pageable pageRequest); Page<HashTagCounted> countAllTweet2HashTag(Pageable pageRequest); }
37.823529
88
0.847589
884a31f883ee0d8df879cc7eadae2e20ec0562f5
898
package com.jivesoftware.os.miru.catwalk.shared; import com.jivesoftware.os.miru.api.base.MiruTermId; import java.util.Arrays; /** * */ public class StrutModelKey { private final MiruTermId[] termIds; public StrutModelKey(MiruTermId[] termIds) { this.termIds = termIds; } @Override public int hashCode() { int hash = 7; hash = 23 * hash + Arrays.deepHashCode(this.termIds); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final StrutModelKey other = (StrutModelKey) obj; if (!Arrays.deepEquals(this.termIds, other.termIds)) { return false; } return true; } }
20.883721
62
0.55902
24c4a470d352f7298ffe6b85028c43dc15f5249c
775
package ru.stqa.pft.sandbox; import org.testng.Assert; import org.testng.annotations.Test; public class PointTests { @Test public void testDistance() { Point p1 = new Point(1,2); Point p2 = new Point(4,6); Assert.assertEquals(p1.findDistance(p2), 5.0); } @Test public void testDistanceWhenZeroY() { Point p1 = new Point(-5,0); Point p2 = new Point(3,0); Assert.assertEquals(p1.findDistance(p2), 8); } @Test public void testDistanceWhenAllZero() { Point p1 = new Point(0,0); Point p2 = new Point(0,0); Assert.assertEquals(p1.findDistance(p2), 0); } @Test public void testDistanceWhenMinus() { Point p1 = new Point(-1,-1); Point p2 = new Point(-1,-4); Assert.assertEquals(p1.findDistance(p2),3); } }
22.142857
50
0.651613
0a0f7d80a221460cae529d5029bb39f7b4594e08
572
package com.thomsonreuters.upa.shared.rdm.marketprice; /** * Market price request flags. */ public class MarketPriceRequestFlags { public static final int NONE = 0; public static final int HAS_QOS = 0x001; public static final int HAS_PRIORITY = 0x002; public static final int HAS_SERVICE_ID = 0x004; public static final int HAS_WORST_QOS = 0x008; public static final int HAS_VIEW = 0x010; public static final int STREAMING = 0x020; public static final int PRIVATE_STREAM = 0x040; private MarketPriceRequestFlags() { } }
28.6
54
0.718531
10f106bbf6140c6ab36df4e40eb5bba591a897a8
6,650
package de.ids_mannheim.korap.query; import java.io.IOException; import java.util.List; import java.util.Map; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.Term; import org.apache.lucene.index.TermContext; import org.apache.lucene.search.spans.SpanQuery; import org.apache.lucene.search.spans.Spans; import org.apache.lucene.util.Bits; import org.apache.lucene.util.ToStringUtils; import de.ids_mannheim.korap.query.spans.MultipleDistanceSpans; /** * SpanMultipleDistanceQuery matches two spans with respect to a list * of distance constraints. No repetition of constraints of the same * unit type (e.g. word, sentence, paragraph) is allowed. For example, * there must only exactly one constraint for word/token-based * distance. A SpanDistanceQuery is created for each constraint.<br /> * <br /> * Examples: * <ul> * * <li> * Search two terms x and y which are separated by minimum two and * maximum three other words within the same sentence. The order of x * and y does not matter. * * <pre> * List&lt;DistanceConstraint&gt; constraints = new * ArrayList&lt;DistanceConstraint&gt;(); * constraints.add(new DistanceConstraint(2, 3, false, false)); * constraints.add(DistanceConstraint(new * SpanElementQuery(&quot;tokens&quot;, &quot;s&quot;), 0, 0, * false, false)); * * SpanMultipleDistanceQuery mdq = SpanMultipleDistanceQuery(x, y, * constraints, * false, true); * </pre> * * </li> * * <li> * Search term x which do <em>not</em> occur with term y in minimum * two and maximum three other words and <em>not</em> in the same * sentence. X must precede y. * * <pre> * List&lt;DistanceConstraint&gt; constraints = new * ArrayList&lt;DistanceConstraint&gt;(); * constraints.add(new DistanceConstraint(2, 3, false, true)); * constraints.add(DistanceConstraint(new * SpanElementQuery(&quot;tokens&quot;, &quot;s&quot;), 0, 0, * false, true)); * * SpanMultipleDistanceQuery mdq = SpanMultipleDistanceQuery(x, y, * constraints, * true, true); * </pre> * * </li> * </ul> * * @author margaretha */ public class SpanMultipleDistanceQuery extends SimpleSpanQuery { private List<DistanceConstraint> constraints; private boolean isOrdered; private String spanName; /** * Constructs a SpanMultipleDistanceQuery for the two given * SpanQueries. * * @param firstClause * the first SpanQuery * @param secondClause * the second SpanQuery * @param constraints * the list of distance constraints * @param isOrdered * a boolean representing the value <code>true</code>, * if * the firstspans must occur before the secondspans, * otherwise * <code>false</code>. * @param collectPayloads * a boolean flag representing the value * <code>true</code> if payloads are to be collected, * otherwise * <code>false</code>. */ public SpanMultipleDistanceQuery (SpanQuery firstClause, SpanQuery secondClause, List<DistanceConstraint> constraints, boolean isOrdered, boolean collectPayloads) { super(firstClause, secondClause, collectPayloads); this.constraints = constraints; this.isOrdered = isOrdered; spanName = "spanMultipleDistance"; } @Override public SpanMultipleDistanceQuery clone () { SpanMultipleDistanceQuery query = new SpanMultipleDistanceQuery( (SpanQuery) firstClause.clone(), (SpanQuery) secondClause.clone(), this.constraints, this.isOrdered, collectPayloads); query.setBoost(getBoost()); return query; } @Override public String toString (String field) { StringBuilder sb = new StringBuilder(); sb.append(this.spanName); sb.append("("); sb.append(firstClause.toString(field)); sb.append(", "); sb.append(secondClause.toString(field)); sb.append(", "); sb.append("["); DistanceConstraint c; int size = constraints.size(); for (int i = 0; i < size; i++) { c = constraints.get(i); sb.append("("); sb.append(c.getUnit()); sb.append("["); sb.append(c.getMinDistance()); sb.append(":"); sb.append(c.getMaxDistance()); sb.append("], "); sb.append(c.isOrdered() ? "ordered, " : "notOrdered, "); sb.append(c.isExclusion() ? "excluded)" : "notExcluded)"); if (i < size - 1) sb.append(", "); } sb.append("])"); sb.append(ToStringUtils.boost(getBoost())); return sb.toString(); } /** * Filters the span matches of each constraint, returning only the * matches * meeting all the constraints. * * @return only the span matches meeting all the constraints. */ @Override public Spans getSpans (LeafReaderContext context, Bits acceptDocs, Map<Term, TermContext> termContexts) throws IOException { SpanDistanceQuery sdq, sdq2; Spans ds, ds2; MultipleDistanceSpans mds = null; boolean exclusion; sdq = new SpanDistanceQuery(firstClause, secondClause, constraints.get(0), collectPayloads); ds = sdq.getSpans(context, acceptDocs, termContexts); for (int i = 1; i < constraints.size(); i++) { sdq2 = new SpanDistanceQuery(firstClause, secondClause, constraints.get(i), collectPayloads); ds2 = sdq2.getSpans(context, acceptDocs, termContexts); exclusion = sdq.isExclusion() && sdq2.isExclusion(); mds = new MultipleDistanceSpans(this, context, acceptDocs, termContexts, ds, ds2, isOrdered, exclusion); ds = mds; } return mds; } /** * Returns the list of distance constraints. * * @return the list of distance constraints */ public List<DistanceConstraint> getConstraints () { return constraints; } /** * Sets the list of distance constraints. * * @param constraints * the list of distance constraints */ public void setConstraints (List<DistanceConstraint> constraints) { this.constraints = constraints; } }
31.367925
75
0.609774
b96dc458a62fde5a41158089847338556ea11cd0
2,149
/**************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * ****************************************************************/ package org.apache.james.jmap.cassandra.upload; import java.time.Clock; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.temporal.ChronoUnit; import java.util.function.Predicate; import javax.inject.Inject; public class BucketNameGenerator { private final Clock clock; @Inject public BucketNameGenerator(Clock clock) { this.clock = clock; } public UploadBucketName current() { int weekCount = currentWeekCount(); return new UploadBucketName(weekCount); } public Predicate<UploadBucketName> evictionPredicate() { final int currentWeekCount = currentWeekCount(); return uploadBucketName -> uploadBucketName.getWeekNumber() < currentWeekCount - 1; } private int currentWeekCount() { return Math.toIntExact(ChronoUnit.WEEKS.between( LocalDate.ofEpochDay(0), LocalDate.ofInstant(clock.instant(), ZoneOffset.UTC))); } }
39.072727
91
0.597487
fb0b38d6fc0e07cd8868dd739f189ba133e24f0a
1,615
package io.ankburov.retrofit.httpclient; import java.io.IOException; import java.io.InputStream; import java.net.http.HttpRequest; import java.time.Duration; import org.jetbrains.annotations.Nullable; import okhttp3.Request; import okhttp3.RequestBody; import okio.Buffer; public class DefaultHttpRequestFactory implements HttpRequestFactory { private static final String CONTENT_TYPE = "Content-Type"; @Override public HttpRequest build(Request request, @Nullable Duration timeout) throws IOException { HttpRequest.Builder builder = HttpRequest.newBuilder() .uri(request.url().uri()) .method(request.method(), getBody(request)); request.headers().forEach(pair -> builder.header(pair.getFirst(), pair.getSecond())); if (request.body() != null && request.body().contentType() != null) { builder.setHeader(CONTENT_TYPE, request.body().contentType().toString()); } if (timeout != null) { builder.timeout(timeout); } return builder.build(); } protected HttpRequest.BodyPublisher getBody(Request request) throws IOException { RequestBody body = request.body(); if (body == null) { return HttpRequest.BodyPublishers.noBody(); } try (Buffer buffer = new Buffer()) { body.writeTo(buffer); try (InputStream bodyStream = buffer.inputStream()) { return HttpRequest.BodyPublishers.ofInputStream(() -> bodyStream); } } } }
31.057692
94
0.627864
eb6617c2a27a38485415a8db2026b4589fe0a0eb
8,091
package com.codingpixel.healingbudz.adapter; import android.content.Context; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Filter; import android.widget.ImageView; import android.widget.TextView; import com.codingpixel.healingbudz.DataModel.GroupsInviteNewBudDataModel; import com.codingpixel.healingbudz.R; import java.util.ArrayList; import java.util.List; public class GroupsInvitBudAutocompleteListAdapter extends ArrayAdapter<GroupsInviteNewBudDataModel> { private final Context mContext; private LayoutInflater mInflater; private final List<GroupsInviteNewBudDataModel> mGroupsInviteNewBudDataModels; private final List<GroupsInviteNewBudDataModel> mGroupsInviteNewBudDataModels_All; private final List<GroupsInviteNewBudDataModel> mGroupsInviteNewBudDataModels_Suggestion; private final int mLayoutResourceId; int filter_type = 0; private ItemClickListener onInviteClickListner; public interface ItemClickListener { void onInviteButtonClick(View view, int position, GroupsInviteNewBudDataModel groupsInviteNewBudDataModel); } public GroupsInvitBudAutocompleteListAdapter(Context context, int resource, List<GroupsInviteNewBudDataModel> GroupsInviteNewBudDataModels, ItemClickListener onInviteClickListner, int filter_type) { super(context, resource, GroupsInviteNewBudDataModels); this.mInflater = LayoutInflater.from(getContext()); this.mContext = context; this.filter_type = filter_type; this.mLayoutResourceId = resource; this.mGroupsInviteNewBudDataModels = new ArrayList<>(GroupsInviteNewBudDataModels); this.mGroupsInviteNewBudDataModels_All = new ArrayList<>(GroupsInviteNewBudDataModels); this.mGroupsInviteNewBudDataModels_Suggestion = new ArrayList<>(); this.onInviteClickListner = onInviteClickListner; } public int getCount() { return mGroupsInviteNewBudDataModels.size(); } public GroupsInviteNewBudDataModel getItem(int position) { return mGroupsInviteNewBudDataModels.get(position); } public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { try { if (convertView == null) { convertView = this.mInflater.inflate(mLayoutResourceId, parent, false); } final GroupsInviteNewBudDataModel GroupsInviteNewBudDataModel = getItem(position); TextView name = convertView.findViewById(R.id.bud_name); if (filter_type == 0) { name.setText(GroupsInviteNewBudDataModel.getName()); } else if (filter_type == 1) { name.setText(GroupsInviteNewBudDataModel.getEmail()); } final ImageView Invite_bud_button = convertView.findViewById(R.id.add_invitation_button); if (GroupsInviteNewBudDataModel.isInvited()) { Invite_bud_button.setImageResource(R.drawable.ic_invite_group_bud_invited_btn); name.setTextColor(Color.parseColor("#f79124")); } else { Invite_bud_button.setImageResource(R.drawable.ic_invite_groups_bud_add_btn); name.setTextColor(Color.parseColor("#808080")); } name.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (filter_type == 0) { if (!GroupsInviteNewBudDataModel.isInvited()) { GroupsInviteNewBudDataModel.setInvited(true); notifyDataSetChanged(); onInviteClickListner.onInviteButtonClick(view, position, GroupsInviteNewBudDataModel); } } } }); Invite_bud_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (filter_type == 0) { if (!GroupsInviteNewBudDataModel.isInvited()) { GroupsInviteNewBudDataModel.setInvited(true); notifyDataSetChanged(); onInviteClickListner.onInviteButtonClick(view, position, GroupsInviteNewBudDataModel); } } } }); } catch (Exception e) { e.printStackTrace(); } return convertView; } @Override public Filter getFilter() { return new Filter() { @Override public String convertResultToString(Object resultValue) { if (filter_type == 0) { return ((GroupsInviteNewBudDataModel) resultValue).getName(); } else { return ((GroupsInviteNewBudDataModel) resultValue).getEmail(); } } @Override protected FilterResults performFiltering(CharSequence constraint) { if (constraint != null) { mGroupsInviteNewBudDataModels_Suggestion.clear(); for (GroupsInviteNewBudDataModel GroupsInviteNewBudDataModel : mGroupsInviteNewBudDataModels_All) { switch (filter_type) { case 0: if (GroupsInviteNewBudDataModel.getName().toLowerCase().startsWith(constraint.toString().toLowerCase())) { mGroupsInviteNewBudDataModels_Suggestion.add(GroupsInviteNewBudDataModel); } break; case 1: if (GroupsInviteNewBudDataModel.getEmail().toLowerCase().startsWith(constraint.toString().toLowerCase())) { mGroupsInviteNewBudDataModels_Suggestion.add(GroupsInviteNewBudDataModel); } break; case 2: if (GroupsInviteNewBudDataModel.getName().toLowerCase().startsWith(constraint.toString().toLowerCase())) { mGroupsInviteNewBudDataModels_Suggestion.add(GroupsInviteNewBudDataModel); } break; } } FilterResults filterResults = new FilterResults(); filterResults.values = mGroupsInviteNewBudDataModels_Suggestion; filterResults.count = mGroupsInviteNewBudDataModels_Suggestion.size(); return filterResults; } else { return new FilterResults(); } } @Override protected void publishResults(CharSequence constraint, FilterResults results) { mGroupsInviteNewBudDataModels.clear(); if (results != null && results.count > 0) { // avoids unchecked cast warning when using mGroupsInviteNewBudDataModels.addAll((ArrayList<GroupsInviteNewBudDataModel>) results.values); List<?> result = (List<?>) results.values; for (Object object : result) { if (object instanceof GroupsInviteNewBudDataModel) { mGroupsInviteNewBudDataModels.add((GroupsInviteNewBudDataModel) object); } } } else if (constraint == null) { // no filter, add entire original list back in mGroupsInviteNewBudDataModels.addAll(mGroupsInviteNewBudDataModels_All); } notifyDataSetChanged(); } }; } }
46.234286
202
0.600667
eb45c74ed1c791e2017f30495c58be7d936145da
3,051
// Copyright 2016 The Nomulus Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package google.registry.tools.server.javascrap; import static google.registry.mapreduce.inputs.EppResourceInputs.createEntityInput; import static google.registry.util.PipelineUtils.createJobPath; import com.google.appengine.tools.mapreduce.Mapper; import com.google.common.collect.ImmutableList; import google.registry.dns.DnsQueue; import google.registry.mapreduce.MapreduceRunner; import google.registry.model.EppResourceUtils; import google.registry.model.domain.DomainResource; import google.registry.request.Action; import google.registry.request.Response; import google.registry.util.FormattingLogger; import javax.inject.Inject; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; /** A mapreduce that enqueues publish tasks on all active domains. */ @Action(path = "/_dr/task/refreshAllDomains") public class RefreshAllDomainsAction implements Runnable { private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass(); @Inject MapreduceRunner mrRunner; @Inject Response response; @Inject RefreshAllDomainsAction() {} @Override public void run() { response.sendJavaScriptRedirect( createJobPath( mrRunner .setJobName("Refresh all domains") .setModuleName("tools") .setDefaultMapShards(10) .runMapOnly( new RefreshAllDomainsActionMapper(), ImmutableList.of(createEntityInput(DomainResource.class))))); } /** Mapper to refresh all active domain resources. */ public static class RefreshAllDomainsActionMapper extends Mapper<DomainResource, Void, Void> { private static final DnsQueue dnsQueue = DnsQueue.create(); private static final long serialVersionUID = 1356876487351666133L; @Override public void map(final DomainResource domain) { String domainName = domain.getFullyQualifiedDomainName(); if (EppResourceUtils.isActive(domain, DateTime.now(DateTimeZone.UTC))) { try { dnsQueue.addDomainRefreshTask(domainName); getContext().incrementCounter("active domains refreshed"); } catch (Throwable t) { logger.severefmt(t, "Error while refreshing DNS for domain %s", domainName); getContext().incrementCounter("active domains errored"); } } else { getContext().incrementCounter("inactive domains skipped"); } } } }
38.620253
96
0.732219
cbf4d79ffbcc7d893937ae8944bb0f97ac3ae594
239
package org.cynic; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer public class Configuration { }
23.9
74
0.861925
87e80eb3594ae731b8f03abc7bc194630df90a4e
6,869
/*- * << * 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.uav.hook.esclient.transport.interceptors; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import com.creditease.monitor.UAVServer; import com.creditease.monitor.captureframework.spi.CaptureConstants; import com.creditease.monitor.captureframework.spi.CaptureContext; import com.creditease.monitor.captureframework.spi.Monitor; import com.creditease.monitor.proxy.spi.JDKProxyInvokeHandler; import com.creditease.monitor.proxy.spi.JDKProxyInvokeProcessor; import com.creditease.uav.apm.invokechain.spi.InvokeChainConstants; import com.creditease.uav.common.BaseComponent; import com.creditease.uav.hook.esclient.transport.interceptors.TransportIT; import com.creditease.uav.hook.esclient.transport.invokeChain.TransportAdapter; import com.creditease.uav.util.JDKProxyInvokeUtil; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.transport.TransportResponseHandler; public class TransportIT extends BaseComponent{ /** * * ESHandlerProxyInvokeProcessor description: * */ @SuppressWarnings("rawtypes") public class ESHandlerProxyInvokeProcessor extends JDKProxyInvokeProcessor<TransportResponseHandler> { @Override public void preProcess(TransportResponseHandler t, Object proxy, Method method, Object[] args) { } @Override public void catchInvokeException(TransportResponseHandler t, Object proxy, Method method, Object[] args, Throwable e) { doEnd(method, args, -1, e); } @Override public Object postProcess(Object res, TransportResponseHandler t, Object proxy, Method method, Object[] args) { if (method.getName().equals("handleResponse")) { doEnd(method, args, 1, null); } else if (method.getName().equals("handleException")){ doEnd(method, args, -1, (Throwable)args[0]); } return res; } private void doEnd(Method method, Object[] args, int rc, Throwable e) { Map<String, Object> params = new HashMap<String, Object>(); params.put(CaptureConstants.INFO_CLIENT_TARGETSERVER, "elasticsearch"); params.put(CaptureConstants.INFO_CLIENT_RESPONSECODE, rc); params.put(CaptureConstants.INFO_CLIENT_REQUEST_URL, targetURL); params.put(CaptureConstants.INFO_CLIENT_APPID, appid); params.put(CaptureConstants.INFO_CLIENT_TYPE, "elasticsearch.client"); if (e != null) { params.put(CaptureConstants.INFO_CLIENT_RESPONSESTATE, e.toString()); if (logger.isDebugable()) { logger.debug("Elastaicsearch INVOKE Exception: " + targetURL + " action: " + esAction, null); } } else if (logger.isDebugable()) { logger.debug("Elastaicsearch INVOKE End: " + targetURL + " action: " + esAction, null); } UAVServer.instance().runMonitorAsyncCaptureOnServerCapPoint(CaptureConstants.CAPPOINT_APP_CLIENT, Monitor.CapturePhase.DOCAP, params, ccMap); if (ivcContextParams != null) { ivcContextParams.putAll(params); } UAVServer.instance().runSupporter("com.creditease.uav.apm.supporters.InvokeChainSupporter", "runCap", InvokeChainConstants.CHAIN_APP_CLIENT, InvokeChainConstants.CapturePhase.DOCAP, ivcContextParams, TransportAdapter.class, args); } } private Map<String, CaptureContext> ccMap; private String targetURL = ""; private String esAction = ""; private String appid; private Map<String, Object> ivcContextParams = new HashMap<String, Object>(); public TransportIT(String appid) { this.appid = appid; } @SuppressWarnings({ "rawtypes", "unchecked" }) public Object doAsyncStart(Object[] args) { DiscoveryNode node = (DiscoveryNode) args[0]; esAction = (String)args[1]; TransportResponseHandler handler = (TransportResponseHandler)args[4]; String address = node.getHostAddress(); Integer port = node.getAddress().getPort(); targetURL = "elasticsearch://" + address + ":" + port; if (logger.isDebugable()) { logger.debug("Elastaicsearch INVOKE START: " + targetURL + " action: " + esAction, null); } Map<String, Object> params = new HashMap<String, Object>(); params.put(CaptureConstants.INFO_CLIENT_REQUEST_URL, targetURL); params.put(CaptureConstants.INFO_CLIENT_REQUEST_ACTION, esAction); params.put(CaptureConstants.INFO_CLIENT_APPID, appid); params.put(CaptureConstants.INFO_CLIENT_TYPE, "elasticsearch.client"); ccMap = UAVServer.instance().runMonitorAsyncCaptureOnServerCapPoint(CaptureConstants.CAPPOINT_APP_CLIENT, Monitor.CapturePhase.PRECAP, params, null); // register adapter UAVServer.instance().runSupporter("com.creditease.uav.apm.supporters.InvokeChainSupporter", "registerAdapter", TransportAdapter.class); ivcContextParams = (Map<String, Object>) UAVServer.instance().runSupporter( "com.creditease.uav.apm.supporters.InvokeChainSupporter", "runCap", InvokeChainConstants.CHAIN_APP_CLIENT, InvokeChainConstants.CapturePhase.PRECAP, params, TransportAdapter.class, args); if (handler == null) { return null; } handler = JDKProxyInvokeUtil.newProxyInstance(TransportResponseHandler.class.getClassLoader(), new Class<?>[] { TransportResponseHandler.class }, new JDKProxyInvokeHandler<TransportResponseHandler>(handler, new ESHandlerProxyInvokeProcessor())); return handler; } }
39.705202
128
0.646382
a015c3b7c03b5462e4776aba4ca5514ab4941254
343
package io.choerodon.websocket.receive; import org.springframework.web.socket.BinaryMessage; import org.springframework.web.socket.WebSocketSession; /** * * @author [email protected] */ public interface BinaryMessageHandler extends MessageHandler { default void handle(WebSocketSession session, BinaryMessage message){ } }
22.866667
73
0.790087
078b687523553ad452c6f63f0e1a95afa4b7dce4
2,500
package data; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; public class Link { private static File f = new File("./com.lingotechsolutions.data/links.xml"); private static ArrayList<Link> links = new ArrayList<Link>(); private static XStreamer xstream = new XStreamer(); private String url = "empty"; private String account = null; private String pass = null; private String comments = "empty"; public Link(String u, String a, String p, String c) { url = u; account = a; pass = p; comments = c; } public Link(String u, String c) { this(u, null, null, c); } public Link(String u) { this(u, "empty"); } public Link() {} public void setUrl(String u) { url = u; } public void setAccount(String a) { account = a; } public void setPass(String p) { pass = p; } public void setComments(String c) { comments = c; } public String getUrl() { return url; } public String getAccount() { return account; } public String getPass() { return pass; } public String getComments() { return comments; } public static ArrayList<Link> getLinks() { readData(); return links; } public static void initData() { links.clear(); links.add(new Link("NULL")); writeData(); } public static void readData() { try { Boolean complete = false; FileReader reader = new FileReader(f); ObjectInputStream in = xstream.createObjectInputStream(reader); links.clear(); while(complete != true) { Link test = (Link)in.readObject(); if(test != null){ links.add(test); } else { complete = true; } } in.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } public static void writeData() { if(links.isEmpty()) { links.add(new Link()); } try { FileWriter writer = new FileWriter(f); ObjectOutputStream out = xstream.createObjectOutputStream(writer); for(Link l : links) { out.writeObject(l); } out.writeObject(null); out.close(); } catch (IOException e) { e.printStackTrace(); } } public static void removeData(Link link) { readData(); ArrayList<Link> targets = new ArrayList<Link>(); for (Link l : links ) { if (l.getUrl().equals(link.getUrl())) { targets.add(l); } } links.removeAll(targets); writeData(); } public static void addData(Link link) { readData(); removeData(link); links.add(link); writeData(); } }
29.411765
77
0.6736
8178aa3be87b6fe1afdd2af10a31b4fa6ca4fd15
1,700
package org.coeg.routine.backend; import android.app.AlarmManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Build; import android.util.Log; public class AlarmBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.i("Routine", "BROADCAST RECEIVED"); if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { // Reschedule routines to alarm manager // When user reboot their phone startRescheduleAlarmService(context, intent); return; } // Start alarm service startAlarmService(context, intent); } private void startAlarmService(Context context, Intent intent) { Intent intentService = new Intent(context, AlarmService.class); intentService.putExtra("Routine Name", intent.getStringExtra("Routine Name")); intentService.putExtra("Routine ID", intent.getIntExtra("Routine ID", -1)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(intentService); } else { context.startService(intentService); } } private void startRescheduleAlarmService(Context context, Intent intent) { Intent intentService = new Intent(context, RescheduleAlarmService.class); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(intentService); } else { context.startService(intentService); } } }
29.310345
86
0.653529
d73f272a5601c4355256e56f3d023f4491084f17
1,867
package com.lambdaschool.shoppingcart.services; import com.lambdaschool.shoppingcart.ShoppingcartApplication; import com.lambdaschool.shoppingcart.models.Cart; import com.lambdaschool.shoppingcart.models.User; import com.lambdaschool.shoppingcart.models.UserRoles; import org.junit.After; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest(classes = ShoppingcartApplication.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class UserServiceImplTest { @Autowired private UserService userService; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); } @After public void tearDown() throws Exception { } @Test public void aFindAll() { assertEquals(3, userService.findAll().size()); } @Test public void bFindUserById() { assertEquals("test stumps", userService.findUserById(3).getUsername()); } @Test public void cFindByName() { assertEquals("test cinnamon", userService.findByName("test cinnamon").getUsername()); } @Test public void dDelete() { userService.delete(3); assertEquals(2, userService.findAll().size()); } @Test public void eSave() { List<Cart> thisCarts = new ArrayList<>(); List<UserRoles> thisRoles = new ArrayList<>(); User newUser = new User("testjimbov1", "password", "", thisCarts, thisRoles); User savedUser = userService.save(newUser); assertEquals("testjimbov1", savedUser.getUsername()); } }
26.671429
87
0.776647
6455ac80400251bdcbb39ba86053632d8ab8885a
1,445
package de.artfulbird.gardenhero.models.operation; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import de.artfulbird.gardenhero.models.BaseModel; import de.artfulbird.gardenhero.models.measurement.Field; import lombok.*; import org.hibernate.annotations.ColumnDefault; import javax.persistence.*; import java.util.List; @Entity @Getter @Setter @Builder @AllArgsConstructor @RequiredArgsConstructor @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") @Table(name = "OP_PROGRAMS") public class Program extends BaseModel { @Column(nullable = false) private String name; @Column private String type; @Column(nullable = false) private float moistureThresholdLow; @Column(nullable = false) private float moistureThresholdHigh; @Column(nullable = false) private float wateringDurationPerIntervalInSeconds; @Column(nullable = false) private float wateringBreakPerIntervalInSeconds; @Column(nullable = false) private int wateringFrequencyPerIntervalInSeconds; @Column @ColumnDefault(value = "false") private boolean isEnabled; @ManyToOne @JoinColumn(name = "op_center_id", referencedColumnName = "id") private OperationalCenter operationalCenter; @OneToMany(mappedBy = "program",cascade = CascadeType.PERSIST) private List<Field> fields; }
25.803571
90
0.768166
6ec9c7af79b4b21cb26eb31ad6d97d0b09d99e54
7,586
/* * PROJECT: NyARToolkit(Extension) * -------------------------------------------------------------------------------- * The NyARToolkit is Java edition ARToolKit class library. * Copyright (C)2008-2009 Ryo Iizuka * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * For further information please contact. * http://nyatla.jp/nyatoolkit/ * <airmail(at)ebony.plala.or.jp> or <nyatla(at)nyatla.jp> * */ package jp.nyatla.nyartoolkit.core.types.matrix; import jp.nyatla.nyartoolkit.core.types.NyARDoublePoint3d; /** * このクラスは、3x3行列を格納します。 */ public class NyARDoubleMatrix33 implements INyARDoubleMatrix { /** 行列の要素値です。*/ public double m00; /** 行列の要素値です。*/ public double m01; /** 行列の要素値です。*/ public double m02; /** 行列の要素値です。*/ public double m10; /** 行列の要素値です。*/ public double m11; /** 行列の要素値です。*/ public double m12; /** 行列の要素値です。*/ public double m20; /** 行列の要素値です。*/ public double m21; /** 行列の要素値です。*/ public double m22; /** * この関数は、オブジェクトの配列を生成して返します。 * @param i_number * 配列の長さ * @return * 新しいオブジェクト配列 */ public static NyARDoubleMatrix33[] createArray(int i_number) { NyARDoubleMatrix33[] ret=new NyARDoubleMatrix33[i_number]; for(int i=0;i<i_number;i++) { ret[i]=new NyARDoubleMatrix33(); } return ret; } /** * この関数は、要素数9の配列を、行列にセットします。 */ public void setValue(double[] i_value) { this.m00=i_value[0]; this.m01=i_value[1]; this.m02=i_value[2]; this.m10=i_value[3]; this.m11=i_value[4]; this.m12=i_value[5]; this.m20=i_value[6]; this.m21=i_value[7]; this.m22=i_value[8]; return; } /** * この関数は、オブジェクトの内容をインスタンスにコピーします。 * @param i_value * コピー元のオブジェクト */ public void setValue(NyARDoubleMatrix33 i_value) { this.m00=i_value.m00; this.m01=i_value.m01; this.m02=i_value.m02; this.m10=i_value.m10; this.m11=i_value.m11; this.m12=i_value.m12; this.m20=i_value.m20; this.m21=i_value.m21; this.m22=i_value.m22; return; } /** * この関数は、要素数9の配列に、行列の内容をコピーします。 */ public void getValue(double[] o_value) { o_value[0]=this.m00; o_value[1]=this.m01; o_value[2]=this.m02; o_value[3]=this.m10; o_value[4]=this.m11; o_value[5]=this.m12; o_value[6]=this.m20; o_value[7]=this.m21; o_value[8]=this.m22; return; } /** * この関数は、逆行列を計算して、インスタンスにセットします。 * @param i_src * 逆行列を計算するオブジェクト。thisを指定できます。 * @return * 逆行列を得られると、trueを返します。 */ public boolean inverse(NyARDoubleMatrix33 i_src) { final double a11,a12,a13,a21,a22,a23,a31,a32,a33; final double b11,b12,b13,b21,b22,b23,b31,b32,b33; a11=i_src.m00;a12=i_src.m01;a13=i_src.m02; a21=i_src.m10;a22=i_src.m11;a23=i_src.m12; a31=i_src.m20;a32=i_src.m21;a33=i_src.m22; b11=a22*a33-a23*a32; b12=a32*a13-a33*a12; b13=a12*a23-a13*a22; b21=a23*a31-a21*a33; b22=a33*a11-a31*a13; b23=a13*a21-a11*a23; b31=a21*a32-a22*a31; b32=a31*a12-a32*a11; b33=a11*a22-a12*a21; double det_1=a11*b11+a21*b12+a31*b13; if(det_1==0){ return false; } det_1=1/det_1; this.m00=b11*det_1; this.m01=b12*det_1; this.m02=b13*det_1; this.m10=b21*det_1; this.m11=b22*det_1; this.m12=b23*det_1; this.m20=b31*det_1; this.m21=b32*det_1; this.m22=b33*det_1; return true; } /** * この関数は、行列を回転行列として、ZXY系の角度値を計算します。 * @param o_out * 角度値を受け取るオブジェクトです。 * 角度値の範囲は、0-PIです。 */ public final void getZXYAngle(NyARDoublePoint3d o_out) { double sina = this.m21; if (sina >= 1.0) { o_out.x = Math.PI / 2; o_out.y = 0; o_out.z = Math.atan2(-this.m10, this.m00); } else if (sina <= -1.0) { o_out.x = -Math.PI / 2; o_out.y = 0; o_out.z = Math.atan2(-this.m10, this.m00); } else { o_out.x = Math.asin(sina); o_out.z = Math.atan2(-this.m01, this.m11); o_out.y = Math.atan2(-this.m20, this.m22); } } /** * この関数は、行列を回転行列として、ZXY系の角度値をセットします。 * @param i_angle * セットする角度値です。 */ public final void setZXYAngle(NyARDoublePoint3d i_angle) { setZXYAngle(i_angle.x,i_angle.y,i_angle.z); return; } /** * この関数は、行列を回転行列として、ZXY系の角度値をセットします。 * @param i_x * X軸の角度値 * @param i_y * X軸の角度値 * @param i_z * X軸の角度値 */ public final void setZXYAngle(final double i_x, final double i_y, final double i_z) { final double sina = Math.sin(i_x); final double cosa = Math.cos(i_x); final double sinb = Math.sin(i_y); final double cosb = Math.cos(i_y); final double sinc = Math.sin(i_z); final double cosc = Math.cos(i_z); this.m00 = cosc * cosb - sinc * sina * sinb; this.m01 = -sinc * cosa; this.m02 = cosc * sinb + sinc * sina * cosb; this.m10 = sinc * cosb + cosc * sina * sinb; this.m11 = cosc * cosa; this.m12 = sinc * sinb - cosc * sina * cosb; this.m20 = -cosa * sinb; this.m21 = sina; this.m22 = cosb * cosa; return; } /** * この関数は、インスタンスに単位行列をロードします。 */ public void loadIdentity() { this.m00=this.m11=this.m22=1; this.m01=this.m02= this.m10=this.m12= this.m20=this.m21=0; } /** * この関数は、3次元座標を座標変換します。 * @param i_position * 変換する三次元座標 * @param o_out * 変換後の座標を受け取るオブジェクト */ public final void transformVertex(NyARDoublePoint3d i_position,NyARDoublePoint3d o_out) { transformVertex(i_position.x,i_position.y,i_position.z,o_out); return; } /** * この関数は、3次元座標を座標変換します。 * @param i_x * 変換する三次元座標(X) * @param i_y * 変換する三次元座標(Y) * @param i_z * 変換する三次元座標(Z) * @param o_out * 変換後の座標を受け取るオブジェクト */ public final void transformVertex(double i_x,double i_y,double i_z,NyARDoublePoint3d o_out) { o_out.x=this.m00*i_x+this.m01*i_y+this.m02*i_z; o_out.y=this.m10*i_x+this.m11*i_y+this.m12*i_z; o_out.z=this.m20*i_x+this.m21*i_y+this.m22*i_z; return; } /** * この関数は、行列同士の掛け算をして、インスタンスに格納します。 * i_mat_lとi_mat_rには、thisを指定しないでください。 * @param i_mat_l * 左成分の行列 * @param i_mat_r * 右成分の行列 */ public void mul(NyARDoubleMatrix33 i_mat_l,NyARDoubleMatrix33 i_mat_r) { //assert(this!=i_mat_l); //assert(this!=i_mat_r); this.m00=i_mat_l.m00*i_mat_r.m00 + i_mat_l.m01*i_mat_r.m10 + i_mat_l.m02*i_mat_r.m20; this.m01=i_mat_l.m00*i_mat_r.m01 + i_mat_l.m01*i_mat_r.m11 + i_mat_l.m02*i_mat_r.m21; this.m02=i_mat_l.m00*i_mat_r.m02 + i_mat_l.m01*i_mat_r.m12 + i_mat_l.m02*i_mat_r.m22; this.m10=i_mat_l.m10*i_mat_r.m00 + i_mat_l.m11*i_mat_r.m10 + i_mat_l.m12*i_mat_r.m20; this.m11=i_mat_l.m10*i_mat_r.m01 + i_mat_l.m11*i_mat_r.m11 + i_mat_l.m12*i_mat_r.m21; this.m12=i_mat_l.m10*i_mat_r.m02 + i_mat_l.m11*i_mat_r.m12 + i_mat_l.m12*i_mat_r.m22; this.m20=i_mat_l.m20*i_mat_r.m00 + i_mat_l.m21*i_mat_r.m10 + i_mat_l.m22*i_mat_r.m20; this.m21=i_mat_l.m20*i_mat_r.m01 + i_mat_l.m21*i_mat_r.m11 + i_mat_l.m22*i_mat_r.m21; this.m22=i_mat_l.m20*i_mat_r.m02 + i_mat_l.m21*i_mat_r.m12 + i_mat_l.m22*i_mat_r.m22; return; } }
25.979452
93
0.647772
30e903eceaecfff8c66090437339d785e48d9150
3,391
package com.huaweicloud.sdk.live.v1.model; import com.huaweicloud.sdk.core.SdkResponse; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.huaweicloud.sdk.live.v1.model.BandwidthInfo; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import java.util.Objects; /** * Response Object */ public class ShowBandwidthResponse extends SdkResponse { @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value="total") private Integer total; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value="bandwidth_info") private List<BandwidthInfo> bandwidthInfo = null; public ShowBandwidthResponse withTotal(Integer total) { this.total = total; return this; } /** * 查询结果的总元素数量 * @return total */ public Integer getTotal() { return total; } public void setTotal(Integer total) { this.total = total; } public ShowBandwidthResponse withBandwidthInfo(List<BandwidthInfo> bandwidthInfo) { this.bandwidthInfo = bandwidthInfo; return this; } public ShowBandwidthResponse addBandwidthInfoItem(BandwidthInfo bandwidthInfoItem) { if (this.bandwidthInfo == null) { this.bandwidthInfo = new ArrayList<>(); } this.bandwidthInfo.add(bandwidthInfoItem); return this; } public ShowBandwidthResponse withBandwidthInfo(Consumer<List<BandwidthInfo>> bandwidthInfoSetter) { if(this.bandwidthInfo == null ){ this.bandwidthInfo = new ArrayList<>(); } bandwidthInfoSetter.accept(this.bandwidthInfo); return this; } /** * 带宽信息 * @return bandwidthInfo */ public List<BandwidthInfo> getBandwidthInfo() { return bandwidthInfo; } public void setBandwidthInfo(List<BandwidthInfo> bandwidthInfo) { this.bandwidthInfo = bandwidthInfo; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ShowBandwidthResponse showBandwidthResponse = (ShowBandwidthResponse) o; return Objects.equals(this.total, showBandwidthResponse.total) && Objects.equals(this.bandwidthInfo, showBandwidthResponse.bandwidthInfo); } @Override public int hashCode() { return Objects.hash(total, bandwidthInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ShowBandwidthResponse {\n"); sb.append(" total: ").append(toIndentedString(total)).append("\n"); sb.append(" bandwidthInfo: ").append(toIndentedString(bandwidthInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
26.492188
103
0.645532
145c8d279697d40db591f6ef51dd87af4b7011a5
328
package com.neu.onlinebanking.dao; import java.util.List; import com.neu.onlinebanking.pojo.InternalRecipient; public interface InternalRecipientDao { List<InternalRecipient> findall(); InternalRecipient findByName(String theName); void deleteByName(String theName); void save(InternalRecipient recipient); }
17.263158
52
0.789634
b933f7f09d0c7086743500cb7e6bee9b32ac2049
4,336
/* * Copyright (c) 2015 Evident Solutions Oy * * 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.dalesbred.query; import org.dalesbred.annotation.SQL; import org.junit.Test; import java.util.List; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class NamedParameterSqlParserTest { @Test public void simpleQuery() { assertNamedParameters("SELECT * FROM foo WHERE col = :col", "SELECT * FROM foo WHERE col = ?", singletonList("col")); } @Test public void queryLiteralLikeNamedParameter() { assertNamedParameters("SELECT * FROM foobaz f WHERE f.id = :id AND f.col = ':notanamedparameter'", "SELECT * FROM foobaz f WHERE f.id = ? AND f.col = ':notanamedparameter'", singletonList("id")); } @Test public void queryWithLineCommentWithoutLineEnd() { assertNamedParameters("SELECT *, f.col::TEXT FROM foobar f WHERE f.id = :id -- comment :notnamedparameter", "SELECT *, f.col::TEXT FROM foobar f WHERE f.id = ? -- comment :notnamedparameter", singletonList("id")); } @Test public void queryWithLineComment() { assertNamedParameters("SELECT *, f.col::TEXT FROM foobar f -- comment :notnamedparameter \n WHERE f.id = :id", "SELECT *, f.col::TEXT FROM foobar f -- comment :notnamedparameter \n WHERE f.id = ?", singletonList("id")); } @Test public void queryWithBlockComment() { assertNamedParameters("SELECT *, f.col::TEXT /* comment :notanamedparameter */ FROM foobar f WHERE f.id = :id", "SELECT *, f.col::TEXT /* comment :notanamedparameter */ FROM foobar f WHERE f.id = ?", singletonList("id")); } @Test public void queryWithPostgresqlCast() { assertNamedParameters("SELECT *, f.col::TEXT FROM foobar f WHERE f.id = :id", "SELECT *, f.col::TEXT FROM foobar f WHERE f.id = ?", singletonList("id")); } @Test public void complexQuery() { assertNamedParameters("SELECT *, 1::TEXT FROM foobar f WHERE f.id = :id AND /* comment :notparameter */ f.qwerty = :bar*/snafu*/ AND f.literal = 'laalaa :pai puppa' AND f.test =:test /*what*/ /* */ -- ef ", "SELECT *, 1::TEXT FROM foobar f WHERE f.id = ? AND /* comment :notparameter */ f.qwerty = ?*/snafu*/ AND f.literal = 'laalaa :pai puppa' AND f.test =? /*what*/ /* */ -- ef ", asList("id", "bar", "test")); } @Test public void quotedStrings() { assertNamedParameters("select 'foo '' :bar'", "select 'foo '' :bar'", emptyList()); } @Test public void doubleQuotes() { assertNamedParameters("select \" :bar \"", "select \" :bar \"", emptyList()); } private static void assertNamedParameters(@SQL String sql, @SQL String expected, List<String> parameters) { NamedParameterSql result = NamedParameterSqlParser.parseSqlStatement(sql); assertThat(result.getSql(), is(expected)); assertThat(result.getParameterNames(), is(parameters)); } }
42.097087
218
0.656135
1b072a0de0c8a3ae0e973938e3b550a39df45bf4
3,768
package com.symphony.bdk.http.api; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.symphony.bdk.http.api.util.ApiUtils; import com.symphony.bdk.http.api.util.TypeReference; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @ExtendWith(MockitoExtension.class) class HttpClientTest { @Mock private ApiClient apiClient; @Captor private ArgumentCaptor<List<Pair>> queryParams; @Captor private ArgumentCaptor<Map<String, String>> headerParams; @Captor private ArgumentCaptor<Map<String, String>> cookieParams; @Captor private ArgumentCaptor<Map<String, Object>> formParams; @Test public void usageWithFormParams() throws ApiException { final HttpClient httpClient = HttpClient.builder(this::mockedApiClientBuilder) .basePath("https://localhost:8080") .header("Connection", "Keep-Alive") .header("Keep-Alive", "timeout=5, max=1000") .cookie("foo", "bar") .build(); httpClient.path("/api/v1/users") .header("Authorization", "Bearer AbCdEf123456") .queryParam("test1", "test2") .formParam("test3", "test4") .formParam("test3", "test5") .get(new TypeReference<String>() {}); verify(apiClient).invokeAPI(eq("/api/v1/users"), eq("GET"), queryParams.capture(), isNull(), headerParams.capture(), cookieParams.capture(), formParams.capture(), isNull(), eq("application/json"), any(), any()); assertEquals(Collections.singletonList(new Pair("test1", "test2")), queryParams.getValue()); assertEquals(new HashMap<String, String>() {{ put("Connection", "Keep-Alive"); put("Keep-Alive", "timeout=5, max=1000"); put("Authorization", "Bearer AbCdEf123456"); }}, headerParams.getValue()); assertEquals(Collections.singletonMap("foo", "bar"), cookieParams.getValue()); assertEquals(Collections.singletonMap("test3", Arrays.asList("test4", "test5")), formParams.getValue()); } @Test public void usageWithoutFormParams() throws ApiException { final HttpClient httpClient = HttpClient.builder(this::mockedApiClientBuilder) .basePath("https://localhost:8080") .build(); httpClient.path("/api/v1/users") .get(new TypeReference<String>() {}); verify(apiClient).invokeAPI(eq("/api/v1/users"), eq("GET"), queryParams.capture(), isNull(), headerParams.capture(), cookieParams.capture(), formParams.capture(), isNull(), eq("application/json"), any(), any()); assertNull(queryParams.getValue()); assertEquals(Collections.emptyMap(), headerParams.getValue()); assertEquals(Collections.emptyMap(), cookieParams.getValue()); assertEquals(Collections.emptyMap(), formParams.getValue()); } @Test public void userAgent() { assertTrue(ApiUtils.getUserAgent().matches("^Symphony-BDK-Java/\\S+ Java/\\S+")); } private ApiClientBuilder mockedApiClientBuilder() { final ApiClientBuilder apiClientBuilder = mock(ApiClientBuilder.class); when(apiClientBuilder.build()).thenReturn(apiClient); return apiClientBuilder; } }
34.568807
118
0.718418
df7483da680fc0d221abaa338d1832c289e10464
322
package eu.fivegmedia.aaa.service.catalogue.dto; import java.io.Serializable; public class CatalogueUserResourceDTO implements Serializable{ private static final long serialVersionUID = 1L; public String catalog_user; public String catalog_tenant; public String resource_id; public String resource_properties; }
23
62
0.826087
ad75317f256ba3a1c526a017f2a8ce984470b3e5
4,893
/* * This file is generated by jOOQ. */ package com.yg.gqlwfdl.dataaccess.db.tables.records; import com.yg.gqlwfdl.dataaccess.db.tables.DiscountRate; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.Record1; import org.jooq.Record3; import org.jooq.Row3; import org.jooq.impl.UpdatableRecordImpl; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.11.2" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class DiscountRateRecord extends UpdatableRecordImpl<DiscountRateRecord> implements Record3<Long, String, Double> { private static final long serialVersionUID = -998790737; /** * Setter for <code>public.discount_rate.id</code>. */ public void setId(Long value) { set(0, value); } /** * Getter for <code>public.discount_rate.id</code>. */ public Long getId() { return (Long) get(0); } /** * Setter for <code>public.discount_rate.description</code>. */ public void setDescription(String value) { set(1, value); } /** * Getter for <code>public.discount_rate.description</code>. */ public String getDescription() { return (String) get(1); } /** * Setter for <code>public.discount_rate.value</code>. */ public void setValue(Double value) { set(2, value); } /** * Getter for <code>public.discount_rate.value</code>. */ public Double getValue() { return (Double) get(2); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Record1<Long> key() { return (Record1) super.key(); } // ------------------------------------------------------------------------- // Record3 type implementation // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Row3<Long, String, Double> fieldsRow() { return (Row3) super.fieldsRow(); } /** * {@inheritDoc} */ @Override public Row3<Long, String, Double> valuesRow() { return (Row3) super.valuesRow(); } /** * {@inheritDoc} */ @Override public Field<Long> field1() { return DiscountRate.DISCOUNT_RATE.ID; } /** * {@inheritDoc} */ @Override public Field<String> field2() { return DiscountRate.DISCOUNT_RATE.DESCRIPTION; } /** * {@inheritDoc} */ @Override public Field<Double> field3() { return DiscountRate.DISCOUNT_RATE.VALUE; } /** * {@inheritDoc} */ @Override public Long component1() { return getId(); } /** * {@inheritDoc} */ @Override public String component2() { return getDescription(); } /** * {@inheritDoc} */ @Override public Double component3() { return getValue(); } /** * {@inheritDoc} */ @Override public Long value1() { return getId(); } /** * {@inheritDoc} */ @Override public String value2() { return getDescription(); } /** * {@inheritDoc} */ @Override public Double value3() { return getValue(); } /** * {@inheritDoc} */ @Override public DiscountRateRecord value1(Long value) { setId(value); return this; } /** * {@inheritDoc} */ @Override public DiscountRateRecord value2(String value) { setDescription(value); return this; } /** * {@inheritDoc} */ @Override public DiscountRateRecord value3(Double value) { setValue(value); return this; } /** * {@inheritDoc} */ @Override public DiscountRateRecord values(Long value1, String value2, Double value3) { value1(value1); value2(value2); value3(value3); return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached DiscountRateRecord */ public DiscountRateRecord() { super(DiscountRate.DISCOUNT_RATE); } /** * Create a detached, initialised DiscountRateRecord */ public DiscountRateRecord(Long id, String description, Double value) { super(DiscountRate.DISCOUNT_RATE); set(0, id); set(1, description); set(2, value); } }
20.472803
122
0.503781
c26264276c5d6f6c9d33744d41cb75c1869ebf1a
4,604
package com.usthe.tom.service.impl; import com.usthe.sureness.matcher.TreePathRoleMatcher; import com.usthe.tom.dao.AuthResourceDao; import com.usthe.tom.dao.AuthRoleDao; import com.usthe.tom.dao.AuthRoleResourceBindDao; import com.usthe.tom.pojo.entity.AuthResource; import com.usthe.tom.pojo.entity.AuthRole; import com.usthe.tom.pojo.entity.AuthRoleResourceBind; import com.usthe.tom.service.RoleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Example; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Optional; /** * @author tomsun28 * @date 13:10 2019-08-04 */ @Service @Transactional(rollbackFor = Exception.class) public class RoleServiceImpl implements RoleService { @Autowired private AuthRoleDao authRoleDao; @Autowired private AuthResourceDao authResourceDao; @Autowired private AuthRoleResourceBindDao roleResourceBindDao; @Autowired private TreePathRoleMatcher treePathRoleMatcher; @Autowired private StringRedisTemplate redisTemplate; @Override public boolean isRoleExist(AuthRole authRole) { AuthRole role = AuthRole.builder() .name(authRole.getName()).code(authRole.getCode()).build(); return authRoleDao.exists(Example.of(role)); } @Override @Cacheable(value = "role", key = "#authRole.id", unless = "#result eq null") public boolean addRole(AuthRole authRole) { if (isRoleExist(authRole)) { return false; } else { authRoleDao.saveAndFlush(authRole); return true; } } @Override public boolean updateRole(AuthRole authRole) { if (authRoleDao.existsById(authRole.getId())) { authRoleDao.saveAndFlush(authRole); return true; } else { return false; } } @Override public boolean deleteRole(Long roleId) { if (authRoleDao.existsById(roleId)) { authRoleDao.deleteById(roleId); return true; } else { return false; } } @Override public Optional<List<AuthRole>> getAllRole() { List<AuthRole> roleList = authRoleDao.findAll(); return Optional.of(roleList); } @Override public Page<AuthRole> getPageRole(Integer currentPage, Integer pageSize) { PageRequest pageRequest = PageRequest.of(currentPage, pageSize); return authRoleDao.findAll(pageRequest); } @Override public Page<AuthResource> getPageResourceOwnRole(Long roleId, Integer currentPage, Integer pageSize) { PageRequest pageRequest = PageRequest.of(currentPage, pageSize, Sort.Direction.ASC, "id"); return authResourceDao.findRoleOwnResource(roleId, pageRequest); } @Override public Page<AuthResource> getPageResourceNotOwnRole(Long roleId, Integer currentPage, Integer pageSize) { PageRequest pageRequest = PageRequest.of(currentPage, pageSize, Sort.Direction.ASC, "id"); return authResourceDao.findRoleNotOwnResource(roleId, pageRequest); } @Override public void authorityRoleResource(Long roleId, Long resourceId) { // Determine whether this resource and role exist if (!authRoleDao.existsById(roleId) || !authResourceDao.existsById(resourceId)) { throw new DataConflictException("roleId or resourceId not exist"); } // insert it in database, if existed the unique index will work AuthRoleResourceBind bind = AuthRoleResourceBind .builder().roleId(roleId).resourceId(resourceId).build(); roleResourceBindDao.saveAndFlush(bind); // refresh resource path data tree treePathRoleMatcher.rebuildTree(); redisTemplate.delete("tom-enable-resource"); redisTemplate.delete("tom-disable-resource"); } @Override public void deleteAuthorityRoleResource(Long roleId, Long resourceId) { roleResourceBindDao.deleteRoleResourceBind(roleId, resourceId); // refresh resource path data tree treePathRoleMatcher.rebuildTree(); redisTemplate.delete("tom-enable-resource"); redisTemplate.delete("tom-disable-resource"); } }
34.358209
109
0.706342
0ee3f7f7b26ce0c28fad0a472a59d1fee0567844
329
/* * @test /nodynamiccopyright/ * @bug 6843077 * @summary test incomplete vararg declaration * @author Mahmood Ali * @compile/fail/ref=IncompleteVararg.out -XDrawDiagnostics -source 1.8 IncompleteVararg.java */ class IncompleteArray { // the last variable may be vararg void method(int @A test) { } } @interface A { }
23.5
93
0.720365
e14d6deffc082d424c6184bfa2175305c830f2df
1,422
package com.wondernect.elements.easyoffice.excel.handler; /** * Copyright (C), 2020, wondernect.com * FileName: ESExcelItemHandler * Author: chenxun * Date: 2020-07-22 00:37 * Description: excel数据处理类 * 1、需要展示的属性名需要继承该接口进行展示配置 * 2、需要处理展示数据的属性名才需要继承该接口进行数据转换 */ public abstract class ESExcelItemHandler<T> { /** * excel列属性名 * @return excel列属性名 */ private String itemName; /** * excel列展示名称 * @return excel列展示名称 */ private String itemTitle; /** * excel列展示顺序 * @return 序号 */ private int itemOrder; /** * 构造方法 * @param itemName 导入导出属性名 * @param itemTitle 导入导出标题 * @param itemOrder 导入导出排序 */ public ESExcelItemHandler(String itemName, String itemTitle, int itemOrder) { this.itemName = itemName; this.itemTitle = itemTitle; this.itemOrder = itemOrder; } public String getItemName() { return itemName; } public String getItemTitle() { return itemTitle; } public int getItemOrder() { return itemOrder; } /** * 导出处理对应属性值,返回展示的值 * @param object 属性原始值 * @return 处理后excel展示的值 */ public abstract Object handleExcelExportItemObject(T object); /** * 导入处理对应属性值,返回对应对象属性类型值 * @param object 属性原始值 * @return 处理后导入数据库对象的属性值 */ public abstract T handleExcelImportItemObject(Object object); }
20.314286
81
0.624473
4022fa68440c819ce77062fcca256dca26cf3348
1,110
package com.dankideacentral.dic.activities; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import com.dankideacentral.dic.R; import com.dankideacentral.dic.fragments.OAuthWebViewFragment; public class OAuthActivity extends FragmentActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String authenticationUrl = getIntent().getStringExtra( getString(R.string.string_extra_authentication_url)); Bundle args = new Bundle(); args.putString(getString(R.string.string_extra_authentication_url), authenticationUrl); FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); Fragment oAuthWebViewFragment = Fragment.instantiate( getApplicationContext(), OAuthWebViewFragment.class.getName(), args); fragmentTransaction.add(android.R.id.content, oAuthWebViewFragment); fragmentTransaction.commit(); } }
41.111111
97
0.761261
f7164884ffaf3319b9ed275765ee04ebb472cbb8
2,916
package timeline.lizimumu.com.util; import android.os.Environment; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import timeline.lizimumu.com.AppConst; public class CrashHandler implements Thread.UncaughtExceptionHandler { private static CrashHandler INSTANCE = new CrashHandler(); private Thread.UncaughtExceptionHandler mDefaultHandler; private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.getDefault()); private CrashHandler() { } public static CrashHandler getInstance() { return INSTANCE; } public void init() { mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(this); } public void uncaughtException(Thread thread, Throwable ex) { if (!handleException(ex) && mDefaultHandler != null) { mDefaultHandler.uncaughtException(thread, ex); } else { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } android.os.Process.killProcess(android.os.Process.myPid()); System.exit(1); } } private boolean handleException(Throwable ex) { if (ex == null) return false; saveCrashInfo2File(ex); return true; } private void saveCrashInfo2File(Throwable ex) { StringBuffer sb = new StringBuffer(); Writer writer = new StringWriter(); PrintWriter pw = new PrintWriter(writer); ex.printStackTrace(pw); Throwable cause = ex.getCause(); while (cause != null) { cause.printStackTrace(pw); cause = cause.getCause(); } pw.close(); String result = writer.toString(); sb.append(result); long timestamp = System.currentTimeMillis(); String time = format.format(new Date()); String fileName = "crash-" + time + "-" + timestamp + ".log"; if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { try { File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + AppConst.LOG_DIR); boolean ok = true; if (!dir.exists()) { ok = dir.mkdirs(); } if (ok) { FileOutputStream fos = new FileOutputStream(new File(dir, fileName)); fos.write(sb.toString().getBytes()); fos.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
32.4
133
0.600137
475a89f5d4d363cd23fb14d9bc400db59325678d
7,170
package com.tonight.manage.organization.managingmoneyapp; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.tonight.manage.organization.managingmoneyapp.Custom.CustomProfilePopup; import com.tonight.manage.organization.managingmoneyapp.Object.MemberListItem; import com.tonight.manage.organization.managingmoneyapp.Server.GroupMemberJSONParser; import com.tonight.manage.organization.managingmoneyapp.Server.NetworkDefineConstant; import java.io.UnsupportedEncodingException; import java.net.UnknownHostException; import java.util.ArrayList; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; /** * Created by hooo5 on 2016-11-07. */ public class MemberListActivity extends AppCompatActivity { private RecyclerView mMemeberListRecyclerView; private MemberAdapter mMemberAdapter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.member_main); Intent i = getIntent(); if(i==null) { Toast.makeText(this, "오류가 발생했습니다. 다시 실행해 주세요", Toast.LENGTH_SHORT).show(); return; } String groupcode = i.getStringExtra("groupcode"); String groupName = i.getStringExtra("groupName"); TextView groupNameText = (TextView) findViewById(R.id.groupNameText); groupNameText.setText(groupName); Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); setSupportActionBar(toolbar); mMemeberListRecyclerView = (RecyclerView) findViewById(R.id.memberListRecyclerView); mMemeberListRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mMemeberListRecyclerView.setHasFixedSize(true); mMemberAdapter = new MemberAdapter(this); mMemeberListRecyclerView.setAdapter(mMemberAdapter); new LoadMemberListAsyncTask().execute(groupcode); } @Override public void onBackPressed() { super.onBackPressed(); } class MemberAdapter extends RecyclerView.Adapter<MemberListActivity.MemberAdapter.ViewHolder> { private LayoutInflater mLayoutInflater; private ArrayList<MemberListItem> memberDatas; private Context mContext; public MemberAdapter(Context context) { mContext = context; mLayoutInflater = LayoutInflater.from(context); memberDatas = new ArrayList<>(); } public void addAllItem(ArrayList<MemberListItem> datas) { this.memberDatas = datas; } @Override public MemberListActivity.MemberAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new MemberListActivity.MemberAdapter.ViewHolder(mLayoutInflater.inflate(R.layout.member_list_item, parent, false)); } @Override public void onBindViewHolder(final MemberListActivity.MemberAdapter.ViewHolder holder, final int position) { //test holder.personName.setText(memberDatas.get(position).getUsername()); holder.view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CustomProfilePopup customProfilePopup = CustomProfilePopup.newInstance(memberDatas.get(position)); customProfilePopup.show(getSupportFragmentManager(), "profile"); } }); Glide.with(getApplicationContext()) .load(memberDatas.get(position).getProfileimg()) .override(150, 150) .into(holder.profileImageView); } @Override public int getItemCount() { return memberDatas.size(); } public class ViewHolder extends RecyclerView.ViewHolder { View view; TextView personName; RecyclerView recyclerView; ImageView profileImageView; public ViewHolder(View v) { super(v); view = v; personName = (TextView) v.findViewById(R.id.memberListPersonName); recyclerView = (RecyclerView) v.findViewById(R.id.memberListRecyclerView); profileImageView = (ImageView) v.findViewById(R.id.memberListProfileImageView); } } } public class LoadMemberListAsyncTask extends AsyncTask<String, Integer, ArrayList<MemberListItem>> { @Override protected ArrayList<MemberListItem> doInBackground(String... args) { String requestURL = ""; Response response = null; try { requestURL = NetworkDefineConstant.SERVER_URL_EVENT_LIST; OkHttpClient toServer = NetworkDefineConstant.getOkHttpClient(); FormBody.Builder builder = new FormBody.Builder(); builder.add("signal", "2") .add("groupcode", args[0]); FormBody formBody = builder.build(); Request request = new Request.Builder() .url(requestURL) .post(formBody) .build(); response = toServer.newCall(request).execute(); ResponseBody responseBody = response.body(); boolean flag = response.isSuccessful(); int responseCode = response.code(); if (responseCode >= 400) return null; if (flag) { if(responseBody != null) { Glide.get(getApplicationContext()).clearDiskCache(); return GroupMemberJSONParser.parseMemberListItems((responseBody.string())); } } } catch (UnknownHostException une) { Log.e("connectionFail", une.toString()); } catch (UnsupportedEncodingException uee) { Log.e("connectionFail", uee.toString()); } catch (Exception e) { Log.e("connectionFail", e.toString()); } finally { if (response != null) { response.close(); } } return null; } @Override protected void onPostExecute(ArrayList<MemberListItem> result) { if (result != null && result.size() > 0) { mMemberAdapter.addAllItem(result); mMemberAdapter.notifyDataSetChanged(); } } } }
35.85
134
0.637238
a43a6ebddbc66689d60aef375c9299de01221d2b
9,970
// Copyright (c) 2002 Graz University of Technology. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. The end-user documentation included with the redistribution, if any, must // include the following acknowledgment: // // "This product includes software developed by IAIK of Graz University of // Technology." // // Alternately, this acknowledgment may appear in the software itself, if and // wherever such third-party acknowledgments normally appear. // // 4. The names "Graz University of Technology" and "IAIK of Graz University of // Technology" must not be used to endorse or promote products derived from this // software without prior written permission. // // 5. Products derived from this software may not be called "IAIK PKCS Wrapper", // nor may "IAIK" appear in their name, without prior written permission of // Graz University of Technology. // // THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE LICENSOR BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, // OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. package iaik.pkcs.pkcs11.objects; import iaik.pkcs.pkcs11.Session; import iaik.pkcs.pkcs11.TokenException; import iaik.pkcs.pkcs11.wrapper.Constants; /** * Objects of this class represent PKCS#11 objects of type storage as defined in PKCSC#11 2.11, but * is compatible to version 2.01. * * @author Karl Scheibelhofer * @version 1.0 * @invariants (token_ <> null) and (private_ <> null) and (modifiable_ <> null) and (label_ <> * null) */ public class Storage extends Object { /** * True, if object is a token object (not a session object). */ protected BooleanAttribute token_; /** * True, if this is a private object. */ protected BooleanAttribute private_; /** * True, if this object is modifiable. */ protected BooleanAttribute modifiable_; /** * The label of this object. */ protected CharArrayAttribute label_; /** * The default constructor. An application use this constructor to instanciate an object that * serves as a template. It may also be useful for working with vendor-defined objects. * */ public Storage() { super(); } /** * Constructor taking the reference to the PKCS#11 module for accessing the object's attributes, * the session handle to use for reading the attribute values and the object handle. This * constructor read all attributes that a storage object must contain. * * @param session * The session to use for reading attributes. This session must have the appropriate * rights; i.e. it must be a user-session, if it is a private object. * @param objectHandle * The object handle as given from the PKCS#111 module. * @exception TokenException * If getting the attributes failed. * @preconditions (session <> null) * */ protected Storage(Session session, long objectHandle) throws TokenException { super(session, objectHandle); } /** * Put all attributes of the given object into the attributes table of this object. This method is * only static to be able to access invoke the implementation of this method for each class * separately (see use in clone()). * * @param object * The object to handle. * @preconditions (object <> null) * */ protected static void putAttributesInTable(Storage object) { if (object == null) { throw new NullPointerException("Argument \"object\" must not be null."); } object.attributeTable_.put(Attribute.TOKEN, object.token_); object.attributeTable_.put(Attribute.PRIVATE, object.private_); object.attributeTable_.put(Attribute.MODIFIABLE, object.modifiable_); object.attributeTable_.put(Attribute.LABEL, object.label_); } /** * Allocates the attribute objects for this class and adds them to the attribute table. * */ protected void allocateAttributes() { super.allocateAttributes(); token_ = new BooleanAttribute(Attribute.TOKEN); private_ = new BooleanAttribute(Attribute.PRIVATE); modifiable_ = new BooleanAttribute(Attribute.MODIFIABLE); label_ = new CharArrayAttribute(Attribute.LABEL); putAttributesInTable(this); } /** * Create a (deep) clone of this object. * * @return A clone of this object. * * @postconditions (result <> null) and (result instanceof Storage) and (result.equals(this)) */ public java.lang.Object clone() { Storage clone = (Storage) super.clone(); clone.token_ = (BooleanAttribute) this.token_.clone(); clone.private_ = (BooleanAttribute) this.private_.clone(); clone.modifiable_ = (BooleanAttribute) this.modifiable_.clone(); clone.label_ = (CharArrayAttribute) this.label_.clone(); putAttributesInTable(clone); // put all cloned attributes into the new table return clone; } /** * Compares all member variables of this object with the other object. Returns only true, if all * are equal in both objects. * * @param otherObject * The other object to compare to. * @return True, if other is an instance of this class and all member variables of both objects * are equal. False, otherwise. */ public boolean equals(java.lang.Object otherObject) { boolean equal = false; if (otherObject instanceof Storage) { Storage other = (Storage) otherObject; equal = (this == other) || (super.equals(other) && this.token_.equals(other.token_) && this.private_.equals(other.private_) && this.modifiable_.equals(other.modifiable_) && this.label_ .equals(other.label_)); } return equal; } /** * Check, if this is a token object. * * @return Its value is true, if this is an token object. * * @postconditions (result <> null) */ public BooleanAttribute getToken() { return token_; } /** * Check, if this is a private object. * * @return Its value is true, if this is a private object. * * @postconditions (result <> null) */ public BooleanAttribute getPrivate() { return private_; } /** * Check, if this is a modifiable object. * * @return Its value is true, if this is a modifiable object. * * @postconditions (result <> null) */ public BooleanAttribute getModifiable() { return modifiable_; } /** * Get the label attribute of this object. * * @return Contains the label as a char array. * * @postconditions (result <> null) */ public CharArrayAttribute getLabel() { return label_; } /** * Read the values of the attributes of this object from the token. * * @param session * The session handle to use for reading attributes. This session must have the * appropriate rights; i.e. it must be a user-session, if it is a private object. * @exception TokenException * If getting the attributes failed. * @preconditions (session <> null) * */ public void readAttributes(Session session) throws TokenException { super.readAttributes(session); // Object.getAttributeValue(session, objectHandle_, token_); // Object.getAttributeValue(session, objectHandle_, private_); // Object.getAttributeValue(session, objectHandle_, modifiable_); // Object.getAttributeValue(session, objectHandle_, label_); Object.getAttributeValues(session, objectHandle_, new Attribute[] { token_, private_, modifiable_, label_ }); } /** * This method returns a string representation of the current object. The output is only for * debugging purposes and should not be used for other purposes. * * @return A string presentation of this object for debugging output. * * @postconditions (result <> null) */ public String toString() { StringBuffer buffer = new StringBuffer(128); buffer.append(super.toString()); buffer.append(Constants.NEWLINE); buffer.append(Constants.INDENT); buffer.append("Token: "); buffer.append(token_.toString()); buffer.append(Constants.NEWLINE); buffer.append(Constants.INDENT); buffer.append("Private: "); buffer.append(private_.toString()); buffer.append(Constants.NEWLINE); buffer.append(Constants.INDENT); buffer.append("Modifiable: "); buffer.append(modifiable_.toString()); buffer.append(Constants.NEWLINE); buffer.append(Constants.INDENT); buffer.append("Label: "); buffer.append(label_.toString()); return buffer.toString(); } /** * The overriding of this method should ensure that the objects of this class work correctly in a * hashtable. * * @return The hash code of this object. */ public int hashCode() { return token_.hashCode() ^ private_.hashCode() ^ modifiable_.hashCode() ^ label_.hashCode(); } }
33.013245
100
0.687663
cd4b480076d9c2c55f0d7191ca089997f3fc5027
3,589
package io.digisic.bank.util; import io.digisic.bank.model.TransactionType; public class Patterns { // Common public static final String DATE_FORMAT = "MM/dd/yyyy"; public static final String TRANSACTION_AMOUNT = "^(?=.+)(?:[1-9]\\d*|0)?(?:\\.\\d+)?$"; // User public static final String USER_PASSWORD = "(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"; public static final String USER_ROLE = "USER|ADMIN|API"; // User Profile public static final String USER_TITLE = "Mr.|Mrs.|Ms."; public static final String USER_GENDER = "M|F"; public static final String USER_SSN = "^\\d{3}-?\\d{2}-?\\d{4}$"; public static final String USER_DOB = "\\d{1,2}/\\d{1,2}/\\d{4}"; public static final String USER_EMAIL = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"; public static final String USER_PHONE_REQ = "^[+]?([0-9]*[\\.\\s\\-\\(\\)]|[0-9]+){3,24}$"; public static final String USER_PHONE_NOT_REQ = "^$|^[+]?([0-9]*[\\.\\s\\-\\(\\)]|[0-9]+){3,24}$"; // ATM Search public static final String US_ZIPCODE = "^[0-9]{5}(?:-[0-9]{4})?$"; // Role public static final String ROLE_USER = "USER"; public static final String ROLE_ADMIN = "ADMIN"; public static final String ROLE_API = "API"; // Account public static final String ACCT_OWN_TYPE_CODE = Constants.ACCT_OWN_IND_CODE + "|" + Constants.ACCT_OWN_JNT_CODE; public static final String ACCT_TYPE_CODE = Constants.ACCT_CHK_STD_CODE + "|" + Constants.ACCT_CHK_INT_CODE + "|" + Constants.ACCT_SAV_STD_CODE + "|" + Constants.ACCT_SAV_MMA_CODE; public static final String ACCT_TRAN_TYPE_CODE = Constants.ACCT_TRAN_TYPE_ATM_CODE + "|" + Constants.ACCT_TRAN_TYPE_CHARGE_CODE + "|" + Constants.ACCT_TRAN_TYPE_CHECK_CODE + "|" + Constants.ACCT_TRAN_TYPE_CHECK_FEE_CODE + "|" + Constants.ACCT_TRAN_TYPE_DEBIT_CODE + "|" + Constants.ACCT_TRAN_TYPE_DEPOSIT_CODE + "|" + Constants.ACCT_TRAN_TYPE_DIRECT_DEP_CODE + "|" + Constants.ACCT_TRAN_TYPE_DIV_CREDIT_CODE + "|" + Constants.ACCT_TRAN_TYPE_EFT_CODE + "|" + Constants.ACCT_TRAN_TYPE_FEE_CODE + "|" + Constants.ACCT_TRAN_TYPE_INT_INCOME_CODE + "|" + Constants.ACCT_TRAN_TYPE_LATE_FEE_CODE + "|" + Constants.ACCT_TRAN_TYPE_OVERDRAFT_CODE + "|" + Constants.ACCT_TRAN_TYPE_OVERDRAFT_FEE_CODE + "|" + Constants.ACCT_TRAN_TYPE_PAYMENT_CODE + "|" + Constants.ACCT_TRAN_TYPE_POS_CODE + "|" + Constants.ACCT_TRAN_TYPE_REFUND_CODE + "|" + Constants.ACCT_TRAN_TYPE_WITHDRAWL_CODE + "|" + Constants.ACCT_TRAN_TYPE_XFER_CODE + "|" + Constants.ACCT_TRAN_TYPE_XFER_FEE_CODE; public static final String ACCT_TRAN_ACTION = TransactionType.CAT_CREDIT + "|" + TransactionType.CAT_DEBIT; // Promotions public static final String PROMO_ACCT_TYPE = Constants.PROMO_ACCT_TYPE_BLUE + "|" + Constants.PROMO_ACCT_TYPE_GOLD + "|" + Constants.PROMO_ACCT_TYPE_PLATINUM; // Visa Service public static final String VISA_ACCOUNT = "^([a-zA-Z0-9_\\\\-\\\\.]+)"; // Credit Application Service public static final String CREDIT_APP_EMP_STATUS = "Employed|Self-Employed|Retired|Student|Unemployed"; public static final String CREDIT_APP_BANK_ACCTS = "Checking and Savings|Checking Only|Savings Only|Neither"; }
45.43038
172
0.623015