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 |
|---|---|---|---|---|---|
29469ff70192173ed1ea09d494f8fd30c6782dbd | 2,793 | package life.catalogue.es.nu.suggest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.client.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import life.catalogue.api.search.NameUsageSuggestRequest;
import life.catalogue.api.search.NameUsageSuggestResponse;
import life.catalogue.api.search.NameUsageSuggestion;
import life.catalogue.es.EsException;
import life.catalogue.es.EsNameUsage;
import life.catalogue.es.EsUtil;
import life.catalogue.es.NameUsageSuggestionService;
import life.catalogue.es.ddl.Analyzer;
import life.catalogue.es.nu.NameUsageQueryService;
import life.catalogue.es.query.EsSearchRequest;
import life.catalogue.es.response.EsResponse;
public class NameUsageSuggestionServiceEs extends NameUsageQueryService implements NameUsageSuggestionService {
@SuppressWarnings("unused")
private static final Logger LOG = LoggerFactory.getLogger(NameUsageSuggestionServiceEs.class);
public NameUsageSuggestionServiceEs(String indexName, RestClient client) {
super(indexName, client);
}
@Override
public NameUsageSuggestResponse suggest(NameUsageSuggestRequest request) {
try {
return suggest(index, request);
} catch (IOException e) {
throw new EsException(e);
}
}
@VisibleForTesting
public NameUsageSuggestResponse suggest(String index, NameUsageSuggestRequest request) throws IOException {
validateRequest(request);
String[] terms = EsUtil.getSearchTerms(client, index, Analyzer.SCINAME_AUTO_COMPLETE, request.getQ());
request.setSearchTerms(terms);
RequestTranslator translator = new RequestTranslator(request);
EsSearchRequest query = translator.translate();
EsResponse<EsNameUsage> esResponse = executeSearchRequest(index, query);
List<NameUsageSuggestion> suggestions = new ArrayList<>();
SearchHitConverter suggestionFactory = new SearchHitConverter(request);
esResponse.getHits().getHits().forEach(hit -> {
if (hit.matchedQuery(QTranslator.SN_QUERY_NAME)) {
suggestions.add(suggestionFactory.createSuggestion(hit, false));
}
if (hit.matchedQuery(QTranslator.VN_QUERY_NAME)) {
suggestions.add(suggestionFactory.createSuggestion(hit, true));
}
});
return new NameUsageSuggestResponse(suggestions);
}
private static void validateRequest(NameUsageSuggestRequest request) {
if (StringUtils.isBlank(request.getQ())) {
throw new IllegalArgumentException("Missing q parameter");
}
if (request.getDatasetKey() == null || request.getDatasetKey() < 1) {
throw new IllegalArgumentException("Missing/invalid datasetKey parameter");
}
}
}
| 38.791667 | 111 | 0.7773 |
ce19356f8628cff9541153c149bdd1750d6fd450 | 9,607 | /*
* Copyright (c) 2016-2019 VMware, Inc. All Rights Reserved.
*
* This product is licensed to you under the Apache License, Version 2.0 (the "License").
* You may not use this product except in compliance with the License.
*
* This product may include a number of subcomponents with separate copyright notices
* and license terms. Your use of these subcomponents is subject to the terms and
* conditions of the subcomponent's license, as noted in the LICENSE file.
*/
package com.vmware.mangle.unittest.services.helpers;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertNotNull;
import java.util.Arrays;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.vmware.mangle.cassandra.model.faults.specs.CommandExecutionFaultSpec;
import com.vmware.mangle.cassandra.model.faults.specs.CpuFaultSpec;
import com.vmware.mangle.cassandra.model.faults.specs.DockerFaultSpec;
import com.vmware.mangle.cassandra.model.faults.specs.K8SResourceNotReadyFaultSpec;
import com.vmware.mangle.cassandra.model.faults.specs.TaskSpec;
import com.vmware.mangle.cassandra.model.faults.specs.VMDiskFaultSpec;
import com.vmware.mangle.cassandra.model.redis.faults.specs.RedisDelayFaultSpec;
import com.vmware.mangle.cassandra.model.tasks.Task;
import com.vmware.mangle.cassandra.model.tasks.TaskStatus;
import com.vmware.mangle.cassandra.model.tasks.TaskTrigger;
import com.vmware.mangle.cassandra.model.tasks.commands.CommandInfo;
import com.vmware.mangle.model.aws.faults.spec.AwsEC2InstanceStateFaultSpec;
import com.vmware.mangle.model.aws.faults.spec.AwsRDSFaultSpec;
import com.vmware.mangle.model.azure.faults.spec.AzureVMNetworkFaultSpec;
import com.vmware.mangle.services.PluginService;
import com.vmware.mangle.services.helpers.FaultTaskFactory;
import com.vmware.mangle.services.mockdata.FaultsMockData;
import com.vmware.mangle.services.mockdata.TasksMockData;
import com.vmware.mangle.task.framework.helpers.AbstractTaskHelper;
import com.vmware.mangle.utils.exceptions.MangleException;
/**
* Unit test cases for {@link FaultTaskFactory}
*
* @author kumargautam
*/
public class FaultTaskFactoryTest {
@Mock
private PluginService pluginService;
@Mock
private AbstractTaskHelper<TaskSpec> taskHelper;
@InjectMocks
private FaultTaskFactory faultTaskFactory;
private FaultsMockData faultsMockData = new FaultsMockData();
@BeforeMethod
public void setUpBeforeClass() {
MockitoAnnotations.initMocks(this);
}
/**
* Test method for
* {@link com.vmware.mangle.services.helpers.FaultTaskFactory#getTask(com.vmware.mangle.cassandra.model.faults.specs.FaultSpec)}.
*
* @throws MangleException
*/
@SuppressWarnings({ "rawtypes" })
@Test
public void testGetTaskFaultSpec() throws MangleException {
RedisDelayFaultSpec faultSpec = faultsMockData.getRedisDelayFaultSpec();
TasksMockData<?> tasksMockData = new TasksMockData<>(faultSpec);
Task taskObj = tasksMockData.getDummy1Task();
mockGetTaskTest(taskObj);
assertNotNull(faultTaskFactory.getTask(faultSpec));
verifyGetTaskTest();
}
/**
* Test method for
* {@link com.vmware.mangle.services.helpers.FaultTaskFactory#getTask(com.vmware.mangle.cassandra.model.faults.specs.FaultSpec)}.
*
* @throws MangleException
*/
@SuppressWarnings({ "rawtypes" })
@Test
public void testGetTaskFaultForK8SFaultSpec() throws MangleException {
K8SResourceNotReadyFaultSpec faultSpec = faultsMockData.getK8SResourceNotReadyFaultSpec();
TasksMockData<?> tasksMockData = new TasksMockData<>(faultSpec);
Task taskObj = tasksMockData.getDummy1Task();
mockGetTaskTest(taskObj);
assertNotNull(faultTaskFactory.getTask(faultSpec));
verifyGetTaskTest();
}
/**
* Test method for
* {@link com.vmware.mangle.services.helpers.FaultTaskFactory#getTask(com.vmware.mangle.cassandra.model.faults.specs.FaultSpec)}.
*
* @throws MangleException
*/
@SuppressWarnings({ "rawtypes" })
@Test
public void testGetTaskFaultForDockerFaultSpec() throws MangleException {
DockerFaultSpec faultSpec = faultsMockData.getDockerPauseFaultSpec();
TasksMockData<?> tasksMockData = new TasksMockData<>(faultSpec);
Task taskObj = tasksMockData.getDummy1Task();
mockGetTaskTest(taskObj);
assertNotNull(faultTaskFactory.getTask(faultSpec));
verifyGetTaskTest();
}
/**
* Test method for
* {@link com.vmware.mangle.services.helpers.FaultTaskFactory#getTask(com.vmware.mangle.cassandra.model.faults.specs.FaultSpec)}.
*
* @throws MangleException
*/
@SuppressWarnings({ "rawtypes" })
@Test
public void testGetTaskFaultForVMFaultSpec() throws MangleException {
VMDiskFaultSpec faultSpec = faultsMockData.getVMDiskFaultSpec();
TasksMockData<?> tasksMockData = new TasksMockData<>(faultSpec);
Task taskObj = tasksMockData.getDummy1Task();
mockGetTaskTest(taskObj);
assertNotNull(faultTaskFactory.getTask(faultSpec));
verifyGetTaskTest();
}
/**
* Test method for
* {@link com.vmware.mangle.services.helpers.FaultTaskFactory#getTask(com.vmware.mangle.cassandra.model.faults.specs.FaultSpec)}.
*
* @throws MangleException
*/
@SuppressWarnings({ "rawtypes" })
@Test
public void testGetTaskFaultForAwsEC2FaultSpec() throws MangleException {
AwsEC2InstanceStateFaultSpec faultSpec = faultsMockData.getAwsEC2InstanceStateFaultSpec();
TasksMockData<?> tasksMockData = new TasksMockData<>(faultSpec);
Task taskObj = tasksMockData.getDummy1Task();
mockGetTaskTest(taskObj);
assertNotNull(faultTaskFactory.getTask(faultSpec));
verifyGetTaskTest();
}
/**
* Test method for
* {@link com.vmware.mangle.services.helpers.FaultTaskFactory#getTask(com.vmware.mangle.cassandra.model.faults.specs.FaultSpec)}.
*
* @throws MangleException
*/
@SuppressWarnings({ "rawtypes" })
@Test
public void testGetTaskFaultForAwsRDSFaultSpec() throws MangleException {
AwsRDSFaultSpec faultSpec = faultsMockData.getAwsRDSFaultSpec();
TasksMockData<?> tasksMockData = new TasksMockData<>(faultSpec);
Task taskObj = tasksMockData.getDummy1Task();
mockGetTaskTest(taskObj);
assertNotNull(faultTaskFactory.getTask(faultSpec));
verifyGetTaskTest();
}
/**
* Test method for
* {@link com.vmware.mangle.services.helpers.FaultTaskFactory#getTask(com.vmware.mangle.cassandra.model.faults.specs.FaultSpec)}.
*
* @throws MangleException
*/
@SuppressWarnings({ "rawtypes" })
@Test
public void testGetTaskFaultForAzureVMFaultSpec() throws MangleException {
AzureVMNetworkFaultSpec faultSpec = faultsMockData.getAzureVMNetworkBlockFaultSpec();
TasksMockData<?> tasksMockData = new TasksMockData<>(faultSpec);
Task taskObj = tasksMockData.getDummy1Task();
mockGetTaskTest(taskObj);
assertNotNull(faultTaskFactory.getTask(faultSpec));
verifyGetTaskTest();
}
/**
* Test method for
* {@link com.vmware.mangle.services.helpers.FaultTaskFactory#getTask(com.vmware.mangle.cassandra.model.faults.specs.FaultSpec)}.
*
* @throws MangleException
*/
@SuppressWarnings({ "rawtypes" })
@Test
public void testGetTaskFaultForK8SFaultTrigger() throws MangleException {
CpuFaultSpec faultSpec = faultsMockData.getK8SCPUFaultSpec();
TasksMockData<?> tasksMockData = new TasksMockData<>(faultSpec);
Task taskObj = tasksMockData.getDummy1Task();
mockGetTaskTest(taskObj);
assertNotNull(faultTaskFactory.getTask(faultSpec));
verifyGetTaskTest();
}
/**
* Test method for
* {@link com.vmware.mangle.services.helpers.FaultTaskFactory#getRemediationTask(Task, String)}.
*
* @throws MangleException
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testGetRemediationTask() throws MangleException {
CpuFaultSpec faultSpec = faultsMockData.getK8SCPUFaultSpec();
TasksMockData<?> tasksMockData = new TasksMockData<>(faultSpec);
Task taskObj = tasksMockData.getDummy1Task();
((TaskTrigger) taskObj.getTriggers().peek()).setTaskStatus(TaskStatus.COMPLETED);
((CommandExecutionFaultSpec) taskObj.getTaskData())
.setRemediationCommandInfoList(Arrays.asList(CommandInfo.builder("test").build()));
mockGetTaskTest(taskObj);
assertNotNull(faultTaskFactory.getRemediationTask(taskObj, taskObj.getId()));
verifyGetTaskTest();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void mockGetTaskTest(Task taskObj) throws MangleException {
when(pluginService.getExtension(anyString())).thenReturn(taskHelper);
when(taskHelper.init(any(TaskSpec.class), anyString())).thenReturn(taskObj);
}
private void verifyGetTaskTest() throws MangleException {
verify(pluginService, times(1)).getExtension(anyString());
verify(taskHelper, times(1)).init(any(TaskSpec.class), anyString());
}
}
| 40.535865 | 133 | 0.728427 |
020baa2f40b2801fa3e303e4ddfe658b34f0fe29 | 1,727 | package org.openntf.conference.graph;
import org.openntf.domino.graph2.annotations.AdjacencyUnique;
import org.openntf.domino.graph2.annotations.IncidenceUnique;
import org.openntf.domino.graph2.annotations.TypedProperty;
import org.openntf.domino.graph2.builtin.DEdgeFrame;
import org.openntf.domino.graph2.builtin.DVertexFrame;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.frames.InVertex;
import com.tinkerpop.frames.OutVertex;
import com.tinkerpop.frames.modules.typedgraph.TypeValue;
@TypeValue("Track")
public interface Track extends DVertexFrame {
@TypeValue(Includes.LABEL)
public static interface Includes extends DEdgeFrame {
public static final String LABEL = "Includes";
@InVertex
public Track getTrack();
@OutVertex
public Presentation getSession();
}
@TypedProperty("Title")
public String getTitle();
@TypedProperty("Title")
public void setTitle(String title);
@TypedProperty("Description")
public String getDescription();
@TypedProperty("Description")
public void setDescription(String description);
@AdjacencyUnique(label = Includes.LABEL, direction = Direction.IN)
public Iterable<Presentation> getIncludesSessions();
@AdjacencyUnique(label = Includes.LABEL, direction = Direction.IN)
public Includes addIncludesSession(Presentation session);
@AdjacencyUnique(label = Includes.LABEL, direction = Direction.IN)
public void removeIncludesSession(Presentation session);
@IncidenceUnique(label = Includes.LABEL, direction = Direction.IN)
public Iterable<Includes> getIncludes();
@IncidenceUnique(label = Includes.LABEL, direction = Direction.IN)
public void removeIncludes(Includes includes);
}
| 31.4 | 68 | 0.776491 |
7510369bda01652a8c4b843ba9ad0c66f552c422 | 6,230 | package com.cordys.uiunit.eastwind.designtime;
import org.junit.Test;
import com.cordys.cm.uiunit.elements.cordys.ITree;
import com.cordys.cm.uiunit.elements.cordys.ITreeItem;
import com.cordys.cm.uiunit.elements.html.IFrame;
import com.cordys.cm.uiunit.exceptions.UIUnitException;
import com.cordys.cm.uiunit.framework.IKeyboard;
import com.cordys.cm.uiunit.framework.IMouse;
import com.cordys.cm.uiunit.junit4.annotation.UIUnitTimeout;
import com.cordys.cm.uiunit.message.Messages;
import com.cordys.cws.uiunit.util.folder.IUICWSFolder;
import com.cordys.cws.uiunit.util.project.IUIProject;
import com.cordys.datatransformation.cwsutilities.IDatamap;
import com.cordys.datatransformation.cwsutilities.IDatamapEditor;
import com.cordys.webservice.cwsutilities.DataTransformationWebServiceInterfaceProperties;
import com.cordys.webservice.cwsutilities.IUIWebServiceDefinitionSet;
import com.cordys.webservice.cwsutilities.IUIWebServiceDefinitionSetCreatorWizard;
import com.cordys.webservice.cwsutilities.SourceType;
@UIUnitTimeout(1200000)
public class DataTransformationManager extends WorkSpaceOrganizer{
IUIProject project = null;
ITree sourcetree = null;
ITree targettree = null;
@Test
public void createSalesProductionDT(){
project = getProject();
IUICWSFolder datamapFolder = project.getExistingChildDocument(IUICWSFolder.class, EastWindArtifacts.FOLDER_DATAMAP);
IDatamap salesDataTrans=(IDatamap)datamapFolder.addDocument(IDatamap.class);
IDatamapEditor datmapEditor = salesDataTrans.openEditor();
salesDataTrans.openEditor();
datmapEditor.save(EastWindArtifacts.DATAMAP_SALESPRODUCTIONDATAMAP,EastWindArtifacts.DATAMAP_SALESPRODUCTIONDATAMAP);
datmapEditor.zoomSourceSchemaFragment(project.getName()+"\\Custom Schemas\\OrdersOne\\"+EastWindArtifacts.SCHEMA_FRAG_ORDERS,true);
datmapEditor.zoomSourceSchemaFragment(project.getName()+"\\Custom Schemas\\ProductionOne\\"+EastWindArtifacts.SCHEMA_FRAG_PRODUCTION,false);
IFrame modelerFrame =datmapEditor.findElement(IFrame.class, "modelerFrame");
sourcetree = modelerFrame.findElement(ITree.class, "sourcetree_elem");
targettree = modelerFrame.findElement(ITree.class, "targettree_elem");
sourcetree.getRoot().expandAll();
targettree.getRoot().expandAll();
ITreeItem souOrderId= sourcetree.findItem("sch:OrderID");
IMouse mouse= this.getContext().getRootContext().getTestEnvironment().getMouse();
IKeyboard kbd=this.getContext().getRootContext().getTestEnvironment().getKeyboard();
souOrderId.moveMouseToThis();
mouse.click();
ITreeItem tarOrderId = targettree.findItem("sch:OrderID");
kbd.controlKeyDown();
tarOrderId.moveMouseToThis();
mouse.click();
datmapEditor.createLinkFromNodeToNode("sch:OrderID","sch:OrderID",sourcetree,targettree);
datmapEditor.createLinkFromNodeToNode("sch:ProductID","sch:ProductID",sourcetree,targettree);
datmapEditor.createLinkFromNodeToNode("sch:UnitPrice","sch:UnitPrice",sourcetree,targettree);
datmapEditor.createLinkFromNodeToNode("sch:Quantity","sch:Quantity",sourcetree,targettree);
datmapEditor.createLinkFromNodeToNode("sch:Discount","sch:Discount",sourcetree,targettree);
datmapEditor.createLinkFromNodeToNode("sch:CustomerID","sch:CustomerID",sourcetree,targettree);
datmapEditor.createLinkFromNodeToNode("sch:EmployeeID","sch:EmployeeID",sourcetree,targettree);
datmapEditor.createLinkFromNodeToNode("sch:OrderDate","sch:OrderDate",sourcetree,targettree);
datmapEditor.createLinkFromNodeToNode("sch:RequiredDate","sch:RequiredDate",sourcetree,targettree);
datmapEditor.createLinkFromNodeToNode("sch:ShippedDate","sch:ShippedDate",sourcetree,targettree);
datmapEditor.createLinkFromNodeToNode("sch:ShipVia","sch:ShipVia",sourcetree,targettree);
datmapEditor.createLinkFromNodeToNode("sch:Freight","sch:Freight",sourcetree,targettree);
datmapEditor.createLinkFromNodeToNode("sch:ShipName","sch:ShipName",sourcetree,targettree);
datmapEditor.createLinkFromNodeToNode("sch:ShipAddress","sch:ShipAddress",sourcetree,targettree);
datmapEditor.createLinkFromNodeToNode("sch:ShipCity","sch:ShipCity",sourcetree,targettree);
datmapEditor.createLinkFromNodeToNode("sch:ShipRegion","sch:ShipRegion",sourcetree,targettree);
datmapEditor.createLinkFromNodeToNode("sch:ShipPostalCode","sch:ShipPostalCode",sourcetree,targettree);
datmapEditor.createLinkFromNodeToNode("sch:ShipCountry","sch:ShipCountry",sourcetree,targettree);
kbd.controlKeyUp();
datmapEditor.save();
datmapEditor.close();
}
@Test
public void generateSalesProductionDTWebService(){
project = getProject();
if(project == null)
throw new UIUnitException(Messages.ELEMENT_NOT_FOUND_EXCEPTION,IUIProject.class,"Project SalesDemo not found..");
IUICWSFolder folder = project.getExistingChildDocument(IUICWSFolder.class,EastWindArtifacts.FOLDER_WEBSERVICEDATAMAP);
if(folder == null)
throw new UIUnitException(Messages.ELEMENT_NOT_FOUND_EXCEPTION,IUICWSFolder.class,"folder webservicesdatamap not found..");
IUIWebServiceDefinitionSetCreatorWizard wsdefsetcreationwizz = (IUIWebServiceDefinitionSetCreatorWizard)folder.addDocumentWithWizard(IUIWebServiceDefinitionSet.class);
wsdefsetcreationwizz.setSourceType(SourceType.DATA_TRANSFORMATION);
wsdefsetcreationwizz.setName(EastWindArtifacts.WS_DEFINITIONSET_DATATRANSFORMATION);
wsdefsetcreationwizz.setNameSpace("http://schemas.cordys.com/saleproductionmapws");
DataTransformationWebServiceInterfaceProperties dtwsiProperties = new DataTransformationWebServiceInterfaceProperties();
dtwsiProperties.setDocumentName(EastWindArtifacts.DATAMAP_SALESPRODUCTIONDATAMAP);
dtwsiProperties.setWebServiceInterfaceName(EastWindArtifacts.WS_INTERFACE_DATATRANSFORMATION);
dtwsiProperties.setWebServiceOperationName(EastWindArtifacts.WS_OPERATION_DATATRANSFORMATION);
wsdefsetcreationwizz.createWebServiceInterface( dtwsiProperties);
wsdefsetcreationwizz.close();
}
}
| 54.649123 | 174 | 0.791011 |
00a8348ea6a13ed1eaa6c2e8db393f96a8708778 | 3,340 | /*
* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazon.janusgraph;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.apache.log4j.Appender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import com.amazon.janusgraph.testutils.CiHeartbeat;
/**
*
* @author Johan Jacobs
*
*/
@RunWith(MockitoJUnitRunner.class)
public class TestCiHeartbeat {
@Rule
public final TestName testName = new TestName();
@Mock
private Appender mockAppender;
@Captor
private ArgumentCaptor<LoggingEvent> captorLoggingEvent;
@Before
public void setup() {
final Logger root = Logger.getRootLogger();
root.addAppender(mockAppender);
root.setLevel(Level.WARN);
}
@Test
public void testHeartbeatConsoleOutput() throws InterruptedException {
final CiHeartbeat ciHeartbeat = new CiHeartbeat(500, 3);
ciHeartbeat.startHeartbeat(testName.getMethodName());
Thread.sleep(2000);
ciHeartbeat.stopHeartbeat();
verify(mockAppender, times(6)).doAppend(captorLoggingEvent.capture());
final LoggingEvent unitTestStartEvent = captorLoggingEvent.getAllValues().get(0);
Assert.assertEquals("Heartbeat - [started] - testHeartbeatConsoleOutput - 0ms", unitTestStartEvent.getMessage());
final LoggingEvent heartbeatOneEvent = captorLoggingEvent.getAllValues().get(1);
Assert.assertTrue(heartbeatOneEvent.getMessage().toString().contains("Heartbeat - [1] - testHeartbeatConsoleOutput - "));
final LoggingEvent heartbeatTwoEvent = captorLoggingEvent.getAllValues().get(2);
Assert.assertTrue(heartbeatTwoEvent.getMessage().toString().contains("Heartbeat - [2] - testHeartbeatConsoleOutput - "));
final LoggingEvent heartbeatThreeEvent = captorLoggingEvent.getAllValues().get(3);
Assert.assertTrue(heartbeatThreeEvent.getMessage().toString().contains("Heartbeat - [3] - testHeartbeatConsoleOutput - "));
final LoggingEvent heartbeatfourEvent = captorLoggingEvent.getAllValues().get(4);
Assert.assertTrue(heartbeatfourEvent.getMessage().toString().contains("Heartbeat - [4] - testHeartbeatConsoleOutput - "));
final LoggingEvent unitTestEndEvent = captorLoggingEvent.getAllValues().get(5);
Assert.assertTrue(unitTestEndEvent.getMessage().toString().contains("Heartbeat - [finished] - testHeartbeatConsoleOutput - "));
}
}
| 35.531915 | 135 | 0.738623 |
3a885324b70c0d923e0e36724da9cce4f2a292e5 | 450 | package br.com.pandox.nursery;
import br.com.pandox.nursery.view.rest.Link;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public abstract interface DataTransferObject {
void addLink(Link link);
void setLinks(List<Link> links);
List<Link> getLinks();
}
| 22.5 | 61 | 0.788889 |
05e2cc621d98b2b9ba899495428688889c5d9626 | 4,338 | package com.fanaticaltest.datadriventest.models;
import java.util.ArrayList;
import java.util.List;
public class Scenario {
private Integer id;
private String name;
private String description;
private List<GherkinsTag> gherkinsTags;
private List<Step> steps;
private PythonDependencies pythonDependencies;
private PythonDefSetup pythonDefSetup;
private PythonDefTearDown pythonDefTearDown;
private Feature feature;
//Constructor
public Scenario() {}
//Getter and Setter
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = "Scenario: " + name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<GherkinsTag> getGherkinsTags() {
return gherkinsTags;
}
public void setGherkinsTags(ArrayList<GherkinsTag> gherkinsTags) {
this.gherkinsTags = gherkinsTags;
}
public List<Step> getSteps() {
return steps;
}
public void setSteps(ArrayList<Step> steps) {
this.steps = steps;
}
public PythonDependencies getPythonDependencies() {
return pythonDependencies;
}
public void setPythonDependencies(PythonDependencies pythonDependencies) {
this.pythonDependencies = pythonDependencies;
}
public PythonDefSetup getPythonDefSetup() {
return pythonDefSetup;
}
public void setPythonDefSetup(PythonDefSetup pythonDefSetup) {
this.pythonDefSetup = pythonDefSetup;
}
public PythonDefTearDown getPythonDefTearDown() {
return pythonDefTearDown;
}
public void setPythonDefTearDown(PythonDefTearDown pythonDefTearDown) {
this.pythonDefTearDown = pythonDefTearDown;
}
public Feature getFeature() {
return feature;
}
public void setFeature(Feature feature) {
this.feature = feature;
}
//Methods
public String toGherkinsFile()
{
String buildScenario = "";
if (this.gherkinsTags.size()>0)
{
buildScenario += "\t";
for (GherkinsTag gherkinsTag : gherkinsTags)
{
buildScenario += gherkinsTag.toGherkinsFile();
}
}
buildScenario += "\n";
buildScenario += "\t" + this.name + "\n";
if (this.steps.size()>0)
{
for (Step step : steps)
{
buildScenario += "\t\t" + step.toGherkinsFile() + "\n";
}
}
buildScenario += "\n";
return buildScenario;
}
public String toPython()
{
String buildPythonFile = "";
buildPythonFile += this.pythonDependencies.toPython() + "\n";
buildPythonFile += "class DataDriverTest(unittest.TestCase):" + "\n\n";
buildPythonFile += this.pythonDefSetup.toPython()+ "\n";
buildPythonFile += "\tdef test(self):\n";
if (this.steps.size()>0)
{
for (Step step : this.steps)
{
buildPythonFile += step.toPython();
}
}
buildPythonFile += "\n";
buildPythonFile += this.pythonDefTearDown.toPython()+ "\n";
buildPythonFile += "if __name__ == \"__main__\":" + "\n";
buildPythonFile += "\tunittest.main()" + "\n";
return buildPythonFile;
}
private String toPythonPerStep()
{
String output = "";
for (Step s : steps)
{
output += s.toPython();
}
return output;
}
@Override
public String toString() {
return "Scenario{" +
"id=" + id +
", name='" + name + '\'' +
", description='" + description + '\'' +
", gherkinsTags=" + gherkinsTags +
", steps=" + toPythonPerStep() +
", pythonDependencies=" + pythonDependencies +
", pythonDefSetup=" + pythonDefSetup +
", pythonDefTearDown=" + pythonDefTearDown +
//", feature=" + feature +
'}';
}
} | 23.835165 | 79 | 0.568234 |
0382b8b545c33305060407052ffa31ee0b914cbc | 2,329 | package io.renren.modules.derive.controller;
import java.util.Arrays;
import java.util.Map;
import io.renren.common.validator.ValidatorUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.renren.modules.derive.entity.XsIssueEntity;
import io.renren.modules.derive.service.XsIssueService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
/**
*
*
* @author chenshun
* @email sunlightcs@gmail.com
* @date 2019-10-23 14:25:06
*/
@RestController
@RequestMapping("derive/xsissue")
public class XsIssueController {
@Autowired
private XsIssueService xsIssueService;
/**
* 列表
*/
@RequestMapping("/list")
@RequiresPermissions("gkzr:xsissue:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = xsIssueService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
@RequiresPermissions("gkzr:xsissue:info")
public R info(@PathVariable("id") Integer id){
XsIssueEntity xsIssue = xsIssueService.selectById(id);
return R.ok().put("xsIssue", xsIssue);
}
/**
* 保存
*/
@RequestMapping("/save")
@RequiresPermissions("gkzr:xsissue:save")
public R save(@RequestBody XsIssueEntity xsIssue){
xsIssueService.insert(xsIssue);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
@RequiresPermissions("gkzr:xsissue:update")
public R update(@RequestBody XsIssueEntity xsIssue){
ValidatorUtils.validateEntity(xsIssue);
xsIssueService.updateAllColumnById(xsIssue);//全部更新
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
@RequiresPermissions("gkzr:xsissue:delete")
public R delete(@RequestBody Integer[] ids){
xsIssueService.deleteBatchIds(Arrays.asList(ids));
return R.ok();
}
}
| 25.043011 | 62 | 0.689137 |
7b81ea96fd9ba22f7c4c738824436b27fac32e4f | 1,851 | package com.nhl.dflib.series;
import com.nhl.dflib.DoubleSeries;
import com.nhl.dflib.Series;
public class DoubleSingleValueSeries extends DoubleBaseSeries {
private final double value;
private final int size;
public DoubleSingleValueSeries(double value, int size) {
this.value = value;
this.size = size;
}
@Override
public int size() {
return size;
}
@Override
public double getDouble(int index) {
return value;
}
@Override
public void copyToDouble(double[] to, int fromOffset, int toOffset, int len) {
if (fromOffset + len > size) {
throw new ArrayIndexOutOfBoundsException(fromOffset + len);
}
int targetIdx = toOffset;
for (int i = fromOffset; i < len; i++) {
to[targetIdx++] = get(i);
}
}
@Override
public DoubleSeries materializeDouble() {
return this;
}
@Override
public DoubleSeries rangeOpenClosedDouble(int fromInclusive, int toExclusive) {
return fromInclusive == 0 && toExclusive == size()
? this
: new DoubleSingleValueSeries(value, toExclusive - fromInclusive);
}
@Override
public DoubleSeries headDouble(int len) {
return len < size ? new DoubleSingleValueSeries(value, len) : this;
}
@Override
public DoubleSeries tailDouble(int len) {
return len < size ? new DoubleSingleValueSeries(value, len) : this;
}
@Override
public double max() {
return value;
}
@Override
public double min() {
return value;
}
@Override
public double sum() {
return value * size;
}
@Override
public double avg() {
return value;
}
@Override
public double median() {
return value;
}
}
| 21.776471 | 83 | 0.599136 |
051573f9250b734f28b4198096f3cf7ff1e3d667 | 8,765 | package actions;
import actions.commands.AddToFavoriteCommand;
import actions.commands.AddToSeenCommand;
import actions.commands.RateCommand;
import actions.queries.ActorQuery;
import actions.queries.MovieQuery;
import actions.queries.ShowQuery;
import actions.queries.UserQuery;
import actions.recommendations.BestUnseenRecommendation;
import actions.recommendations.PopularRecommendation;
import actions.recommendations.StandardRecommendation;
import actions.recommendations.SearchRecommendation;
import actions.recommendations.FavoriteRecommendation;
import common.Constants;
import entertainment.Genre;
import fileio.ActionInputData;
import utils.Utils;
import java.util.ArrayList;
import java.util.List;
public final class ActionFactory {
private ActionFactory() { }
/** ActionFactory receives a list of data and creates the specified action classes
* @param data is the data parsed into the action type classes
* */
public static List<Action> createActionList(final List<ActionInputData> data) {
List<Action> result = new ArrayList<>();
for (var d : data) {
Action action = createAction(d);
result.add(action);
}
return result;
}
private static Action createAction(final ActionInputData data) {
String actionType = data.getActionType();
return switch (actionType) {
case Constants.COMMAND -> createCommand(data);
case Constants.QUERY -> createQuery(data);
case Constants.RECOMMENDATION -> createRecommendation(data);
default -> null;
};
}
private static Action createCommand(final ActionInputData data) {
String commandType = data.getType();
return switch (commandType) {
case Constants.FAVORITE -> createFavoriteCommand(data);
case Constants.VIEW -> createSeenCommand(data);
case Constants.RATING -> createRatingCommand(data);
default -> null;
};
}
private static Action createQuery(final ActionInputData data) {
String objectType = data.getObjectType();
return switch (objectType) {
case Constants.ACTORS -> createActorQuery(data);
case Constants.MOVIES -> createMovieQuery(data);
case Constants.SHOWS -> createShowQuery(data);
case Constants.USERS -> createUserQuery(data);
default -> null;
};
}
private static Action createRecommendation(final ActionInputData data) {
String recommendationType = data.getType();
return switch (recommendationType) {
case Constants.STANDARD -> createStandardRecomm(data);
case Constants.BEST_UNSEEN -> createBestUnseenRecomm(data);
case Constants.POPULAR -> createPopularRecomm(data);
case Constants.FAVORITE -> createFavoriteRecomm(data);
case Constants.SEARCH -> createSearchRecomm(data);
default -> null;
};
}
private static Action createFavoriteCommand(final ActionInputData data) {
int id = data.getActionId();
String actionType = data.getActionType();
AddToFavoriteCommand command = new AddToFavoriteCommand(id, actionType);
command.setUser(data.getUsername());
command.setTitle(data.getTitle());
return command;
}
private static Action createSeenCommand(final ActionInputData data) {
int id = data.getActionId();
String actionType = data.getActionType();
AddToSeenCommand command = new AddToSeenCommand(id, actionType);
command.setUser(data.getUsername());
command.setTitle(data.getTitle());
return command;
}
private static Action createRatingCommand(final ActionInputData data) {
int id = data.getActionId();
String actionType = data.getActionType();
RateCommand command = new RateCommand(id, actionType);
command.setUser(data.getUsername());
command.setTitle(data.getTitle());
command.setGrade(data.getGrade());
command.setCurrentSeason(data.getSeasonNumber());
return command;
}
private static Action createActorQuery(final ActionInputData data) {
int id = data.getActionId();
int keywordsIndex = 2;
int awardsIndex = keywordsIndex + 1;
String actionType = data.getActionType();
List<String> keywords = data.getFilters().get(keywordsIndex);
List<String> awards = data.getFilters().get(awardsIndex);
ActorQuery query = new ActorQuery(id, actionType);
query.setObjectType(data.getObjectType());
query.setSortType(data.getSortType());
query.setCriteria(data.getCriteria());
query.setLimit(data.getNumber());
query.setKeywordsFilter(keywords);
query.setAwardsFilter(awards);
return query;
}
private static Action createMovieQuery(final ActionInputData data) {
int id = data.getActionId();
String actionType = data.getActionType();
List<String> yearFilter = data.getFilters().get(0);
List<String> genreFilter = data.getFilters().get(1);
MovieQuery query = new MovieQuery(id, actionType);
query.setObjectType(data.getObjectType());
query.setSortType(data.getSortType());
query.setCriteria(data.getCriteria());
query.setLimit(data.getNumber());
if (yearFilter.get(0) != null) {
int year = Integer.parseInt(yearFilter.get(0));
query.setYear(year);
}
if (genreFilter.get(0) != null) {
Genre genre = Utils.stringToGenre(genreFilter.get(0));
query.setGenre(genre);
}
return query;
}
private static Action createShowQuery(final ActionInputData data) {
int id = data.getActionId();
String actionType = data.getActionType();
List<String> yearFilter = data.getFilters().get(0);
List<String> genreFilter = data.getFilters().get(1);
ShowQuery query = new ShowQuery(id, actionType);
query.setObjectType(data.getObjectType());
query.setSortType(data.getSortType());
query.setCriteria(data.getCriteria());
query.setLimit(data.getNumber());
if (yearFilter.get(0) != null) {
int year = Integer.parseInt(yearFilter.get(0));
query.setYear(year);
}
if (genreFilter.get(0) != null) {
Genre genre = Utils.stringToGenre(genreFilter.get(0));
query.setGenre(genre);
}
return query;
}
private static Action createUserQuery(final ActionInputData data) {
int id = data.getActionId();
String actionType = data.getActionType();
UserQuery query = new UserQuery(id, actionType);
query.setObjectType(data.getObjectType());
query.setSortType(data.getSortType());
query.setCriteria(data.getCriteria());
query.setLimit(data.getNumber());
return query;
}
private static Action createStandardRecomm(final ActionInputData data) {
int id = data.getActionId();
String actionType = data.getActionType();
StandardRecommendation recomm = new StandardRecommendation(id, actionType);
recomm.setUsername(data.getUsername());
return recomm;
}
private static Action createBestUnseenRecomm(final ActionInputData data) {
int id = data.getActionId();
String actionType = data.getActionType();
BestUnseenRecommendation recomm = new BestUnseenRecommendation(id, actionType);
recomm.setUsername(data.getUsername());
return recomm;
}
private static Action createPopularRecomm(final ActionInputData data) {
int id = data.getActionId();
String actionType = data.getActionType();
PopularRecommendation recomm = new PopularRecommendation(id, actionType);
recomm.setUsername(data.getUsername());
return recomm;
}
private static Action createFavoriteRecomm(final ActionInputData data) {
int id = data.getActionId();
String actionType = data.getActionType();
FavoriteRecommendation recomm = new FavoriteRecommendation(id, actionType);
recomm.setUsername(data.getUsername());
return recomm;
}
private static Action createSearchRecomm(final ActionInputData data) {
int id = data.getActionId();
String actionType = data.getActionType();
SearchRecommendation recomm = new SearchRecommendation(id, actionType);
Genre genre = Utils.stringToGenre(data.getGenre());
recomm.setGenre(genre);
recomm.setUsername(data.getUsername());
return recomm;
}
}
| 37.297872 | 87 | 0.663662 |
86db1bea96facec28add666fec0c7736c428ff74 | 20,512 | /*******************************************************************************
* Copyright (c) 2000, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Martin Oberhuber (Wind River) - [105554] handle cyclic symbolic links
* Martin Oberhuber (Wind River) - [232426] shared prefix histories for symlinks
* Serge Beauchamp (Freescale Semiconductor) - [252996] add resource filtering
* Martin Oberhuber (Wind River) - [292267] OutOfMemoryError due to leak in UnifiedTree
*******************************************************************************/
package org.eclipse.core.internal.localstore;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
import org.eclipse.core.filesystem.*;
import org.eclipse.core.internal.refresh.RefreshJob;
import org.eclipse.core.internal.resources.*;
import org.eclipse.core.internal.utils.Queue;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.jobs.Job;
/**
* Represents the workspace's tree merged with the file system's tree.
*/
public class UnifiedTree {
/** special node to mark the separation of a node's children */
protected static final UnifiedTreeNode childrenMarker= new UnifiedTreeNode(null, null, null, null, false);
private static final Iterator EMPTY_ITERATOR= Collections.EMPTY_LIST.iterator();
/** special node to mark the beginning of a level in the tree */
protected static final UnifiedTreeNode levelMarker= new UnifiedTreeNode(null, null, null, null, false);
private static final IFileInfo[] NO_CHILDREN= new IFileInfo[0];
/** Singleton to indicate no local children */
private static final IResource[] NO_RESOURCES= new IResource[0];
/**
* True if the level of the children of the current node are valid according to the requested
* refresh depth, false otherwise
*/
protected boolean childLevelValid= false;
/** an IFileTree which can be used to build a unified tree */
protected IFileTree fileTree= null;
/** Spare node objects available for reuse */
protected ArrayList freeNodes= new ArrayList();
/** tree's actual level */
protected int level;
/** our queue */
protected Queue queue;
/** path prefixes for checking symbolic link cycles */
protected PrefixPool pathPrefixHistory, rootPathHistory;
/** tree's root */
protected IResource root;
/**
* The root must only be a file or a folder.
*/
public UnifiedTree(IResource root) {
setRoot(root);
}
/**
* Pass in a a root for the tree, a file tree containing all of the entries for this tree and a
* flag indicating whether the UnifiedTree should consult the fileTree where possible for
* entries
*
* @param root
* @param fileTree
*/
public UnifiedTree(IResource root, IFileTree fileTree) {
this(root);
this.fileTree= fileTree;
}
public void accept(IUnifiedTreeVisitor visitor) throws CoreException {
accept(visitor, IResource.DEPTH_INFINITE);
}
/**
* Performs a breadth-first traversal of the unified tree, passing each node to the provided
* visitor.
*/
public void accept(IUnifiedTreeVisitor visitor, int depth) throws CoreException {
Assert.isNotNull(root);
initializeQueue();
setLevel(0, depth);
while (!queue.isEmpty()) {
UnifiedTreeNode node= (UnifiedTreeNode)queue.remove();
if (isChildrenMarker(node))
continue;
if (isLevelMarker(node)) {
if (!setLevel(getLevel() + 1, depth))
break;
continue;
}
if (visitor.visit(node))
addNodeChildrenToQueue(node);
else
removeNodeChildrenFromQueue(node);
//allow reuse of the node, but don't let the freeNodes list grow infinitely
if (freeNodes.size() < 32767) {
//free memory-consuming elements of the node for garbage collection
node.releaseForGc();
freeNodes.add(node);
}
//else, the whole node will be garbage collected since there is no
//reference to it any more.
}
}
protected void addChildren(UnifiedTreeNode node) {
Resource parent= (Resource)node.getResource();
// is there a possibility to have children?
int parentType= parent.getType();
if (parentType == IResource.FILE && !node.isFolder())
return;
//don't refresh resources in closed or non-existent projects
if (!parent.getProject().isAccessible())
return;
// get the list of resources in the file system
// don't ask for local children if we know it doesn't exist locally
IFileInfo[] list= node.existsInFileSystem() ? getLocalList(node) : NO_CHILDREN;
int localIndex= 0;
// See if the children of this resource have been computed before
ResourceInfo resourceInfo= parent.getResourceInfo(false, false);
int flags= parent.getFlags(resourceInfo);
boolean unknown= ResourceInfo.isSet(flags, ICoreConstants.M_CHILDREN_UNKNOWN);
// get the list of resources in the workspace
if (!unknown && (parentType == IResource.FOLDER || parentType == IResource.PROJECT) && parent.exists(flags, true)) {
IResource target= null;
UnifiedTreeNode child= null;
IResource[] members;
try {
members= ((IContainer)parent).members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS | IContainer.INCLUDE_HIDDEN);
} catch (CoreException e) {
members= NO_RESOURCES;
}
int workspaceIndex= 0;
//iterate simultaneously over file system and workspace members
while (workspaceIndex < members.length) {
target= members[workspaceIndex];
String name= target.getName();
IFileInfo localInfo= localIndex < list.length ? list[localIndex] : null;
int comp= localInfo != null ? name.compareTo(localInfo.getName()) : -1;
//special handling for linked resources
if (target.isLinked()) {
//child will be null if location is undefined
child= createChildForLinkedResource(target);
workspaceIndex++;
//if there is a matching local file, skip it - it will be blocked by the linked resource
if (comp == 0)
localIndex++;
} else if (comp == 0) {
// resource exists in workspace and file system --> localInfo is non-null
//create workspace-only node for symbolic link that creates a cycle
if (localInfo.getAttribute(EFS.ATTRIBUTE_SYMLINK) && localInfo.isDirectory() && isRecursiveLink(node.getStore(), localInfo))
child= createNode(target, null, null, true);
else
child= createNode(target, null, localInfo, true);
localIndex++;
workspaceIndex++;
} else if (comp > 0) {
// resource exists only in file system
//don't create a node for symbolic links that create a cycle
if (localInfo.getAttribute(EFS.ATTRIBUTE_SYMLINK) && localInfo.isDirectory() && isRecursiveLink(node.getStore(), localInfo))
child= null;
else
child= createChildNodeFromFileSystem(node, localInfo);
localIndex++;
} else {
// resource exists only in the workspace
child= createNode(target, null, null, true);
workspaceIndex++;
}
if (child != null)
addChildToTree(node, child);
}
}
/* process any remaining resource from the file system */
addChildrenFromFileSystem(node, list, localIndex);
/* Mark the children as now known */
if (unknown) {
// Don't open the info - we might not be inside a workspace-modifying operation
resourceInfo= parent.getResourceInfo(false, false);
if (resourceInfo != null)
resourceInfo.clear(ICoreConstants.M_CHILDREN_UNKNOWN);
}
/* if we added children, add the childMarker separator */
if (node.getFirstChild() != null)
addChildrenMarker();
}
protected void addChildrenFromFileSystem(UnifiedTreeNode node, IFileInfo[] childInfos, int index) {
if (childInfos == null)
return;
for (int i= index; i < childInfos.length; i++) {
IFileInfo info= childInfos[i];
//don't create a node for symbolic links that create a cycle
if (!info.getAttribute(EFS.ATTRIBUTE_SYMLINK) || !info.isDirectory() || !isRecursiveLink(node.getStore(), info))
addChildToTree(node, createChildNodeFromFileSystem(node, info));
}
}
protected void addChildrenMarker() {
addElementToQueue(childrenMarker);
}
protected void addChildToTree(UnifiedTreeNode node, UnifiedTreeNode child) {
if (node.getFirstChild() == null)
node.setFirstChild(child);
addElementToQueue(child);
}
protected void addElementToQueue(UnifiedTreeNode target) {
queue.add(target);
}
protected void addNodeChildrenToQueue(UnifiedTreeNode node) {
/* if the first child is not null we already added the children */
/* If the children won't be at a valid level for the refresh depth, don't bother adding them */
if (!childLevelValid || node.getFirstChild() != null)
return;
addChildren(node);
if (queue.isEmpty())
return;
//if we're about to change levels, then the children just added
//are the last nodes for their level, so add a level marker to the queue
UnifiedTreeNode nextNode= (UnifiedTreeNode)queue.peek();
if (isChildrenMarker(nextNode))
queue.remove();
nextNode= (UnifiedTreeNode)queue.peek();
if (isLevelMarker(nextNode))
addElementToQueue(levelMarker);
}
protected void addRootToQueue() {
//don't refresh in closed projects
if (!root.getProject().isAccessible())
return;
IFileStore store= ((Resource)root).getStore();
IFileInfo fileInfo= fileTree != null ? fileTree.getFileInfo(store) : store.fetchInfo();
UnifiedTreeNode node= createNode(root, store, fileInfo, root.exists());
if (node.existsInFileSystem() || node.existsInWorkspace())
addElementToQueue(node);
}
/**
* Creates a tree node for a resource that is linked in a different file system location.
*/
protected UnifiedTreeNode createChildForLinkedResource(IResource target) {
IFileStore store= ((Resource)target).getStore();
return createNode(target, store, store.fetchInfo(), true);
}
/**
* Creates a child node for a location in the file system. Does nothing and returns null if the
* location does not correspond to a valid file/folder.
*/
protected UnifiedTreeNode createChildNodeFromFileSystem(UnifiedTreeNode parent, IFileInfo info) {
IPath childPath= parent.getResource().getFullPath().append(info.getName());
int type= info.isDirectory() ? IResource.FOLDER : IResource.FILE;
IResource target= getWorkspace().newResource(childPath, type);
return createNode(target, null, info, false);
}
/**
* Factory method for creating a node for this tree. If the file exists on disk, either the
* parent store or child store can be provided. Providing only the parent store avoids creation
* of the child store in cases where it is not needed. The store object is only needed for
* directories for simple file system traversals, so this avoids creating store objects for all
* files.
*/
protected UnifiedTreeNode createNode(IResource resource, IFileStore store, IFileInfo info, boolean existsWorkspace) {
//first check for reusable objects
UnifiedTreeNode node= null;
int size= freeNodes.size();
if (size > 0) {
node= (UnifiedTreeNode)freeNodes.remove(size - 1);
node.reuse(this, resource, store, info, existsWorkspace);
return node;
}
//none available, so create a new one
return new UnifiedTreeNode(this, resource, store, info, existsWorkspace);
}
protected Iterator getChildren(UnifiedTreeNode node) {
/* if first child is null we need to add node's children to queue */
if (node.getFirstChild() == null)
addNodeChildrenToQueue(node);
/* if the first child is still null, the node does not have any children */
if (node.getFirstChild() == null)
return EMPTY_ITERATOR;
/* get the index of the first child */
int index= queue.indexOf(node.getFirstChild());
/* if we do not have children, just return an empty enumeration */
if (index == -1)
return EMPTY_ITERATOR;
/* create an enumeration with node's children */
List result= new ArrayList(10);
while (true) {
UnifiedTreeNode child= (UnifiedTreeNode)queue.elementAt(index);
if (isChildrenMarker(child))
break;
result.add(child);
index= queue.increment(index);
}
return result.iterator();
}
protected int getLevel() {
return level;
}
protected IFileInfo[] getLocalList(UnifiedTreeNode node) {
try {
final IFileStore store= node.getStore();
IFileInfo[] list= fileTree != null ? fileTree.getChildInfos(store) : store.childInfos(EFS.NONE, null);
if (list == null || list.length == 0)
return NO_CHILDREN;
list= ((Resource)node.getResource()).filterChildren(list, false);
int size= list.length;
if (size > 1)
quickSort(list, 0, size - 1);
return list;
} catch (CoreException e) {
//treat failure to access the directory as a non-existent directory
return NO_CHILDREN;
}
}
protected Workspace getWorkspace() {
return (Workspace)root.getWorkspace();
}
protected void initializeQueue() {
//initialize the queue
if (queue == null)
queue= new Queue(100, false);
else
queue.reset();
//initialize the free nodes list
if (freeNodes == null)
freeNodes= new ArrayList(100);
else
freeNodes.clear();
addRootToQueue();
addElementToQueue(levelMarker);
}
protected boolean isChildrenMarker(UnifiedTreeNode node) {
return node == childrenMarker;
}
protected boolean isLevelMarker(UnifiedTreeNode node) {
return node == levelMarker;
}
private static class PatternHolder {
//Initialize-on-demand Holder class to avoid compiling Pattern if never needed
//Pattern: A UNIX relative path that just points backward
public static Pattern trivialSymlinkPattern= Pattern.compile("\\.[./]*"); //$NON-NLS-1$
}
/**
* Initialize history stores for symbolic links. This may be done when starting a visitor, or
* later on demand.
*/
protected void initLinkHistoriesIfNeeded() {
if (pathPrefixHistory == null) {
//Bug 232426: Check what life cycle we need for the histories
Job job= Job.getJobManager().currentJob();
if (job instanceof RefreshJob) {
//we are running from the RefreshJob: use the path history of the job
RefreshJob refreshJob= (RefreshJob)job;
pathPrefixHistory= refreshJob.getPathPrefixHistory();
rootPathHistory= refreshJob.getRootPathHistory();
} else {
//Local Histories
pathPrefixHistory= new PrefixPool(20);
rootPathHistory= new PrefixPool(20);
}
}
if (rootPathHistory.size() == 0) {
//add current root to history
IFileStore rootStore= ((Resource)root).getStore();
try {
java.io.File rootFile= rootStore.toLocalFile(EFS.NONE, null);
if (rootFile != null) {
IPath rootProjPath= root.getProject().getLocation();
if (rootProjPath != null) {
try {
java.io.File rootProjFile= new java.io.File(rootProjPath.toOSString());
rootPathHistory.insertShorter(rootProjFile.getCanonicalPath() + '/');
} catch (IOException ioe) {
/*ignore here*/
}
}
rootPathHistory.insertShorter(rootFile.getCanonicalPath() + '/');
}
} catch (CoreException e) {
/*ignore*/
} catch (IOException e) {
/*ignore*/
}
}
}
/**
* Check if the given child represents a recursive symbolic link.
* <p>
* On remote EFS stores, this check is not exhaustive and just finds trivial recursive symbolic
* links pointing up in the tree.
* </p>
* <p>
* On local stores, where {@link java.io.File#getCanonicalPath()} is available, the test is
* exhaustive but may also find some false positives with transitive symbolic links. This may
* lead to suppressing duplicates of already known resources in the tree, but it will never lead
* to not finding a resource at all. See bug 105554 for details.
* </p>
*
* @param parentStore EFS IFileStore representing the parent folder
* @param localInfo child representing a symbolic link
* @return <code>true</code> if the given child represents a recursive symbolic link.
*/
private boolean isRecursiveLink(IFileStore parentStore, IFileInfo localInfo) {
//Try trivial pattern first - works also on remote EFS stores
String linkTarget= localInfo.getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET);
if (linkTarget != null && PatternHolder.trivialSymlinkPattern.matcher(linkTarget).matches()) {
return true;
}
//Need canonical paths to check all other possibilities
try {
java.io.File parentFile= parentStore.toLocalFile(EFS.NONE, null);
//If this store cannot be represented as a local file, there is nothing we can do
//In the future, we could try to resolve the link target
//against the remote file system to do more checks.
if (parentFile == null)
return false;
//get canonical path for both child and parent
java.io.File childFile= new java.io.File(parentFile, localInfo.getName());
String parentPath= parentFile.getCanonicalPath() + '/';
String childPath= childFile.getCanonicalPath() + '/';
//get or instantiate the prefix and root path histories.
//Might be done earlier - for now, do it on demand.
initLinkHistoriesIfNeeded();
//insert the parent for checking loops
pathPrefixHistory.insertLonger(parentPath);
if (pathPrefixHistory.containsAsPrefix(childPath)) {
//found a potential loop: is it spanning up a new tree?
if (!rootPathHistory.insertShorter(childPath)) {
//not spanning up a new tree, so it is a real loop.
return true;
}
} else if (rootPathHistory.hasPrefixOf(childPath)) {
//child points into a different portion of the tree that we visited already before, or will certainly visit.
//This does not introduce a loop yet, but introduces duplicate resources.
//TODO Ideally, such duplicates should be modelled as linked resources. See bug 105534
return false;
} else {
//child neither introduces a loop nor points to a known tree.
//It probably spans up a new tree of potential prefixes.
rootPathHistory.insertShorter(childPath);
}
} catch (IOException e) {
//ignore
} catch (CoreException e) {
//ignore
}
return false;
}
protected boolean isValidLevel(int currentLevel, int depth) {
switch (depth) {
case IResource.DEPTH_INFINITE:
return true;
case IResource.DEPTH_ONE:
return currentLevel <= 1;
case IResource.DEPTH_ZERO:
return currentLevel == 0;
default:
return currentLevel + 1000 <= depth;
}
}
/**
* Sorts the given array of strings in place. This is not using the sorting framework to avoid
* casting overhead.
*/
protected void quickSort(IFileInfo[] infos, int left, int right) {
int originalLeft= left;
int originalRight= right;
IFileInfo mid= infos[(left + right) / 2];
do {
while (mid.compareTo(infos[left]) > 0)
left++;
while (infos[right].compareTo(mid) > 0)
right--;
if (left <= right) {
IFileInfo tmp= infos[left];
infos[left]= infos[right];
infos[right]= tmp;
left++;
right--;
}
} while (left <= right);
if (originalLeft < right)
quickSort(infos, originalLeft, right);
if (left < originalRight)
quickSort(infos, left, originalRight);
return;
}
/**
* Remove from the last element of the queue to the first child of the given node.
*/
protected void removeNodeChildrenFromQueue(UnifiedTreeNode node) {
UnifiedTreeNode first= node.getFirstChild();
if (first == null)
return;
while (true) {
if (first.equals(queue.removeTail()))
break;
}
node.setFirstChild(null);
}
/**
* Increases the current tree level by one. Returns true if the new level is still valid for the
* given depth
*/
protected boolean setLevel(int newLevel, int depth) {
level= newLevel;
childLevelValid= isValidLevel(level + 1, depth);
return isValidLevel(level, depth);
}
private void setRoot(IResource root) {
this.root= root;
}
}
| 36.112676 | 130 | 0.688768 |
a491f33fa3276d53a8407e67eef8ec683a1325b8 | 7,818 | /*
MIT License
https://opensource.org/licenses/MIT
Copyright 2020 Lukasz Machowski
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 io.nanovc.merges;
import io.nanovc.CommitAPI;
import io.nanovc.ContentAPI;
import io.nanovc.DifferenceState;
import io.nanovc.RepoPath;
/**
* A merge handler where the last change (in time) wins when a merge conflict is detected.
*/
public abstract class LastWinsMergeEngineBase
extends DiffingMergeEngineBase
implements LastWinsMergeEngineAPI
{
/**
* Resolves the conflict when there were changes for the given content in both the source and destination branches.
*
* @param path The path of the content that is conflicting.
* @param sourceCommit The commit in the source branch that is conflicted.
* @param sourceContent The content in the source branch that is conflicted at this path.
* @param sourceDifference The difference between the common ancestor and the source commit at this path.
* @param destinationCommit The commit in the destination branch that is conflicted.
* @param destinationContent The content in the destination branch that is conflicted at this path.
* @param destinationDifference The difference between the common ancestor and the destination commit at this path.
* @return The merged bytes to use for the resolved conflict. Return null to not include any content in the merged area for this path.
*/
@Override
protected <TContent extends ContentAPI> byte[] resolveConflictForChangesInSourceAndDestinationBranches(RepoPath path, CommitAPI sourceCommit, TContent sourceContent, DifferenceState sourceDifference, CommitAPI destinationCommit, TContent destinationContent, DifferenceState destinationDifference)
{
// Check which commit is last:
if (sourceCommit.getTimestamp().getInstant().isAfter(destinationCommit.getTimestamp().getInstant()))
{
// The source commit is after the destination commit.
return sourceContent.asByteArray();
}
else
{
// The destination commit is after the source commit.
return destinationContent.asByteArray();
}
}
/**
* Resolves the conflict when there were changes for the given content in the source branch but a deletion in the destination branch.
*
* @param path The path of the content that is conflicting.
* @param sourceCommit The commit in the source branch that is conflicted.
* @param sourceContent The content in the source branch that is conflicted at this path.
* @param sourceDifference The difference between the common ancestor and the source commit at this path.
* @param destinationCommit The commit in the destination branch that is conflicted.
* @param destinationDifference The difference between the common ancestor and the destination commit at this path.
* @return The merged bytes to use for the resolved conflict. Return null to not include any content in the merged area for this path.
*/
@Override
protected <TContent extends ContentAPI> byte[] resolveConflictForChangesInSourceBranchButDeletionInDestinationBranch(RepoPath path, CommitAPI sourceCommit, TContent sourceContent, DifferenceState sourceDifference, CommitAPI destinationCommit, DifferenceState destinationDifference)
{
// Check which commit is last:
if (sourceCommit.getTimestamp().getInstant().isAfter(destinationCommit.getTimestamp().getInstant()))
{
// The source commit is after the destination commit.
return sourceContent.asByteArray();
}
else
{
// The destination commit is after the source commit.
return null;
}
}
/**
* Resolves the conflict when there was a deletion of the given content in the source branch but a change in the destination branch.
*
* @param path The path of the content that is conflicting.
* @param sourceCommit The commit in the source branch that is conflicted.
* @param sourceDifference The difference between the common ancestor and the source commit at this path.
* @param destinationCommit The commit in the destination branch that is conflicted.
* @param destinationContent The content in the destination branch that is conflicted at this path.
* @param destinationDifference The difference between the common ancestor and the destination commit at this path.
* @return The merged bytes to use for the resolved conflict. Return null to not include any content in the merged area for this path.
*/
@Override
protected <TContent extends ContentAPI> byte[] resolveConflictForDeletionInSourceBranchButChangeInDestinationBranch(RepoPath path, CommitAPI sourceCommit, DifferenceState sourceDifference, CommitAPI destinationCommit, TContent destinationContent, DifferenceState destinationDifference)
{
// Check which commit is last:
if (sourceCommit.getTimestamp().getInstant().isAfter(destinationCommit.getTimestamp().getInstant()))
{
// The source commit is after the destination commit.
return null;
}
else
{
// The destination commit is after the source commit.
return destinationContent.asByteArray();
}
}
/**
* Resolves the conflict when there were changes for the given content in the source and destination branches when doing a two way merge.
* A two way merge means that neither of the commits shared a common ancestor.
*
* @param path The path of the content that is conflicting.
* @param sourceCommit The commit in the source branch that is conflicted.
* @param destinationCommit The commit in the destination branch that is conflicted.
* @param destinationContent The content in the destination branch that is conflicted at this path.
* @return The merged bytes to use for the resolved conflict.
*/
@Override
protected <TContent extends ContentAPI> byte[] resolveConflictForTwoWayMerge(RepoPath path, CommitAPI sourceCommit, TContent sourceContent, CommitAPI destinationCommit, TContent destinationContent)
{
// Check which commit is last:
if (sourceCommit.getTimestamp().getInstant().isAfter(destinationCommit.getTimestamp().getInstant()))
{
// The source commit is after the destination commit.
return sourceContent.asByteArray();
}
else
{
// The destination commit is after the source commit.
return destinationContent.asByteArray();
}
}
}
| 57.911111 | 461 | 0.718214 |
3fab58b8c48c87e7652247b6e65536c6f6a3f134 | 360 | /**
* remove
*/
public class Testelimpa {
public static void main(String[] args) {
Genics<String> vetor = new Genics<String>();
vetor.adiciona("joão");
vetor.adiciona("maria");
vetor.adiciona("fred");
System.out.println(vetor);
vetor.limpa();
System.out.println(vetor);
}
} | 20 | 52 | 0.536111 |
7cf99743a1d8609f6b189668c5cc058107294b5c | 395 | package com.p2pgate.vk_gate.service.gateways;
import com.p2pgate.lib.domain.PayAccept;
import com.p2pgate.vk_gate.rest.exception.PayApiException;
/**
*
* Created by Олег on 20.09.2019.
*/
public interface GateService {
String refillWalletConfirm(String md, String PaRes, String payment_id) throws PayApiException;
String refillWallet(PayAccept request) throws PayApiException;
}
| 23.235294 | 98 | 0.782278 |
0913c02b0f485730f23325186727e072eaa6d48c | 1,398 | package com.nmfzone.app.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
@Table(name="users")
@Entity
public class User implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id")
private Long id;
@NotEmpty
@Column(name="name")
private String name;
@NotNull
@Column(name="age")
private int age;
public User() {}
//@PersistenceConstructor
public User(String name, int age)
{
this.name = name;
this.age = age;
}
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
@Override
public String toString()
{
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
| 17.259259 | 74 | 0.61588 |
287c953e82d8c95326b4bd9e1c6a37231db01992 | 1,043 | package com.vpr.server.security;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
public class Hasher {
public static byte[] HashPassword(String password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
// Credit: https://www.baeldung.com/java-password-hashing
// Generate hash with PBKDF2
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
return factory.generateSecret(spec).getEncoded();
}
public static byte[] GenerateSalt(){
// Credit: https://www.baeldung.com/java-password-hashing
// Create a salt
SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);
return salt;
}
}
| 35.965517 | 126 | 0.718121 |
23aaca61d9b519fdbbfd5f343ac0a9df1c4940b0 | 3,938 | /**
* Copyright (C) 2014 Karlsruhe Institute of Technology
*
*
* 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.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.kit.dama.mdm.dataorganization.impl.jpa;
import edu.kit.dama.authorization.entities.IAuthorizationContext;
import edu.kit.dama.authorization.exceptions.UnauthorizedAccessAttemptException;
import edu.kit.dama.commons.types.DigitalObjectId;
import edu.kit.dama.mdm.core.IMetaDataManager;
import edu.kit.dama.mdm.core.MetaDataManagement;
import edu.kit.dama.mdm.dataorganization.entity.core.ICollectionNode;
import edu.kit.dama.mdm.dataorganization.entity.core.IDataOrganizationNode;
import edu.kit.dama.mdm.dataorganization.entity.core.IFileNode;
import edu.kit.dama.mdm.dataorganization.impl.jpa.persistence.PersistenceFacade;
import edu.kit.dama.mdm.dataorganization.service.exception.DataOrganizationError;
/**
* Utility functions for the JPA implementation.
*
* @author pasic
*/
public final class JPAImplUtil {
/**
* Hidden constructor.
*/
private JPAImplUtil() {
}
/**
* Converts some IDataOrganizationNode to JPA data organization node.
*
* @param pDataOrganizationNode the node to be converted.
*
* @return a corresponding JPA data organization node.
*/
public static DataOrganizationNode convertDataOrganizationNode(IDataOrganizationNode pDataOrganizationNode) {
DataOrganizationNode newDon = null;
if (null == pDataOrganizationNode) {
return null;
}
if (pDataOrganizationNode instanceof DataOrganizationNode) {
if (pDataOrganizationNode instanceof FileTree) {
newDon = new CollectionNode((ICollectionNode) pDataOrganizationNode);
} else {
newDon = (DataOrganizationNode) pDataOrganizationNode;
}
} else if (pDataOrganizationNode instanceof ICollectionNode) {
newDon = new CollectionNode((ICollectionNode) pDataOrganizationNode);
} else if (pDataOrganizationNode instanceof IFileNode) {
newDon = new FileNode((IFileNode) pDataOrganizationNode);
}
if (null == newDon) {
throw new DataOrganizationError("node:IDataOrganizationNode should be either"
+ " instance of IFileNode or instance of ICollectionNode");
}
return newDon;
}
public static int renameView(DigitalObjectId pObjectId, String pOldName, String pNewName, IAuthorizationContext pContext) throws UnauthorizedAccessAttemptException {
String pu = PersistenceFacade.getInstance().getPersistenceUnitName();
IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager(pu);
mdm.setAuthorizationContext(pContext);
try {
// int attribChanges = mdm.performUpdate("UPDATE Attribute a SET a.viewName=?1 WHERE a.annotatedNode.digitalObjectIDStr=?2 AND a.annotatedNode.viewName=?3", new Object[]{pNewName, pObjectId.getStringRepresentation(), pOldName});
// System.out.println("CHANGE " + attribChanges);
return mdm.performUpdate("UPDATE DataOrganizationNode n SET n.viewName=?1 WHERE n.digitalObjectIDStr=?2 AND n.viewName=?3", new Object[]{pNewName, pObjectId.getStringRepresentation(), pOldName});
} finally {
mdm.close();
}
}
}
| 43.755556 | 241 | 0.718385 |
214ccaaf350ab97af258fe7c7946a5d3adcc02ce | 3,824 | package com.bloomhousemc.thermus.common.items;
import com.bloomhousemc.thermus.common.blocks.boiler.BoilerBlock;
import com.bloomhousemc.thermus.common.blocks.boiler.BoilerBlockEntity;
import com.bloomhousemc.thermus.common.components.ITemperature;
import net.minecraft.block.BlockState;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUsageContext;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.TypedActionResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class DebugThermusItem extends Item {
public DebugThermusItem(Settings settings) {
super(settings);
}
@Override
public ActionResult useOnBlock(ItemUsageContext context) {
if(context.getWorld().isClient || context.getPlayer().isSneaking())return ActionResult.PASS;
BlockPos blockPos = context.getBlockPos();
BlockState blockState = context.getWorld().getBlockState(blockPos);
if(blockState.getBlock() instanceof BoilerBlock boilerBlock){
//context.getWorld().setBlockState(blockPos, blockState.with(LIT, !blockState.get(LIT)));
BoilerBlockEntity boilerBlockEntity = (BoilerBlockEntity) context.getWorld().getBlockEntity(blockPos);
System.out.println(boilerBlockEntity.getItems());
}
try {
double i = ITemperature.get(blockState).getTemperature();
System.out.println("Temperature: "+i);
}catch(Exception e){
System.out.println("Did not find temperature in target");
}
try {
double i = ITemperature.get(blockState).getTemperatureModifier();
System.out.println("TemperatureModifier: "+i);
}catch(Exception e){
System.out.println("Did not find modifier in target");
}
try {
double i = ITemperature.get(blockState).getTargetTemperature();
System.out.println("Target Temperature: "+i);
}catch(Exception e){
System.out.println("Did not find targetTemperature in target");
}
return ActionResult.PASS;
}
@Override
public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) {
if (!world.isClient) {
if (user.isSneaking()) {
try {
double i = ITemperature.get(user).getTemperature();
System.out.println("Temperature: " + i);
} catch (Exception e) {
System.out.println("Did not find temperature in you");
}
try {
double i = ITemperature.get(user).getTemperatureModifier();
System.out.println("Temperature Modifier: " + i);
} catch (Exception e) {
System.out.println("Did not find temperatureModifier in you");
}
try {
double i = ITemperature.get(user).getTargetTemperature();
System.out.println("Target Temperature: " + i);
} catch (Exception e) {
System.out.println("Did not find targetTemperature in you");
}
}
}
return TypedActionResult.pass(user.getStackInHand(hand));
}
@Override
public void appendTooltip(ItemStack stack, @Nullable World world, List<Text> tooltip, TooltipContext context) {
tooltip.add(new TranslatableText("Shift-click to use on self"));
}
}
| 39.42268 | 115 | 0.644613 |
c8716b8c00c008d646b43a99ec35f9c0ce76a646 | 2,306 | package com.tesco.crypt.kmip.operation.model.messages.getattributes;
import com.tesco.crypt.kmip.operation.model.attributes.Attributes;
import com.tesco.crypt.kmip.operation.model.messages.ResponseBatchItem;
import com.tesco.crypt.kmip.ttlv.model.Structure;
import com.tesco.crypt.kmip.ttlv.model.TTLV;
import com.tesco.crypt.kmip.ttlv.model.enums.enumerations.Operation;
import com.tesco.crypt.kmip.ttlv.model.values.TextStringValue;
import lombok.Data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static com.tesco.crypt.kmip.operation.TTLVToBatchItemsDecoder.checkAndCast;
import static com.tesco.crypt.kmip.operation.TTLVToBatchItemsDecoder.invalidMessageTag;
import static com.tesco.crypt.kmip.ttlv.model.enums.MessageTag.ATTRIBUTE;
import static com.tesco.crypt.kmip.ttlv.model.enums.MessageTag.UNIQUE_IDENTIFIER;
@Data
public class GetAttributesResponse extends ResponseBatchItem {
private String objectId;
private Attributes attributes;
@Override
public Operation getOperation() {
return Operation.GET_ATTRIBUTES;
}
@Override
public void decode(List<TTLV> payloadItems) {
for (TTLV payloadItem : payloadItems) {
switch (payloadItem.getTag()) {
case UNIQUE_IDENTIFIER:
objectId = checkAndCast(payloadItem, TextStringValue.class).getValue();
break;
case ATTRIBUTE:
if (attributes == null) {
attributes = new Attributes();
}
attributes.decode(checkAndCast(payloadItem, Structure.class).getTtlvs());
break;
default:
invalidMessageTag(payloadItem, Arrays.asList(UNIQUE_IDENTIFIER, ATTRIBUTE));
}
}
}
@Override
public List<TTLV> encode() {
List<TTLV> payload = new ArrayList<>();
if (objectId != null) {
payload.add(
new TextStringValue()
.setValue(objectId)
.setTag(UNIQUE_IDENTIFIER)
);
}
if (attributes != null) {
payload.addAll(attributes.encode());
}
return getOperationResponse(payload, getOperation());
}
}
| 34.939394 | 96 | 0.649176 |
9b5beeff610d84eaf21d14e727592d23ddd3da56 | 4,186 | /*
* 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 view.animal;
import controller.AnimalController;
import controller.ClienteController;
import java.util.ArrayList;
import javax.swing.RowSorter;
import javax.swing.SortOrder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import model.Animal;
import model.ClienteAnimal;
/**
*
* @author kairos-04
*/
public class ListarAnimais extends javax.swing.JInternalFrame {
ArrayList<ClienteAnimal> listaAnimaisDonos = new ArrayList<>();
AnimalController animalController = new AnimalController();
ClienteController clienteController = new ClienteController();
Animal animal = new Animal();
ClienteAnimal clienteAnimal = new ClienteAnimal();
/**
* Creates new form ListarAnimais
*/
public ListarAnimais() {
initComponents();
String colunas[] = {"ID", "Nome", "Espécie", "Raça", "Idade", "Dono - Telefone"};
Object data[][] = {};
DefaultTableModel modelo = new DefaultTableModel(data, colunas);
jTable1.setModel(modelo);
jTable1.setAutoCreateRowSorter(true);
jTable1.getColumnModel().getColumn(0).setMaxWidth(40);
jTable1.getColumnModel().getColumn(0).setMinWidth(40);
jTable1.getColumnModel().getColumn(4).setMaxWidth(50);
jTable1.getColumnModel().getColumn(4).setMinWidth(50);
//ordenando pela coluna de nome
TableRowSorter<TableModel> sorter = new TableRowSorter<>(jTable1.getModel());
jTable1.setRowSorter(sorter);
ArrayList<RowSorter.SortKey> sortKeys = new ArrayList<>();
int columnIndexToSort = 1;
sortKeys.add(new RowSorter.SortKey(columnIndexToSort, SortOrder.ASCENDING));
sorter.setSortKeys(sortKeys);
sorter.sort();
listaAnimaisDonos = animalController.pegarAnimaisComDonos(clienteAnimal);
for (ClienteAnimal ca : listaAnimaisDonos) {
modelo.addRow(new Object[]{
ca.getIdAnimal(),
ca.getNomeAnimal(),
ca.getEspecieAnimal(),
ca.getRacaAnimal(),
ca.getIdadeAnimal(),
ca.getNomeDono() + " - " + ca.getTelefoneDono()
});
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
setBorder(null);
setClosable(true);
setTitle("Clínica Veterinária - Todos os Animais");
setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/book_open.png"))); // NOI18N
jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 895, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 383, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
}
| 37.044248 | 124 | 0.682991 |
3016bf5fe9d4e0363e28f2bc3c34f660aa83695c | 1,972 | package com.njqg.orchard.library_core.utils;
import android.content.Context;
import android.util.Log;
/**
* description:
* author: hans
* date: 2017/7/25
* e-mail: hxxx1992@163.com
*/
public class LogUtils {
public static void e(Context context, String log) {
if (LibConstant.IS_DEBUG_MODE) {
try {
Log.e(context.getClass().getSimpleName(), log);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
public static void e(String log) {
if (LibConstant.IS_DEBUG_MODE) {
try {
Log.e("log", log);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
public static void e(String tag, String str) {
if (LibConstant.IS_DEBUG_MODE) {
try {
Log.e(tag, str);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
public static void w(String tag, String str) {
if (LibConstant.IS_DEBUG_MODE) {
try {
Log.w(tag, str);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
public static void i(String tag, String str) {
if (LibConstant.IS_DEBUG_MODE) {
try {
Log.i(tag, str);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
public static void d(String tag, String str) {
if (LibConstant.IS_DEBUG_MODE) {
try {
Log.d(tag, str);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
public static void v(String tag, String str) {
if (LibConstant.IS_DEBUG_MODE) {
try {
Log.v(tag, str);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
}
| 23.47619 | 63 | 0.461968 |
a4abff4a809a28e348c4d86a2bbc38aa50ef3a3a | 271 | package contagionJVM.NWNX;
public class VariableType {
public static final int IntVar = 1;
public static final int FloatVar = 2;
public static final int StringVar = 3;
public static final int ObjectVar = 4;
public static final int LocationVar = 5;
}
| 27.1 | 44 | 0.715867 |
96f5254b496aa54c066c14cbcc59e337698a7491 | 2,226 | package collections.core.hierarchy;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
public class Hierarchy {
public static void main(String[] args) {
// the super interface
Collection collection;
// List interface
// extends the Collection interface
// insertion order preserver
// duplicates allowed
List list;
// classes that implement List, subclasses
ArrayList arrayList;
LinkedList linkedList;
Vector vector; Stack stack; // Stack extends Vector
// Set interface
// extends the Collection interface
// insertion order is not preserved
// duplicates are not allowed
Set set;
// classes/interfaces that implement/extend Set, subclasses/subinterfaces
HashSet hashSet; LinkedHashSet linkedHashSet; // LinkedHashSet extends HashSet
SortedSet sortedSet; NavigableSet navigableSet; TreeSet treeSet; // TreeSet implements NavigableSet that extends SortedSet
// Queue interface
// extends the Collection interface
// prior to proccessment
// first in first out order
Queue queue;
// classes that implement/extend Queue, subclasses
PriorityQueue priorityQueue;
BlockingQueue blockingQueue; LinkedBlockingQueue linkedBlockingQueue;PriorityBlockingQueue priorityBlockingQueue; // both implement BlockingQueue
// Map interface
// does not extend the Collection interface
// key: value pairs
Map map;
// classes/interfaces that implement/extend Map, subclasses/subinterfaces
HashMap hashMap; LinkedHashMap linkedHashMap; // LinkedHashMap extend HashMap
WeakHashMap weakHashMap;
IdentityHashMap identityHashMap;
Dictionary dictionary; /* ---- */ Hashtable hashtable; Properties properties; // Properties extend HashTable that extends abstract Dictionary and implements Map
SortedMap sortedMap; NavigableMap navigableMap; TreeMap treeMap; // TreeMap implements NavigableMap that extends SortedMap
}
}
| 34.78125 | 168 | 0.701258 |
6075a7c627d52f3417ab978875be25b5c5172be1 | 11,075 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package se.semmi.midiassistant;
/*
* MidiInDump.java
*
* This file is part of jsresources.org
*/
/*
* Copyright (c) 1999 - 2001 by Matthias Pfisterer
* Copyright (c) 2003 by Florian Bomers
* 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.
*
* 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.
*/
/*
|<--- this code is formatted to fit into 80 columns --->|
*/
import java.io.IOException;
import javax.sound.midi.Transmitter;
import javax.sound.midi.Receiver;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Synthesizer;
/* If the compilation fails because this class is not available,
get gnu.getopt from the URL given in the comment below.
*/
//import gnu.getopt.Getopt;
/** <titleabbrev>MidiInDump</titleabbrev>
<title>Listens to a MIDI port and dump the received event to the console</title>
<formalpara><title>Purpose</title>
<para>Listens to a MIDI port and dump the received event to the console.</para></formalpara>
<formalpara><title>Usage</title>
<para>
<cmdsynopsis>
<command>java MidiInDump</command>
<arg choice="plain"><option>-l</option></arg>
</cmdsynopsis>
<cmdsynopsis>
<command>java MidiInDump</command>
<arg choice="plain"><option>-d <replaceable>devicename</replaceable></option></arg>
<arg choice="plain"><option>-n <replaceable>device#</replaceable></option></arg>
</cmdsynopsis>
</para></formalpara>
<formalpara><title>Parameters</title>
<variablelist>
<varlistentry>
<term><option>-l</option></term>
<listitem><para>list the availabe MIDI devices</para></listitem>
</varlistentry>
<varlistentry>
<term><option>-d <replaceable>devicename</replaceable></option></term>
<listitem><para>reads from named device (see <option>-l</option>)</para></listitem>
</varlistentry>
<varlistentry>
<term><option>-n <replaceable>device#</replaceable></option></term>
<listitem><para>reads from device with given index (see <option>-l</option>)</para></listitem>
</varlistentry>
</variablelist>
</formalpara>
<formalpara><title>Bugs, limitations</title>
<para>
For the Sun J2SDK 1.3.x or 1.4.0, MIDI IN does not work. See the <olink targetdoc="faq_midi" targetptr="faq_midi">FAQ</olink> for alternatives.
</para></formalpara>
<formalpara><title>Source code</title>
<para>
<ulink url="MidiInDump.java.html">MidiInDump.java</ulink>,
<ulink url="DumpReceiver.java.html">DumpReceiver.java</ulink>,
<ulink url="MidiCommon.java.html">MidiCommon.java</ulink>,
<ulink url="http://www.urbanophile.com/arenn/hacking/download.html">gnu.getopt.Getopt</ulink>
</para>
</formalpara>
*/
public class MidiDump {
/** Flag for debugging messages.
If true, some messages are dumped to the console
during operation.
*/
private static boolean DEBUG = true;
public static void main(String[] args)
throws Exception {
/*
* The device name/index to listen to.
*/
String strDeviceName = null;
int nDeviceIndex = -1;
boolean bUseDefaultSynthesizer = false;
// TODO: synchronize options with MidiPlayer
//MidiCommon.listDevicesAndExit(true, false);
//MidiCommon.getMidiDeviceInfo(nDeviceIndex);
MidiDevice.Info[] aInfos = MidiSystem.getMidiDeviceInfo();
for (int i = 0; i < aInfos.length; i++) {
try {
MidiDevice device = MidiSystem.getMidiDevice(aInfos[i]);
boolean bAllowsInput = (device.getMaxTransmitters() != 0);
boolean bAllowsOutput = (device.getMaxReceivers() != 0);
System.out.println("" + i + " "
+ (bAllowsInput ? "IN " : " ")
+ (bAllowsOutput ? "OUT " : " ")
+ aInfos[i].getName() + ", "
+ aInfos[i].getVendor() + ", "
+ aInfos[i].getVersion() + ", "
+ aInfos[i].getDescription());
} catch (MidiUnavailableException e) {
// device is obviously not available...
out(e);
}
}
if (aInfos.length == 0) {
out("[No devices available]");
}
MidiDevice.Info info;
info = MidiCommon.getMidiDeviceInfo(4);
MidiDevice inputDevice = null;
try {
inputDevice = MidiSystem.getMidiDevice(info);
inputDevice.open();
} catch (MidiUnavailableException e) {
out(e);
}
if (inputDevice == null) {
out("wasn't able to retrieve MidiDevice");
System.exit(1);
}
Receiver r = new DumpReceiver(System.out);
try {
Transmitter t = inputDevice.getTransmitter();
t.setReceiver(r);
} catch (MidiUnavailableException e) {
out("wasn't able to connect the device's Transmitter to the Receiver:");
out(e);
inputDevice.close();
System.exit(1);
}
while (1==1) {
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
System.out.println(ex);
}
}
/*
* Parsing of command-line options takes place...
*/
/*
Getopt g = new Getopt("MidiInDump", args, "hlsd:n:D");
int c;
while ((c = g.getopt()) != -1)
{
switch (c)
{
case 'h':
printUsageAndExit();
case 'l':
MidiCommon.listDevicesAndExit(true, false);
case 's':
bUseDefaultSynthesizer = true;
break;
case 'd':
strDeviceName = g.getOptarg();
if (DEBUG) { out("MidiInDump.main(): device name: " + strDeviceName); }
break;
case 'n':
nDeviceIndex = Integer.parseInt(g.getOptarg());
if (DEBUG) { out("MidiInDump.main(): device index: " + nDeviceIndex); }
break;
case 'D':
DEBUG = true;
break;
case '?':
printUsageAndExit();
default:
out("MidiInDump.main(): getopt() returned " + c);
break;
}
}
if ((strDeviceName == null) && (nDeviceIndex < 0))
{
out("device name/index not specified!");
printUsageAndExit();
}
MidiDevice.Info info;
if (strDeviceName != null)
{
info = MidiCommon.getMidiDeviceInfo(strDeviceName, false);
}
else
{
info = MidiCommon.getMidiDeviceInfo(nDeviceIndex);
}
if (info == null)
{
if (strDeviceName != null)
{
out("no device info found for name " + strDeviceName);
}
else
{
out("no device info found for index " + nDeviceIndex);
}
System.exit(1);
}
MidiDevice inputDevice = null;
try
{
inputDevice = MidiSystem.getMidiDevice(info);
inputDevice.open();
}
catch (MidiUnavailableException e)
{
out(e);
}
if (inputDevice == null)
{
out("wasn't able to retrieve MidiDevice");
System.exit(1);
}
Receiver r = new DumpReceiver(System.out);
try
{
Transmitter t = inputDevice.getTransmitter();
t.setReceiver(r);
}
catch (MidiUnavailableException e)
{
out("wasn't able to connect the device's Transmitter to the Receiver:");
out(e);
inputDevice.close();
System.exit(1);
}
if (bUseDefaultSynthesizer)
{
Synthesizer synth = MidiSystem.getSynthesizer();
synth.open();
r = synth.getReceiver();
try
{
Transmitter t = inputDevice.getTransmitter();
t.setReceiver(r);
}
catch (MidiUnavailableException e)
{
out("wasn't able to connect the device's Transmitter to the default Synthesizer:");
out(e);
inputDevice.close();
System.exit(1);
}
}
out("now running; interupt the program with [ENTER] when finished");
try
{
System.in.read();
}
catch (IOException ioe)
{
}
inputDevice.close();
out("Received "+((DumpReceiver) r).seCount+" sysex messages with a total of "+((DumpReceiver) r).seByteCount+" bytes");
out("Received "+((DumpReceiver) r).smCount+" short messages with a total of "+((DumpReceiver) r).smByteCount+" bytes");
out("Received a total of "+(((DumpReceiver) r).smByteCount + ((DumpReceiver) r).seByteCount)+" bytes");
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
if (DEBUG) { out(e); }
}
*
*/
}
private static void printUsageAndExit() {
out("MidiInDump: usage:");
out(" java MidiInDump -h");
out(" gives help information");
out(" java MidiInDump -l");
out(" lists available MIDI devices");
out(" java MidiInDump [-D] [-d <input device name>] [-n <device index>]");
out(" -d <input device name>\treads from named device (see '-l')");
out(" -n <input device index>\treads from device with given index(see '-l')");
out(" -D\tenables debugging output");
System.exit(1);
}
private static void out(String strMessage) {
System.out.println(strMessage);
}
private static void out(Throwable t) {
if (DEBUG) {
t.printStackTrace();
} else {
out(t.toString());
}
}
}
/*** MidiInDump.java ***/
| 30.935754 | 143 | 0.591061 |
98879909dfac413d7fe3bb191584ae146d8ae34a | 322 | package com.example.jpaexamples.example06.fetch.repository;
import com.example.jpaexamples.example06.fetch.entity.User06;
import com.example.jpaexamples.repository.BaseRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface User06Repository extends BaseRepository<User06, Integer> {
}
| 32.2 | 75 | 0.854037 |
9b028f9e508435e6ecd8fe1a6ea72df1db6c2722 | 29,027 | package de.kaffeemitkoffein.tinyweatherforecastgermany;
/**
* IMPORTANT NOTE: this class is work in progress and not used yet. It will unify all the single ContentProviders.
*/
import android.content.*;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
public class WeatherContentProvider extends ContentProvider {
static final String AUTHORITY = "de.kaffeemitkoffein.tinyweatherforecastgermany";
public static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "weather";
private SQLiteDatabase database;
public static final String TABLE_NAME_FORECASTS = "forecasts";
public static final String TABLE_NAME_WARNINGS = "warnings";
public static final String TABLE_NAME_TEXTS = "texts";
public static final String TABLE_NAME_AREAS = "areas";
private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
private static final int URICODE_FORECAST_SINGLE = 10;
private static final int URICODE_FORECAST_ALL = 11;
private static final int URICODE_WARNING_SINGLE = 20;
private static final int URICODE_WARNING_ALL = 21;
private static final int URICODE_TEXT_SINGLE = 30;
private static final int URICODE_TEXT_ALL = 31;
private static final int URICODE_AREA_SINGLE = 40;
private static final int URICODE_AREA_ALL = 41;
static {
uriMatcher.addURI(AUTHORITY, TABLE_NAME_FORECASTS, URICODE_FORECAST_SINGLE);
uriMatcher.addURI(AUTHORITY, TABLE_NAME_FORECASTS+"/*", URICODE_FORECAST_ALL);
uriMatcher.addURI(AUTHORITY, TABLE_NAME_WARNINGS, URICODE_WARNING_SINGLE);
uriMatcher.addURI(AUTHORITY, TABLE_NAME_WARNINGS+"/*", URICODE_WARNING_ALL);
uriMatcher.addURI(AUTHORITY, TABLE_NAME_TEXTS, URICODE_TEXT_SINGLE);
uriMatcher.addURI(AUTHORITY, TABLE_NAME_TEXTS+"/*", URICODE_TEXT_ALL);
uriMatcher.addURI(AUTHORITY, TABLE_NAME_AREAS, URICODE_AREA_SINGLE);
uriMatcher.addURI(AUTHORITY, TABLE_NAME_AREAS+"/*", URICODE_AREA_ALL);
}
@Override
public boolean onCreate() {
Context context = getContext();
WeatherDatabaseHelper weatherDatabaseHelper = new WeatherDatabaseHelper(context);
database = weatherDatabaseHelper.getWritableDatabase();
if (database!=null){
return true;
}
return false;
}
private String getTablenameFromUri(Uri uri) throws IllegalArgumentException{
String tableName="";
switch (uriMatcher.match(uri)){
case URICODE_FORECAST_SINGLE:
case URICODE_FORECAST_ALL :
tableName = TABLE_NAME_FORECASTS; break;
case URICODE_WARNING_SINGLE :
case URICODE_WARNING_ALL :
tableName=TABLE_NAME_WARNINGS; break;
case URICODE_TEXT_SINGLE :
case URICODE_TEXT_ALL :
tableName=TABLE_NAME_TEXTS; break;
case URICODE_AREA_SINGLE :
case URICODE_AREA_ALL :
tableName=TABLE_NAME_AREAS; break;
default: throw new IllegalArgumentException("Unknown Uri: "+uri);
}
return tableName;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) throws IllegalArgumentException{
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(getTablenameFromUri(uri));
Cursor c = qb.query(database,projection,selection,selectionArgs,null,null,sortOrder);
return c;
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues contentValues) throws IllegalArgumentException{
String tableName=getTablenameFromUri(uri);
long rowId = database.insert(tableName,null,contentValues);
// generate single item uri
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.authority(AUTHORITY);
switch (uriMatcher.match(uri)){
case URICODE_FORECAST_SINGLE:
case URICODE_FORECAST_ALL :
uriBuilder.appendPath(TABLE_NAME_FORECASTS); break;
case URICODE_WARNING_SINGLE :
case URICODE_WARNING_ALL :
uriBuilder.appendPath(TABLE_NAME_WARNINGS); break;
case URICODE_TEXT_SINGLE :
case URICODE_TEXT_ALL :
uriBuilder.appendPath(TABLE_NAME_TEXTS); break;
case URICODE_AREA_SINGLE :
case URICODE_AREA_ALL :
uriBuilder.appendPath(TABLE_NAME_AREAS); break;
default: throw new IllegalArgumentException("Unknown Uri: "+uri);
}
Uri uriResult = uriBuilder.build();
uriResult = ContentUris.withAppendedId(uriResult,rowId);
return uriResult;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
String tableName=getTablenameFromUri(uri);
int numberDeleted = database.delete(tableName,selection,selectionArgs);
return numberDeleted;
}
@Override
public int update(Uri uri, ContentValues contentValues, String selection, String[] selectionArgs) {
String tableName=getTablenameFromUri(uri);
int numberUpdated = database.update(tableName,contentValues,selection,selectionArgs);
return numberUpdated;
}
public static class WeatherDatabaseHelper extends SQLiteOpenHelper {
public static final String SQL_COMMAND_DROP_TABLE_FORECASTS = "DROP TABLE IF EXISTS " + TABLE_NAME_FORECASTS;
public static final String SQL_COMMAND_DROP_TABLE_WARNINGS = "DROP TABLE IF EXISTS " + TABLE_NAME_WARNINGS;
public static final String SQL_COMMAND_DROP_TABLE_TEXTS = "DROP TABLE IF EXISTS " + TABLE_NAME_TEXTS;
public static final String SQL_COMMAND_DROP_TABLE_AREAS = "DROP TABLE IF EXISTS " + TABLE_NAME_AREAS;
/*
* SQL Data for the Forecasts
*/
public static final String KEY_FORECASTS_id="id";
public static final String KEY_FORECASTS_timetext="timetext";
public static final String KEY_FORECASTS_timestamp="timestamp";
public static final String KEY_FORECASTS_name="name";
public static final String KEY_FORECASTS_description="description";
public static final String KEY_FORECASTS_longitude="longitude";
public static final String KEY_FORECASTS_latitude="latitude";
public static final String KEY_FORECASTS_altitude="altitude";
public static final String KEY_FORECASTS_polling_time="polling_time";
public static final String KEY_FORECASTS_elements="elements";
public static final String KEY_FORECASTS_timesteps="timesteps";
public static final String KEY_FORECASTS_TTT="TTT";
public static final String KEY_FORECASTS_E_TTT="E_TTT";
public static final String KEY_FORECASTS_T5cm="T5cm";
public static final String KEY_FORECASTS_Td="Td";
public static final String KEY_FORECASTS_E_Td="E_Td";
public static final String KEY_FORECASTS_Tx="Tx";
public static final String KEY_FORECASTS_Tn="Tn";
public static final String KEY_FORECASTS_TM="TM";
public static final String KEY_FORECASTS_TG="TG";
public static final String KEY_FORECASTS_DD="DD";
public static final String KEY_FORECASTS_E_DD="E_DD";
public static final String KEY_FORECASTS_FF="FF";
public static final String KEY_FORECASTS_E_FF="E_FF";
public static final String KEY_FORECASTS_FX1="FX1";
public static final String KEY_FORECASTS_FX3="FX3";
public static final String KEY_FORECASTS_FXh="FXh";
public static final String KEY_FORECASTS_FXh25="FXh25";
public static final String KEY_FORECASTS_FXh40="FXh40";
public static final String KEY_FORECASTS_FXh55="FXh55";
public static final String KEY_FORECASTS_FX625="FX625";
public static final String KEY_FORECASTS_FX640="FX640";
public static final String KEY_FORECASTS_FX655="FX655";
public static final String KEY_FORECASTS_RR1c="RR1c";
public static final String KEY_FORECASTS_RRL1c="RRL1c";
public static final String KEY_FORECASTS_RR3="RR3";
public static final String KEY_FORECASTS_RR6="RR6";
public static final String KEY_FORECASTS_RR3c="RR3c";
public static final String KEY_FORECASTS_RR6c="RR6c";
public static final String KEY_FORECASTS_RRhc="RRhc";
public static final String KEY_FORECASTS_RRdc="RRdc";
public static final String KEY_FORECASTS_RRS1c="RRS1c";
public static final String KEY_FORECASTS_RRS3c="RRS3c";
public static final String KEY_FORECASTS_R101="R101";
public static final String KEY_FORECASTS_R102="R102";
public static final String KEY_FORECASTS_R103="R103";
public static final String KEY_FORECASTS_R105="R105";
public static final String KEY_FORECASTS_R107="R107";
public static final String KEY_FORECASTS_R110="R110";
public static final String KEY_FORECASTS_R120="R120";
public static final String KEY_FORECASTS_R130="R130";
public static final String KEY_FORECASTS_R150="R150";
public static final String KEY_FORECASTS_RR1o1="RR1o1";
public static final String KEY_FORECASTS_RR1w1="RR1w1";
public static final String KEY_FORECASTS_RR1u1="RR1u1";
public static final String KEY_FORECASTS_R600="R600";
public static final String KEY_FORECASTS_Rh00="Rh00";
public static final String KEY_FORECASTS_R602="R602";
public static final String KEY_FORECASTS_Rh02="Rh02";
public static final String KEY_FORECASTS_Rd02="Rd02";
public static final String KEY_FORECASTS_R610="R610";
public static final String KEY_FORECASTS_Rh10="Rh10";
public static final String KEY_FORECASTS_R650="R650";
public static final String KEY_FORECASTS_Rh50="Rh50";
public static final String KEY_FORECASTS_Rd00="Rd00";
public static final String KEY_FORECASTS_Rd10="Rd10";
public static final String KEY_FORECASTS_Rd50="Rd50";
public static final String KEY_FORECASTS_wwPd="wwPd";
public static final String KEY_FORECASTS_DRR1="DRR1";
public static final String KEY_FORECASTS_wwZ="wwZ";
public static final String KEY_FORECASTS_wwZ6="wwZ6";
public static final String KEY_FORECASTS_wwZh="wwZh";
public static final String KEY_FORECASTS_wwD="wwD";
public static final String KEY_FORECASTS_wwD6="wwD6";
public static final String KEY_FORECASTS_wwDh="wwDh";
public static final String KEY_FORECASTS_wwC="wwC";
public static final String KEY_FORECASTS_wwC6="wwC6";
public static final String KEY_FORECASTS_wwCh="wwCh";
public static final String KEY_FORECASTS_wwT="wwT";
public static final String KEY_FORECASTS_wwT6="wwT6";
public static final String KEY_FORECASTS_wwTh="wwTh";
public static final String KEY_FORECASTS_wwTd="wwTd";
public static final String KEY_FORECASTS_wwL="wwL";
public static final String KEY_FORECASTS_wwL6="wwL6";
public static final String KEY_FORECASTS_wwLh="wwLh";
public static final String KEY_FORECASTS_wwS="wwS";
public static final String KEY_FORECASTS_wwS6="wwS6";
public static final String KEY_FORECASTS_wwSh="wwSh";
public static final String KEY_FORECASTS_wwF="wwF";
public static final String KEY_FORECASTS_wwF6="wwF6";
public static final String KEY_FORECASTS_wwFh="wwFh";
public static final String KEY_FORECASTS_wwP="wwP";
public static final String KEY_FORECASTS_wwP6="wwP6";
public static final String KEY_FORECASTS_wwPh="wwPh";
public static final String KEY_FORECASTS_VV10="VV10";
public static final String KEY_FORECASTS_ww="ww";
public static final String KEY_FORECASTS_ww3="ww3";
public static final String KEY_FORECASTS_W1W2="W1W2";
public static final String KEY_FORECASTS_WPc11="WPc11";
public static final String KEY_FORECASTS_WPc31="WPc31";
public static final String KEY_FORECASTS_WPc61="WPc61";
public static final String KEY_FORECASTS_WPch1="WPch1";
public static final String KEY_FORECASTS_WPcd1="WPcd1";
public static final String KEY_FORECASTS_N="N";
public static final String KEY_FORECASTS_N05="N05";
public static final String KEY_FORECASTS_Nl="Nl";
public static final String KEY_FORECASTS_Nm="Nm";
public static final String KEY_FORECASTS_Nh="Nh";
public static final String KEY_FORECASTS_Nlm="Nlm";
public static final String KEY_FORECASTS_H_BsC="H_BsC";
public static final String KEY_FORECASTS_PPPP="PPPP";
public static final String KEY_FORECASTS_E_PPP="E_PPP";
public static final String KEY_FORECASTS_RadS3="RadS3";
public static final String KEY_FORECASTS_RRad1="RRad1";
public static final String KEY_FORECASTS_Rad1h="Rad1h";
public static final String KEY_FORECASTS_RadL3="RadL3";
public static final String KEY_FORECASTS_VV="VV";
public static final String KEY_FORECASTS_D1="D1";
public static final String KEY_FORECASTS_SunD="SunD";
public static final String KEY_FORECASTS_SunD3="SunD3";
public static final String KEY_FORECASTS_RSunD="RSunD";
public static final String KEY_FORECASTS_PSd00="PSd00";
public static final String KEY_FORECASTS_PSd30="PSd30";
public static final String KEY_FORECASTS_PSd60="PSd60";
public static final String KEY_FORECASTS_wwM="wwM";
public static final String KEY_FORECASTS_wwM6="wwM6";
public static final String KEY_FORECASTS_wwMh="wwMh";
public static final String KEY_FORECASTS_wwMd="wwMd";
public static final String KEY_FORECASTS_PEvap="PEvap";
public static final String SQL_COMMAND_CREATE_TABLE_FORECASTS = "CREATE TABLE " + TABLE_NAME_FORECASTS + "("
+ KEY_FORECASTS_id + " INTEGER PRIMARY KEY ASC,"
+ KEY_FORECASTS_timetext + " TEXT,"
+ KEY_FORECASTS_name + " TEXT,"
+ KEY_FORECASTS_description + " TEXT,"
+ KEY_FORECASTS_longitude + " REAL,"
+ KEY_FORECASTS_latitude + " REAL,"
+ KEY_FORECASTS_altitude + " REAL,"
+ KEY_FORECASTS_timesteps + " TEXT,"
+ KEY_FORECASTS_TTT + " TEXT,"
+ KEY_FORECASTS_E_TTT + " TEXT,"
+ KEY_FORECASTS_T5cm + " TEXT,"
+ KEY_FORECASTS_Td + " TEXT,"
+ KEY_FORECASTS_E_Td + " TEXT,"
+ KEY_FORECASTS_Tx + " TEXT,"
+ KEY_FORECASTS_Tn + " TEXT,"
+ KEY_FORECASTS_TM + " TEXT,"
+ KEY_FORECASTS_TG + " TEXT,"
+ KEY_FORECASTS_DD + " TEXT,"
+ KEY_FORECASTS_E_DD + " TEXT,"
+ KEY_FORECASTS_FF + " TEXT,"
+ KEY_FORECASTS_E_FF + " TEXT,"
+ KEY_FORECASTS_FX1 + " TEXT,"
+ KEY_FORECASTS_FX3 + " TEXT,"
+ KEY_FORECASTS_FXh + " TEXT,"
+ KEY_FORECASTS_FXh25 + " TEXT,"
+ KEY_FORECASTS_FXh40 + " TEXT,"
+ KEY_FORECASTS_FXh55 + " TEXT,"
+ KEY_FORECASTS_FX625 + " TEXT,"
+ KEY_FORECASTS_FX640 + " TEXT,"
+ KEY_FORECASTS_FX655 + " TEXT,"
+ KEY_FORECASTS_RR1c + " TEXT,"
+ KEY_FORECASTS_RRL1c + " TEXT,"
+ KEY_FORECASTS_RR3 + " TEXT,"
+ KEY_FORECASTS_RR6 + " TEXT,"
+ KEY_FORECASTS_RR3c + " TEXT,"
+ KEY_FORECASTS_RR6c + " TEXT,"
+ KEY_FORECASTS_RRhc + " TEXT,"
+ KEY_FORECASTS_RRdc + " TEXT,"
+ KEY_FORECASTS_RRS1c + " TEXT,"
+ KEY_FORECASTS_RRS3c + " TEXT,"
+ KEY_FORECASTS_R101 + " TEXT,"
+ KEY_FORECASTS_R102 + " TEXT,"
+ KEY_FORECASTS_R103 + " TEXT,"
+ KEY_FORECASTS_R105 + " TEXT,"
+ KEY_FORECASTS_R107 + " TEXT,"
+ KEY_FORECASTS_R110 + " TEXT,"
+ KEY_FORECASTS_R120 + " TEXT,"
+ KEY_FORECASTS_R130 + " TEXT,"
+ KEY_FORECASTS_R150 + " TEXT,"
+ KEY_FORECASTS_RR1o1 + " TEXT,"
+ KEY_FORECASTS_RR1w1 + " TEXT,"
+ KEY_FORECASTS_RR1u1 + " TEXT,"
+ KEY_FORECASTS_R600 + " TEXT,"
+ KEY_FORECASTS_Rh00 + " TEXT,"
+ KEY_FORECASTS_R602 + " TEXT,"
+ KEY_FORECASTS_Rh02 + " TEXT,"
+ KEY_FORECASTS_Rd02 + " TEXT,"
+ KEY_FORECASTS_R610 + " TEXT,"
+ KEY_FORECASTS_Rh10 + " TEXT,"
+ KEY_FORECASTS_R650 + " TEXT,"
+ KEY_FORECASTS_Rh50 + " TEXT,"
+ KEY_FORECASTS_Rd00 + " TEXT,"
+ KEY_FORECASTS_Rd10 + " TEXT,"
+ KEY_FORECASTS_Rd50 + " TEXT,"
+ KEY_FORECASTS_wwPd + " TEXT,"
+ KEY_FORECASTS_DRR1 + " TEXT,"
+ KEY_FORECASTS_wwZ + " TEXT,"
+ KEY_FORECASTS_wwZ6 + " TEXT,"
+ KEY_FORECASTS_wwZh + " TEXT,"
+ KEY_FORECASTS_wwD + " TEXT,"
+ KEY_FORECASTS_wwD6 + " TEXT,"
+ KEY_FORECASTS_wwDh + " TEXT,"
+ KEY_FORECASTS_wwC + " TEXT,"
+ KEY_FORECASTS_wwC6 + " TEXT,"
+ KEY_FORECASTS_wwCh + " TEXT,"
+ KEY_FORECASTS_wwT + " TEXT,"
+ KEY_FORECASTS_wwT6 + " TEXT,"
+ KEY_FORECASTS_wwTh + " TEXT,"
+ KEY_FORECASTS_wwTd + " TEXT,"
+ KEY_FORECASTS_wwL + " TEXT,"
+ KEY_FORECASTS_wwL6 + " TEXT,"
+ KEY_FORECASTS_wwLh + " TEXT,"
+ KEY_FORECASTS_wwS + " TEXT,"
+ KEY_FORECASTS_wwS6 + " TEXT,"
+ KEY_FORECASTS_wwSh + " TEXT,"
+ KEY_FORECASTS_wwF + " TEXT,"
+ KEY_FORECASTS_wwF6 + " TEXT,"
+ KEY_FORECASTS_wwFh + " TEXT,"
+ KEY_FORECASTS_wwP + " TEXT,"
+ KEY_FORECASTS_wwP6 + " TEXT,"
+ KEY_FORECASTS_wwPh + " TEXT,"
+ KEY_FORECASTS_VV10 + " TEXT,"
+ KEY_FORECASTS_ww + " TEXT,"
+ KEY_FORECASTS_ww3 + " TEXT,"
+ KEY_FORECASTS_W1W2 + " TEXT,"
+ KEY_FORECASTS_WPc11 + " TEXT,"
+ KEY_FORECASTS_WPc31 + " TEXT,"
+ KEY_FORECASTS_WPc61 + " TEXT,"
+ KEY_FORECASTS_WPch1 + " TEXT,"
+ KEY_FORECASTS_WPcd1 + " TEXT,"
+ KEY_FORECASTS_N + " TEXT,"
+ KEY_FORECASTS_N05 + " TEXT,"
+ KEY_FORECASTS_Nl + " TEXT,"
+ KEY_FORECASTS_Nm + " TEXT,"
+ KEY_FORECASTS_Nh + " TEXT,"
+ KEY_FORECASTS_Nlm + " TEXT,"
+ KEY_FORECASTS_H_BsC + " TEXT,"
+ KEY_FORECASTS_PPPP + " TEXT,"
+ KEY_FORECASTS_E_PPP + " TEXT,"
+ KEY_FORECASTS_RadS3 + " TEXT,"
+ KEY_FORECASTS_RRad1 + " TEXT,"
+ KEY_FORECASTS_Rad1h + " TEXT,"
+ KEY_FORECASTS_RadL3 + " TEXT,"
+ KEY_FORECASTS_VV + " TEXT,"
+ KEY_FORECASTS_D1 + " TEXT,"
+ KEY_FORECASTS_SunD + " TEXT,"
+ KEY_FORECASTS_SunD3 + " TEXT,"
+ KEY_FORECASTS_RSunD + " TEXT,"
+ KEY_FORECASTS_PSd00 + " TEXT,"
+ KEY_FORECASTS_PSd30 + " TEXT,"
+ KEY_FORECASTS_PSd60 + " TEXT,"
+ KEY_FORECASTS_wwM + " TEXT,"
+ KEY_FORECASTS_wwM6 + " TEXT,"
+ KEY_FORECASTS_wwMh + " TEXT,"
+ KEY_FORECASTS_wwMd + " TEXT,"
+ KEY_FORECASTS_PEvap + " TEXT,"
+ KEY_FORECASTS_timestamp + " INTEGER,"
+ KEY_FORECASTS_polling_time + " INTEGER,"
+ KEY_FORECASTS_elements + " INTEGER" + "" + ");";
/*
* SQL Data for the Warnings
*/
public static final String KEY_WARNINGS_id = "id";
public static final String KEY_WARNINGS_polling_time = "polling_time";
public static final String KEY_WARNINGS_identifier = "identifier";
public static final String KEY_WARNINGS_sender = "sender";
public static final String KEY_WARNINGS_sent = "sent";
public static final String KEY_WARNINGS_status = "status";
public static final String KEY_WARNINGS_msgType = "msgType";
public static final String KEY_WARNINGS_source = "source";
public static final String KEY_WARNINGS_scope = "scope";
public static final String KEY_WARNINGS_codes = "codes";
public static final String KEY_WARNINGS_references = "reference_key";
public static final String KEY_WARNINGS_language = "language";
public static final String KEY_WARNINGS_category = "category";
public static final String KEY_WARNINGS_event = "event";
public static final String KEY_WARNINGS_responseType = "responseType";
public static final String KEY_WARNINGS_urgency = "urgency";
public static final String KEY_WARNINGS_severity = "severity";
public static final String KEY_WARNINGS_certainty = "certainty";
public static final String KEY_WARNINGS_effective = "effective";
public static final String KEY_WARNINGS_onset = "onset";
public static final String KEY_WARNINGS_expires = "expires";
public static final String KEY_WARNINGS_senderName = "senderName";
public static final String KEY_WARNINGS_headline = "headline";
public static final String KEY_WARNINGS_description = "description";
public static final String KEY_WARNINGS_instruction = "instruction";
public static final String KEY_WARNINGS_web = "web";
public static final String KEY_WARNINGS_contact = "contact";
public static final String KEY_WARNINGS_profile_version = "profile_version";
public static final String KEY_WARNINGS_license = "license";
public static final String KEY_WARNINGS_ii = "ii";
public static final String KEY_WARNINGS_groups = "groups";
public static final String KEY_WARNINGS_area_color = "area_color";
public static final String KEY_WARNINGS_parameter_names = "parameter_names";
public static final String KEY_WARNINGS_parameter_values = "parameter_values";
public static final String KEY_WARNINGS_polygons = "polygons";
public static final String KEY_WARNINGS_excluded_polygons = "excluded_polygons";
public static final String KEY_WARNINGS_area_names = "area_names";
public static final String KEY_WARNINGS_area_warncellIDs = "area_warncellIDs";
public static final String SQL_COMMAND_CREATE_TABLE_WARNINGS = "CREATE TABLE " + TABLE_NAME_WARNINGS + "("
+ KEY_WARNINGS_id + " INTEGER PRIMARY KEY ASC,"
+ KEY_WARNINGS_polling_time + " INTEGER,"
+ KEY_WARNINGS_identifier + " TEXT,"
+ KEY_WARNINGS_sender + " TEXT,"
+ KEY_WARNINGS_sent + " INTEGER,"
+ KEY_WARNINGS_status + " TEXT,"
+ KEY_WARNINGS_msgType + " TEXT,"
+ KEY_WARNINGS_source + " TEXT,"
+ KEY_WARNINGS_scope + " TEXT,"
+ KEY_WARNINGS_codes + " TEXT,"
+ KEY_WARNINGS_references + " TEXT,"
+ KEY_WARNINGS_language + " TEXT,"
+ KEY_WARNINGS_category + " TEXT,"
+ KEY_WARNINGS_event + " TEXT,"
+ KEY_WARNINGS_responseType + " TEXT,"
+ KEY_WARNINGS_urgency + " TEXT,"
+ KEY_WARNINGS_severity + " TEXT,"
+ KEY_WARNINGS_certainty + " TEXT,"
+ KEY_WARNINGS_effective + " INTEGER,"
+ KEY_WARNINGS_onset + " INTEGER,"
+ KEY_WARNINGS_expires + " INTEGER,"
+ KEY_WARNINGS_senderName + " TEXT,"
+ KEY_WARNINGS_headline + " TEXT,"
+ KEY_WARNINGS_description + " TEXT,"
+ KEY_WARNINGS_instruction + " TEXT,"
+ KEY_WARNINGS_web + " TEXT,"
+ KEY_WARNINGS_contact + " TEXT,"
+ KEY_WARNINGS_profile_version + " TEXT,"
+ KEY_WARNINGS_license + " TEXT,"
+ KEY_WARNINGS_ii + " TEXT,"
+ KEY_WARNINGS_groups + " TEXT,"
+ KEY_WARNINGS_area_color + " TEXT,"
+ KEY_WARNINGS_parameter_names + " TEXT,"
+ KEY_WARNINGS_parameter_values + " TEXT,"
+ KEY_WARNINGS_polygons + " TEXT,"
+ KEY_WARNINGS_excluded_polygons + " TEXT,"
+ KEY_WARNINGS_area_names + " TEXT,"
+ KEY_WARNINGS_area_warncellIDs + " TEXT" + ");";
/*
* SQL Data for the Texts
*/
public static final String KEY_TEXTS_id = "id";
public static final String KEY_TEXTS_identifier = "identifier";
public static final String KEY_TEXTS_weburl = "weburl";
public static final String KEY_TEXTS_content = "content";
public static final String KEY_TEXTS_title = "title";
public static final String KEY_TEXTS_subtitle = "subtitle";
public static final String KEY_TEXTS_issued_text = "issued_text";
public static final String KEY_TEXTS_type = "type";
public static final String KEY_TEXTS_issued = "issued";
public static final String KEY_TEXTS_polled = "polled";
public static final String KEY_TEXTS_outdated = "outdated";
public static final String SQL_COMMAND_CREATE_TABLE_TEXTS = "CREATE TABLE " + TABLE_NAME_TEXTS + "("
+ KEY_TEXTS_id + " INTEGER PRIMARY KEY ASC,"
+ KEY_TEXTS_identifier + " TEXT,"
+ KEY_TEXTS_weburl + " TEXT,"
+ KEY_TEXTS_content + " TEXT,"
+ KEY_TEXTS_title + " TEXT,"
+ KEY_TEXTS_subtitle + " TEXT,"
+ KEY_TEXTS_issued_text + " TEXT,"
+ KEY_TEXTS_type + " INTEGER,"
+ KEY_TEXTS_issued + " INTEGER,"
+ KEY_TEXTS_polled+ " INTEGER,"
+ KEY_TEXTS_outdated + " INTEGER"
+ ");";
/*
* SQL Data for the Areas
*/
public static final String KEY_AREAS_id = "id";
public static final String KEY_AREAS_warncellid = "warncellid";
public static final String KEY_AREAS_warncenter = "warncenter";
public static final String KEY_AREAS_type = "type";
public static final String KEY_AREAS_name = "name";
public static final String KEY_AREAS_polygonstring = "polygonstring";
public static final String SQL_COMMAND_CREATE_TABLE_AREAS = "CREATE TABLE " + TABLE_NAME_AREAS + "("
+ KEY_AREAS_id + " INTEGER PRIMARY KEY ASC,"
+ KEY_AREAS_warncellid + " TEXT,"
+ KEY_AREAS_warncenter + " TEXT,"
+ KEY_AREAS_type + " INTEGER,"
+ KEY_AREAS_name + " TEXT,"
+ KEY_AREAS_polygonstring + " TEXT"
+ ");";
public WeatherDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(SQL_COMMAND_CREATE_TABLE_FORECASTS);
sqLiteDatabase.execSQL(SQL_COMMAND_CREATE_TABLE_WARNINGS);
sqLiteDatabase.execSQL(SQL_COMMAND_CREATE_TABLE_TEXTS);
sqLiteDatabase.execSQL(SQL_COMMAND_CREATE_TABLE_AREAS);
}
@Override
public void onConfigure(SQLiteDatabase db) {
super.onConfigure(db);
setWriteAheadLoggingEnabled(true);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
// drop data & re-create tables
sqLiteDatabase.execSQL(SQL_COMMAND_DROP_TABLE_FORECASTS);
sqLiteDatabase.execSQL(SQL_COMMAND_DROP_TABLE_WARNINGS);
sqLiteDatabase.execSQL(SQL_COMMAND_DROP_TABLE_TEXTS);
sqLiteDatabase.execSQL(SQL_COMMAND_DROP_TABLE_AREAS);
onCreate(sqLiteDatabase);
}
}
}
| 51.01406 | 146 | 0.633927 |
d51561377fbfbdcd63ac751ab56fc3e77f20c8f9 | 201 | // extends Exception para que la clase NotaMal herede de Exception
public class NotaMal extends Exception{
public NotaMal() {
super("Excepcion definida por el usuario, nota incorrecta");
}
}
| 28.714286 | 67 | 0.741294 |
2d5a8af022658d85a7bfae5dee6a78bf0cc66f65 | 1,456 | package com.netease.yunxin.nertc.nertcvoiceroom.model.custom;
import com.netease.yunxin.nertc.nertcvoiceroom.util.JsonUtil;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachmentParser;
import org.json.JSONException;
import org.json.JSONObject;
public class CustomAttachParser implements MsgAttachmentParser {
private static final String KEY_TYPE = "type";
private static final String KEY_DATA = "data";
@Override
public MsgAttachment parse(String json) {
CustomAttachment attachment = null;
JSONObject object = JsonUtil.parse(json);
if (object == null) {
return null;
}
int type = object.optInt(KEY_TYPE);
JSONObject data = object.optJSONObject(KEY_DATA);
switch (type) {
case CustomAttachmentType.CLOSER_ROOM:
attachment = new CloseRoomAttach();
break;
}
if (attachment != null) {
attachment.fromJson(data);
}
return attachment;
}
public static String packData(int type, JSONObject data) {
JSONObject object = new JSONObject();
try {
object.put(KEY_TYPE, type);
if (data != null) {
object.put(KEY_DATA, data);
}
} catch (JSONException e) {
e.printStackTrace();
}
return object.toString();
}
}
| 28.54902 | 65 | 0.622253 |
847bd8d3e875b9ba66ed88c2d11f43ce810da219 | 984 | package com.itgacl.magic4j.modules.sys.excel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import com.itgacl.magic4j.libcommon.excel.LocalDateTimeConverter;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 岗位导出Excel模板
*/
@Data
@ColumnWidth(20)
@HeadRowHeight(20)
@ContentRowHeight(18)
public class PostExcel implements Serializable {
@ExcelProperty("岗位ID")
private Long id;
@ExcelProperty("岗位编码")
private String postCode;
@ExcelProperty("岗位名称")
private String postName;
@ExcelProperty("显示顺序")
private Integer orderNum;
@ExcelProperty("岗位类型")
private String postCategory;
@ExcelProperty(value = "创建时间",converter = LocalDateTimeConverter.class)
private LocalDateTime createTime;
}
| 24.6 | 76 | 0.760163 |
6210bbb9b4140c3ff1a511239a86a4dbb7ae9717 | 1,020 | package org.wickedsource.coderadar.score.rest.scoreprofile;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.wickedsource.coderadar.testframework.category.ControllerTest;
import org.wickedsource.coderadar.testframework.template.ControllerTestTemplate;
import static org.wickedsource.coderadar.factories.databases.DbUnitFactory.Projects.SINGLE_PROJECT;
@Category(ControllerTest.class)
public class ScoreProfileControllerTest extends ControllerTestTemplate {
@Test
public void createScoreProfile() {
System.out.print("ScoreProfileTest");
}
@Test
@DatabaseSetup(SINGLE_PROJECT)
public void updateScoreProfile() {
}
@Test
@DatabaseSetup(SINGLE_PROJECT)
public void getScoreProfile() {
}
@Test
@DatabaseSetup(SINGLE_PROJECT)
public void deleteScoreProfile() {
}
@Test
@DatabaseSetup(SINGLE_PROJECT)
public void listScoreProfiles() {
}
} | 26.842105 | 99 | 0.766667 |
9e88bd111b64571f395c6f9ef69a94ee17d50205 | 2,464 | package net.fishtron.apps.cellplaza.v2;
import net.fishtron.gen.Gen;
import net.fishtron.eval.EvalLib;
import net.fishtron.trees.AppTree;
import net.fishtron.utils.AB;
import net.fishtron.utils.Checker;
import net.fishtron.utils.F;
import net.fishtron.utils.Log;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.Random;
/** Created by tom on 19.03.2017 */
public class CellPlaza {
public static final String BASE_DIR = "eva/cellplaza";
public static final String CONFIG_PATH = BASE_DIR + "/config.json";
public static void main(String[] args) {
Checker ch = new Checker();
JSONObject config = F.loadJson(CONFIG_PATH).getJSONObject("cellPlaza");
run(config, ch);
ch.results();
}
private static void run(JSONObject config, Checker ch) {
JSONArray plazasToRun = config.getJSONArray("run");
JSONObject plazaConfigs = config.getJSONObject("plazas");
for (String plazaDir : F.map(plazasToRun, x->(String)x)) {
runPlaza(plazaDir, plazaConfigs.getJSONObject(plazaDir), ch);
}
}
private static void runPlaza(String plazaDir, JSONObject plazaConfig, Checker ch) {
Random rand = ch.getRandom();
int numStates = plazaConfig.getInt("numStates");
JSONArray pixelSizes = plazaConfig.getJSONArray("pixelSizes");
CellOpts opts = new CellOpts(numStates, plazaDir, pixelSizes, false);
EvalLib lib = Libs.mkLib(opts);
JSONObject allParamsInfo = Libs.mkAllParamsInfo(opts, ch);
AB<AppTree,Rule> rule = genBitRule(lib, allParamsInfo, ch);
JSONArray coreNames = allParamsInfo.getJSONObject("seedImg").getJSONArray("filename");
String coreName = (String) F.randomElement(coreNames, rand);
CellWorld w = new CellWorld(opts, coreName, rule._2(), false);
int numSteps = 100;
w.writeState();
for (int s = 0; s < numSteps; s++) {
w.step();
w.writeState();
}
Log.it();
Log.it("ruleCode = "+rule._1());
Log.it("coreName = "+coreName);
}
private static AB<AppTree,Rule> genBitRule(EvalLib lib, JSONObject allParamsInfo, Checker ch) {
Gen gen = new Gen(Libs.gamma, ch);
AppTree tree = gen.genOne(1, Libs.ruleType);
tree = tree.randomizeParams(allParamsInfo, ch.getRandom());
Rule rule = (Rule) lib.eval(tree);
return AB.mk(tree,rule);
}
}
| 32 | 99 | 0.652192 |
0e06a3e6eb308bcb07f3a3de38f496e0eac6424a | 12,541 | /**
* Xtreme Media Player a cross-platform media player.
* Copyright (C) 2005-2011 Besmir Beqiri
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package xtrememp;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;
import java.awt.Rectangle;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xtrememp.playlist.Playlist.PlayMode;
import xtrememp.ui.skin.DarkSapphireSkin;
import xtrememp.ui.table.PlaylistColumn;
import xtrememp.util.Utilities;
import xtrememp.visualization.FullSpectrogram;
/**
*
* @author Besmir Beqiri
*/
public final class Settings {
private static final Logger logger = LoggerFactory.getLogger(Settings.class);
private static final String CACHE_DIR = ".xtrememp";
private static final String SETTINGS_FILE = "settings.conf";
private static final String PROPERTY_CACHE_DIR = "xtrememp.cache.dir";
private static final String PROPERTY_PLAYER_AUDIO_GAIN = "xtrememp.player.audio.gain";
private static final String PROPERTY_PLAYER_AUDIO_PAN = "xtrememp.player.audio.pan";
private static final String PROPERTY_PLAYER_AUDIO_MUTE = "xtrememp.player.audio.mute";
private static final String PROPERTY_PLAYER_AUDIO_MIXERNAME = "xtrememp.player.audio.mixer.name";
private static final String PROPERTY_EQUILAZER_PRESET_INDEX = "xtrememp.equilazer.preset.index";
private static final String PROPERTY_LAST_DIR = "xtrememp.last.dir";
private static final String PROPERTY_LAST_VIEW = "xtrememp.last.view";
private static final String PROPERTY_PLAYLIST_POSITION = "xtrememp.playlist.position";
private static final String PROPERTY_PLAYLIST_COLUMNS = "xtrememp.playlist.columns";
private static final String PROPERTY_PLAYLIST_PLAYMODE = "xtrememp.playlist.playmode";
private static final String PROPERTY_VISUALIZATION = "xtrememp.visualization";
private static final String PROPERTY_LANGUAGE_INDEX = "xtrememp.language.index";
private static final String PROPERTY_GUI_EFFECTS = "xtrememp.gui.effects";
private static final String PROPERTY_SKIN = "xtrememp.skin";
private static final String PROPERTY_UPDATES_AUTOMATIC = "xtrememp.update.automatic";
private static final String PROPERTY_MAINFRAME_X = "xtrememp.mainframe.x";
private static final String PROPERTY_MAINFRAME_Y = "xtrememp.mainframe.y";
private static final String PROPERTY_MAINFRAME_WIDTH = "xtrememp.mainframe.width";
private static final String PROPERTY_MAINFRAME_HEIGHT = "xtrememp.mainframe.height";
private static final Properties properties = new Properties();
public static void setPlaylistColumns(PlaylistColumn[] playlistColumns) {
StringBuilder propertyColumns = new StringBuilder();
for (PlaylistColumn playlistColumn : playlistColumns) {
propertyColumns.append(playlistColumn.name()).append(":");
propertyColumns.append(playlistColumn.getWidth()).append(";");
}
properties.setProperty(PROPERTY_PLAYLIST_COLUMNS, propertyColumns.toString());
}
public static PlaylistColumn[] getPlaylistColumns() {
PlaylistColumn[] defaultPlaylistColumns = PlaylistColumn.values();
StringBuilder defaultColumns = new StringBuilder();
for (PlaylistColumn playlistColumn : defaultPlaylistColumns) {
defaultColumns.append(playlistColumn.name()).append(":");
defaultColumns.append(playlistColumn.getWidth()).append(";");
}
String propertyColumns = properties.getProperty(PROPERTY_PLAYLIST_COLUMNS,
defaultColumns.toString());
Pattern pattern = Pattern.compile("[:;]");
String[] columns = pattern.split(propertyColumns, 0);
int columnCount = columns.length / 2;
if (columnCount <= 0) { //The config file might be corrupted → restore default.
propertyColumns = defaultColumns.toString();
columns = pattern.split(propertyColumns, 0);
columnCount = columns.length / 2;
}
PlaylistColumn[] playlistColumns = new PlaylistColumn[columnCount];
for (int i = 0; i < columnCount; i++) {
PlaylistColumn column = PlaylistColumn.valueOf(columns[2*i]);
column.setWidth(Integer.parseInt(columns[2*i + 1]));
playlistColumns[i] = column;
}
return playlistColumns;
}
public static void setLanguageIndex(int languageIndex) {
properties.setProperty(PROPERTY_LANGUAGE_INDEX, Integer.toString(languageIndex));
}
public static int getLanguageIndex() {
return Integer.parseInt(properties.getProperty(PROPERTY_LANGUAGE_INDEX, "0"));
}
public static void setUIEffectsEnabled(boolean gfxUI) {
properties.setProperty(PROPERTY_GUI_EFFECTS, Boolean.toString(gfxUI));
}
public static boolean isUIEffectsEnabled() {
return Boolean.parseBoolean(properties.getProperty(PROPERTY_GUI_EFFECTS, Boolean.toString(true)));
}
public static void setLastView(String lastView) {
properties.setProperty(PROPERTY_LAST_VIEW, lastView);
}
public static String getLastView() {
return properties.getProperty(PROPERTY_LAST_VIEW, Utilities.PLAYLIST_MANAGER);
}
public static void setLastDir(String lastDir) {
properties.setProperty(PROPERTY_LAST_DIR, lastDir);
}
public static String getLastDir() {
return properties.getProperty(PROPERTY_LAST_DIR, System.getProperty("user.dir"));
}
public static String getVisualization() {
return properties.getProperty(PROPERTY_VISUALIZATION, FullSpectrogram.NAME);
}
public static void setVisualization(String visualization) {
properties.setProperty(PROPERTY_VISUALIZATION, visualization);
}
public static int getPlaylistPosition() {
return Integer.parseInt(properties.getProperty(PROPERTY_PLAYLIST_POSITION, "0"));
}
public static void setPlaylistPosition(int playlistPosition) {
properties.setProperty(PROPERTY_PLAYLIST_POSITION, Integer.toString(playlistPosition));
}
public static PlayMode getPlayMode() {
return PlayMode.valueOf(properties.getProperty(PROPERTY_PLAYLIST_PLAYMODE, PlayMode.REPEAT_ALL.name()));
}
public static void setPlayMode(PlayMode playMode) {
properties.setProperty(PROPERTY_PLAYLIST_PLAYMODE, playMode.name());
}
public static boolean isMuted() {
return Boolean.parseBoolean(properties.getProperty(PROPERTY_PLAYER_AUDIO_MUTE, Boolean.toString(false)));
}
public static void setMuted(boolean mute) {
properties.setProperty(PROPERTY_PLAYER_AUDIO_MUTE, Boolean.toString(mute));
}
public static int getGain() {
return Integer.parseInt(properties.getProperty(PROPERTY_PLAYER_AUDIO_GAIN, String.valueOf(Utilities.MAX_GAIN)));
}
public static void setGain(int gain) {
properties.setProperty(PROPERTY_PLAYER_AUDIO_GAIN, Integer.toString(gain));
}
public static int getPan() {
return Integer.parseInt(properties.getProperty(PROPERTY_PLAYER_AUDIO_PAN, "0"));
}
public static void setPan(int pan) {
properties.setProperty(PROPERTY_PLAYER_AUDIO_PAN, Integer.toString(pan));
}
public static String getMixerName() {
return properties.getProperty(PROPERTY_PLAYER_AUDIO_MIXERNAME, "");
}
public static void setMixerName(String mixerName) {
properties.setProperty(PROPERTY_PLAYER_AUDIO_MIXERNAME, mixerName);
}
public static int getEqualizerPresetIndex() {
return Integer.parseInt(properties.getProperty(PROPERTY_EQUILAZER_PRESET_INDEX, "0"));
}
public static void setEqualizerPresetIndex(int eqIndex) {
properties.setProperty(PROPERTY_EQUILAZER_PRESET_INDEX, Integer.toString(eqIndex));
}
public static String getSkin() {
return properties.getProperty(PROPERTY_SKIN, DarkSapphireSkin.class.getName());
}
public static void setSkin(String className) {
properties.setProperty(PROPERTY_SKIN, className);
}
public static File getCacheDir() {
File cacheDir = new File(properties.getProperty(PROPERTY_CACHE_DIR, System.getProperty("user.home")), CACHE_DIR);
if (!cacheDir.exists()) {
cacheDir.mkdir();
}
return cacheDir;
}
public static void setCacheDir(File parent) {
properties.setProperty(PROPERTY_CACHE_DIR, parent.getPath());
configureLogback();
}
public static void configureLogback() {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
try {
JoranConfigurator jc = new JoranConfigurator();
jc.setContext(context);
context.reset();
context.putProperty("CACHE_DIR", getCacheDir().getPath());
// override default configuration
jc.doConfigure(Settings.class.getResourceAsStream("/xtrememp/resources/logback.xml"));
} catch (JoranException ex) {
logger.error(ex.getMessage());
}
StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}
public static boolean isAutomaticUpdatesEnabled() {
return Boolean.parseBoolean(properties.getProperty(PROPERTY_UPDATES_AUTOMATIC, Boolean.toString(true)));
}
public static void setAutomaticUpdatesEnabled(boolean b) {
properties.setProperty(PROPERTY_UPDATES_AUTOMATIC, Boolean.toString(b));
}
/**
* Gets the bounds of the application main frame in the form of a
* <code>Rectangle</code> object.
*
* @return a rectangle indicating this component's bounds
*/
public static Rectangle getMainFrameBounds() {
String x = properties.getProperty(PROPERTY_MAINFRAME_X, "0");
String y = properties.getProperty(PROPERTY_MAINFRAME_Y, "0");
String width = properties.getProperty(PROPERTY_MAINFRAME_WIDTH, "1016");
String height = properties.getProperty(PROPERTY_MAINFRAME_HEIGHT, "552");
return new Rectangle(Integer.parseInt(x), Integer.parseInt(y), Integer.parseInt(width), Integer.parseInt(height));
}
/**
* Sets the application main frame new size and location.
*
* @param r the bounding rectangle for this component
*/
public static void setMainFrameBounds(Rectangle r) {
properties.setProperty(PROPERTY_MAINFRAME_X, Integer.toString(r.x));
properties.setProperty(PROPERTY_MAINFRAME_Y, Integer.toString(r.y));
properties.setProperty(PROPERTY_MAINFRAME_WIDTH, Integer.toString(r.width));
properties.setProperty(PROPERTY_MAINFRAME_HEIGHT, Integer.toString(r.height));
}
/**
* Reads all the properties from the settings file.
*/
public static void loadSettings() {
File file = new File(getCacheDir(), SETTINGS_FILE);
if (file.exists()) {
try {
FileInputStream fis = new FileInputStream(file);
properties.load(fis);
fis.close();
} catch (IOException ex) {
logger.error(ex.getMessage(), ex);
}
}
}
/**
* Writes all the properties in the settings file.
*/
public static void storeSettings() {
try {
File file = new File(getCacheDir(), SETTINGS_FILE);
FileOutputStream fos = new FileOutputStream(file);
properties.store(fos, "Xtreme Media Player Settings");
fos.close();
} catch (IOException ex) {
logger.error(ex.getMessage(), ex);
}
}
}
| 40.585761 | 122 | 0.709274 |
f142793e5c008899b598aefd5435da0fa9bce046 | 7,930 | package org.js4ms.io.channel;
/*
* #%L
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* MessageSource.java [org.js4ms.jsdk:io]
* %%
* Copyright (C) 2009 - 2014 Cisco Systems, 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.
* #L%
*/
import java.io.IOException;
/**
* An abstract message source that sends a stream of messages to an {@link OutputChannel}.
*
* @author Greg Bumgardner (gbumgard)
*/
public abstract class MessageSource<Message> {
/*-- Inner Classes -------------------------------------------------------*/
/**
* An enumeration of {@link MessageSource} object states.
*/
enum State {
/** Source open but not sending messages. */
Ready,
/** Source starting. */
Starting,
/** Source started and sending messages. */
Started,
/** Source stopping. */
Stopping,
/** Source closing. */
Closing,
/** Source closed. */
Closed,
/** Source failed due to error. */
Failed
}
/*-- Member Variables ----------------------------------------------------*/
/**
* Tracks the current state for this message source;
*/
private State state;
/**
* The output channel that will receive messages produced by this message source.
*/
private final OutputChannel<Message> outputChannel;
/*-- Member Functions ----------------------------------------------------*/
/**
* Constructs the message source leaving it in the {@link MessageSource.State#Ready
* Ready} state.
*
* @param outputChannel
*/
protected MessageSource(final OutputChannel<Message> outputChannel) {
this.state = State.Ready;
this.outputChannel = outputChannel;
}
/**
* Gets the current {@link MessageSource.State State} of this source.
*
* @return An enumerator value describing the current state.
*/
public State getState() {
return this.state;
}
/**
* Attempts to start this message source leaving the source in the
* {@link MessageSource.State#Started Started} state if
* successful.
* Calls the {@link #doStart()} method which derived classes must implement to perform
* any actions required to start the source.
*
* @throws IOException
* If an I/O error occurs while starting the source.
* @throws InterruptedException
* @throws IllegalStateException
* The message source cannot be started in its current state.
*/
public final void start() throws IOException, InterruptedException {
if (this.state == State.Started) {
return;
}
if (this.state == State.Ready) {
try {
this.state = State.Starting;
doStart();
this.state = State.Started;
}
catch (IOException e) {
abort();
throw e;
}
}
else {
throw new IllegalStateException();
}
}
/**
* Performs actions required to start the start source.
*
* @throws IOException
* If an I/O error occurs while starting the source.
* @throws InterruptedException
*/
protected abstract void doStart() throws IOException, InterruptedException;
/**
* Attempts to stop this message source leaving the source in the
* {@link MessageSource.State#Ready Ready} state if successful.
* Calls the {@link #doStop()} method which derived classes must implement to perform
* any actions required to stop the source.
*
* @throws IOException
* If an I/O error occurs while stopping the source.
* @throws InterruptedException
* If the calling thread is interrupted while stopping the source.
* @throws IllegalStateException
* The message source cannot be stopped in its current state.
*/
public final void stop() throws IOException, InterruptedException {
if (this.state == State.Ready) {
return;
}
if (this.state == State.Started) {
try {
this.state = State.Stopping;
doStop();
this.state = State.Ready;
}
catch (IOException e) {
abort();
throw e;
}
}
else {
throw new IllegalStateException();
}
}
/**
* Performs actions required to stop the message source.
*
* @throws IOException
* If an I/O error occurs while stopping the source.
* @throws InterruptedException
* If the calling thread is interrupted while stopping the source.
*/
protected abstract void doStop() throws IOException, InterruptedException;
/**
* Attempts to close this message source leaving the source in the
* {@link MessageSource.State#Closed Closed} state if successful.
* Calls the {@link #doClose()} method which derived classes must implement to perform
* any actions required to stop the source.
*
* @throws InterruptedException
* If the calling thread is interrupted while closing the source.
* @throws IllegalStateException
* The message source cannot be closed in its current state.
*/
public final void close() throws InterruptedException {
if (this.state == State.Closed) {
return;
}
if (this.state != State.Failed) {
try {
this.state = State.Closing;
doClose();
this.state = State.Closed;
}
catch (IOException e) {
abort();
}
}
else {
throw new IllegalStateException();
}
}
/**
* Performs actions required to close the message source.
* Default implementation closes the OutputChannel bound to this message source.
*
* @throws IOException
* If an I/O error occurs while closing the source.
* @throws InterruptedException
* If the calling thread is interrupted while closing the source.
*/
protected void doClose() throws IOException, InterruptedException {
this.outputChannel.close();
}
/**
* Called to indicate that another operation has failed.
* Attempts to close this message source and places the source in the
* {@link MessageSource.State#Failed Failed} state.
*
* @throws InterruptedException
* If the calling thread is interrupted while closing the source.
*/
protected void abort() throws InterruptedException {
switch (this.state) {
case Ready:
case Starting:
case Started:
case Stopping:
try {
doClose();
this.state = State.Closed;
}
catch (IOException e) {
this.state = State.Failed;
}
break;
case Closing:
this.state = State.Failed;
break;
case Closed:
case Failed:
break;
}
}
}
| 30.976563 | 90 | 0.564817 |
92d28b8dfe538bc9fbd3766002fa8ab2b8963214 | 2,549 | /* *******************************************************************************************************
Copyright (c) 2015 EXILANT Technologies Private Limited
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.exilant.exility.core;
class AddColumnStep extends AbstractStep
{
String gridName;
String columnName;
Expression expression;
AddColumnStep() {
this.gridName = null;
this.columnName = null;
this.expression = null;
this.stepType = StepType.ADDCOLUMNSTEP;
}
@Override
String executeStep(final DataCollection dc, final DbHandle handle) throws ExilityException {
if (this.gridName == null || this.gridName.equals("")) {
dc.addMessage("exilityError", "Grid name not specified to add the column");
return "next";
}
final Grid grid = dc.getGrid(this.gridName);
if (grid == null) {
dc.addMessage("exilityError", String.valueOf(this.gridName) + " not found in dc. You have used this grid name in an AddColumn Step.");
return "next";
}
final Value val = this.expression.evaluate(dc);
final ValueList valueList = new ValueList(grid.getNumberOfRows());
for (int i = 0; i < valueList.length(); ++i) {
valueList.setValue(val, i);
}
grid.addColumn(this.columnName, valueList);
dc.addGrid(this.gridName, grid);
return "next";
}
}
| 45.517857 | 146 | 0.64339 |
822ac43ead698afe69629edf24920ea04234bd9a | 925 | /*
* Author: Stefan Andritoiu <stefan.andritoiu@intel.com>
* Copyright (c) 2015 Intel Corporation.
*
* This program and the accompanying materials are made available under the
* terms of the The MIT License which is available at
* https://opensource.org/licenses/MIT.
*
* SPDX-License-Identifier: MIT
*/
//NOT TESTED!!!
public class MPL3115A2_Example {
public static void main(String[] args) throws InterruptedException {
// ! [Interesting]
// Instantiate a MPL3115A2 sensor on I2C
upm_mpl3115a2.MPL3115A2 sensor = new upm_mpl3115a2.MPL3115A2(0);
while (true) {
System.out.println("Pressure: " + sensor.getPressure());
System.out.println("Altitude: " + sensor.getAltitude());
System.out.println("Sealevel pressure: " + sensor.getSealevelPressure());
System.out.println("Temperature: " + sensor.getTemperature());
System.out.println();
Thread.sleep(1000);
}
// ! [Interesting]
}
} | 28.90625 | 76 | 0.71027 |
80076d268030f6b60b81a9b3f7578bf1d0cdf8fc | 1,348 | package com.example.demo.models;
public class WindSurfer {
private String mysails;
private double myweight;
private String experienceLevel;
private double location[];
private int sailOrBoard;
// Constructors
public WindSurfer() {}
public WindSurfer(double weight, String experienceLevel, double location[], String sails,int sa) {
this.experienceLevel = experienceLevel;
this.myweight = weight;
this.location = location;
this.mysails = sails;
this.sailOrBoard = sa;
}
public int getSailOrBoard() {
return sailOrBoard;
}
public void setSailOrBoard(int sailOrBoard) {
this.sailOrBoard = sailOrBoard;
}
public String getMysails() {
return mysails;
}
public void setMysails(String mysails) {
this.mysails = mysails;
}
public double getMyweight() {
return myweight;
}
public void setMyweight(double myweight) {
this.myweight = myweight;
}
public String getExperienceLevel() {
return experienceLevel;
}
public void setExperienceLevel(String experienceLevel) {
this.experienceLevel = experienceLevel;
}
public double getLocation()[] {
return location;
}
public void setLocation(double location[]) {
this.location = location;
}
}
| 18.465753 | 102 | 0.652077 |
40d0ea7853900e270af6a4b6d082dae8aa1ad463 | 383 | package uk.co.sleonard.unison;
/**
* The Interface UNISoNLogger.
*
* @author Stephen <github@leonarduk.com>
* @since v1.0.0
*
*/
public interface UNISoNLogger {
/**
* Alert.
*
* @param message
* the message
*/
public void alert(String message);
/**
* Log.
*
* @param message
* the message
*/
public void log(String message);
}
| 13.678571 | 41 | 0.579634 |
b5a572fa6b95541c275661573563e5cfaf673e94 | 1,886 | package com.zandgall.arvopia.utils;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
public class Chart {
double[] vals;
String[] components;
String name;
int x, y, width, height;
Slice[] slices;
public Chart(double[] vals, String[] components, Color[] colors, String name, int x, int y, int width, int height) {
this.vals = vals;
this.name = name;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.components = components;
slices = new Slice[vals.length];
for(int i = 0; i<slices.length; i++) {
slices[i]=new Slice(vals[i], components[i], colors[i]);
}
}
public void update(double[] vals) {
for(int i = 0; i<slices.length; i++) {
slices[i].value = vals[i];
}
}
public void render(Graphics g) {
drawPie((Graphics2D) g, new Rectangle(x, y, width, height), slices);
g.setColor(Color.black);
g.drawString(name, x+width/2, y+height/2);
for(int i = 0; i<slices.length; i++) {
g.setColor(slices[i].color);
g.fillRect(x, y+height+10+i*20, width, 15);
g.setColor(Color.black);
g.drawString(slices[i].name, x, y+height+23+i*20);
}
}
void drawPie(Graphics2D g, Rectangle area, Slice[] slices) {
double total = 0.0D;
for (int i = 0; i < slices.length; i++) {
total += slices[i].value;
}
double curValue = 0.0D;
int startAngle = 0;
for (int i = 0; i < slices.length; i++) {
startAngle = (int) (curValue * 360 / total);
int arcAngle = (int) (slices[i].value * 360 / total);
g.setColor(slices[i].color);
g.fillArc(area.x, area.y, area.width, area.height, startAngle, arcAngle);
curValue += slices[i].value;
}
}
class Slice {
double value;
Color color;
String name;
public Slice(double value, String name, Color color) {
this.value = value;
this.color = color;
this.name = name;
}
}
}
| 23.283951 | 117 | 0.635207 |
c16abf89157a7ca64ae63b7dfb0021c23a352491 | 410 | package com.data2.salmon.core.engine.intercept;
import lombok.extern.slf4j.Slf4j;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author data2
*/
@Slf4j
public class ParamsInterceptor implements CutPointInterceptor {
@Override
public void execute(Object obj) {
log.info("[{}] execute sql start.", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
}
| 20.5 | 108 | 0.709756 |
68dc393a6984f1f8fb9fd8404bef52b5db2b3bff | 62 | class List<T> {}
class Foo {
List<? extends <caret>>
} | 7.75 | 25 | 0.548387 |
4114b40df6885ba47d102af766537bcec56c97eb | 2,757 | package ch.yoursource.causationfinder.service;
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import ch.yoursource.causationfinder.dto.UpdateUserDto;
import ch.yoursource.causationfinder.entity.Role;
import ch.yoursource.causationfinder.entity.User;
import ch.yoursource.causationfinder.repository.RoleRepository;
import ch.yoursource.causationfinder.repository.UserRepository;
@Service
public class UserServiceImpl implements UserService {
private UserRepository userRepository;
private RoleRepository roleRepository;
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
public UserServiceImpl(
UserRepository userRepository,
RoleRepository roleRepository,
BCryptPasswordEncoder bCryptPasswordEncoder
) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
@Override
public void save(User user) {
if (user.getPassword() != null) {
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
}
Role userRole = roleRepository.findByName("ROLE_USER");
if (userRole == null) {
throw new RuntimeException("Default user role not found.");
}
Set<Role> userRoles = new HashSet<Role>();
userRoles.add(userRole);
user.setRoles(userRoles);
userRepository.save(user);
}
// method needed because spring would encode the already hashed password again
// when saving the user after registration confirmed
@Override
public void update(User user) {
userRepository.save(user);
}
@Override
public User findByUsername(String username) {
return userRepository.findByUsername(username);
}
@Override
public User findByEmail(String email) {
return userRepository.findByEmail(email);
}
@Override
public void saveUpdatedUserData(User currentUser, UpdateUserDto updateUserDto) {
currentUser.setUsername(updateUserDto.getUsername());
currentUser.setFirstName(updateUserDto.getFirstName());
currentUser.setLastName(updateUserDto.getLastName());
currentUser.setEmail(updateUserDto.getEmail());
currentUser.setBirthdate(updateUserDto.getBirthdate());
userRepository.save(currentUser);
}
@Override
public void saveChangedPassword(User currentUser, String newPassword) {
currentUser.setPassword(bCryptPasswordEncoder.encode(newPassword));
userRepository.save(currentUser);
}
}
| 31.329545 | 85 | 0.734857 |
aa134e8bb82e7d5ad340c63981e2d64801d7e325 | 291 | package com.example.designpattern.creationalpattern.factorypattern;
import android.util.Log;
public abstract class Plane {
protected double rate;
public abstract void getRate();
public void calculateBill(int units){
Log.i("Plane", String.valueOf(units*rate));
}
}
| 22.384615 | 67 | 0.725086 |
ba1955e4091c208dcadf06ebfc8c7a04f6842c7c | 566 | package cn.fxn.svm.core.ui.camera;
import com.yalantis.ucrop.UCrop;
/**
* @author:Matthew
* @date:2018/11/2
* @email:guocheng0816@163.com
* @func:请求码
*/
public class RequestCode {
/**
* 拍照
*/
public static final int TAKE_PHOTO=4;
/**
* 相册选择
*/
public static final int PICK_PHOTO=5;
/**
* 裁剪
*/
public static final int CROP_PHOTO=UCrop.REQUEST_CROP;
/**
* 裁剪错误
*/
public static final int CROP_ERROR=UCrop.RESULT_ERROR;
/**
* 扫描二维码
*/
public static final int SCAN=7;
}
| 16.171429 | 58 | 0.579505 |
9cf911f3bc657a18fe13e8e3ea01d9acbe50dbc4 | 756 | package network.exceptions;
/**
* Lost connection to server. Consistency cannot be maintained!
* This exception is thrown when a connection was previously successfully
* established but is now closed due to network partition or failure.
*
* @author CharlesXu
*/
public class SessionExpiredException extends RuntimeException {
private static final long serialVersionUID = -3226542240801771473L;
public SessionExpiredException() {}
/**
* Create an exception based on an issue in our code.
*/
public SessionExpiredException(String msg) {
super(msg);
}
/**
* Create an exception based on a caught exception with a different message.
*/
public SessionExpiredException(Throwable cause) {
super(cause);
}
}
| 25.2 | 80 | 0.727513 |
c8771b2da658070ed0c359bfb5a3bc68fa269905 | 4,982 | package info.bitrich.xchangestream.poloniex2;
import com.fasterxml.jackson.databind.ObjectMapper;
import info.bitrich.xchangestream.core.StreamingMarketDataService;
import info.bitrich.xchangestream.poloniex2.dto.*;
import info.bitrich.xchangestream.service.netty.StreamingObjectMapperHelper;
import io.reactivex.Observable;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.marketdata.OrderBook;
import org.knowm.xchange.dto.marketdata.Ticker;
import org.knowm.xchange.dto.marketdata.Trade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.SortedMap;
import static org.knowm.xchange.poloniex.PoloniexAdapters.*;
/**
* Created by Lukas Zaoralek on 10.11.17.
*/
public class PoloniexStreamingMarketDataService implements StreamingMarketDataService {
private static final Logger LOG = LoggerFactory.getLogger(PoloniexStreamingMarketDataService.class);
private final PoloniexStreamingService service;
private final Map<CurrencyPair, Integer> currencyPairMap;
public PoloniexStreamingMarketDataService(PoloniexStreamingService service, Map<CurrencyPair, Integer> currencyPairMap) {
this.service = service;
this.currencyPairMap = currencyPairMap;
}
@Override
public Observable<OrderBook> getOrderBook(CurrencyPair currencyPair, Object... args) {
Observable<PoloniexOrderbook> subscribedOrderbook = service.subscribeCurrencyPairChannel(currencyPair)
.scan(
Optional.empty(),
(Optional<PoloniexOrderbook> orderbook, List<PoloniexWebSocketEvent> poloniexWebSocketEvents) ->
poloniexWebSocketEvents.stream()
.filter(s ->
s instanceof PoloniexWebSocketOrderbookInsertEvent
|| s instanceof PoloniexWebSocketOrderbookModifiedEvent
)
.reduce(
orderbook,
(poloniexOrderbook, s) -> getPoloniexOrderbook(orderbook, s),
(o1, o2) -> {
throw new UnsupportedOperationException("No parallel execution");
}
)
)
.filter(Optional::isPresent)
.map(Optional::get);
return subscribedOrderbook.map(s -> adaptPoloniexDepth(s.toPoloniexDepth(), currencyPair));
}
@Override
public Observable<Ticker> getTicker(CurrencyPair currencyPair, Object... args) {
final ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper();
int currencyPairId = currencyPairMap.getOrDefault(currencyPair, 0);
Observable<PoloniexWebSocketTickerTransaction> subscribedChannel = service.subscribeChannel("1002")
.map(s -> mapper.readValue(s.toString(), PoloniexWebSocketTickerTransaction.class));
return subscribedChannel
.filter(s -> s.getPairId() == currencyPairId)
.map(s -> adaptPoloniexTicker(s.toPoloniexTicker(currencyPair), currencyPair));
}
@Override
public Observable<Trade> getTrades(CurrencyPair currencyPair, Object... args) {
Observable<PoloniexWebSocketTradeEvent> subscribedTrades = service.subscribeCurrencyPairChannel(currencyPair)
.flatMapIterable(poloniexWebSocketEvents -> poloniexWebSocketEvents)
.filter(PoloniexWebSocketTradeEvent.class::isInstance)
.map(PoloniexWebSocketTradeEvent.class::cast)
.share();
return subscribedTrades
.map(s -> adaptPoloniexPublicTrade(s.toPoloniexPublicTrade(currencyPair), currencyPair));
}
private Optional<PoloniexOrderbook> getPoloniexOrderbook(
final Optional<PoloniexOrderbook> orderbook, final PoloniexWebSocketEvent s
) {
if (s.getEventType().equals("i")) {
OrderbookInsertEvent insertEvent = ((PoloniexWebSocketOrderbookInsertEvent) s).getInsert();
SortedMap<Double, Double> asks = insertEvent.toDepthLevels(OrderbookInsertEvent.ASK_SIDE);
SortedMap<Double, Double> bids = insertEvent.toDepthLevels(OrderbookInsertEvent.BID_SIDE);
return Optional.of(new PoloniexOrderbook(asks, bids));
} else {
OrderbookModifiedEvent modifiedEvent = ((PoloniexWebSocketOrderbookModifiedEvent) s).getModifiedEvent();
orderbook.orElseThrow(() -> new IllegalStateException("Orderbook update received before initial snapshot"))
.modify(modifiedEvent);
return orderbook;
}
}
}
| 48.843137 | 125 | 0.650141 |
105977590c5534c91c66f51e65f6445dccf8b913 | 168 | package eu.midnightdust.visualoverhaul.util;
public class JukeboxPacketUpdate {
public static boolean invUpdate = true;
public static int playerUpdate = -1;
}
| 24 | 44 | 0.767857 |
6f0df04a8edcd39f505c664749876baa57b6d9c6 | 3,416 | package moe.langua.lab.melonpi;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
public class BootStrap {
static double result = 0D;
static AtomicInteger taskNumber = new AtomicInteger(0);
static final int CORES = Runtime.getRuntime().availableProcessors();
static final int ONE_HALF_CORES = (int) (CORES * 1.5);
static final int DOUBLE_CORES = CORES * 2;
static final int operationPerLoop = 0x800;
static final int loopTime = 0x111;
public static void main(String[] inputs) throws InterruptedException {
String name = "";
if (inputs.length != 0) {
for(String x:inputs){
name = name.concat(x+" ");
}
}
System.out.println("Yay, I am going to calculate pi. It may takes a few minutes...");
long timestamp = System.currentTimeMillis();
startPiThreads(1);
long singleResult = System.currentTimeMillis() - timestamp;
resetResult(false);
timestamp = System.currentTimeMillis();
startPiThreads(CORES);
long multiThreadResult = System.currentTimeMillis() - timestamp;
resetResult(false);
timestamp = System.currentTimeMillis();
startPiThreads(ONE_HALF_CORES);
long onePointFiveTimesThreadsResult = System.currentTimeMillis() - timestamp;
resetResult(false);
timestamp = System.currentTimeMillis();
startPiThreads(DOUBLE_CORES);
long twoTimesThreadsResult = System.currentTimeMillis() - timestamp;
resetResult(true);
Properties properties = System.getProperties();
if(name.length()!=0) System.out.println("Device: "+ name);
System.out.println("System: ");
System.out.println(" Name: "+properties.getProperty("os.name"));
System.out.println(" Version: "+properties.getProperty("os.version"));
System.out.println(" Architecture: "+properties.getProperty("os.arch"));
System.out.println("Java Runtime: ");
System.out.println(" Java Version: "+properties.getProperty("java.version"));
System.out.println(" JVM Version: "+properties.getProperty("java.vm.version"));
System.out.println(" JVM Vendor: "+properties.getProperty("java.vm.vendor"));
System.out.println("Performance: ");
System.out.println(" Single thread: " + (double) singleResult / 1000 + "s");
System.out.println(" Multi threads("+CORES+"): " + (double) multiThreadResult / 1000 + "s");
System.out.println(" Multi threads("+ONE_HALF_CORES+"): " + (double) onePointFiveTimesThreadsResult / 1000 + "s");
System.out.println(" Multi threads("+DOUBLE_CORES+"): " + (double) twoTimesThreadsResult / 1000 + "s");
}
private static void startPiThreads(int threadsNumber) throws InterruptedException {
PiThread[] piThreads = new PiThread[threadsNumber];
for (int i = 0; i < piThreads.length; i++) {
piThreads[i] = new PiThread();
piThreads[i].start();
}
for (PiThread x : piThreads) {
x.join();
}
}
private static void resetResult(boolean print){
if(print) System.out.println("The pi you calculated is... "+result+"!");
result = 0;
taskNumber.set(0);
}
static synchronized void submit(double result) {
BootStrap.result += result;
}
}
| 40.188235 | 123 | 0.636124 |
3daa7355998337ecbc8ebef4245cbdd1d9b36572 | 224 | package com.kbryant.quickcore.event;
import com.kbryant.quickcore.util.ApiException;
/**
* 返回结果回调接口
*
* @param <T>
*/
public interface RespEvent<T> {
void isOk(T t);
void isError(ApiException apiException);
}
| 14.933333 | 47 | 0.696429 |
5b28c27c9629e2904fca23bd6c40630991064b7c | 2,152 | package com.qtin.sexyvc.ui.fund.detail;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BaseModel;
import com.qtin.sexyvc.mvp.model.api.cache.CacheManager;
import com.qtin.sexyvc.mvp.model.api.service.ServiceManager;
import com.qtin.sexyvc.ui.bean.BaseEntity;
import com.qtin.sexyvc.ui.bean.CodeEntity;
import com.qtin.sexyvc.ui.bean.FundFollowRequest;
import com.qtin.sexyvc.ui.bean.FundUnFollowRequest;
import com.qtin.sexyvc.ui.bean.UserEntity;
import com.qtin.sexyvc.ui.bean.UserInfoEntity;
import com.qtin.sexyvc.ui.fund.detail.bean.FundDetailBackBean;
import java.util.List;
import javax.inject.Inject;
import rx.Observable;
/**
* Created by ls on 17/4/26.
*/
@ActivityScope
public class FundDetailModel extends BaseModel<ServiceManager,CacheManager> implements FundDetailContract.Model {
@Inject
public FundDetailModel(ServiceManager serviceManager, CacheManager cacheManager) {
super(serviceManager, cacheManager);
}
@Override
public Observable<BaseEntity<FundDetailBackBean>> queryFundDetail(String token, long fund_id, long comment_id,int page_size,int auth_state) {
return mServiceManager.getCommonService().queryFundDetail(token,fund_id,comment_id, page_size,auth_state);
}
@Override
public String getToken() {
List<UserEntity> list=mCacheManager.getDaoSession().getUserEntityDao().queryBuilder().build().list();
if(list!=null&&!list.isEmpty()){
return list.get(0).getU_token();
}
return "";
}
@Override
public UserInfoEntity getUserInfo() {
List<UserInfoEntity> list=mCacheManager.getDaoSession().getUserInfoEntityDao().queryBuilder().build().list();
if(list!=null&&!list.isEmpty()){
return list.get(0);
}
return null;
}
@Override
public Observable<CodeEntity> followFund(FundFollowRequest entity) {
return mServiceManager.getCommonService().followFund(entity);
}
@Override
public Observable<CodeEntity> unFollowFund(FundUnFollowRequest entity) {
return mServiceManager.getCommonService().unFollowFund(entity);
}
}
| 34.709677 | 145 | 0.734201 |
063b7ef0943844953a973d3a7a2daada8b20f931 | 123 | package com.raven.pattern.proxy.staticproxy;
public interface Human {
/**
* eat method
*/
void eat();
}
| 13.666667 | 44 | 0.601626 |
e7122936dedee278440c0eff04b653fabc60f40b | 6,045 | package de.eorg.cumulusgenius.client.View;
import com.google.gwt.user.client.ui.HTML;
import com.smartgwt.client.types.ListGridEditEvent;
import com.smartgwt.client.types.RowEndEditAction;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.layout.HLayout;
import de.eorg.cumulusgenius.client.CumulusGenius;
import de.eorg.cumulusgenius.client.View.Handlers.ViewHandler;
import de.eorg.cumulusgenius.client.datasource.CSRequirementsXmlDS;
import de.eorg.cumulusgenius.client.datasource.VMRequirementsXmlDS;
public class RequirementsView extends AbstractView {
public RequirementsView() {
setHeading(new HTML("<h1>Requirements</h1>", true));
setInstructions(new HTML(
"<h2>Please define Requirements which have to be met by your System</h2>",
true));
// Überschrift setzen
HTML vMconstraints = new HTML(
"<h2>Virtual Machine Image Constraints</h2>", true);
// erstes Grid erstellen
Canvas vMcanvas = new Canvas();
final ListGrid vMGrid = new ListGrid();
vMGrid.setWidth(500);
vMGrid.setHeight(150);
vMGrid.setCellHeight(22);
vMGrid.setDataSource(VMRequirementsXmlDS.getInstance());
final ListGridField nameTypeField = new ListGridField("name", "Name");
final ListGridField interconnectionsField = new ListGridField("constraint",
"Constraint");
final ListGridField valueFiel = new ListGridField("value", "Value");
final ListGridField softwareField = new ListGridField("metric", "Metric");
vMGrid.setAutoFetchData(true);
vMGrid.setCanEdit(true);
vMGrid.setModalEditing(true);
vMGrid.setEditEvent(ListGridEditEvent.CLICK);
vMGrid.setListEndEditAction(RowEndEditAction.NEXT);
vMGrid.setAutoSaveEdits(false);
vMcanvas.addChild(vMGrid);
// Buttons zum editieren der Tabelle
IButton addComponentButton = new IButton("Add Component");
addComponentButton.setTop(250);
addComponentButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
vMGrid.startEditingNew();
}
});
vMcanvas.addChild(addComponentButton);
IButton saveButton = new IButton("Save");
saveButton.setTop(250);
saveButton.setLeft(110);
saveButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
vMGrid.saveAllEdits();
}
});
vMcanvas.addChild(saveButton);
IButton deleteButton = new IButton("Delete Component");
deleteButton.setTop(250);
deleteButton.setLeft(220);
deleteButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
vMGrid.removeSelectedData();
}
});
vMcanvas.addChild(deleteButton);
//Überschrift setzen
HTML cSconstraints = new HTML("<h2>Cloud Service Constraints</h2>",
true);
//zweites Grid erstellen
Canvas cScanvas = new Canvas();
final ListGrid cSGrid = new ListGrid();
cSGrid.setWidth(500);
cSGrid.setHeight(150);
cSGrid.setCellHeight(22);
cSGrid.setDataSource(CSRequirementsXmlDS.getInstance());
final ListGridField cS_nameTypeField = new ListGridField("name", "Name");
final ListGridField cs_interconnectionsField = new ListGridField("constraint",
"Constraint");
final ListGridField cS_valueFiel = new ListGridField("value", "Value");
final ListGridField cS_softwareField = new ListGridField("metric", "Metric");
cSGrid.setAutoFetchData(true);
cSGrid.setCanEdit(true);
cSGrid.setModalEditing(true);
cSGrid.setEditEvent(ListGridEditEvent.CLICK);
cSGrid.setListEndEditAction(RowEndEditAction.NEXT);
cSGrid.setAutoSaveEdits(false);
cScanvas.addChild(cSGrid);
// Buttons zum editieren der Tabelle
IButton cS_addComponentButton = new IButton("Add Component");
cS_addComponentButton.setTop(250);
cS_addComponentButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
cSGrid.startEditingNew();
}
});
cScanvas.addChild(cS_addComponentButton);
IButton cS_saveButton = new IButton("Save");
cS_saveButton.setTop(250);
cS_saveButton.setLeft(110);
cS_saveButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
cSGrid.saveAllEdits();
}
});
cScanvas.addChild(cS_saveButton);
IButton cS_deleteButton = new IButton("Delete Component");
cS_deleteButton.setTop(250);
cS_deleteButton.setLeft(220);
cS_deleteButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
cSGrid.removeSelectedData();
}
});
cScanvas.addChild(cS_deleteButton);
// Back und Next Button bauen
IButton backButton = new IButton("Back");
backButton.setTop(100);
IButton nextButton = new IButton("Next");
nextButton.setTop(100);
nextButton.setLeft(220);
backButton.addClickHandler(new ViewHandler(CumulusGenius.componentsView));
nextButton.addClickHandler(new ViewHandler(CumulusGenius.criteriaView));
/**nextButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event){
dao.createVMRequirement(nameTypeField.getValueField(), interconnectionsField.getValueField(), valueFiel.getValueField(),softwareField.getValueField());
dao.createCSRequirement(cS_nameTypeField.getValueField(), cs_interconnectionsField.getValueField(), cS_valueFiel.getValueField(), cS_softwareField.getValueField());
}
});*/
HLayout buttonLayout = new HLayout();
buttonLayout.setHeight(150);
buttonLayout.setMembersMargin(5);
buttonLayout.setLayoutMargin(10);
buttonLayout.addChild(backButton);
buttonLayout.addChild(nextButton);
// Alles auf in Layout packen
getLayout().add(getHeading());
getLayout().add(getInstructions());
getLayout().add(vMconstraints);
getLayout().add(vMcanvas);
getLayout().add(cSconstraints);
getLayout().add(cScanvas);
getLayout().add(buttonLayout);
}
}
| 33.39779 | 168 | 0.75517 |
8d34478b52e8774d3d07c977e3273363e03eac00 | 46,774 | /**
* @author GHUANG
* @version 2019年12月28日 下午8:02:42
*
*/
package com.centricsoftware.commons.utils;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.sql.RowSet;
import com.centricsoftware.config.entity.CsProperties;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HSEUtil {
private static final Logger log = LoggerFactory.getLogger(HSEUtil.class);
public static HashMap<String, String> typemap = null;
public static HashMap<String, String> attrmap = null;
public static CsProperties CSProperties;
static{
CSProperties = NodeUtil.getProperties();
}
/**
* ED BO对象表 ER BO存在多值属性且为ref类型 EN BO存在多值属性且为数字类型 ET BO存在多值属性且为String类型
*/
static {
attrmap = new HashMap();
attrmap.put("__Parent__", "the_parent_id");
attrmap.put("Node Name", "node_name");
attrmap.put("Node Type", "node_type");
attrmap.put("URL", "the_cnl");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// System.out.println(camel4underline("C8_User_TRApprover"));
try {
System.out.println(camel4underline(
"PartMaterial:__Parent__@Child,ApparelBOMRevision:__Parent__@PartMaterial,ApparelBOM:__Parent__@ApparelBOMRevision,Style:__Parent__@ApparelBOM"));
HashMap colattrmap = new HashMap();
colattrmap.put("Child", "__Parent__,TrackingColor");
colattrmap.put("PartMaterial:__Parent__@Child#PartMaterial", "Node Name_0");
HashMap<String, String> resultmap = HSEUtil.queryAttributesbyUrls("C123", "",
"PartMaterialTracking", colattrmap,
null);
System.out.println("result=" + resultmap);
getMultiAttribute("C0/673276478|Style", "433738", "Style", "BOMMainMaterials", "ref", null);
// getSingleAttribute("C0/673276478|Style", "433738", "C8_SA_AFSStatus", "Style", "", null);
getSingleAttribute("C0/673276478|Style", "433738", "Node Name", "Style",
"Category2:Category2,Category1:Category1,Season:ParentSeason", null);
getSingleAttribute("", "75276", "Node Name", "ApparelBOM", "", null);
getSingleAttribute("", "75276", "Node Name", "ApparelBOM", "Style:__Parent__", null);
HashMap pmap = new HashMap();
pmap.put("Category2:Category2", camel4underline("Node Name") + "_0");
pmap.put("Category1:Category1", camel4underline("Node Name") + "_1");
pmap.put("Category1:Category1,Season:ParentSeason",
camel4underline("Node Name") + "_2," + camel4underline("Code") + "_3");
pmap.put("Child", camel4underline("Node Name"));
HashMap map = new HashMap();
map.put("Code", "123");
queryAttributes("Style", pmap, map, null);
queryAttributesWithConfbyUrl("C0/673276478|Style", "", "PartMaterial", "cs.view.bomview.item.", "",
"where a",
null);
} catch (Exception e) {
}
}
/**
* 驼峰转下划线
*
* @param data
* @return
*/
public static String camel4underline(String data) {
List record = new ArrayList();
String result = "";
if (attrmap.containsKey(data)) {
return attrmap.get(data);
}
for (Map.Entry<String, String> m : attrmap.entrySet()) {
String rep = m.getValue();
String key = m.getKey();
data = data.replaceAll(key, rep);
}
Pattern pattern = Pattern.compile("[0-9]*");
StringBuffer sb = new StringBuffer(data);
int dl = data.length();
for (int ii = 1; ii < dl - 1; ii++) {
if (Character.isLowerCase(sb.charAt(ii)) && Character.isUpperCase(sb.charAt(ii + 1))) {
sb.insert(ii + 1, '_');
ii++;
dl++;
continue;
}
String numstr = Character.toString(sb.charAt(ii));
Matcher isNum = pattern.matcher(numstr);
if (isNum.matches() && Character.isUpperCase(sb.charAt(ii + 1))) {
sb.insert(ii + 1, '_');
ii++;
dl++;
continue;
}
if (Character.isUpperCase(sb.charAt(ii)) && Character.isLowerCase(sb.charAt(ii + 1))) {
if ('_' == (sb.charAt(ii - 1)) || ',' == (sb.charAt(ii - 1)) || '@' == (sb.charAt(ii - 1))
|| '#' == (sb.charAt(ii - 1)) || ':' == (sb.charAt(ii - 1))) {
continue;
} else {
sb.insert(ii, '_');
ii++;
dl++;
}
}
}
for (int iii = 0; iii < sb.length(); iii++) {
if (Character.isUpperCase(sb.charAt(iii))) {
sb.setCharAt(iii, (char) (sb.charAt(iii) + 32));
}
}
result += sb.toString();
return result;
}
/* *//**
* 多属性查询数据 对象条件
*
* @param type
* @param attribute
* targetattr@type:attr
* @param conmap
* @param multiType
* @return
* @author GHUANG
* @version 2019年12月29日 下午12:12:09
*//*
* public static List<HashMap<String, String>> queryAttributes(String type, String attributes,
* HashMap<String, String> conmap, DBUtil util) { String sql = "select a.id,"; RowSet rs = null;
* List<HashMap<String, String>> rlist = new ArrayList(); try { List<String> list = null; if
* (attributes.length() > 0) { list = Arrays.asList(attributes.split(",")); for (String attr : list) { sql
* += "a." + camel4underline(attr) + ","; } }
*
* if (sql.endsWith(",")) { sql = sql.substring(0, sql.lastIndexOf(",")); } sql += " from " + "ed_" +
* camel4underline(type) + " a where "; String condition = ""; for (Map.Entry<String, String> artMap :
* conmap.entrySet()) { String key = artMap.getKey(); String value = artMap.getValue();
*
* condition += "a." + camel4underline(key) + "='" + value + "' and "; } if (condition.endsWith("and ")) {
* condition = condition.substring(0, condition.lastIndexOf("and")); } sql += condition;
*
* if (sql.length() > 0) { CSILog.outInfo("ATTRIBUTS=" + sql, "HSE"); rs = util.query(sql);
*
* while (rs.next()) { HashMap<String, String> colmap = new HashMap(); for (String attrname : list) {
* colmap.put(attrname, rs.getString(attrname)); } rlist.add(colmap); } rs.close(); } } catch (Exception e)
* { CSILog.exceptionInfo("Exception", e); } finally { if (rs != null) { try { rs.close(); } catch
* (SQLException s) { rs = null; } } } return rlist; }
*/
/**
* 根据配置文件进行查询 属性key 改为type+"_"+attr+"_" +seq数字 path为类型:path@+上级类型 spec=a.id,a.the_cnl
*
* @param url
* 根据URL查询或id查询
* @param id
* @param type
* 查询BO类型
* @param key
* 配置文件的key
* @param spec
* 提供查询属性的额外定义
* @param specwhere
* 提供where条件的额外定义
* @param util
* @return
* @author GHUANG
* @version 2020年6月2日 下午3:58:48
*/
public static LinkedHashMap<String, HashMap<String, String>> queryAttributesWithConfbyUrl(String url, String id,
String type, String key, String spec, String specwhere, DBUtil util) {
LinkedHashMap<String, HashMap<String, String>> rmap = new LinkedHashMap();
RowSet rs = null;
try {
String sql = "select a.the_cnl,";
List<String> list = new ArrayList();
String pathwhere = "";
String attrsql = "";
if (spec.length() > 0) {
String specstr[] = spec.split(",");
for (int s = 0; s < specstr.length; s++) {
if (specstr[s].indexOf(".") < 0) {
sql += "a." + specstr[s] + ",";
list.add(specstr[s]);
} else {
sql += specstr[s] + ",";
list.add(specstr[s].substring(specstr[s].indexOf(".") + 1));
}
}
}
int qamount = Integer.parseInt(CSProperties.getValue(key + "hseamount", "0"));
int r = 0;
HashMap<String, String> typemap = new HashMap();
ArrayList<String> onepathlist = new ArrayList();
typemap.put("child", "a");
for (int i = 1; i < qamount; i++) {
String attrkeys = CSProperties.getValue(key + i + ".hseattrname", "");
// System.out.println(key + i + ".hseattrname" + "=" + attrkeys);
String path = CSProperties.getValue(key + i + ".hseattrpath", "");
String attrbo = CSProperties.getValue(key + i + ".hsebotype", "");
String multitype = CSProperties.getValue(key + i + ".hseisonly", "");
// String value = "";
path = camel4underline(path);
// System.out.println(path);
multitype = camel4underline(multitype);
if (attrkeys.length() > 0) {
attrkeys = camel4underline(attrkeys);
}
attrbo = camel4underline(attrbo);
if (!path.equalsIgnoreCase("Child")) {
List<String> pathlist = Arrays.asList(path.split(","));
int n = 0;
for (n = 0; n < pathlist.size(); n++) {
String p = pathlist.get(n);
String ptype = p.substring(0, p.indexOf(":"));
String pattr = p.substring(p.indexOf(":") + 1, p.lastIndexOf("@"));
String lasttype = p.substring(p.lastIndexOf("@") + 1);
String temppath = "";
String abbr = " p" + r + n;
if (typemap.containsKey(ptype) && !multitype.equalsIgnoreCase(ptype)) {
abbr = typemap.get(ptype);
} else {
typemap.put(ptype, " p" + r + n);
}
if (typemap.get(lasttype) == null) {
System.out.println(pathlist);
}
temppath = " LEFT JOIN ed_" + ptype + abbr + " ON " + typemap.get(lasttype) + "." + pattr
+ " = " + abbr + ".id \r\n";
if (!onepathlist.contains(temppath)) {
onepathlist.add(temppath);
pathwhere += temppath;
}
}
if (attrkeys.length() > 0) {
if (attrkeys.contains(",")) {
List<String> attrkeylist = Arrays.asList(attrkeys.split(","));
for (String attrkey : attrkeylist) {
String attr = attrkey.substring(0, attrkey.lastIndexOf("_"));
// String atype = attrkey.substring(0, attrkey.indexOf("_"));
attrsql += typemap.get(attrbo) + "." + attr + " as " + attrkey + ",";
list.add(attrkey);
}
} else {
String attr = attrkeys.substring(0, attrkeys.lastIndexOf("_"));
// String atype = attrkeys.substring(0, attrkeys.indexOf("_"));
attrsql += typemap.get(attrbo) + "." + attr + " as " + attrkeys + ",";
list.add(attrkeys);
}
}
r++;
} else {
if (attrkeys.length() > 0) {
if (attrkeys.contains(",")) {
List<String> attrkeylist = Arrays.asList(attrkeys.split(","));
for (String attrkey : attrkeylist) {
String attr = attrkey.substring(0, attrkey.lastIndexOf("_"));
attrsql += "a." + attr + " as " + attrkey + ",";
list.add(attrkey);
}
} else {
String attr = attrkeys.substring(0, attrkeys.lastIndexOf("_"));
attrsql += "a." + attr + " as " + attrkeys + ",";
list.add(attrkeys);
}
}
}
}
sql += attrsql;
if (sql.endsWith(",")) {
sql = sql.substring(0, sql.lastIndexOf(","));
}
sql += " from " + "ed_" + camel4underline(type) + " a" + pathwhere;
String where = "";
if (url.length() > 0) {
if (url.contains(",")) {
url = "'" + url.replace(",", "','") + "'";
} else {
url = "'" + url + "'";
}
where = " where a.THE_CNL in (" + url + ")";
} else if (id.length() > 0) {
if (id.contains(",")) {
id = "'" + id.replace(",", "','") + "'";
} else {
id = "'" + id + "'";
}
where = " where a.id in (" + id + ")";
}
if (specwhere.length() == 0) {
sql += where;
} else {
sql += specwhere;
}
if (sql.length() > 0) {
log.info("Config ATTRIBUTS PATH SQL=" + sql);
rs = util.query(sql);
log.info("ATTR list" + list);
while (rs.next()) {
HashMap<String, String> colmap = new HashMap();
String thecnl = rs.getString("the_cnl");
for (String attrname : list) {
String value = rs.getString(attrname);
if (spec.contains(attrname)) {
colmap.put(attrname, value);
} else {
String seqkey = attrname.substring(attrname.lastIndexOf("_") + 1);
String attrtype = CSProperties.getValue(key + seqkey + ".hseattrtype", "");
if (value == null) {
// CSILog.outInfo("--null value--" + attrname, log);
value = "";
}
if (attrtype.equals("enum")) {
if (value.indexOf(":") > 0) {
// value = getEnumValueZH(value, util);
value = NodeUtil.getEnumEnDisplay(value);
}
colmap.put(seqkey, value);
} else {
colmap.put(seqkey, value);
}
}
}
rmap.put(thecnl, colmap);
colmap = null;
}
list = null;
rs.close();
rs = null;
}
} catch (Exception e) {
log.error("Exception", e);
} finally {
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException s) {
rs = null;
}
}
}
return rmap;
}
public static LinkedHashMap<String, HashMap<String, String>> queryAttributesWithConfbyId(String url, String id,
String type, String key, String spec, String specwhere, DBUtil util) {
LinkedHashMap<String, HashMap<String, String>> rmap = new LinkedHashMap();
RowSet rs = null;
try {
String sql = "select a.id,";
List<String> list = new ArrayList();
String pathwhere = "";
String attrsql = "";
if (spec.length() > 0) {
String specstr[] = spec.split(",");
for (int s = 0; s < specstr.length; s++) {
if (specstr[s].indexOf(".") < 0) {
sql += "a." + specstr[s] + ",";
list.add(specstr[s]);
} else {
sql += specstr[s] + ",";
list.add(specstr[s].substring(specstr[s].indexOf(".") + 1));
}
}
}
int qamount = Integer.parseInt(CSProperties.getValue(key + "hseamount", "0"));
int r = 0;
HashMap<String, String> typemap = new HashMap();
ArrayList<String> onepathlist = new ArrayList();
typemap.put("child", "a");
for (int i = 1; i < qamount; i++) {
String attrkeys = CSProperties.getValue(key + i + ".hseattrname", "");
// System.out.println(key + i + ".hseattrname" + "=" + attrkeys);
String path = CSProperties.getValue(key + i + ".hseattrpath", "");
String attrbo = CSProperties.getValue(key + i + ".hsebotype", "");
String multitype = CSProperties.getValue(key + i + ".hseisonly", "");
// if (attrkeys == null || attrkeys.length() == 0) {
// continue;
//
// }
// String value = "";
path = camel4underline(path);
// System.out.println(path);
multitype = camel4underline(multitype);
if (attrkeys.length() > 0) {
attrkeys = camel4underline(attrkeys);
}
attrbo = camel4underline(attrbo);
if (!path.equalsIgnoreCase("Child")) {
List<String> pathlist = Arrays.asList(path.split(","));
int n = 0;
for (n = 0; n < pathlist.size(); n++) {
String p = pathlist.get(n);
String ptype = p.substring(0, p.indexOf(":"));
String pattr = p.substring(p.indexOf(":") + 1, p.lastIndexOf("@"));
String lasttype = p.substring(p.lastIndexOf("@") + 1);
String temppath = "";
String abbr = " p" + r + n;
if (typemap.containsKey(ptype) && !multitype.equalsIgnoreCase(ptype)) {
abbr = typemap.get(ptype);
} else {
typemap.put(ptype, " p" + r + n);
}
if (typemap.get(lasttype) == null) {
System.out.println(pathlist);
}
temppath = " LEFT JOIN ed_" + ptype + abbr + " ON " + typemap.get(lasttype) + "." + pattr
+ " = " + abbr + ".id \r\n";
if (!onepathlist.contains(temppath)) {
onepathlist.add(temppath);
pathwhere += temppath;
}
}
if (attrkeys.length() > 0) {
if (attrkeys.contains(",")) {
List<String> attrkeylist = Arrays.asList(attrkeys.split(","));
for (String attrkey : attrkeylist) {
String attr = attrkey.substring(0, attrkey.lastIndexOf("_"));
// String atype = attrkey.substring(0, attrkey.indexOf("_"));
attrsql += typemap.get(attrbo) + "." + attr + " as " + attrkey + ",";
list.add(attrkey);
}
} else {
String attr = attrkeys.substring(0, attrkeys.lastIndexOf("_"));
// String atype = attrkeys.substring(0, attrkeys.indexOf("_"));
attrsql += typemap.get(attrbo) + "." + attr + " as " + attrkeys + ",";
list.add(attrkeys);
}
}
r++;
} else {
if (attrkeys.length() > 0) {
if (attrkeys.contains(",")) {
List<String> attrkeylist = Arrays.asList(attrkeys.split(","));
for (String attrkey : attrkeylist) {
String attr = attrkey.substring(0, attrkey.lastIndexOf("_"));
attrsql += "a." + attr + " as " + attrkey + ",";
list.add(attrkey);
}
} else {
String attr = attrkeys.substring(0, attrkeys.lastIndexOf("_"));
attrsql += "a." + attr + " as " + attrkeys + ",";
list.add(attrkeys);
}
}
}
}
sql += attrsql;
if (sql.endsWith(",")) {
sql = sql.substring(0, sql.lastIndexOf(","));
}
sql += " from " + "ed_" + camel4underline(type) + " a" + pathwhere;
String where = "";
if (url.length() > 0) {
if (url.contains(",")) {
url = "'" + url.replace(",", "','") + "'";
} else {
url = "'" + url + "'";
}
where = " where a.THE_CNL in (" + url + ")";
} else if (id.length() > 0) {
if (id.contains(",")) {
id = "'" + id.replace(",", "','") + "'";
} else {
id = "'" + id + "'";
}
where = " where a.id in (" + id + ")";
}
if (specwhere.length() == 0) {
sql += where;
} else {
sql += specwhere;
}
if (sql.length() > 0) {
log.info("Config ATTRIBUTS PATH SQL=" + sql);
rs = util.query(sql);
log.info("ATTR list" + list);
while (rs.next()) {
HashMap<String, String> colmap = new HashMap();
String thecnl = rs.getString("id");
for (String attrname : list) {
String value = rs.getString(attrname);
if (spec.contains(attrname)) {
colmap.put(attrname, value);
} else {
String seqkey = attrname.substring(attrname.lastIndexOf("_") + 1);
String attrtype = CSProperties.getValue(key + seqkey + ".hseattrtype", "");
if (value == null) {
// CSILog.outInfo("--null value--" + attrname, log);
value = "";
}
if (attrtype.equals("enum")) {
if (value.indexOf(":") > 0) {
// value = getEnumValueZH(value, util);
value = NodeUtil.getEnumEnDisplay(value);
}
colmap.put(seqkey, value);
} else {
colmap.put(seqkey, value);
}
}
}
rmap.put(thecnl, colmap);
colmap = null;
}
list = null;
rs.close();
rs = null;
}
} catch (Exception e) {
log.error("Exception", e);
} finally {
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException s) {
rs = null;
}
}
}
return rmap;
}
/**
* 按条件进行查询
*
* @param type
* 对象BO
* @param attrmap
* 要获取对象属性的map path为key,获取属性用逗号,分隔,属性加BO类型# ,key为child则获取当前对象属性
* @param conmap
* 查询条件的map,仅限当前对象属性
* @param util
* DBUtil
* @return
* @author GHUANG
* @version 2020年5月2日 下午9:45:59
*/
public static List<HashMap<String, String>> queryAttributes(String type, HashMap<String, String> attrmap,
HashMap<String, String> conmap, DBUtil util) {
String sql = "select a.id,";
RowSet rs = null;
List<HashMap<String, String>> rlist = new ArrayList();
try {
List<String> list = new ArrayList();
String pathwhere = "";
String attrsql = "";
if (attrmap.size() > 0) {
int r = 0;
for (Map.Entry<String, String> map : attrmap.entrySet()) {
String path = map.getKey();
String attrkeys = map.getValue();
path = camel4underline(path);
attrkeys = camel4underline(attrkeys);
if (!path.equalsIgnoreCase("Child")) {
List<String> pathlist = Arrays.asList(path.split(","));
int n = 0;
for (n = 0; n < pathlist.size(); n++) {
String p = pathlist.get(n);
String ptype = p.substring(0, p.indexOf(":"));
String pattr = p.substring(p.indexOf(":") + 1);
String temppath = "";
if (n == 0) {
temppath = " LEFT JOIN ed_" + ptype + " p" + r + n + " ON a." + pattr + " = p" + r + n
+ ".id \r\n";
} else {
temppath = " LEFT JOIN ed_" + ptype + " p" + r + n + " ON p" + r + (n - 1) + "." + pattr
+ " = p" + r + n + ".id \r\n";
}
pathwhere += temppath;
}
if (attrkeys.contains(",")) {
List<String> attrkeylist = Arrays.asList(attrkeys.split(","));
for (String attrkey : attrkeylist) {
String attr = attrkey.substring(0, attrkey.lastIndexOf("_"));
attrsql += "p" + r + (n - 1) + "." + attr + " as " + attrkey + ",";
list.add(attrkey);
}
} else {
String attr = attrkeys.substring(0, attrkeys.lastIndexOf("_"));
attrsql += "p" + r + (n - 1) + "." + attr + " as " + attrkeys + ",";
list.add(attrkeys);
}
r++;
} else {
if (attrkeys.contains(",")) {
List<String> attrkeylist = Arrays.asList(attrkeys.split(","));
for (String attrkey : attrkeylist) {
attrsql += "a." + attrkey + ",";
list.add(attrkey);
}
} else {
attrsql += "a." + attrkeys + ",";
list.add(attrkeys);
}
}
}
} else {
return rlist;
}
sql += attrsql;
if (sql.endsWith(",")) {
sql = sql.substring(0, sql.lastIndexOf(","));
}
sql += " from " + "ed_" + camel4underline(type) + " a" + pathwhere + " where ";
String condition = "";
for (Map.Entry<String, String> artMap : conmap.entrySet()) {
String key = artMap.getKey();
String value = artMap.getValue();
condition += "a." + camel4underline(key) + "='" + value + "' and ";
}
if (condition.endsWith("and ")) {
condition = condition.substring(0, condition.lastIndexOf("and"));
}
sql += condition;
if (sql.length() > 0) {
log.error("ATTRIBUTS PATH SQL=" + sql);
rs = util.query(sql);
while (rs.next()) {
HashMap<String, String> colmap = new HashMap();
for (String attrname : list) {
colmap.put(attrname, rs.getString(attrname));
}
rlist.add(colmap);
}
// rs = null;
conmap = null;
rs.close();
rs = null;
}
} catch (Exception e) {
log.error("Exception", e);
} finally {
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException s) {
rs = null;
}
}
}
return rlist;
}
public static List<HashMap<String, String>> queryBO(String type,
HashMap<String, String> conmap, DBUtil util) {
String sql = "select a.id,";
RowSet rs = null;
List<HashMap<String, String>> rlist = new ArrayList();
try {
List<String> list = new ArrayList();
String pathwhere = "";
sql += "select a.the_cnl from " + "ed_" + camel4underline(type) + " a" + pathwhere + " where ";
String condition = "";
for (Map.Entry<String, String> artMap : conmap.entrySet()) {
String key = artMap.getKey();
String value = artMap.getValue();
condition += "a." + camel4underline(key) + "='" + value + "' and ";
}
if (condition.endsWith("and ")) {
condition = condition.substring(0, condition.lastIndexOf("and"));
}
sql += condition;
if (sql.length() > 0) {
log.info("ATTRIBUTS PATH SQL=" + sql);
rs = util.query(sql);
while (rs.next()) {
HashMap<String, String> colmap = new HashMap();
for (String attrname : list) {
colmap.put(attrname, rs.getString(attrname));
}
rlist.add(colmap);
}
// rs = null;
conmap = null;
rs.close();
rs = null;
}
} catch (Exception e) {
log.error("Exception", e);
} finally {
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException s) {
rs = null;
}
}
}
return rlist;
}
/**
*
* @param url
* 可以多个url
* @param id
* 可以多个id
* @param type
* @param attrmap
* 属性map,格式路径
* @param util
* @return
* @author GHUANG
* @version 2020年6月2日 下午4:10:47
*/
public static HashMap<String, String> queryAttributesbyUrls(String url, String id, String type,
HashMap<String, String> attrmap,
DBUtil util) {
String sql = "select a.id,";
RowSet rs = null;
HashMap<String, String> colmap = new HashMap();
try {
List<String> list = new ArrayList();
String pathwhere = "";
String where = "";
String attrsql = "";
if (url.length() > 0) {
if (url.contains(",")) {
url = "'" + url.replace(",", "','") + "'";
} else {
url = "'" + url + "'";
}
where = " where a.THE_CNL in (" + url + ")";
} else if (id.length() > 0) {
if (id.contains(",")) {
id = "'" + id.replace(",", "','") + "'";
} else {
id = "'" + id + "'";
}
where = " where a.id in (" + id + ")";
} else {
return null;
}
if (attrmap.size() > 0) {
int r = 0;
HashMap<String, String> typemap = new HashMap();
ArrayList<String> onepathlist = new ArrayList();
typemap.put("child", "a");
for (Map.Entry<String, String> map : attrmap.entrySet()) {
String path = map.getKey();
String attrkeys = map.getValue();
path = camel4underline(path);
attrkeys = camel4underline(attrkeys);
if (!path.equalsIgnoreCase("Child")) {
String attrbo = path.substring(path.indexOf("#") + 1);
path = path.substring(0, path.indexOf("#"));
List<String> pathlist = Arrays.asList(path.split(","));
int n = 0;
for (n = 0; n < pathlist.size(); n++) {
String p = pathlist.get(n);
String ptype = p.substring(0, p.indexOf(":"));
String pattr = p.substring(p.indexOf(":") + 1, p.lastIndexOf("@"));
String lasttype = p.substring(p.lastIndexOf("@") + 1);
String temppath = "";
String abbr = " p" + r + n;
if (typemap.containsKey(ptype)) {
abbr = typemap.get(ptype);
} else {
typemap.put(ptype, " p" + r + n);
}
if (typemap.get(lasttype) == null) {
System.out.println(pathlist);
}
temppath = " LEFT JOIN ed_" + ptype + abbr + " ON " + typemap.get(lasttype) + "." + pattr
+ " = " + abbr + ".id \r\n";
if (!onepathlist.contains(temppath)) {
onepathlist.add(temppath);
pathwhere += temppath;
}
}
if (attrkeys.length() > 0) {
if (attrkeys.contains(",")) {
List<String> attrkeylist = Arrays.asList(attrkeys.split(","));
for (String attrkey : attrkeylist) {
String attr = attrkey.substring(0, attrkey.lastIndexOf("_"));
// String atype = attrkey.substring(0, attrkey.indexOf("_"));
attrsql += typemap.get(attrbo) + "." + attr + " as " + attrkey + ",";
list.add(attrkey);
}
} else {
String attr = attrkeys.substring(0, attrkeys.lastIndexOf("_"));
// String atype = attrkeys.substring(0, attrkeys.indexOf("_"));
attrsql += typemap.get(attrbo) + "." + attr + " as " + attrkeys + ",";
list.add(attrkeys);
}
}
r++;
} else {
if (attrkeys.length() > 0) {
if (attrkeys.contains(",")) {
List<String> attrkeylist = Arrays.asList(attrkeys.split(","));
for (String attrkey : attrkeylist) {
String attr = attrkey.substring(0, attrkey.lastIndexOf("_"));
attrsql += "a." + attr + " as " + attrkey + ",";
list.add(attrkey);
}
} else {
String attr = attrkeys.substring(0, attrkeys.lastIndexOf("_"));
attrsql += "a." + attr + " as " + attrkeys + ",";
list.add(attrkeys);
}
}
}
}
} else {
return null;
}
sql += attrsql;
if (sql.endsWith(",")) {
sql = sql.substring(0, sql.lastIndexOf(","));
}
sql += " from " + "ed_" + camel4underline(type) + " a" + pathwhere + " " + where;
if (sql.length() > 0) {
log.info("AttrURLS PATH SQL=" + sql);
rs = util.query(sql);
while (rs.next()) {
colmap.put("id", rs.getString("id"));
for (String attrname : list) {
colmap.put(attrname, rs.getString(attrname));
}
}
rs.close();
rs = null;
}
} catch (Exception e) {
log.error("Exception", e);
} finally {
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException s) {
rs = null;
}
}
}
return colmap;
}
/**
* 单个属性获取
*
* @param url
* @param id
* @param attribute
* @param type
* @param path
* Type:Attribute,Type2:Attribute2
* @param util
* @return
* @author GHUANG
* @version 2020年4月30日 上午11:43:37
*/
public static String getSingleAttribute(String url, String id, String attribute, String type, String path,
DBUtil util) {
String value = "";
RowSet rs = null;
attribute = camel4underline(attribute);
try {
String where = "";
if (url.length() > 0 && !url.equals("centric:")) {
where = " where a.THE_CNL = '" + url + "'";
} else if (id.length() > 0 && !id.equals("1")) {
where = " where a.id = '" + id + "'";
} else {
return "";
}
String pathwhere = "";
String attr = "";
int n = 0;
if (path.length() > 0) {
List<String> pathlist = Arrays.asList(path.split(","));
for (n = 0; n < pathlist.size(); n++) {
String p = pathlist.get(n);
if (p.length() == 0) {
continue;
}
String ptype = camel4underline(p.substring(0, p.indexOf(":")));
String pattr = camel4underline(p.substring(p.indexOf(":") + 1));
String temppath = "";
if (n == 0) {
temppath = " LEFT JOIN ed_" + ptype + " p" + n + " ON a." + pattr + " = p" + n
+ ".id \r\n";
attr = "p0";
} else {
temppath = " LEFT JOIN ed_" + ptype + " p" + n + " ON p" + (n - 1) + "." + pattr
+ " = p" + n + ".id \r\n";
attr = "p" + (n - 1);
}
pathwhere += temppath;
}
} else {
attr = "a";
}
String sql = "select " + attr + "." + attribute + " from ed_" + camel4underline(type)
+ " a"
+ pathwhere + where;
log.info("SINGLE&expres=" + sql);
rs = util.query(sql);
while (rs.next()) {
value = rs.getString(attribute);
}
rs.close();
} catch (Exception e) {
log.error("Exception", e);
} finally {
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException s) {
rs = null;
}
}
}
return value;
}
/**
* 从 id 获取URL
*
* @param id
* @param type
* @param path
* @param util
* @return
* @author GHUANG
* @version 2020年4月30日 上午9:41:30
*/
public static String getBOUrlbyID(String id, String type, String path, DBUtil util) {
if (id.length() == 0) {
return null;
}
if (id.equals("1")) {
return "centric:";
}
String value = "";
RowSet rs = null;
try {
String sql = "select the_cnl from ed_" + camel4underline(type)
+ " where id = '" + id + "'";
log.info("BO=" + sql);
rs = util.query(sql);
while (rs.next()) {
value = rs.getString("the_cnl");
}
rs.close();
rs = null;
} catch (Exception e) {
log.error("Exception", e);
} finally {
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException s) {
rs = null;
}
}
}
return value;
}
/**
* 多值属性获取
*
* @param url
* @param ID
* @param botype
* @param attribute
* @param attrtype
* @param util
* @return
* @author GHUANG
* @version 2020年4月30日 上午11:43:12
*/
public static String getMultiAttribute(String url, String ID, String botype, String attribute,
String attrtype, DBUtil util) {
String sql = "select ";
RowSet rs = null;
String table = "";
botype = camel4underline(botype);
// attribute = camel4underline(attribute);
String id_sql = "";
String value = "";
try {
String mtable = "ed_" + botype;
String leftjoin = "";
if (ID.length() > 0) {
id_sql = " and a.id='" + ID + "'";
} else if (url.length() > 0) {
leftjoin = "left join " + mtable + " b on a.id=b.id ";
id_sql = "and b.the_cnl='" + url + "'";
}
if (attrtype.equals("ref")) {
table = "er_" + botype;
sql += " a.ref_id from " + table + " a " + leftjoin + " where a.attr_id='"
+ attribute + "' " + id_sql + " order by a.map_key";
;
} else if (attrtype.equals("string")) {
table = "et_" + botype;
sql += " a.text_value from " + table + " a " + leftjoin + " where a.attr_id='" + attribute + "' "
+ id_sql
+ "+ order by a.map_key";
} else if (attrtype.equals("number")) {
table = "en_" + botype;
sql += " a.num_value from " + table + " a " + leftjoin + " where a.attr_id='" + attribute + "' "
+ id_sql
+ " order by a.map_key";
}
log.info("MULTI=" + sql);
if (sql.length() > 0) {
rs = util.query(sql);
}
while (rs.next()) {
if (attrtype.equals("ref")) {
value += rs.getString("ref_id") + ",";
} else if (attrtype.equals("number")) {
value += rs.getString("num_value") + ",";
} else if (attrtype.equals("string")) {
value += rs.getString("text_value") + ",";
}
}
rs.close();
rs = null;
} catch (Exception e) {
log.error("Exception", e);
} finally {
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException s) {
rs = null;
}
}
}
if (value.endsWith(",")) {
value = value.substring(0, value.lastIndexOf(","));
}
return value;
}
/**
* 获取Enum值
*
* @param attribute
* @return
* @author GHUANG
* @version 2019年12月29日 下午4:46:23
*/
public static String getEnumValueZH(String attribute, DBUtil util) {
RowSet rs = null;
String value = "";
try {
String sql = "select a.text_value from et_locale_configuration a where a.map_key='" + attribute
+ "' and id in(select id from ed_locale_configuration b where b.node_name='zh')";
log.info("ENUM SEARCH=" + sql);
if (sql.length() > 0) {
rs = util.query(sql);
}
while (rs.next()) {
value = rs.getString(1);
}
rs.close();
rs = null;
} catch (Exception e) {
log.error("Exception", e);
} finally {
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException s) {
rs = null;
}
}
}
return value;
}
}
| 40.357204 | 166 | 0.401313 |
f82b297ab0283aab5e85cc9f8000edac57c303ac | 6,015 | /*
*
* * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
* * For more information: http://www.orientechnologies.com
*
*/
package com.orientechnologies.orient.core.record.impl;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.record.ORecordElement;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.record.ORecordAbstract;
import com.orientechnologies.orient.core.serialization.OMemoryStream;
import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializerFactory;
import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializerRaw;
/**
* The rawest representation of a record. It's schema less. Use this if you need to store Strings or byte[] without matter about the
* content. Useful also to store multimedia contents and binary files. The object can be reused across calls to the database by
* using the reset() at every re-use.
*/
@SuppressWarnings({ "unchecked" })
public class ORecordBytes extends ORecordAbstract {
private static final long serialVersionUID = 1L;
public static final byte RECORD_TYPE = 'b';
private static final byte[] EMPTY_SOURCE = new byte[] {};
public ORecordBytes() {
setup();
}
public ORecordBytes(final ODatabaseDocumentInternal iDatabase) {
setup();
ODatabaseRecordThreadLocal.INSTANCE.set(iDatabase);
}
public ORecordBytes(final ODatabaseDocumentInternal iDatabase, final byte[] iSource) {
this(iSource);
ODatabaseRecordThreadLocal.INSTANCE.set(iDatabase);
}
public ORecordBytes(final byte[] iSource) {
super(iSource);
_dirty = true;
_contentChanged = true;
setup();
}
public ORecordBytes(final ORID iRecordId) {
_recordId = (ORecordId) iRecordId;
setup();
}
public ORecordBytes reset(final byte[] iSource) {
reset();
_source = iSource;
return this;
}
public ORecordBytes copy() {
return (ORecordBytes) copyTo(new ORecordBytes());
}
@Override
public ORecordBytes fromStream(final byte[] iRecordBuffer) {
_source = iRecordBuffer;
_status = ORecordElement.STATUS.LOADED;
return this;
}
@Override
public byte[] toStream() {
return _source;
}
public byte getRecordType() {
return RECORD_TYPE;
}
@Override
protected void setup() {
super.setup();
_recordFormat = ORecordSerializerFactory.instance().getFormat(ORecordSerializerRaw.NAME);
}
/**
* Reads the input stream in memory. This is less efficient than {@link #fromInputStream(InputStream, int)} because allocation is
* made multiple times. If you already know the input size use {@link #fromInputStream(InputStream, int)}.
*
* @param in
* Input Stream, use buffered input stream wrapper to speed up reading
* @return Buffer read from the stream. It's also the internal buffer size in bytes
* @throws IOException
*/
public int fromInputStream(final InputStream in) throws IOException {
final OMemoryStream out = new OMemoryStream();
try {
final byte[] buffer = new byte[OMemoryStream.DEF_SIZE];
int readBytesCount;
while (true) {
readBytesCount = in.read(buffer, 0, buffer.length);
if (readBytesCount == -1) {
break;
}
out.write(buffer, 0, readBytesCount);
}
out.flush();
_source = out.toByteArray();
} finally {
out.close();
}
_size = _source.length;
return _size;
}
/**
* Reads the input stream in memory specifying the maximum bytes to read. This is more efficient than
* {@link #fromInputStream(InputStream)} because allocation is made only once.
*
* @param in
* Input Stream, use buffered input stream wrapper to speed up reading
* @param maxSize
* Maximum size to read
* @return Buffer count of bytes that are read from the stream. It's also the internal buffer size in bytes
* @throws IOException
* if an I/O error occurs.
*/
public int fromInputStream(final InputStream in, final int maxSize) throws IOException {
final byte[] buffer = new byte[maxSize];
int totalBytesCount = 0;
int readBytesCount;
while (totalBytesCount < maxSize) {
readBytesCount = in.read(buffer, totalBytesCount, buffer.length - totalBytesCount);
if (readBytesCount == -1) {
break;
}
totalBytesCount += readBytesCount;
}
if (totalBytesCount == 0) {
_source = EMPTY_SOURCE;
_size = 0;
} else if (totalBytesCount == maxSize) {
_source = buffer;
_size = maxSize;
} else {
_source = Arrays.copyOf(buffer, totalBytesCount);
_size = totalBytesCount;
}
return _size;
}
public void toOutputStream(final OutputStream out) throws IOException {
checkForLoading();
if (_source.length > 0) {
out.write(_source);
}
}
}
| 33.049451 | 133 | 0.675312 |
216192a62cfc83ba504975092513c45360c3316b | 317 | package com.activeandroid.util;
import java.util.HashMap;
final class SQLiteUtils$1 extends HashMap<Class<?>, SQLiteUtils.SQLiteType>
{
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.activeandroid.util.SQLiteUtils.1
* JD-Core Version: 0.6.0
*/ | 26.416667 | 83 | 0.722397 |
45d2c11386368f7d4707fe5c01efe47d637a04e4 | 231 | package com.funrep.lispinjava.errors;
import com.funrep.lispinjava.lispvalues.LispError;
public class ArgCountError extends LispError {
public ArgCountError() {
super("Argument count doesn't match the function.");
}
}
| 21 | 57 | 0.757576 |
8aea1d9d2e95b97f9464537fd11bb701fd48037e | 344 | package io.snice.networking.bundles.buffer;
import io.snice.buffer.Buffer;
import io.snice.buffer.Buffers;
import io.snice.networking.common.Connection;
public interface BufferConnection extends Connection<BufferEvent> {
void send(Buffer buffer);
default void send(final String buffer) {
send(Buffers.wrap(buffer));
}
}
| 22.933333 | 67 | 0.752907 |
a79ae92a4af42830692250860aef44cfa881592e | 1,146 | package org.carlos_witek.back_to_the_future_iii;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Application {
public static void main( String[] args ) {
printCurrentThreadName( "poin1" );
ExecutorService executorService = Executors.newCachedThreadPool();
final CompletableFuture<Void> future1a = CompletableFuture.runAsync( task( "poin2", 2 ),
executorService );
final CompletableFuture<Void> future1b = CompletableFuture.runAsync( task( "poin3", 2 ),
executorService );
future1b.join();
final CompletableFuture<Void> future2 = future1a.thenRun( task( "poin5", 3 ) );
future2.join();
}
private static Runnable task( final String string, final long millis ) {
return () -> {
printCurrentThreadName( string );
if ( millis > 0 ) {
try {
Thread.sleep( millis );
} catch ( InterruptedException e ) {
e.printStackTrace();
}
}
};
}
private static void printCurrentThreadName( final String string ) {
System.out.println( string + " : " + Thread.currentThread().getName() );
}
}
| 25.466667 | 90 | 0.705934 |
86ccba52dc3226ad79b366331ddebb82a3c3cef4 | 4,054 | package org.jzy3d.emulgl.opengl;
import org.junit.Test;
import org.jzy3d.chart.Chart;
import org.jzy3d.chart.factories.EmulGLChartFactory;
import org.jzy3d.colors.Color;
import org.jzy3d.colors.ColorMapper;
import org.jzy3d.colors.colormaps.ColorMapRainbow;
import org.jzy3d.maths.Range;
import org.jzy3d.painters.IPainter;
import org.jzy3d.plot3d.builder.Mapper;
import org.jzy3d.plot3d.builder.SurfaceBuilder;
import org.jzy3d.plot3d.builder.concrete.OrthonormalGrid;
import org.jzy3d.plot3d.primitives.Shape;
import org.jzy3d.plot3d.primitives.Wireframeable;
import org.jzy3d.plot3d.primitives.axis.AxisBox;
import org.jzy3d.plot3d.rendering.canvas.Quality;
import org.jzy3d.utils.LoggerUtils;
import static org.mockito.Mockito.*;
/**
* {@AxisBox} and
* @author martin
*
*/
public class TestDepthRange {
@Test
public void whenRenderAxis_DepthRangeModifiedByAxis() {
LoggerUtils.minimal();
// When
EmulGLChartFactory factory = new EmulGLChartFactory();
Chart chart = factory.newChart(Quality.Advanced());
Shape surface = surface();
chart.add(surface);
IPainter painter = spy(chart.getView().getPainter());
// ----------------------------------------------
// Then surface will NOT update depth range
surface.setPolygonWireframeDepthTrick(false);
surface.draw(painter);
verify(painter, never()).glDepthRangef(0, 1);
// ----------------------------------------------
// Then axis will update depth range
chart.getView().getAxis().draw(painter);
// Called that way to push the depth range farther
verify(painter, atLeast(1)).glDepthRangef(AxisBox.NO_OVERLAP_DEPTH_RATIO, 1);
// Called that way for reset
verify(painter, atLeast(1)).glDepthRangef(0, 1);
}
@Test
public void whenRenderSurface_DepthRangeModifiedBySurface() {
LoggerUtils.minimal();
// When
EmulGLChartFactory factory = new EmulGLChartFactory();
Chart chart = factory.newChart(Quality.Advanced());
Shape surface = surface();
chart.add(surface);
IPainter painter = spy(chart.getView().getPainter());
// ----------------------------------------------
// Then surface will NOT update depth range
surface.setPolygonWireframeDepthTrick(false);
surface.draw(painter);
verify(painter, never()).glDepthRangef(0, 1);
// ----------------------------------------------
// Then surface WILL update depth range
surface.setPolygonWireframeDepthTrick(true);
surface.draw(painter);
// config for face
verify(painter, atLeast(1)).glDepthRangef(0, 1-Wireframeable.NO_OVERLAP_DEPTH_RATIO);
// config for wireframe
verify(painter, atLeast(1)).glDepthRangef(Wireframeable.NO_OVERLAP_DEPTH_RATIO, 1);
// back to default config
verify(painter, atLeast(1)).glDepthRangef(0, 1);
// ----------------------------------------------
// Then axis will update depth range
chart.getView().getAxis().draw(painter);
// Called that way to push the depth range farther
verify(painter, atLeast(1)).glDepthRangef(AxisBox.NO_OVERLAP_DEPTH_RATIO, 1);
// Called that way for reset
verify(painter, atLeast(1)).glDepthRangef(0, 1);
}
private static Shape surface() {
Mapper mapper = new Mapper() {
@Override
public double f(double x, double y) {
return x * Math.sin(x * y);
}
};
Range range = new Range(-3, 3);
int steps = 50;
SurfaceBuilder builder = new SurfaceBuilder();
Shape surface = builder.orthonormal(new OrthonormalGrid(range, steps, range, steps), mapper);
ColorMapper colorMapper = new ColorMapper(new ColorMapRainbow(), surface.getBounds().getZmin(),
surface.getBounds().getZmax(), new Color(1, 1, 1, ALPHA_FACTOR));
surface.setColorMapper(colorMapper);
surface.setFaceDisplayed(true);
surface.setWireframeDisplayed(true);
surface.setWireframeColor(Color.BLACK);
return surface;
}
static final float ALPHA_FACTOR = 0.75f;
}
| 30.02963 | 99 | 0.659102 |
18d04974ecef5041f18b567382587a6238935b9e | 2,392 | /*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.polardbx.druid.bvt.sql.mysql.select;
import com.alibaba.polardbx.druid.sql.MysqlTest;
import com.alibaba.polardbx.druid.sql.SQLUtils;
import com.alibaba.polardbx.druid.sql.ast.SQLStatement;
import com.alibaba.polardbx.druid.sql.ast.statement.SQLSelectStatement;
import com.alibaba.polardbx.druid.sql.parser.SQLParserFeature;
import com.alibaba.polardbx.druid.util.JdbcConstants;
import java.util.List;
public class MySqlSelectTest_175_hints extends MysqlTest {
public void test_0() throws Exception {
String sql = "SELECT/!TDDL:t1.id=1 and t2.id=1*/ * FROM t1 INNER JOIN SELECT val FROM t2 WHERE id=1";
//
List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL, SQLParserFeature.TDDLHint);
SQLSelectStatement stmt = (SQLSelectStatement)statementList.get(0);
assertEquals(1, statementList.size());
assertEquals("SELECT /*TDDL:t1.id=1 and t2.id=1*/ *\n" +
"FROM t1\n" +
"\tINNER JOIN (\n" +
"\t\tSELECT val\n" +
"\t\tFROM t2\n" +
"\t\tWHERE id = 1\n" +
"\t)", stmt.toString());
assertEquals("select /*TDDL:t1.id=1 and t2.id=1*/ *\n" +
"from t1\n" +
"\tinner join (\n" +
"\t\tselect val\n" +
"\t\tfrom t2\n" +
"\t\twhere id = 1\n" +
"\t)", stmt.toLowerCaseString());
assertEquals("SELECT /*TDDL:t1.id=1 and t2.id=1*/ *\n" +
"FROM t1\n" +
"\tINNER JOIN (\n" +
"\t\tSELECT val\n" +
"\t\tFROM t2\n" +
"\t\tWHERE id = ?\n" +
"\t)", stmt.toParameterizedString());
}
} | 37.375 | 121 | 0.61413 |
fcea561a042eb856e194448654217e55557339f2 | 779 | package com.tonels.temp.large;
import com.alibaba.excel.EasyExcel;
import com.tonels.core.large.LargeDataTest;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
/**
* @author Jiaju Zhuang
*/
@Ignore
public class TempLargeDataTest {
private static final Logger LOGGER = LoggerFactory.getLogger(LargeDataTest.class);
@Test
public void read() throws Exception {
long start = System.currentTimeMillis();
EasyExcel.read(new FileInputStream("D:\\test\\MRP生产视图(1).xlsx"), LargeData.class, new LargeDataListener())
.headRowNumber(2).sheet().doRead();
LOGGER.info("Large data total time spent:{}", System.currentTimeMillis() - start);
}
}
| 28.851852 | 114 | 0.716303 |
0b48fcfcfb46b4400eb3fb478959ec92a1df0268 | 16,309 | /*
* Copyright (c) 2006-2017 DMDirc Developers
*
* 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.dmdirc;
import com.dmdirc.events.QuerySelfActionEvent;
import com.dmdirc.events.QuerySelfMessageEvent;
import com.dmdirc.events.ServerAuthNoticeEvent;
import com.dmdirc.events.ServerAwayEvent;
import com.dmdirc.events.ServerBackEvent;
import com.dmdirc.events.ServerCtcpEvent;
import com.dmdirc.events.ServerCtcpReplyEvent;
import com.dmdirc.events.ServerErrorEvent;
import com.dmdirc.events.ServerGotPingEvent;
import com.dmdirc.events.ServerInviteReceivedEvent;
import com.dmdirc.events.ServerMotdEndEvent;
import com.dmdirc.events.ServerMotdLineEvent;
import com.dmdirc.events.ServerMotdStartEvent;
import com.dmdirc.events.ServerNickChangeEvent;
import com.dmdirc.events.ServerNoPingEvent;
import com.dmdirc.events.ServerNoticeEvent;
import com.dmdirc.events.ServerNumericEvent;
import com.dmdirc.events.ServerPingSentEvent;
import com.dmdirc.events.ServerServerNoticeEvent;
import com.dmdirc.events.ServerStonedEvent;
import com.dmdirc.events.ServerUnknownActionEvent;
import com.dmdirc.events.ServerUnknownMessageEvent;
import com.dmdirc.events.ServerUnknownNoticeEvent;
import com.dmdirc.events.ServerUserModesEvent;
import com.dmdirc.events.ServerWalldesyncEvent;
import com.dmdirc.events.ServerWallopsEvent;
import com.dmdirc.events.ServerWallusersEvent;
import com.dmdirc.events.StatusBarMessageEvent;
import com.dmdirc.events.UserInfoResponseEvent;
import com.dmdirc.interfaces.Connection;
import com.dmdirc.events.eventbus.EventBus;
import com.dmdirc.parser.common.AwayState;
import com.dmdirc.parser.events.AuthNoticeEvent;
import com.dmdirc.parser.events.AwayStateEvent;
import com.dmdirc.parser.events.ChannelSelfJoinEvent;
import com.dmdirc.parser.events.ConnectErrorEvent;
import com.dmdirc.parser.events.ErrorInfoEvent;
import com.dmdirc.parser.events.InviteEvent;
import com.dmdirc.parser.events.MOTDEndEvent;
import com.dmdirc.parser.events.MOTDLineEvent;
import com.dmdirc.parser.events.MOTDStartEvent;
import com.dmdirc.parser.events.NickChangeEvent;
import com.dmdirc.parser.events.NickInUseEvent;
import com.dmdirc.parser.events.NumericEvent;
import com.dmdirc.parser.events.ParserErrorEvent;
import com.dmdirc.parser.events.PingFailureEvent;
import com.dmdirc.parser.events.PingSentEvent;
import com.dmdirc.parser.events.PingSuccessEvent;
import com.dmdirc.parser.events.PrivateActionEvent;
import com.dmdirc.parser.events.PrivateCTCPEvent;
import com.dmdirc.parser.events.PrivateCTCPReplyEvent;
import com.dmdirc.parser.events.PrivateMessageEvent;
import com.dmdirc.parser.events.PrivateNoticeEvent;
import com.dmdirc.parser.events.ServerReadyEvent;
import com.dmdirc.parser.events.SocketCloseEvent;
import com.dmdirc.parser.events.UnknownActionEvent;
import com.dmdirc.parser.events.UnknownMessageEvent;
import com.dmdirc.parser.events.UnknownNoticeEvent;
import com.dmdirc.parser.events.UserInfoEvent;
import com.dmdirc.parser.events.UserModeChangeEvent;
import com.dmdirc.parser.events.UserModeDiscoveryEvent;
import com.dmdirc.parser.events.WallDesyncEvent;
import com.dmdirc.parser.events.WallopEvent;
import com.dmdirc.parser.events.WalluserEvent;
import com.dmdirc.ui.StatusMessage;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import javax.annotation.Nonnull;
import net.engio.mbassy.listener.Handler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.dmdirc.util.LogUtils.APP_ERROR;
import static com.dmdirc.util.LogUtils.USER_ERROR;
/**
* Handles parser events for a Server object.
*/
public class ServerEventHandler extends EventHandler {
private static final Logger LOG = LoggerFactory.getLogger(ServerEventHandler.class);
/** The server instance that owns this event handler. */
private final Server owner;
/** Group chat manager to poke for channel events. */
private final GroupChatManagerImpl groupChatManager;
/** Event bus to post events to. */
private final EventBus eventBus;
/**
* Creates a new instance of ServerEventHandler.
*
* @param owner The Server instance that we're handling events for
* @param eventBus The event bus to post events to
*/
public ServerEventHandler(final Server owner, final GroupChatManagerImpl groupChatManager,
final EventBus eventBus) {
this.owner = owner;
this.groupChatManager = groupChatManager;
this.eventBus = eventBus;
}
@Nonnull
@Override
protected Connection getConnection() {
return owner;
}
@Handler
public void onChannelSelfJoin(final ChannelSelfJoinEvent event) {
groupChatManager.addChannel(event.getChannel());
}
@Handler
public void onPrivateMessage(final PrivateMessageEvent event) {
if (!owner.hasQuery(event.getHost())) {
((Query) owner.getQuery(event.getHost())).onPrivateMessage(event);
}
}
@Handler
public void onPrivateAction(final PrivateActionEvent event) {
if (!owner.hasQuery(event.getHost())) {
((Query) owner.getQuery(event.getHost())).onPrivateAction(event);
}
}
@Handler
public void onWhoisEvent(final UserInfoEvent event) {
eventBus.publishAsync(new UserInfoResponseEvent(
event.getDate(), owner, owner.getUser(event.getClient().getNickname()),
event.getInfo()));
}
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
@Handler
public void onErrorInfo(final ParserErrorEvent event) {
LOG.warn(APP_ERROR, "Error in parser", event.getThrowable());
}
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
@Handler
public void onErrorInfo(final ErrorInfoEvent event) {
final StringBuilder errorString = new StringBuilder();
errorString.append("Parser exception.\n\n");
errorString.append("\tLast line:\t");
errorString.append(event.getErrorInfo().getLastLine()).append('\n');
errorString.append("\tServer:\t");
errorString.append(owner.getAddress()).append('\n');
errorString.append("\tAdditional Information:\n");
for (final String line : event.getParser().getServerInformationLines()) {
errorString.append("\t\t").append(line).append('\n');
}
final Exception ex = event.getErrorInfo().isException() ? event.getErrorInfo().getException()
: new Exception(errorString.toString()); // NOPMD
LOG.warn(event.getErrorInfo().isUserError() ? USER_ERROR : APP_ERROR,
event.getErrorInfo().getData(), ex);
}
@Handler
public void onPrivateCTCP(final PrivateCTCPEvent event) {
final ServerCtcpEvent coreEvent = new ServerCtcpEvent(owner, owner.getUser(event.getHost()),
event.getType(), event.getMessage());
eventBus.publish(coreEvent);
if (!coreEvent.isHandled()) {
owner.sendCTCPReply(owner.getUser(event.getHost()).getNickname(), event.getType(),
event.getMessage());
}
}
@Handler
public void onPrivateCTCPReply(final PrivateCTCPReplyEvent event) {
eventBus.publish(new ServerCtcpReplyEvent(owner, owner.getUser(event.getHost()),
event.getType(), event.getMessage()));
}
@Handler
public void onSocketClosed(final SocketCloseEvent event) {
if (owner.getParser().orElse(null) == event.getParser()) {
owner.onSocketClosed();
}
}
@Handler
public void onPrivateNotice(final PrivateNoticeEvent event) {
eventBus.publishAsync(new ServerNoticeEvent(owner, owner.getUser(event.getHost()),
event.getMessage()));
}
@Handler
public void onServerNotice(final com.dmdirc.parser.events.ServerNoticeEvent event) {
eventBus.publishAsync(
new ServerServerNoticeEvent(owner, owner.getLocalUser().get(), event.getMessage()));
}
@Handler
public void onMOTDStart(final MOTDStartEvent event) {
eventBus.publishAsync(new ServerMotdStartEvent(owner, event.getData()));
}
@Handler
public void onMOTDLine(final MOTDLineEvent event) {
eventBus.publishAsync(new ServerMotdLineEvent(owner, event.getData()));
}
@Handler
public void onMOTDEnd(final MOTDEndEvent event) {
eventBus.publishAsync(new ServerMotdEndEvent(owner, event.getData()));
}
@Handler
public void onNumeric(final NumericEvent event) {
eventBus.publishAsync(new ServerNumericEvent(owner, event.getNumeric(), event.getToken()));
}
@Handler
public void onPingFailed(final PingFailureEvent event) {
eventBus.publishAsync(new StatusBarMessageEvent(new StatusMessage(
"No ping reply from " + owner.getWindowModel().getName() + " for over " +
(int) Math.floor(event.getParser().getPingTime() / 1000.0) + " seconds.",
owner.getWindowModel().getConfigManager())));
eventBus.publishAsync(new ServerNoPingEvent(owner, event.getParser().getPingTime()));
if (event.getParser().getPingTime()
>= owner.getWindowModel().getConfigManager().getOptionInt("server", "pingtimeout")) {
LOG.warn("Server appears to be stoned, reconnecting");
eventBus.publishAsync(new ServerStonedEvent(owner));
owner.reconnect();
}
}
@Handler
public void onPingSent(final PingSentEvent event) {
eventBus.publishAsync(new ServerPingSentEvent(owner));
}
@Handler
public void onPingSuccess(final PingSuccessEvent event) {
eventBus.publishAsync(new ServerGotPingEvent(owner,
owner.getParser().get().getServerLatency()));
}
@Handler
public void onAwayState(final AwayStateEvent event) {
owner.updateAwayState(event.getNewState() == AwayState.AWAY ?
Optional.of(event.getReason()) : Optional.empty());
if (event.getNewState() == AwayState.AWAY) {
eventBus.publishAsync(new ServerAwayEvent(owner, event.getReason()));
} else if (event.getOldState() != AwayState.UNKNOWN) {
eventBus.publishAsync(new ServerBackEvent(owner));
}
}
@Handler
public void onConnectError(final ConnectErrorEvent event) {
owner.onConnectError(event.getErrorInfo());
}
@Handler
public void onNickInUse(final NickInUseEvent event) {
final String lastNick = event.getParser().getLocalClient().getNickname();
// If our last nick is still valid, ignore the in use message
if (!event.getParser().getStringConverter().equalsIgnoreCase(lastNick, event.getNickname())) {
return;
}
String newNick = lastNick + new Random().nextInt(10);
final List<String> alts = owner.getProfile().getNicknames();
int offset = 0;
// Loop so we can check case sensitivity
for (String alt : alts) {
offset++;
if (event.getParser().getStringConverter().equalsIgnoreCase(alt, lastNick)) {
break;
}
}
if (offset < alts.size() && !alts.get(offset).isEmpty()) {
newNick = alts.get(offset);
}
event.getParser().getLocalClient().setNickname(newNick);
}
@Handler
public void onServerReady(final ServerReadyEvent event) {
owner.onPost005();
}
@Handler
public void onNoticeAuth(final AuthNoticeEvent event) {
eventBus.publishAsync(new ServerAuthNoticeEvent(owner, event.getMessage()));
}
@Handler
public void onUnknownNotice(final UnknownNoticeEvent event) {
eventBus.publishAsync(new ServerUnknownNoticeEvent(
owner, event.getHost(), event.getTarget(),event.getMessage()));
}
@Handler
public void onUnknownMessage(final UnknownMessageEvent event) {
if (event.getParser().getLocalClient().equals(event.getParser().getClient(event.getHost()))) {
// Local client
eventBus.publishAsync(
new QuerySelfMessageEvent(
(Query) owner.getQuery(event.getTarget()),
owner.getLocalUser().get(),
event.getMessage()));
} else {
eventBus.publishAsync(new ServerUnknownMessageEvent(
owner, event.getHost(), event.getTarget(), event.getMessage()));
}
}
@Handler
public void onUnknownAction(final UnknownActionEvent event) {
if (event.getParser().getLocalClient().equals(event.getParser().getClient(event.getHost()))) {
// Local client
eventBus.publishAsync(
new QuerySelfActionEvent(
(Query) owner.getQuery(event.getTarget()),
owner.getLocalUser().get(),
event.getMessage()));
} else {
eventBus.publishAsync(new ServerUnknownActionEvent(
owner, event.getHost(), event.getTarget(), event.getMessage()));
}
}
@Handler
public void onUserModeChanged(final UserModeChangeEvent event) {
eventBus.publishAsync(new ServerUserModesEvent(
owner, owner.getUser(event.getClient().getHostname()), event.getModes()));
}
@Handler
public void onUserModeDiscovered(final UserModeDiscoveryEvent event) {
eventBus.publishAsync(new ServerUserModesEvent(
owner, owner.getUser(event.getClient().getHostname()), event.getModes()));
}
@Handler
public void onInvite(final InviteEvent event) {
final Invite invite = new Invite(owner.getInviteManager(), event.getChannel(),
owner.getUser(event.getUserHost()));
owner.getInviteManager().addInvite(invite);
eventBus.publishAsync(new ServerInviteReceivedEvent(owner,
owner.getUser(event.getUserHost()), event.getChannel(), invite));
}
@Handler
public void onWallop(final WallopEvent event) {
eventBus.publishAsync(new ServerWallopsEvent(owner,
owner.getUser(event.getHost()), event.getMessage()));
}
@Handler
public void onWalluser(final WalluserEvent event) {
eventBus.publishAsync(new ServerWallusersEvent(owner,
owner.getLocalUser().get(), event.getMessage()));
}
@Handler
public void onWallDesync(final WallDesyncEvent event) {
eventBus.publishAsync(new ServerWalldesyncEvent(owner,
owner.getLocalUser().get(), event.getMessage()));
}
@Handler
public void onNickChanged(final NickChangeEvent event) {
if (event.getClient().equals(owner.getParser().get().getLocalClient())) {
eventBus.publishAsync(new ServerNickChangeEvent(owner,
event.getOldNick(), event.getClient().getNickname()));
owner.updateTitle();
}
owner.handleNickChange(event.getClient(), event.getOldNick());
}
@Handler
public void onServerError(final com.dmdirc.parser.events.ServerErrorEvent event) {
eventBus.publishAsync(new ServerErrorEvent(owner, event.getMessage()));
}
}
| 38.738717 | 119 | 0.694463 |
35a18c56246894fead2de6e47c9fc996033831b1 | 536 | //package org.launchcode.neighborgoods;
//@Configuration
//class WebApplicationConfig implements WebMvcConfigurer {
//
// // Create spring-managed object to allow the app to access our filter
// @Bean
// public AuthenticationFilter authenticationFilter() {
// return new AuthenticationFilter();
// }
//
// // Register the filter with the Spring container
// @Override
// public void addInterceptors(InterceptorRegistry registry) {
// registry.addInterceptor( authenticationFilter() );
// }
//
//}
| 28.210526 | 75 | 0.69403 |
e822c92f6b7b99f9cda4056b14d04ab35df68bcc | 9,419 | package ru.job4j;
/**
* @author Sergey Volkov (rusobraz@mail.ru)
* @version $Id$
* @since 29.09.2018
*/
import ru.job4j.start.*;
import ru.job4j.models.Item;
import org.junit.Test;
import org.junit.Before;
import org.junit.After;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static java.awt.SystemColor.menu;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertThat;
/**
* @author Sergey Volkov (rusobraz@mail.ru)
* @version $Id$
* @since 26.02.2018
*/
public class StartUIJOutPutTest {
private final PrintStream stdout = System.out;
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
private final String showMenu = String.valueOf(new StringBuilder()
.append("//////////////////////////////////////////////////////////")
.append(System.lineSeparator())
.append("Menu")
.append(System.lineSeparator())
.append("Add the request - 0")
.append(System.lineSeparator())
.append("Show all applications - 1")
.append(System.lineSeparator())
.append("Edit the application id - 2")
.append(System.lineSeparator())
.append("Delete the request id - 3")
.append(System.lineSeparator())
.append("Select the application id - 4")
.append(System.lineSeparator())
.append("Choose the application name - 5")
.append(System.lineSeparator())
.append("The program exit - 6")
.append(System.lineSeparator())
.append("//////////////////////////////////////////////////////////")
.append(System.lineSeparator())
.toString());
@Before
public void loadOutPut() {
System.setOut(new PrintStream(out));
}
@After
public void backOutPut() {
System.setOut(this.stdout);
}
@Test
public void whenEditDeleteExceptDelSelectByIdSelectByNameExitThenShow() {
Tracker tracker = new Tracker();
tracker.add(new Item("test name", "test desc"));
String id = tracker.getAll().get(0).getId();
String name = tracker.getAll().get(0).getName();
String[] massShow = {"0", "second test name", "second test desc", "1", "2", id, "new name test", "new desc test", "2", "111", "new name test", "new desc test", "4", id, "4", "111", "5", "new name test", "5", "name", "3", id, "3", id, "6"};
StubInput input = new StubInput(massShow);
new StartUIJ(input, tracker).initConsumer(StartUIJ::init);
assertThat(
new String(out.toByteArray()),
is(
new StringBuilder()
.append(showMenu)//Add Item
.append("------------ Adding new applications --------------")
.append(System.lineSeparator())
.append("------------ A new application getId : ")
.append(tracker.findByName("second test name").get(0).getId())
.append(" -----------")
.append(System.lineSeparator())
.append(showMenu)//Show Item
.append("------------Review of all applications---------------")
.append(System.lineSeparator())
.append("0) id: ")
.append(id)
.append(" name: test name description: test desc")
.append(System.lineSeparator())
.append("1) id: ")
.append(tracker.findByName("second test name").get(0).getId())
.append(" name: second test name description: second test desc")
.append(System.lineSeparator())
.append(showMenu)//Edit Item
.append("------------Edit the application id--------------")
.append(System.lineSeparator())
.append("------------- The parameters application id: ")
.append(id)
.append(" ----------------")
.append(System.lineSeparator())
.append("name: test name")
.append(System.lineSeparator())
.append("description: test desc")
.append(System.lineSeparator())
.append("Replaced with the following settings: ")
.append(System.lineSeparator())
.append("new name: new name test")
.append(System.lineSeparator())
.append("new description: new desc test")
.append(System.lineSeparator())
.append(showMenu)//No Edit
.append("------------Edit the application id--------------")
.append(System.lineSeparator())
.append("-----------Application id: 111 does not exist-------------------")
.append(System.lineSeparator())
.append(showMenu)//Find id
.append("---------------The output of the application to the screen id---------------")
.append(System.lineSeparator())
.append("------------The parameters application id: ")
.append(id)
.append(" ------------------")
.append(System.lineSeparator())
.append("name: new name test")
.append(System.lineSeparator())
.append("description: new desc test")
.append(System.lineSeparator())
.append(showMenu)//No find id
.append("---------------The output of the application to the screen id---------------")
.append(System.lineSeparator())
.append("-----------Application id: 111 does not exist-------------------")
.append(System.lineSeparator())
.append(showMenu)//Find name
.append("------------The choice of applications by name--------------")
.append(System.lineSeparator())
.append("----------You have the following application name: new name test ----------------")
.append(System.lineSeparator())
.append("0) id: ")
.append(id)
.append(" description: new desc test")
.append(System.lineSeparator())
.append(showMenu)//No find name
.append("------------The choice of applications by name--------------")
.append(System.lineSeparator())
.append("-------------Applications with the name: name does not exist-------------------")
.append(System.lineSeparator())
.append(showMenu)//Delete
.append("------------The withdrawal of an application by id --------------")
.append(System.lineSeparator())
.append("Application id: ")
.append(id)
.append(System.lineSeparator())
.append("name: new name test")
.append(System.lineSeparator())
.append("description: new desc test")
.append(System.lineSeparator())
.append("-------------------Deleted----------------------")
.append(System.lineSeparator())
.append(showMenu)//No delete
.append("------------The withdrawal of an application by id --------------")
.append(System.lineSeparator())
.append("----------- Application id: ")
.append(id)
.append(" does not exist-------------------")
.append(System.lineSeparator())
.append(showMenu)
.append("------------Exit!--------------")
.append(System.lineSeparator())
.toString()
)
);
}
} | 54.445087 | 247 | 0.412252 |
fd6fcacdd8dd9b20cb7c8a8090690bef4b98a796 | 1,181 | package io.vertx.httpproxy.impl;
import io.vertx.core.MultiMap;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpHeaders;
import io.vertx.httpproxy.Body;
import io.vertx.httpproxy.ProxyResponse;
import java.util.Date;
class Resource {
final String absoluteUri;
final int statusCode;
final MultiMap headers;
final long timestamp;
final long maxAge;
final Date lastModified;
final String etag;
final Buffer content = Buffer.buffer();
Resource(String absoluteUri, int statusCode, MultiMap headers, long timestamp, long maxAge) {
String lastModifiedHeader = headers.get(HttpHeaders.LAST_MODIFIED);
this.absoluteUri = absoluteUri;
this.statusCode = statusCode;
this.headers = headers;
this.timestamp = timestamp;
this.maxAge = maxAge;
this.lastModified = lastModifiedHeader != null ? ParseUtils.parseHeaderDate(lastModifiedHeader) : null;
this.etag = headers.get(HttpHeaders.ETAG);
}
void sendTo(ProxyResponse proxyResponse) {
proxyResponse.setStatusCode(200);
proxyResponse.headers().addAll(headers);
proxyResponse.setBody(Body.body(content));
proxyResponse.send(ar -> {
});
}
}
| 28.119048 | 107 | 0.740051 |
475b3b6f1bf4bf008f1b10f585e306952b009f41 | 2,694 | package com.kvtrades.simpleorderform;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.kvtrades.simpleorderform.model.ProductOrder;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
public class ProductOrderAdapter extends RecyclerView.Adapter<ProductOrderAdapter.ProductOrderAdapterVH> {
public ArrayList<ProductOrder> orders;
public Context context;
private String ip = "http://10.0.2.2:8080";
private String approot = "/2021_github_projects/order-form/";
Intent i;
Activity activity;
public ProductOrderAdapter(Context context, Activity activity) {
this.context = context;
this.activity = activity;
}
public void setProductOrders(ArrayList<ProductOrder> orders) {
this.orders = orders;
notifyDataSetChanged();
}
@NonNull
@NotNull
@Override
public ProductOrderAdapter.ProductOrderAdapterVH onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
return new ProductOrderAdapter.ProductOrderAdapterVH(LayoutInflater.from(context).inflate(R.layout.orders_rv_item, parent,false));
}
@Override
public void onBindViewHolder(@NonNull @NotNull ProductOrderAdapter.ProductOrderAdapterVH holder, int position) {
ProductOrder order = orders.get(position);
String title = order.getProductTitle();
double price = order.getPrice();
int qty = order.getQty();
double sum = order.getSum();
String cDate = order.getOrderDate();
holder.proTitleTV.setText(title);
holder.proPriceTV.setText(""+price);
holder.proQtyTV.setText(""+qty);
holder.proSumTV.setText(""+sum);
holder.clientOrderDateTV.setText(cDate);
}
@Override
public int getItemCount() {
return orders.size();
}
public class ProductOrderAdapterVH extends RecyclerView.ViewHolder {
TextView proTitleTV, proPriceTV, proQtyTV, proSumTV, clientOrderDateTV;
public ProductOrderAdapterVH(@NonNull @NotNull View itemView) {
super(itemView);
proTitleTV = itemView.findViewById(R.id.proTitleTV);
proPriceTV = itemView.findViewById(R.id.proPriceTV);
proQtyTV = itemView.findViewById(R.id.proQtyTV);
proSumTV = itemView.findViewById(R.id.proSumTV);
clientOrderDateTV = itemView.findViewById(R.id.clientOrderDateTV);
}
}
}
| 32.853659 | 138 | 0.712695 |
d36cad2c1391b13a0fbc8ab9a944ca0adb040a9b | 5,642 | package user_interface;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Map;
import java.util.Optional;
import java.util.ResourceBundle;
import cellsociety_team18.Simulation;
import cellsociety_team18.SimulationController;
import cellsociety_team18.State;
import graphic_elements.GraphicPolygon;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.util.Duration;
import javafx.scene.control.ChoiceDialog;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.CornerRadii;
/**
* @author elliott This class controls the user interface.
*/
public class ViewController {
private final Dimension DEFAULT_SIZE = new Dimension(900, 500);
private final String DEFAULT_RESOURCE_PACKAGE = "resources";
private final int GRID_SIZE = 480;
private final int CONTROL_PANEL_WIDTH = 400;
private SimulationController mySimulationController = new SimulationController();
private ArrayList<SimulationView> mySimulationViews = new ArrayList<SimulationView>();
private PopulationGraph myGraph;
private Timeline myAnimation;
private ResourceBundle myResources = ResourceBundle.getBundle("UIStrings");
/**
* @param stage
* The main window.
* @return a View Controller.
*/
public ViewController(Stage stage) {
stage.setTitle("CellSociety");
stage.setResizable(false);
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
public void handle(WindowEvent we) {
System.exit(0);
}
});
setupUI(stage);
}
/**
* Create and start the animation.
*/
public void start(int delay) {
if (mySimulationViews.size() > 0) {
KeyFrame frame = new KeyFrame(Duration.millis(delay), e -> step());
myAnimation = new Timeline();
myAnimation.setCycleCount(Timeline.INDEFINITE);
myAnimation.getKeyFrames().add(frame);
myAnimation.play();
}
}
/**
* Pause the animation.
*/
public void stop() {
if (myAnimation != null) {
myAnimation.pause();
}
}
/**
* Created all the UI components.
*/
private void setupUI(Stage stage) {
Scene scene = new Scene(createPane(), DEFAULT_SIZE.width, DEFAULT_SIZE.height, Color.WHITE);
stage.setScene(scene);
stage.show();
}
private BorderPane createPane() {
BorderPane borderPane = new BorderPane();
borderPane.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
ControlPanel controlPanel = new ControlPanel(this, myResources, CONTROL_PANEL_WIDTH);
borderPane.setLeft(controlPanel);
myGraph = new PopulationGraph(DEFAULT_SIZE.width - CONTROL_PANEL_WIDTH, DEFAULT_SIZE.height);
borderPane.setCenter(myGraph);
return borderPane;
}
/**
* Updates the simulation on each time step.
*/
public void step() {
if (mySimulationViews.size() > 0) {
mySimulationController.step();
myGraph.update(mySimulationController.getProportions());
updateGrids();
}
}
/**
* Creates a simulation.
*
* @param game
* A String identifying the game.
*/
public Simulation newSimulation(String game, String configuration) {
return mySimulationController.create(game, configuration);
}
/**
* Displays the simulation created by the user.
*
* @param simulation
* The simulation to be displayed.
* @param size
* The size of the grid to be displayed.
*/
public void displaySimulation(Simulation simulation) {
simulation.setup();
mySimulationController.add(simulation);
DisplayGrid grid = new DisplayGrid(this, simulation, GRID_SIZE,
simulation.getSettings().getParameter("cellType"),
Boolean.parseBoolean(simulation.getSettings().getParameter("outlineGrid")),
simulation.getSettings().getIntParameter("cellSize"));
grid.update(simulation.getGrid());
SimulationView view = new SimulationView(simulation, grid, GRID_SIZE, mySimulationViews.size() + 1);
view.setOnCloseRequest(new EventHandler<WindowEvent>() {
public void handle(WindowEvent we) {
stop();
mySimulationController.remove(view.getSimulation());
mySimulationViews.remove(view);
myGraph.update(mySimulationController.getProportions());
}
});
mySimulationViews.add(view);
}
/**
* Shuffles the cells and reloads the current simulation.
*/
public void shuffleGrid() {
stop();
mySimulationController.shuffle();
myGraph.clear();
updateGrids();
}
/**
* Updates the visualizations.
*/
private void updateGrids() {
for (SimulationView view : mySimulationViews) {
view.update();
}
}
/**
* Handles a click on a cell.
*
* @param graphicCell
* The cell that was clicked.
* @param simulation
* The simulation that was clicked.
*/
public void cellClicked(GraphicPolygon graphicCell, Simulation simulation) {
if (myAnimation == null || myAnimation.getStatus() == Animation.Status.PAUSED) {
Map<String, State> states = simulation.getGame().getStates();
ChoiceDialog<String> dialog = new ChoiceDialog<>(GraphicPolygon.getStateName(states, graphicCell),
states.keySet());
dialog.setTitle("State");
dialog.setHeaderText("Each cell can have several states.");
dialog.setContentText("Choose your cell's state:");
Optional<String> result = dialog.showAndWait();
result.ifPresent(picked -> {
graphicCell.update(states.get(picked));
updateGrids();
});
}
}
}
| 28.639594 | 109 | 0.728111 |
a6469f9dcaa1db8daa9ff681aa905934daec1839 | 4,367 |
package com.github.sellersj.artifactchecker.model.owasp;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"message", "stackTrace", "innerException"})
public class Properties__9 {
@JsonProperty("message")
private Message message;
@JsonProperty("stackTrace")
private StackTrace stackTrace;
@JsonProperty("innerException")
private InnerException innerException;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("message")
public Message getMessage() {
return message;
}
@JsonProperty("message")
public void setMessage(Message message) {
this.message = message;
}
@JsonProperty("stackTrace")
public StackTrace getStackTrace() {
return stackTrace;
}
@JsonProperty("stackTrace")
public void setStackTrace(StackTrace stackTrace) {
this.stackTrace = stackTrace;
}
@JsonProperty("innerException")
public InnerException getInnerException() {
return innerException;
}
@JsonProperty("innerException")
public void setInnerException(InnerException innerException) {
this.innerException = innerException;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(Properties__9.class.getName()).append('@').append(Integer.toHexString(System.identityHashCode(this)))
.append('[');
sb.append("message");
sb.append('=');
sb.append(((this.message == null) ? "<null>" : this.message));
sb.append(',');
sb.append("stackTrace");
sb.append('=');
sb.append(((this.stackTrace == null) ? "<null>" : this.stackTrace));
sb.append(',');
sb.append("innerException");
sb.append('=');
sb.append(((this.innerException == null) ? "<null>" : this.innerException));
sb.append(',');
sb.append("additionalProperties");
sb.append('=');
sb.append(((this.additionalProperties == null) ? "<null>" : this.additionalProperties));
sb.append(',');
if (sb.charAt((sb.length() - 1)) == ',') {
sb.setCharAt((sb.length() - 1), ']');
} else {
sb.append(']');
}
return sb.toString();
}
@Override
public int hashCode() {
int result = 1;
result = ((result * 31) + ((this.stackTrace == null) ? 0 : this.stackTrace.hashCode()));
result = ((result * 31) + ((this.innerException == null) ? 0 : this.innerException.hashCode()));
result = ((result * 31) + ((this.additionalProperties == null) ? 0 : this.additionalProperties.hashCode()));
result = ((result * 31) + ((this.message == null) ? 0 : this.message.hashCode()));
return result;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Properties__9) == false) {
return false;
}
Properties__9 rhs = ((Properties__9) other);
return (((((this.stackTrace == rhs.stackTrace)
|| ((this.stackTrace != null) && this.stackTrace.equals(rhs.stackTrace)))
&& ((this.innerException == rhs.innerException)
|| ((this.innerException != null) && this.innerException.equals(rhs.innerException))))
&& ((this.additionalProperties == rhs.additionalProperties)
|| ((this.additionalProperties != null) && this.additionalProperties.equals(rhs.additionalProperties))))
&& ((this.message == rhs.message) || ((this.message != null) && this.message.equals(rhs.message))));
}
}
| 34.385827 | 120 | 0.627204 |
aaaf91129e3de74a1f25956fedad60c83255f733 | 1,389 | package testcases.junit;
import junit.framework.TestCase;
import org.junit.Test;
import java.util.*;
import testcases.*;
public class FieldTest extends TestCase {
RefField1<FieldTestClass> f1 = new RefField1<FieldTestClass>();
RefField2<FieldTestClass> f2 = new RefField2<FieldTestClass>();
@Test public void testField11() {
assertTrue(f1.publicfoo == 0);
}
@Test public void testField12() {
assertTrue(f1.publiclist1 == null);
}
@Test public void testField13() {
assertTrue(f1.publiclist2 == null);
}
@Test public void testField21() {
assertTrue(f2.getpublicfoo() == 0);
}
}
class RefField1<X> {
<F1>[f1]for(F1 f1 : X.fields)
public F1 f1;
}
class RefField2<X> {
<F2>[f2] for (F2 f2 : RefField1<X>.fields)
protected F2 f2;
<F3>[f3] for (F3 f3 : RefField1<X>.fields; no get#f3() : Object.fields )
public F3 get#f3() { return f3; }
}
class FieldTestClass {
public int publicfoo = 0;
public List publiclist1 = null;
public List publiclist2 = new ArrayList();
protected int protectedfoo = 0;
protected List protectedlist1 = null;
protected List protectedlist2 = new ArrayList();
private int privatefoo = 0;
private List privatelist1 = null;
private List privatelist2 = new ArrayList();
int nomodfoo;
List noModList1 = null;
List noModList2 = new ArrayList();
}
| 24.368421 | 76 | 0.668107 |
8be70da347c7669203954758f050f98d9c9208d9 | 846 | package io.katharsis.core.internal.utils;
import io.katharsis.errorhandling.exception.KatharsisException;
/**
* Indicate an exception when accessing resource properties
*/
public class PropertyException extends KatharsisException {
private final Class<?> resourceClass;
private final String field;
public PropertyException(Throwable cause, Class<?> resourceClass, String field) {
super(cause.getMessage(), cause);
this.resourceClass = resourceClass;
this.field = field;
}
public PropertyException(String message, Class<?> resourceClass, String field) {
super(message);
this.resourceClass = resourceClass;
this.field = field;
}
public Class<?> getResourceClass() {
return resourceClass;
}
public String getField() {
return field;
}
}
| 25.636364 | 85 | 0.686761 |
b46702652e5caee6b5dd746045425b9c8b59c384 | 2,627 | /*
* Copyright (c) 2014-2017 Neil Ellis
*
* 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 dollar.api;
public class VarFlags {
private final boolean declaration;
private final boolean fixed;
private final boolean isVolatile;
private final boolean numeric;
private final boolean pure;
private final boolean readonly;
/**
* @param readonly true if the variable cannot be changed
* @param isVolatile true if the variable can be accessed by multiple threads
* @param fixed true if the variable is a fixed/static value
* @param pure true if the variable contains a pure value (i.e. a pure function/expession)
* @param numeric true if the variable should be a number (i.e. $1, $2)
* @param declaration true if this is the first use (declaration)
*/
public VarFlags(boolean readonly, boolean isVolatile, boolean fixed, boolean pure, boolean numeric, boolean declaration) {
this.readonly = readonly;
this.isVolatile = isVolatile;
this.fixed = fixed;
this.pure = pure;
this.numeric = numeric;
this.declaration = declaration;
}
/**
* @param readonly true if the variable cannot be changed
* @param isVolatile true if the variable can be accessed by multiple threads
* @param declaration true if this is the first use (declaration)
*/
public VarFlags(boolean readonly, boolean isVolatile, boolean declaration, boolean pure) {
this.readonly = readonly;
this.isVolatile = isVolatile;
this.declaration = declaration;
fixed = false;
this.pure = pure;
numeric = false;
}
public boolean isDeclaration() {
return declaration;
}
public boolean isFixed() {
return fixed;
}
public boolean isNumeric() {
return numeric;
}
public boolean isPure() {
return pure;
}
public boolean isReadonly() {
return readonly;
}
public boolean isVolatile() {
return isVolatile;
}
}
| 31.27381 | 126 | 0.65512 |
698246faea49043b7699ea90d21c0faef10bbf61 | 25,274 | /*******************************************************************************
* Copyright (c) 2000, 2013 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.swt.widgets;
import org.eclipse.swt.internal.win32.*;
import org.eclipse.swt.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.events.*;
/**
* Instances of this class support the layout of selectable
* expand bar items.
* <p>
* The item children that may be added to instances of this class
* must be of type <code>ExpandItem</code>.
* </p><p>
* <dl>
* <dt><b>Styles:</b></dt>
* <dd>V_SCROLL</dd>
* <dt><b>Events:</b></dt>
* <dd>Expand, Collapse</dd>
* </dl>
* </p><p>
* IMPORTANT: This class is <em>not</em> intended to be subclassed.
* </p>
*
* @see ExpandItem
* @see ExpandEvent
* @see ExpandListener
* @see ExpandAdapter
* @see <a href="http://www.eclipse.org/swt/snippets/#expandbar">ExpandBar snippets</a>
* @see <a href="http://www.eclipse.org/swt/examples.php">SWT Example: ControlExample</a>
* @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a>
*
* @since 3.2
* @noextend This class is not intended to be subclassed by clients.
*/
public class ExpandBar extends Composite {
ExpandItem[] items;
int itemCount;
ExpandItem focusItem;
int spacing = 4;
int yCurrentScroll;
int /*long*/ hFont;
/**
* Constructs a new instance of this class given its parent
* and a style value describing its behavior and appearance.
* <p>
* The style value is either one of the style constants defined in
* class <code>SWT</code> which is applicable to instances of this
* class, or must be built by <em>bitwise OR</em>'ing together
* (that is, using the <code>int</code> "|" operator) two or more
* of those <code>SWT</code> style constants. The class description
* lists the style constants that are applicable to the class.
* Style bits are also inherited from superclasses.
* </p>
*
* @param parent a composite control which will be the parent of the new instance (cannot be null)
* @param style the style of control to construct
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the parent</li>
* <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass</li>
* </ul>
*
* @see SWT#V_SCROLL
* @see Widget#checkSubclass
* @see Widget#getStyle
*/
public ExpandBar (Composite parent, int style) {
super (parent, checkStyle (style));
}
/**
* Adds the listener to the collection of listeners who will
* be notified when an item in the receiver is expanded or collapsed
* by sending it one of the messages defined in the <code>ExpandListener</code>
* interface.
*
* @param listener the listener which should be notified
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @see ExpandListener
* @see #removeExpandListener
*/
public void addExpandListener (ExpandListener listener) {
checkWidget ();
if (listener == null) error (SWT.ERROR_NULL_ARGUMENT);
TypedListener typedListener = new TypedListener (listener);
addListener (SWT.Expand, typedListener);
addListener (SWT.Collapse, typedListener);
}
int /*long*/ callWindowProc (int /*long*/ hwnd, int msg, int /*long*/ wParam, int /*long*/ lParam) {
if (handle == 0) return 0;
return OS.DefWindowProc (hwnd, msg, wParam, lParam);
}
protected void checkSubclass () {
if (!isValidSubclass ()) error (SWT.ERROR_INVALID_SUBCLASS);
}
static int checkStyle (int style) {
style &= ~SWT.H_SCROLL;
return style | SWT.NO_BACKGROUND;
}
public Point computeSize (int wHint, int hHint, boolean changed) {
checkWidget ();
int height = 0, width = 0;
if (wHint == SWT.DEFAULT || hHint == SWT.DEFAULT) {
if (itemCount > 0) {
int /*long*/ hDC = OS.GetDC (handle);
int /*long*/ hTheme = 0;
if (isAppThemed ()) {
hTheme = display.hExplorerBarTheme ();
}
int /*long*/ hCurrentFont = 0, oldFont = 0;
if (hTheme == 0) {
if (hFont != 0) {
hCurrentFont = hFont;
} else {
if (!OS.IsWinCE) {
NONCLIENTMETRICS info = OS.IsUnicode ? (NONCLIENTMETRICS) new NONCLIENTMETRICSW () : new NONCLIENTMETRICSA ();
info.cbSize = NONCLIENTMETRICS.sizeof;
if (OS.SystemParametersInfo (OS.SPI_GETNONCLIENTMETRICS, 0, info, 0)) {
LOGFONT logFont = OS.IsUnicode ? (LOGFONT) ((NONCLIENTMETRICSW)info).lfCaptionFont : ((NONCLIENTMETRICSA)info).lfCaptionFont;
hCurrentFont = OS.CreateFontIndirect (logFont);
}
}
}
if (hCurrentFont != 0) {
oldFont = OS.SelectObject (hDC, hCurrentFont);
}
}
height += spacing;
for (int i = 0; i < itemCount; i++) {
ExpandItem item = items [i];
height += item.getHeaderHeight ();
if (item.expanded) height += item.height;
height += spacing;
width = Math.max (width, item.getPreferredWidth (hTheme, hDC));
}
if (hCurrentFont != 0) {
OS.SelectObject (hDC, oldFont);
if (hCurrentFont != hFont) OS.DeleteObject (hCurrentFont);
}
OS.ReleaseDC (handle, hDC);
}
}
if (width == 0) width = DEFAULT_WIDTH;
if (height == 0) height = DEFAULT_HEIGHT;
if (wHint != SWT.DEFAULT) width = wHint;
if (hHint != SWT.DEFAULT) height = hHint;
Rectangle trim = computeTrim (0, 0, width, height);
return new Point (trim.width, trim.height);
}
void createHandle () {
super.createHandle ();
state &= ~CANVAS;
state |= TRACK_MOUSE;
}
void createItem (ExpandItem item, int style, int index) {
if (!(0 <= index && index <= itemCount)) error (SWT.ERROR_INVALID_RANGE);
if (itemCount == items.length) {
ExpandItem [] newItems = new ExpandItem [itemCount + 4];
System.arraycopy (items, 0, newItems, 0, items.length);
items = newItems;
}
System.arraycopy (items, index, items, index + 1, itemCount - index);
items [index] = item;
itemCount++;
if (focusItem == null) focusItem = item;
RECT rect = new RECT ();
OS.GetWindowRect (handle, rect);
item.width = Math.max (0, rect.right - rect.left - spacing * 2);
layoutItems (index, true);
}
void createWidget () {
super.createWidget ();
items = new ExpandItem [4];
if (!isAppThemed ()) {
backgroundMode = SWT.INHERIT_DEFAULT;
}
}
int defaultBackground() {
if (!isAppThemed ()) {
return OS.GetSysColor (OS.COLOR_WINDOW);
}
return super.defaultBackground();
}
void destroyItem (ExpandItem item) {
int index = 0;
while (index < itemCount) {
if (items [index] == item) break;
index++;
}
if (index == itemCount) return;
if (item == focusItem) {
int focusIndex = index > 0 ? index - 1 : 1;
if (focusIndex < itemCount) {
focusItem = items [focusIndex];
focusItem.redraw (true);
} else {
focusItem = null;
}
}
System.arraycopy (items, index + 1, items, index, --itemCount - index);
items [itemCount] = null;
item.redraw (true);
layoutItems (index, true);
}
void drawThemeBackground (int /*long*/ hDC, int /*long*/ hwnd, RECT rect) {
RECT rect2 = new RECT ();
OS.GetClientRect (handle, rect2);
OS.MapWindowPoints (handle, hwnd, rect2, 2);
OS.DrawThemeBackground (display.hExplorerBarTheme (), hDC, OS.EBP_NORMALGROUPBACKGROUND, 0, rect2, null);
}
void drawWidget (GC gc, RECT clipRect) {
int /*long*/ hTheme = 0;
if (isAppThemed ()) {
hTheme = display.hExplorerBarTheme ();
}
if (hTheme != 0) {
RECT rect = new RECT ();
OS.GetClientRect (handle, rect);
OS.DrawThemeBackground (hTheme, gc.handle, OS.EBP_HEADERBACKGROUND, 0, rect, clipRect);
} else {
drawBackground (gc.handle);
}
boolean drawFocus = false;
if (handle == OS.GetFocus ()) {
int uiState = (int)/*64*/OS.SendMessage (handle, OS.WM_QUERYUISTATE, 0, 0);
drawFocus = (uiState & OS.UISF_HIDEFOCUS) == 0;
}
int /*long*/ hCurrentFont = 0, oldFont = 0;
if (hTheme == 0) {
if (hFont != 0) {
hCurrentFont = hFont;
} else {
if (!OS.IsWinCE) {
NONCLIENTMETRICS info = OS.IsUnicode ? (NONCLIENTMETRICS) new NONCLIENTMETRICSW () : new NONCLIENTMETRICSA ();
info.cbSize = NONCLIENTMETRICS.sizeof;
if (OS.SystemParametersInfo (OS.SPI_GETNONCLIENTMETRICS, 0, info, 0)) {
LOGFONT logFont = OS.IsUnicode ? (LOGFONT) ((NONCLIENTMETRICSW)info).lfCaptionFont : ((NONCLIENTMETRICSA)info).lfCaptionFont;
hCurrentFont = OS.CreateFontIndirect (logFont);
}
}
}
if (hCurrentFont != 0) {
oldFont = OS.SelectObject (gc.handle, hCurrentFont);
}
if (foreground != -1) {
OS.SetTextColor (gc.handle, foreground);
}
}
for (int i = 0; i < itemCount; i++) {
ExpandItem item = items[i];
item.drawItem (gc, hTheme, clipRect, item == focusItem && drawFocus);
}
if (hCurrentFont != 0) {
OS.SelectObject (gc.handle, oldFont);
if (hCurrentFont != hFont) OS.DeleteObject (hCurrentFont);
}
}
Control findBackgroundControl () {
Control control = super.findBackgroundControl ();
if (!isAppThemed ()) {
if (control == null) control = this;
}
return control;
}
Control findThemeControl () {
return isAppThemed () ? this : super.findThemeControl ();
}
int getBandHeight () {
if (hFont == 0) return ExpandItem.CHEVRON_SIZE;
int /*long*/ hDC = OS.GetDC (handle);
int /*long*/ oldHFont = OS.SelectObject (hDC, hFont);
TEXTMETRIC lptm = OS.IsUnicode ? (TEXTMETRIC)new TEXTMETRICW() : new TEXTMETRICA();
OS.GetTextMetrics (hDC, lptm);
OS.SelectObject (hDC, oldHFont);
OS.ReleaseDC (handle, hDC);
return Math.max (ExpandItem.CHEVRON_SIZE, lptm.tmHeight + 4);
}
/**
* Returns the item at the given, zero-relative index in the
* receiver. Throws an exception if the index is out of range.
*
* @param index the index of the item to return
* @return the item at the given index
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_INVALID_RANGE - if the index is not between 0 and the number of elements in the list minus 1 (inclusive)</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*/
public ExpandItem getItem (int index) {
checkWidget ();
if (!(0 <= index && index < itemCount)) error (SWT.ERROR_INVALID_RANGE);
return items [index];
}
/**
* Returns the number of items contained in the receiver.
*
* @return the number of items
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*/
public int getItemCount () {
checkWidget ();
return itemCount;
}
/**
* Returns an array of <code>ExpandItem</code>s which are the items
* in the receiver.
* <p>
* Note: This is not the actual structure used by the receiver
* to maintain its list of items, so modifying the array will
* not affect the receiver.
* </p>
*
* @return the items in the receiver
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*/
public ExpandItem [] getItems () {
checkWidget ();
ExpandItem [] result = new ExpandItem [itemCount];
System.arraycopy (items, 0, result, 0, itemCount);
return result;
}
/**
* Returns the receiver's spacing.
*
* @return the spacing
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*/
public int getSpacing () {
checkWidget ();
return spacing;
}
/**
* Searches the receiver's list starting at the first item
* (index 0) until an item is found that is equal to the
* argument, and returns the index of that item. If no item
* is found, returns -1.
*
* @param item the search item
* @return the index of the item
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the item is null</li>
* <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*/
public int indexOf (ExpandItem item) {
checkWidget ();
if (item == null) error (SWT.ERROR_NULL_ARGUMENT);
for (int i = 0; i < itemCount; i++) {
if (items [i] == item) return i;
}
return -1;
}
boolean isAppThemed () {
if (background != -1) return false;
if (foreground != -1) return false;
if (hFont != 0) return false;
return OS.COMCTL32_MAJOR >= 6 && OS.IsAppThemed ();
}
void layoutItems (int index, boolean setScrollbar) {
if (index < itemCount) {
int y = spacing - yCurrentScroll;
for (int i = 0; i < index; i++) {
ExpandItem item = items [i];
if (item.expanded) y += item.height;
y += item.getHeaderHeight () + spacing;
}
for (int i = index; i < itemCount; i++) {
ExpandItem item = items [i];
item.setBounds (spacing, y, 0, 0, true, false);
if (item.expanded) y += item.height;
y += item.getHeaderHeight () + spacing;
}
}
if (setScrollbar) setScrollbar ();
}
void releaseChildren (boolean destroy) {
if (items != null) {
for (int i=0; i<items.length; i++) {
ExpandItem item = items [i];
if (item != null && !item.isDisposed ()) {
item.release (false);
}
}
items = null;
}
focusItem = null;
super.releaseChildren (destroy);
}
/**
* Removes the listener from the collection of listeners who will
* be notified when items in the receiver are expanded or collapsed.
*
* @param listener the listener which should no longer be notified
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @see ExpandListener
* @see #addExpandListener
*/
public void removeExpandListener (ExpandListener listener) {
checkWidget ();
if (listener == null) error (SWT.ERROR_NULL_ARGUMENT);
if (eventTable == null) return;
eventTable.unhook (SWT.Expand, listener);
eventTable.unhook (SWT.Collapse, listener);
}
void reskinChildren (int flags) {
if (items != null) {
for (int i=0; i<items.length; i++) {
ExpandItem item = items [i];
if (item != null ) item.reskin (flags);
}
}
super.reskinChildren (flags);
}
void setBackgroundPixel (int pixel) {
super.setBackgroundPixel (pixel);
if (!OS.IsWinCE) {
int flags = OS.RDW_ERASE | OS.RDW_FRAME | OS.RDW_INVALIDATE | OS.RDW_ALLCHILDREN;
OS.RedrawWindow (handle, null, 0, flags);
}
}
public void setFont (Font font) {
super.setFont (font);
hFont = font != null ? font.handle : 0;
layoutItems (0, true);
}
void setForegroundPixel (int pixel) {
super.setForegroundPixel (pixel);
if (!OS.IsWinCE) {
int flags = OS.RDW_ERASE | OS.RDW_FRAME | OS.RDW_INVALIDATE | OS.RDW_ALLCHILDREN;
OS.RedrawWindow (handle, null, 0, flags);
}
}
void setScrollbar () {
if (itemCount == 0) return;
if ((style & SWT.V_SCROLL) == 0) return;
RECT rect = new RECT();
OS.GetClientRect (handle, rect);
int height = rect.bottom - rect.top;
ExpandItem item = items [itemCount - 1];
int maxHeight = item.y + getBandHeight () + spacing;
if (item.expanded) maxHeight += item.height;
//claim bottom free space
if (yCurrentScroll > 0 && height > maxHeight) {
yCurrentScroll = Math.max (0, yCurrentScroll + maxHeight - height);
layoutItems (0, false);
}
maxHeight += yCurrentScroll;
SCROLLINFO info = new SCROLLINFO ();
info.cbSize = SCROLLINFO.sizeof;
info.fMask = OS.SIF_RANGE | OS.SIF_PAGE | OS.SIF_POS;
info.nMin = 0;
info.nMax = maxHeight;
info.nPage = height;
info.nPos = Math.min (yCurrentScroll, info.nMax);
if (info.nPage != 0) info.nPage++;
OS.SetScrollInfo (handle, OS.SB_VERT, info, true);
}
/**
* Sets the receiver's spacing. Spacing specifies the number of pixels allocated around
* each item.
*
* @param spacing the spacing around each item
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*/
public void setSpacing (int spacing) {
checkWidget ();
if (spacing < 0) return;
if (spacing == this.spacing) return;
this.spacing = spacing;
RECT rect = new RECT ();
OS.GetClientRect (handle, rect);
int width = Math.max (0, (rect.right - rect.left) - spacing * 2);
for (int i = 0; i < itemCount; i++) {
ExpandItem item = items[i];
if (item.width != width) item.setBounds (0, 0, width, item.height, false, true);
}
layoutItems (0, true);
OS.InvalidateRect (handle, null, true);
}
boolean updateTextDirection(int textDirection) {
if (super.updateTextDirection(textDirection)) {
for (int i = 0, n = items.length; i < n; i++) {
if (items[i] != null) {
items[i].updateTextDirection(style & SWT.FLIP_TEXT_DIRECTION);
}
}
return true;
}
return false;
}
void showItem (ExpandItem item) {
Control control = item.control;
if (control != null && !control.isDisposed ()) {
control.setVisible (item.expanded);
}
item.redraw (true);
int index = indexOf (item);
layoutItems (index + 1, true);
}
void showFocus (boolean up) {
RECT rect = new RECT();
OS.GetClientRect (handle, rect);
int height = rect.bottom - rect.top;
int updateY = 0;
if (up) {
if (focusItem.y < 0) {
updateY = Math.min (yCurrentScroll, -focusItem.y);
}
} else {
int itemHeight = focusItem.y + getBandHeight ();
if (focusItem.expanded) {
if (height >= getBandHeight () + focusItem.height) {
itemHeight += focusItem.height;
}
}
if (itemHeight > height) {
updateY = height - itemHeight;
}
}
if (updateY != 0) {
yCurrentScroll = Math.max (0, yCurrentScroll - updateY);
if ((style & SWT.V_SCROLL) != 0) {
SCROLLINFO info = new SCROLLINFO ();
info.cbSize = SCROLLINFO.sizeof;
info.fMask = OS.SIF_POS;
info.nPos = yCurrentScroll;
OS.SetScrollInfo (handle, OS.SB_VERT, info, true);
}
OS.ScrollWindowEx (handle, 0, updateY, null, null, 0, null, OS.SW_SCROLLCHILDREN | OS.SW_INVALIDATE);
for (int i = 0; i < itemCount; i++) {
items [i].y += updateY;
}
}
}
TCHAR windowClass () {
return display.windowClass;
}
int /*long*/ windowProc () {
return display.windowProc;
}
LRESULT WM_KEYDOWN (int /*long*/ wParam, int /*long*/ lParam) {
LRESULT result = super.WM_KEYDOWN (wParam, lParam);
if (result != null) return result;
if (focusItem == null) return result;
switch ((int)/*64*/wParam) {
case OS.VK_SPACE:
case OS.VK_RETURN:
Event event = new Event ();
event.item = focusItem;
sendEvent (focusItem.expanded ? SWT.Collapse : SWT.Expand, event);
focusItem.expanded = !focusItem.expanded;
showItem (focusItem);
return LRESULT.ZERO;
case OS.VK_UP: {
int focusIndex = indexOf (focusItem);
if (focusIndex > 0) {
focusItem.redraw (true);
focusItem = items [focusIndex - 1];
focusItem.redraw (true);
showFocus (true);
return LRESULT.ZERO;
}
break;
}
case OS.VK_DOWN: {
int focusIndex = indexOf (focusItem);
if (focusIndex < itemCount - 1) {
focusItem.redraw (true);
focusItem = items [focusIndex + 1];
focusItem.redraw (true);
showFocus (false);
return LRESULT.ZERO;
}
break;
}
}
return result;
}
LRESULT WM_KILLFOCUS (int /*long*/ wParam, int /*long*/ lParam) {
LRESULT result = super.WM_KILLFOCUS (wParam, lParam);
if (focusItem != null) focusItem.redraw (true);
return result;
}
LRESULT WM_LBUTTONDOWN (int /*long*/ wParam, int /*long*/ lParam) {
LRESULT result = super.WM_LBUTTONDOWN (wParam, lParam);
if (result == LRESULT.ZERO) return result;
int x = OS.GET_X_LPARAM (lParam);
int y = OS.GET_Y_LPARAM (lParam);
for (int i = 0; i < itemCount; i++) {
ExpandItem item = items[i];
boolean hover = item.isHover (x, y);
if (hover && focusItem != item) {
focusItem.redraw (true);
focusItem = item;
focusItem.redraw (true);
forceFocus ();
break;
}
}
return result;
}
LRESULT WM_LBUTTONUP (int /*long*/ wParam, int /*long*/ lParam) {
LRESULT result = super.WM_LBUTTONUP (wParam, lParam);
if (result == LRESULT.ZERO) return result;
if (focusItem == null) return result;
int x = OS.GET_X_LPARAM (lParam);
int y = OS.GET_Y_LPARAM (lParam);
boolean hover = focusItem.isHover (x, y);
if (hover) {
Event event = new Event ();
event.item = focusItem;
sendEvent (focusItem.expanded ? SWT.Collapse : SWT.Expand, event);
focusItem.expanded = !focusItem.expanded;
showItem (focusItem);
}
return result;
}
LRESULT WM_MOUSELEAVE (int /*long*/ wParam, int /*long*/ lParam) {
LRESULT result = super.WM_MOUSELEAVE (wParam, lParam);
if (result != null) return result;
for (int i = 0; i < itemCount; i++) {
ExpandItem item = items [i];
if (item.hover) {
item.hover = false;
item.redraw (false);
break;
}
}
return result;
}
LRESULT WM_MOUSEMOVE (int /*long*/ wParam, int /*long*/ lParam) {
LRESULT result = super.WM_MOUSEMOVE (wParam, lParam);
if (result == LRESULT.ZERO) return result;
int x = OS.GET_X_LPARAM (lParam);
int y = OS.GET_Y_LPARAM (lParam);
for (int i = 0; i < itemCount; i++) {
ExpandItem item = items [i];
boolean hover = item.isHover (x, y);
if (item.hover != hover) {
item.hover = hover;
item.redraw (false);
}
}
return result;
}
LRESULT WM_MOUSEWHEEL (int /*long*/ wParam, int /*long*/ lParam) {
return wmScrollWheel (true, wParam, lParam);
}
LRESULT WM_PAINT (int /*long*/ wParam, int /*long*/ lParam) {
PAINTSTRUCT ps = new PAINTSTRUCT ();
GCData data = new GCData ();
data.ps = ps;
data.hwnd = handle;
GC gc = new_GC (data);
if (gc != null) {
int width = ps.right - ps.left;
int height = ps.bottom - ps.top;
if (width != 0 && height != 0) {
RECT rect = new RECT ();
OS.SetRect (rect, ps.left, ps.top, ps.right, ps.bottom);
drawWidget (gc, rect);
if (hooks (SWT.Paint) || filters (SWT.Paint)) {
Event event = new Event ();
event.gc = gc;
event.x = rect.left;
event.y = rect.top;
event.width = width;
event.height = height;
sendEvent (SWT.Paint, event);
event.gc = null;
}
}
gc.dispose ();
}
return LRESULT.ZERO;
}
LRESULT WM_PRINTCLIENT (int /*long*/ wParam, int /*long*/ lParam) {
LRESULT result = super.WM_PRINTCLIENT (wParam, lParam);
RECT rect = new RECT ();
OS.GetClientRect (handle, rect);
GCData data = new GCData ();
data.device = display;
data.foreground = getForegroundPixel ();
GC gc = GC.win32_new (wParam, data);
drawWidget (gc, rect);
gc.dispose ();
return result;
}
LRESULT WM_SETCURSOR (int /*long*/ wParam, int /*long*/ lParam) {
LRESULT result = super.WM_SETCURSOR (wParam, lParam);
if (result != null) return result;
int hitTest = (short) OS.LOWORD (lParam);
if (hitTest == OS.HTCLIENT) {
for (int i = 0; i < itemCount; i++) {
ExpandItem item = items [i];
if (item.hover) {
int /*long*/ hCursor = OS.LoadCursor (0, OS.IDC_HAND);
OS.SetCursor (hCursor);
return LRESULT.ONE;
}
}
}
return result;
}
LRESULT WM_SETFOCUS (int /*long*/ wParam, int /*long*/ lParam) {
LRESULT result = super.WM_SETFOCUS (wParam, lParam);
if (focusItem != null) focusItem.redraw (true);
return result;
}
LRESULT WM_SIZE (int /*long*/ wParam, int /*long*/ lParam) {
LRESULT result = super.WM_SIZE (wParam, lParam);
RECT rect = new RECT ();
OS.GetClientRect (handle, rect);
int width = Math.max (0, (rect.right - rect.left) - spacing * 2);
for (int i = 0; i < itemCount; i++) {
ExpandItem item = items[i];
if (item.width != width) item.setBounds (0, 0, width, item.height, false, true);
}
setScrollbar ();
OS.InvalidateRect (handle, null, true);
return result;
}
LRESULT wmScroll (ScrollBar bar, boolean update, int /*long*/ hwnd, int msg, int /*long*/ wParam, int /*long*/ lParam) {
LRESULT result = super.wmScroll (bar, true, hwnd, msg, wParam, lParam);
SCROLLINFO info = new SCROLLINFO ();
info.cbSize = SCROLLINFO.sizeof;
info.fMask = OS.SIF_POS;
OS.GetScrollInfo (handle, OS.SB_VERT, info);
int updateY = yCurrentScroll - info.nPos;
OS.ScrollWindowEx (handle, 0, updateY, null, null, 0, null, OS.SW_SCROLLCHILDREN | OS.SW_INVALIDATE);
yCurrentScroll = info.nPos;
if (updateY != 0) {
for (int i = 0; i < itemCount; i++) {
items [i].y += updateY;
}
}
return result;
}
}
| 29.839433 | 132 | 0.66701 |
b341f45a2da7638ef2627b3fa71c0df891fbc5d3 | 604 | package io.r3k.gamify9dotcom.services.challenge;
import io.r3k.gamify9dotcom.domain.ChallengeReponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
public abstract class AbstractChallenge {
protected final String name;
public AbstractChallenge(String name) {
this.name = name;
}
public ResponseEntity success() {
return new ResponseEntity<>(new ChallengeReponse(), HttpStatus.ACCEPTED);
}
public ResponseEntity failure(String message) {
return new ResponseEntity<>(new ChallengeReponse(message), HttpStatus.BAD_REQUEST);
}
}
| 25.166667 | 87 | 0.778146 |
d9870df7ca3c1102c96f0849d62cf1467a0f8c4a | 3,128 | /*
* Copyright 2019 Patrik Karlström.
*
* 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.mapton.api;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import se.trixon.almond.util.Dict;
import se.trixon.almond.util.SystemHelper;
/**
*
* @author Patrik Karlström
*/
public abstract class MUpdater {
protected MPrint mPrint = new MPrint(MKey.UPDATER_LOGGER);
private String mCategory = null;
private String mComment;
private boolean mMarkedForUpdate;
private String mName;
private Runnable mRunnable;
public String getCategory() {
return mCategory;
}
public String getComment() {
return mComment;
}
public abstract String getLastUpdated();
public String getName() {
return mName;
}
public MPrint getPrint() {
return mPrint;
}
public Runnable getRunnable() {
return mRunnable;
}
public boolean isMarkedForUpdate() {
return mMarkedForUpdate;
}
public abstract boolean isOutOfDate();
public void run() {
mRunnable.run();
}
public void setCategory(String category) {
mCategory = category;
}
public void setComment(String comment) {
mComment = comment;
}
public void setMarkedForUpdate(boolean markedForUpdate) {
mMarkedForUpdate = markedForUpdate;
}
public void setName(String name) {
mName = name;
}
public void setPrint(MPrint print) {
mPrint = print;
}
public void setRunnable(Runnable runnable) {
mRunnable = runnable;
}
public static abstract class ByFile extends MUpdater {
private File mFile;
public ByFile() {
}
public abstract Long getAgeLimit();
public File getFile() {
return mFile;
}
@Override
public String getLastUpdated() {
String lastUpdate = "-";
if (mFile != null && mFile.isFile()) {
lastUpdate = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss").format(new Date(mFile.lastModified()));
}
return String.format(Dict.UPDATED_S.toString(), lastUpdate);
}
@Override
public boolean isOutOfDate() {
return mFile != null && (!mFile.exists() || SystemHelper.age(mFile.lastModified()) >= getAgeLimit());
}
public void setFile(File file) {
mFile = file;
}
}
}
| 24.629921 | 114 | 0.606138 |
f90020d154765889100fbbf8522ab3b6637e9deb | 2,037 | package org.knowm.xchange.coinmarketcap.pro.v1.service.marketdata;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.ExchangeFactory;
import org.knowm.xchange.coinmarketcap.pro.v1.CmcExchange;
import org.knowm.xchange.coinmarketcap.pro.v1.dto.marketdata.CmcCurrencyInfo;
import org.knowm.xchange.coinmarketcap.pro.v1.service.CmcMarketDataService;
import org.knowm.xchange.currency.Currency;
public class CurrencyInfoFetchIntegration {
private static Exchange exchange;
private static CmcMarketDataService cmcMarketDataService;
@BeforeClass
public static void setUp() {
exchange = ExchangeFactory.INSTANCE.createExchangeWithoutSpecification(CmcExchange.class);
exchange.applySpecification(((CmcExchange) exchange).getSandboxExchangeSpecification());
cmcMarketDataService = (CmcMarketDataService) exchange.getMarketDataService();
Assume.assumeNotNull(exchange.getExchangeSpecification().getApiKey());
}
@Test
public void getCmcCurrencyInfoTest() throws Exception {
CmcCurrencyInfo currency = cmcMarketDataService.getCmcCurrencyInfo(Currency.BTC);
assertThat(currency).isNotNull();
assertThat(currency.getSymbol()).isEqualTo(Currency.BTC.getSymbol());
}
@Test
public void getCmcMultipleCurrencyInfoTest() throws Exception {
List<Currency> currencyList = Arrays.asList(Currency.BTC, Currency.ETH, Currency.LTC);
Map<String, CmcCurrencyInfo> currencyInfoMap =
cmcMarketDataService.getCmcMultipleCurrencyInfo(currencyList);
assertThat(currencyInfoMap).isNotNull();
assertThat(currencyInfoMap.size()).isEqualTo(3);
assertThat(currencyInfoMap.get(Currency.BTC.getSymbol())).isNotNull();
assertThat(currencyInfoMap.get(Currency.ETH.getSymbol())).isNotNull();
assertThat(currencyInfoMap.get(Currency.LTC.getSymbol())).isNotNull();
}
}
| 38.433962 | 94 | 0.796269 |
8ec68dfde771f25ae5bed2d61c18f9f12bd694c2 | 1,890 | package com.gfirem.elrosacruz;
import android.app.Application;
import android.util.Log;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;
import org.acra.ACRA;
import org.acra.annotation.ReportsCrashes;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
/**
* Created by GFireM on 10/14/2015.
*/
@ReportsCrashes(
formKey = "b856e786e56842b1b8bc0395923d3377",
formUri = "https://collector.tracepot.com/2c4882bc")
public class ApplicationController extends Application {
private static ApplicationController fInstance;
private Tracker mTracker;
public static ApplicationController getInstance() {
if (fInstance == null) {
fInstance = new ApplicationController();
}
return fInstance;
}
@Override
public void onCreate() {
super.onCreate();
try {
fInstance = this;
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder().setDefaultFontPath("fonts/Nexa-Light.ttf")
.setFontAttrId(R.attr.fontPath).build());
ACRA.init(this);
} catch (Exception anEx) {
Log.d("AppController" + "onCreate", anEx.toString());
}
}
/**
* Gets the default {@link Tracker} for this {@link Application}.
*
* @return tracker
*/
synchronized public Tracker getDefaultTracker() {
if (mTracker == null) {
GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
// To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
mTracker = analytics.newTracker("UA-56060946-4");
mTracker.enableExceptionReporting(true);
mTracker.enableAdvertisingIdCollection(false);
mTracker.enableAutoActivityTracking(true);
}
return mTracker;
}
}
| 30 | 116 | 0.655026 |
597834ddb06d48b08912ad301f7c707b26dceca4 | 302 | package com.reminiscence.reminiscence.error;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class errorController {
@GetMapping("/error")
public String getError() {
return "error";
}
}
| 21.571429 | 59 | 0.715232 |
4232eacc7ee34a6b03091f16834d0381515177f6 | 3,173 | /*
* MIT License
*
* Copyright (c) 2020-present Cloudogu GmbH and 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 sonia.scm.pushlog;
//~--- non-JDK imports --------------------------------------------------------
import com.google.common.collect.Lists;
//~--- JDK imports ------------------------------------------------------------
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Sebastian Sdorra
*/
@XmlRootElement(name = "push")
@XmlAccessorType(XmlAccessType.FIELD)
public class PushlogEntry
{
/**
* Constructs ...
*
*/
public PushlogEntry() {}
/**
* Constructs ...
*
*
*
* @param id
* @param username
*/
public PushlogEntry(long id, String username)
{
this.id = id;
this.username = username;
}
//~--- methods --------------------------------------------------------------
/**
* Method description
*
*
* @param id
*/
public void add(String id)
{
getChangesets().add(id);
}
/**
* Method description
*
*
* @param id
*
* @return
*/
public boolean contains(String id)
{
return getChangesets().contains(id);
}
//~--- get methods ----------------------------------------------------------
/**
* Method description
*
*
* @return
*/
public long getId()
{
return id;
}
/**
* Method description
*
*
* @return
*/
public String getUsername()
{
return username;
}
/**
* Method description
*
*
* @return
*/
private List<String> getChangesets()
{
if (changesets == null)
{
changesets = Lists.newArrayList();
}
return changesets;
}
//~--- fields ---------------------------------------------------------------
/** Field description */
@XmlElement(name = "changeset")
private List<String> changesets;
/** Field description */
private long id;
/** Field description */
private String username;
}
| 21.585034 | 81 | 0.595966 |
6cff9043de4a551659af27fb8ce55b1d1a4a3cd2 | 839 | /**
*
*/
package org.pjay.repository;
import org.pjay.entity.UserSecurityInfo;
import org.springframework.data.repository.CrudRepository;
/**
* @author vijayk
*
*/
public interface UserSecurityInfoRepository extends CrudRepository<UserSecurityInfo, Long> {
UserSecurityInfo getByUserName(String userName);
// https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html
// http://levelup.lishman.com/hibernate/hql/joins.php
// http://www.journaldev.com/2954/hibernate-query-language-hql-example-tutorial
// Not used
/**
@Query("from UserSecurityInfo as usf join usf.questionNAnswers as qna where usf.userName = :username and qna.question = :question and LOWER(qna.answer) = LOWER(:answer)")
List<Object[]> isAnswerCorrect(String username, String question, String answer);
*/
}
| 31.074074 | 173 | 0.733015 |
893cd048d27aefdcef0b0a614c138c5bbc286979 | 417 | package pl.altkom.asc.lab.micronaut.poc.policy.search.service.api.v1.queries.findpolicy.dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class PolicyListItemDto {
private String number;
private LocalDate dateFrom;
private LocalDate dateTo;
private String policyHolder;
}
| 23.166667 | 92 | 0.805755 |
861bbaed3c053d8fbec5228ab05aca3c27d8e901 | 1,117 | package upm.softwaredesign.finalproject.order;
import upm.softwaredesign.finalproject.model.Actor;
import upm.softwaredesign.finalproject.model.Product;
import java.util.Date;
import java.util.UUID;
public class Order {
private UUID id;
private UUID transactionGroupId;
private Actor sender;
private Actor receiver;
private Product product;
private Date time;
public Order(){
}
public Order(Actor sender, Product product, Date time) {
this.id = UUID.randomUUID();
this.sender = sender;
this.product = product;
this.time = time;
}
public UUID getId() {
return id;
}
public Actor getSender() {
return sender;
}
public Actor getReceiver() {
return receiver;
}
public Product getProduct() {
return product;
}
public Date getTime() {
return time;
}
public UUID getTransactionGroupId() {
return transactionGroupId;
}
public void setTransactionGroupId(UUID transactionGroupId) {
this.transactionGroupId = transactionGroupId;
}
}
| 17.453125 | 64 | 0.648165 |
727fc5734dbfe17fa5df7f4d29636af87e28ccc4 | 1,992 | /*
* 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.netbeans.modules.project.uiapi;
import java.io.File;
import javax.swing.JFileChooser;
import org.netbeans.api.annotations.common.NonNull;
import org.netbeans.api.annotations.common.NullAllowed;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.SourceGroup;
import org.openide.WizardDescriptor;
/**
* Factory to be implemented by the UI implementation
* @author Petr Hrebejk
*/
public interface ProjectChooserFactory {
public static final String WIZARD_KEY_PROJECT = "project"; // NOI18N
public static final String WIZARD_KEY_TARGET_FOLDER = "targetFolder"; // NOI18N
public static final String WIZARD_KEY_TARGET_NAME = "targetName"; // NOI18N
public static final String WIZARD_KEY_TEMPLATE = "targetTemplate"; // NOI18N
public File getProjectsFolder ();
public void setProjectsFolder (File file);
public JFileChooser createProjectChooser();
public WizardDescriptor.Panel<WizardDescriptor> createSimpleTargetChooser(@NullAllowed Project project, @NonNull SourceGroup[] folders,
WizardDescriptor.Panel<WizardDescriptor> bottomPanel, boolean freeFileExtension);
}
| 36.888889 | 139 | 0.759036 |
350ef3e5bc351edc153a992866df65fda60f04eb | 2,325 | /*
* 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.aliyuncs.sofa.model.v20190815;
import java.util.List;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.sofa.transform.v20190815.QueryCasLoadbalanceSecurityipResponseUnmarshaller;
import com.aliyuncs.transform.UnmarshallerContext;
/**
* @author auto create
* @version
*/
public class QueryCasLoadbalanceSecurityipResponse extends AcsResponse {
private String requestId;
private String resultCode;
private String resultMessage;
private Data data;
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getResultCode() {
return this.resultCode;
}
public void setResultCode(String resultCode) {
this.resultCode = resultCode;
}
public String getResultMessage() {
return this.resultMessage;
}
public void setResultMessage(String resultMessage) {
this.resultMessage = resultMessage;
}
public Data getData() {
return this.data;
}
public void setData(Data data) {
this.data = data;
}
public static class Data {
private Boolean accessControl;
private List<String> ips;
public Boolean getAccessControl() {
return this.accessControl;
}
public void setAccessControl(Boolean accessControl) {
this.accessControl = accessControl;
}
public List<String> getIps() {
return this.ips;
}
public void setIps(List<String> ips) {
this.ips = ips;
}
}
@Override
public QueryCasLoadbalanceSecurityipResponse getInstance(UnmarshallerContext context) {
return QueryCasLoadbalanceSecurityipResponseUnmarshaller.unmarshall(this, context);
}
@Override
public boolean checkShowJsonItemName() {
return false;
}
}
| 23.019802 | 95 | 0.729892 |
b70c370906189b67869d54690023ac9673b63d95 | 2,982 | /*
* 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 com.github.rodionmoiseev.c10n;
import com.github.rodionmoiseev.c10n.annotations.DefaultC10NAnnotations;
import com.github.rodionmoiseev.c10n.annotations.Fr;
import com.github.rodionmoiseev.c10n.test.utils.RuleUtils;
import com.google.common.collect.Sets;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import java.util.Locale;
import java.util.Set;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
/**
* @author rodion
*/
public class ConfiguredC10NModuleTest {
@Rule
public TestRule tmpC10N = RuleUtils.tmpC10NConfiguration();
@Test
public void annotationBoundLocalesAreListedUnderAllLocales() {
ConfiguredC10NModule cm = C10N.configure(new DefaultC10NAnnotations());
assertThat(cm.getAllBoundLocales(), is(set(
Locale.ENGLISH,
Locale.GERMAN,
Locale.FRENCH,
Locale.ITALIAN,
Locale.JAPANESE,
Locale.KOREAN,
new Locale("ru"),
Locale.CHINESE,
new Locale("es")
)));
}
@Test
public void allBoundLocalesAreListedUnderAllLocales() {
ConfiguredC10NModule cm = C10N.configure(new C10NConfigBase() {
@Override
protected void configure() {
bind(Msg.class)
.to(MsgJa.class, Locale.JAPANESE)
.to(MsgGr.class, Locale.GERMAN);
bind(Msg2.class)
.to(Msg2Ru.class, new Locale("ru"));
bindAnnotation(Fr.class).toLocale(Locale.FRENCH);
}
});
assertThat(cm.getAllBoundLocales(), is(set(
Locale.JAPANESE,
Locale.GERMAN,
new Locale("ru"),
Locale.FRENCH)));
}
private static Set<Locale> set(Locale... locales) {
return Sets.newHashSet(locales);
}
interface Msg {
}
static class MsgJa implements Msg {
}
static class MsgGr implements Msg {
}
interface Msg2 {
}
static class Msg2Ru implements Msg2 {
}
}
| 30.121212 | 79 | 0.639168 |
ed12eb5a8e3fe4a7376b70edb1321e4c1f8c2494 | 2,460 | package cmps252.HW4_2.UnitTesting;
import static org.junit.jupiter.api.Assertions.*;
import java.io.FileNotFoundException;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import cmps252.HW4_2.Customer;
import cmps252.HW4_2.FileParser;
@Tag("14")
class Record_3282 {
private static List<Customer> customers;
@BeforeAll
public static void init() throws FileNotFoundException {
customers = FileParser.getCustomers(Configuration.CSV_File);
}
@Test
@DisplayName("Record 3282: FirstName is Lori")
void FirstNameOfRecord3282() {
assertEquals("Lori", customers.get(3281).getFirstName());
}
@Test
@DisplayName("Record 3282: LastName is Krakowski")
void LastNameOfRecord3282() {
assertEquals("Krakowski", customers.get(3281).getLastName());
}
@Test
@DisplayName("Record 3282: Company is Bala Nursing & Retirement Ctr")
void CompanyOfRecord3282() {
assertEquals("Bala Nursing & Retirement Ctr", customers.get(3281).getCompany());
}
@Test
@DisplayName("Record 3282: Address is 1126 S Airport Rd")
void AddressOfRecord3282() {
assertEquals("1126 S Airport Rd", customers.get(3281).getAddress());
}
@Test
@DisplayName("Record 3282: City is Peoria")
void CityOfRecord3282() {
assertEquals("Peoria", customers.get(3281).getCity());
}
@Test
@DisplayName("Record 3282: County is Peoria")
void CountyOfRecord3282() {
assertEquals("Peoria", customers.get(3281).getCounty());
}
@Test
@DisplayName("Record 3282: State is IL")
void StateOfRecord3282() {
assertEquals("IL", customers.get(3281).getState());
}
@Test
@DisplayName("Record 3282: ZIP is 61605")
void ZIPOfRecord3282() {
assertEquals("61605", customers.get(3281).getZIP());
}
@Test
@DisplayName("Record 3282: Phone is 309-697-7488")
void PhoneOfRecord3282() {
assertEquals("309-697-7488", customers.get(3281).getPhone());
}
@Test
@DisplayName("Record 3282: Fax is 309-697-3008")
void FaxOfRecord3282() {
assertEquals("309-697-3008", customers.get(3281).getFax());
}
@Test
@DisplayName("Record 3282: Email is lori@krakowski.com")
void EmailOfRecord3282() {
assertEquals("lori@krakowski.com", customers.get(3281).getEmail());
}
@Test
@DisplayName("Record 3282: Web is http://www.lorikrakowski.com")
void WebOfRecord3282() {
assertEquals("http://www.lorikrakowski.com", customers.get(3281).getWeb());
}
}
| 25.625 | 82 | 0.73252 |
51f025f1b5a3a56c93e923c9702296d6155e17aa | 3,020 | package com.boot.controller.lmcontroller;
import com.boot.constant.LexJSONResult;
import com.boot.pojo.Realcomment;
import com.boot.pojo.VideoComment;
import com.boot.service.VideoCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author lm
* @version 1.8
* @date 2021/7/19 18:29
*/
@RestController
@RequestMapping("/videoComment")
public class VideoCommentController {
@Autowired
private VideoCommentService videoCommentService;
@RequestMapping("/addVideoComment")
public LexJSONResult addVideoComment(@RequestParam("id") long videoId, @RequestParam("content") String videoContent, @RequestParam("username") String userName, @RequestParam("userid") int userid){
VideoComment videoComment = videoCommentService.saveComment(videoId, userName, userid, videoContent);
return LexJSONResult.ok(videoComment);
}
@RequestMapping("/addVideoSubComment")
public LexJSONResult addVideoSubComment(@RequestParam("id") long parentId, @RequestParam("content") String videoContent, @RequestParam("username") String userName, @RequestParam("userid") int userid){
VideoComment videoComment = videoCommentService.saveSubComment(parentId, userName, userid, videoContent);
return LexJSONResult.ok(videoComment);
}
@RequestMapping("/getVideoCommByVideoId/{id}")
public LexJSONResult getRealComment(@PathVariable("id") long id){
List<VideoComment> commentByVideoId = videoCommentService.findCommentByVideoId(id);
return LexJSONResult.ok(commentByVideoId);
}
@RequestMapping("/getVideoCommByParentId/{id}")
public LexJSONResult getRealCommByParentId(@PathVariable("id") long parentId){
List<VideoComment> commentByParentId = videoCommentService.findAllByParentId(parentId);
return LexJSONResult.ok(commentByParentId);
}
@RequestMapping("/updateReplyNum/{commentId}")
public LexJSONResult updateReplyNum(@PathVariable("commentId") long id){
VideoComment commentById = videoCommentService.findCommentById(id);
videoCommentService.updateReplyNum(id);
return LexJSONResult.ok(commentById);
}
@GetMapping("/updateLikeNum")
public LexJSONResult updateLikeNum(@RequestParam("id") long id){
VideoComment commentById = videoCommentService.findCommentById(id);
videoCommentService.updateLikeNum(id);
return LexJSONResult.ok(commentById);
}
@GetMapping("/deleteLikeNum")
public LexJSONResult deleteLikeNum(@RequestParam("id") long id){
VideoComment commentById = videoCommentService.findCommentById(id);
videoCommentService.deleteLikeNum(id);
return LexJSONResult.ok(commentById);
}
@DeleteMapping("/deleteAll/{videoId}")
public LexJSONResult deleteAll(@PathVariable("videoId") long videoId){
videoCommentService.deleteAllByVideoId(videoId);
return LexJSONResult.ok();
}
}
| 39.220779 | 204 | 0.74702 |
b247b90fb41d92d680aee25dcb10204c6ff4bb48 | 945 | package com.yodiwo.plegma;
/**
* Created by ApiGenerator Tool (Java) on 28/08/2015 18:35:00.
*/
/**
* Active Port Keys Payload Informs Node of all currently active Ports (i.e. Ports that are connected and active in currently deployed graphs).
* Should be used to 1. supress events from inactive ports, allowing more efficient use of medium, 2. sync Port states with the server
* Can be either asynchronous (e.g. at Node connection) or as a response to a PortUpdateReq
* Direction: Cloud -> Node
*/
public class PortStateSet extends ApiMsg {
/**
* Type of operation responding to
*/
public int Operation;
/**
* Array of requested Port states.
*/
public PortState[] PortStates;
public PortStateSet() {
}
public PortStateSet(int SeqNo, int Operation, PortState[] PortStates) {
this.SeqNo = SeqNo;
this.Operation = Operation;
this.PortStates = PortStates;
}
}
| 27.794118 | 143 | 0.678307 |
2e5af66cee14fe89fdaf50f1a1a093a7c6a2e888 | 9,403 | /*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orangechain.laplace.cameraqrcode;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import com.google.zxing.ResultPoint;
import com.orangechain.laplace.R;
import com.orangechain.laplace.camera.CameraManager;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public final class ViewfinderView extends View
{
/**
* 刷新界面的时间
*/
private static final long ANIMATION_DELAY = 10L;
private static final int OPAQUE = 0xFF;
/**
* 中间那条线每次刷新移动的距离
*/
private static final int SPEEN_DISTANCE = 10;
private static final int MAX_RESULT_POINTS = 20;
private static final String TAG = ViewfinderView.class.getSimpleName();
/**
* 扫描框中的中间线的宽度
*/
private static int MIDDLE_LINE_WIDTH;
/**
* 扫描框中的中间线的与扫描框左右的间隙
*/
private static int MIDDLE_LINE_PADDING;
/**
* 遮掩层的颜色
*/
private final int maskColor;
private final int resultColor;
private final int resultPointColor;
private final int CORNER_PADDING;
/**
* 画笔对象的引用
*/
private final Paint paint;
/**
* 第一次绘制控件
*/
private boolean isFirst = true;
/**
* 中间滑动线的最顶端位置
*/
private int slideTop;
/**
* 中间滑动线的最底端位置
*/
private int slideBottom;
private Bitmap resultBitmap;
private List<ResultPoint> possibleResultPoints;
private List<ResultPoint> lastPossibleResultPoints;
private CameraManager cameraManager;
private boolean hasNotified = false;
public OnDrawFinishListener getListener() {
return listener;
}
public void setOnDrawFinishListener(OnDrawFinishListener listener) {
this.listener = listener;
}
private OnDrawFinishListener listener;
// This constructor is used when the class is built from an XML resource.
public ViewfinderView(Context context, AttributeSet attrs) {
super(context, attrs);
CORNER_PADDING = dip2px(context, 0.0F);
MIDDLE_LINE_PADDING = dip2px(context, 20.0F);
MIDDLE_LINE_WIDTH = dip2px(context, 3.0F);
paint = new Paint(Paint.ANTI_ALIAS_FLAG); // 开启反锯齿
Resources resources = getResources();
maskColor = resources.getColor(R.color.viewfinder_mask); // 遮掩层颜色
resultColor = resources.getColor(R.color.result_view);
resultPointColor = resources.getColor(R.color.possible_result_points);
possibleResultPoints = new ArrayList<>(5);
lastPossibleResultPoints = null;
}
public void setCameraManager(CameraManager cameraManager) {
this.cameraManager = cameraManager;
}
@Override
public void onDraw(Canvas canvas) {
if (cameraManager == null) {
return; // not ready yet, early draw before done configuring
}
Rect frame = cameraManager.getFramingRect();//获取二维码扫描识别区域,区域外遮罩层
// frame = new Rect(100,100,600,600);
if (frame == null) {
return;
}
// 绘制遮掩层
drawCover(canvas, frame);
if (resultBitmap != null) { // 绘制扫描结果的图
// Draw the opaque result bitmap over the scanning rectangle
paint.setAlpha(0xA0);
canvas.drawBitmap(resultBitmap, null, frame, paint);
} else {
// 画扫描框边上的角
drawRectEdges(canvas, frame);
// 绘制扫描线
drawScanningLine(canvas, frame);
List<ResultPoint> currentPossible = possibleResultPoints;
Collection<ResultPoint> currentLast = lastPossibleResultPoints;
if (currentPossible.isEmpty()) {
lastPossibleResultPoints = null;
} else {
possibleResultPoints = new ArrayList<>(5);
lastPossibleResultPoints = currentPossible;
paint.setAlpha(OPAQUE);
paint.setColor(resultPointColor);
for (ResultPoint point : currentPossible) {
canvas.drawCircle(frame.left + point.getX(), frame.top
+ point.getY(), 6.0f, paint);
}
}
if (currentLast != null) {
paint.setAlpha(OPAQUE / 2);
paint.setColor(resultPointColor);
for (ResultPoint point : currentLast) {
canvas.drawCircle(frame.left + point.getX(), frame.top
+ point.getY(), 3.0f, paint);
}
}
// 只刷新扫描框的内容,其他地方不刷新
postInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top,
frame.right, frame.bottom);
if (listener != null && !hasNotified) {
listener.onDrawFinish(frame);
hasNotified = true;
}
}
}
/**
* 绘制扫描线
*
* @param frame 扫描框
*/
private void drawScanningLine(Canvas canvas, Rect frame) {
// 初始化中间线滑动的最上边和最下边
if (isFirst) {
isFirst = false;
slideTop = frame.top;
slideBottom = frame.bottom;
}
// 绘制中间的线,每次刷新界面,中间的线往下移动SPEEN_DISTANCE
slideTop += SPEEN_DISTANCE;
if (slideTop >= slideBottom) {
slideTop = frame.top;
}
// 从图片资源画扫描线
Rect lineRect = new Rect();
lineRect.left = frame.left + MIDDLE_LINE_PADDING;
lineRect.right = frame.right - MIDDLE_LINE_PADDING;
lineRect.top = slideTop;
lineRect.bottom = (slideTop + MIDDLE_LINE_WIDTH);
canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.jdme_scan_laser), null,
lineRect, paint);
}
/**
* 绘制遮掩层
*/
private void drawCover(Canvas canvas, Rect frame) {
// 获取屏幕的宽和高
int width = canvas.getWidth();
int height = canvas.getHeight();
// Draw the exterior (i.e. outside the framing rect) darkened
paint.setColor(resultBitmap != null ? resultColor : maskColor);
// 画出扫描框外面的阴影部分,共四个部分,扫描框的上面到屏幕上面,扫描框的下面到屏幕下面
// 扫描框的左边面到屏幕左边,扫描框的右边到屏幕右边
canvas.drawRect(0, 0, width, frame.top, paint);
canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);
canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1,
paint);
canvas.drawRect(0, frame.bottom + 1, width, height, paint);
}
/**
* 描绘方形的四个角
*
* @param canvas
* @param frame
*/
private void drawRectEdges(Canvas canvas, Rect frame) {
paint.setColor(Color.WHITE);
paint.setAlpha(OPAQUE);
Resources resources = getResources();
/**
* 这些资源可以用缓存进行管理,不需要每次刷新都新建
*/
Bitmap bitmapCornerTopleft = BitmapFactory.decodeResource(resources,
R.drawable.jdme_scan_corner_top_left);
Bitmap bitmapCornerTopright = BitmapFactory.decodeResource(resources,
R.drawable.jdme_scan_corner_top_right);
Bitmap bitmapCornerBottomLeft = BitmapFactory.decodeResource(resources,
R.drawable.jdme_scan_corner_bottom_left);
Bitmap bitmapCornerBottomRight = BitmapFactory.decodeResource(
resources, R.drawable.jdme_scan_corner_bottom_right);
canvas.drawBitmap(bitmapCornerTopleft, frame.left + CORNER_PADDING,
frame.top + CORNER_PADDING, paint);
canvas.drawBitmap(bitmapCornerTopright, frame.right - CORNER_PADDING
- bitmapCornerTopright.getWidth(), frame.top + CORNER_PADDING,
paint);
canvas.drawBitmap(bitmapCornerBottomLeft, frame.left + CORNER_PADDING,
2 + (frame.bottom - CORNER_PADDING - bitmapCornerBottomLeft
.getHeight()), paint);
canvas.drawBitmap(bitmapCornerBottomRight, frame.right - CORNER_PADDING
- bitmapCornerBottomRight.getWidth(), 2 + (frame.bottom
- CORNER_PADDING - bitmapCornerBottomRight.getHeight()), paint);
bitmapCornerTopleft.recycle();
bitmapCornerTopright.recycle();
bitmapCornerBottomLeft.recycle();
bitmapCornerBottomRight.recycle();
}
public void drawViewfinder() {
Bitmap resultBitmap = this.resultBitmap;
this.resultBitmap = null;
if (resultBitmap != null) {
resultBitmap.recycle();
}
invalidate();
}
/**
* Draw a bitmap with the result points highlighted instead of the live
* scanning display.
*
* @param barcode An image of the decoded barcode.
*/
public void drawResultBitmap(Bitmap barcode) {
resultBitmap = barcode;
invalidate();
}
public void addPossibleResultPoint(ResultPoint point) {
List<ResultPoint> points = possibleResultPoints;
synchronized (points) {
points.add(point);
int size = points.size();
if (size > MAX_RESULT_POINTS) {
// trim it
points.subList(0, size - MAX_RESULT_POINTS / 2).clear();
}
}
}
/**
* dp转px
*
* @param context
* @param dipValue
* @return
*/
private int dip2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
public interface OnDrawFinishListener {
void onDrawFinish(Rect frame);
}
}
| 28.843558 | 101 | 0.680634 |
2268c11fb4e7fa0a2414f2a80e8b64b55663e5c0 | 365 | package com.wfm.platform.dao;
import com.wfm.platform.entities.SysMenu;
public interface SysMenuMapper {
int deleteByPrimaryKey(String id);
int insert(SysMenu record);
int insertSelective(SysMenu record);
SysMenu selectByPrimaryKey(String id);
int updateByPrimaryKeySelective(SysMenu record);
int updateByPrimaryKey(SysMenu record);
} | 21.470588 | 52 | 0.764384 |
3e640af3613f6a74901ca85cd5b27cb629a42542 | 3,713 | package promise.app_base.databinding;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckedTextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.databinding.Bindable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import java.lang.Deprecated;
import java.lang.Object;
import promise.app_base.models.Todo;
public abstract class TodoLayoutBinding extends ViewDataBinding {
@NonNull
public final AppCompatCheckBox checked;
@NonNull
public final AppCompatTextView dateTextView;
@NonNull
public final CheckedTextView titleText;
@Bindable
protected Todo mTodo;
protected TodoLayoutBinding(Object _bindingComponent, View _root, int _localFieldCount,
AppCompatCheckBox checked, AppCompatTextView dateTextView, CheckedTextView titleText) {
super(_bindingComponent, _root, _localFieldCount);
this.checked = checked;
this.dateTextView = dateTextView;
this.titleText = titleText;
}
public abstract void setTodo(@Nullable Todo todo);
@Nullable
public Todo getTodo() {
return mTodo;
}
@NonNull
public static TodoLayoutBinding inflate(@NonNull LayoutInflater inflater,
@Nullable ViewGroup root, boolean attachToRoot) {
return inflate(inflater, root, attachToRoot, DataBindingUtil.getDefaultComponent());
}
/**
* This method receives DataBindingComponent instance as type Object instead of
* type DataBindingComponent to avoid causing too many compilation errors if
* compilation fails for another reason.
* https://issuetracker.google.com/issues/116541301
* @Deprecated Use DataBindingUtil.inflate(inflater, R.layout.todo_layout, root, attachToRoot, component)
*/
@NonNull
@Deprecated
public static TodoLayoutBinding inflate(@NonNull LayoutInflater inflater,
@Nullable ViewGroup root, boolean attachToRoot, @Nullable Object component) {
return ViewDataBinding.<TodoLayoutBinding>inflateInternal(inflater, promise.app_base.R.layout.todo_layout, root, attachToRoot, component);
}
@NonNull
public static TodoLayoutBinding inflate(@NonNull LayoutInflater inflater) {
return inflate(inflater, DataBindingUtil.getDefaultComponent());
}
/**
* This method receives DataBindingComponent instance as type Object instead of
* type DataBindingComponent to avoid causing too many compilation errors if
* compilation fails for another reason.
* https://issuetracker.google.com/issues/116541301
* @Deprecated Use DataBindingUtil.inflate(inflater, R.layout.todo_layout, null, false, component)
*/
@NonNull
@Deprecated
public static TodoLayoutBinding inflate(@NonNull LayoutInflater inflater,
@Nullable Object component) {
return ViewDataBinding.<TodoLayoutBinding>inflateInternal(inflater, promise.app_base.R.layout.todo_layout, null, false, component);
}
public static TodoLayoutBinding bind(@NonNull View view) {
return bind(view, DataBindingUtil.getDefaultComponent());
}
/**
* This method receives DataBindingComponent instance as type Object instead of
* type DataBindingComponent to avoid causing too many compilation errors if
* compilation fails for another reason.
* https://issuetracker.google.com/issues/116541301
* @Deprecated Use DataBindingUtil.bind(view, component)
*/
@Deprecated
public static TodoLayoutBinding bind(@NonNull View view, @Nullable Object component) {
return (TodoLayoutBinding)bind(component, view, promise.app_base.R.layout.todo_layout);
}
}
| 36.762376 | 142 | 0.783194 |
215b6defc824c21d6e47d18057a3ee46fa602f4b | 2,367 | package seedu.knowitall.logic.commands;
import static seedu.knowitall.commons.core.Messages.MESSAGE_INVALID_COMMAND_OUTSIDE_FOLDER;
import static seedu.knowitall.logic.commands.CommandTestUtil.assertCommandFailure;
import static seedu.knowitall.logic.commands.CommandTestUtil.assertCommandSuccess;
import static seedu.knowitall.testutil.TypicalCards.getTypicalCardFolders;
import org.junit.Test;
import seedu.knowitall.logic.CommandHistory;
import seedu.knowitall.model.Model;
import seedu.knowitall.model.ModelManager;
import seedu.knowitall.model.UserPrefs;
import seedu.knowitall.testutil.TypicalIndexes;
/**
* Contains integration tests (interaction with the Model) and junit tests for {@code TestCommand}.
*/
public class TestCommandTest {
private Model model = new ModelManager(getTypicalCardFolders(), new UserPrefs());
private Model expectedModel = new ModelManager(getTypicalCardFolders(), new UserPrefs());
private CommandHistory commandHistory = new CommandHistory();
@Test
public void execute_validTestCommand_success() {
model.enterFolder(TypicalIndexes.INDEX_FIRST_CARD_FOLDER.getZeroBased());
TestCommand testCommand = new TestCommand();
expectedModel.enterFolder(TypicalIndexes.INDEX_FIRST_CARD_FOLDER.getZeroBased());
expectedModel.testCardFolder();
CommandResult expectedCommandResult = new CommandResult(TestCommand.MESSAGE_ENTER_TEST_FOLDER_SUCCESS,
CommandResult.Type.START_TEST_SESSION);
assertCommandSuccess(testCommand, model, commandHistory, expectedCommandResult, expectedModel);
}
@Test
public void execute_invalidTestCommandNotInFolder_fail() {
model.exitFolderToHome();
TestCommand testCommand = new TestCommand();
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_OUTSIDE_FOLDER);
assertCommandFailure(testCommand, model, commandHistory, expectedMessage);
}
@Test
public void execute_invalidTestCommandInsideTestSession_fail() {
TestCommand testCommand = new TestCommand();
model.enterFolder(TypicalIndexes.INDEX_FIRST_CARD_FOLDER.getZeroBased());
model.testCardFolder();
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_OUTSIDE_FOLDER);
assertCommandFailure(testCommand, model, commandHistory, expectedMessage);
}
}
| 45.519231 | 110 | 0.782847 |
1fe6089661232723bfd4046766f76042a756829f | 746 | package com.googlecode.yatspec.junit;
import static com.googlecode.yatspec.Creator.create;
import static java.lang.Class.forName;
import static java.lang.System.getProperty;
public class ParameterResolverFactory {
public static final String PARAMETER_RESOLVER = "yatspec.parameter.resolver";
public static void setParameterResolver(Class<? extends ParameterResolver> aClass) {
System.setProperty(PARAMETER_RESOLVER, aClass.getName());
}
public static ParameterResolver parameterResolver() {
try {
return create(forName(getProperty(PARAMETER_RESOLVER, VarargsParameterResolver.class.getName())));
} catch (Exception e) {
return new VarargsParameterResolver();
}
}
}
| 32.434783 | 110 | 0.731903 |
301c31c0da8b35dc350dfe8b9bbb43f62fcdb7cb | 551 | package io.github.u2ware.data.test.example06;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Table(name = "example06_ManyToOneEntity")
@Data @Builder @AllArgsConstructor @NoArgsConstructor
public class ManyToOneEntity {
@Id @GeneratedValue
private Long seq;
private String name;
private Integer age;
}
| 19.678571 | 54 | 0.767695 |
fc0389b8f501f98cdad1ac5c90e19019f5e9b0ec | 485 | package be.bitbox.traindelay.tracker.core.station;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class CountryTest {
@Test
public void translateFromBelgium() {
Country country = Country.translateFrom("be");
assertThat(country, is(Country.BE));
}
@Test(expected = IllegalArgumentException.class)
public void translateFromUnknown() {
Country.translateFrom("Fake");
}
} | 24.25 | 54 | 0.707216 |
c97dec38fdd6a1ff4b4e0dc52ab9ee10ba7903b3 | 5,946 | /*
* Copyright Debezium Authors.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package io.debezium.relational.history;
import java.io.File;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.fest.assertions.Assertions.assertThat;
import io.debezium.config.Configuration;
import io.debezium.kafka.KafkaCluster;
import io.debezium.relational.Tables;
import io.debezium.relational.ddl.DdlParser;
import io.debezium.relational.ddl.DdlParserSql2003;
import io.debezium.util.Collect;
import io.debezium.util.Testing;
/**
* @author Randall Hauch
*/
public class KafkaDatabaseHistoryTest {
private Configuration config;
private KafkaDatabaseHistory history;
private KafkaCluster kafka;
private File dataDir;
private Map<String, String> source;
private Map<String, Object> position;
private String topicName;
private String ddl;
@Before
public void beforeEach() throws Exception {
source = Collect.hashMapOf("server", "my-server");
setLogPosition(0);
topicName = "schema-changes-topic";
dataDir = Testing.Files.createTestingDirectory("cluster");
Testing.Files.delete(dataDir);
kafka = new KafkaCluster().usingDirectory(dataDir)
.deleteDataPriorToStartup(true)
.deleteDataUponShutdown(true)
.addBrokers(1)
.startup();
history = new KafkaDatabaseHistory();
}
@After
public void afterEach() {
try {
if (history != null) history.stop();
} finally {
history = null;
try {
if (kafka != null) kafka.shutdown();
} finally {
kafka = null;
}
}
}
@Test
public void shouldStartWithEmptyTopicAndStoreDataAndRecoverAllState() throws Exception {
// Create the empty topic ...
kafka.createTopic(topicName, 1, 1);
// Start up the history ...
config = Configuration.create()
.with(KafkaDatabaseHistory.BOOTSTRAP_SERVERS, kafka.brokerList())
.with(KafkaDatabaseHistory.TOPIC, topicName)
.build();
history.configure(config,null);
history.start();
DdlParser recoveryParser = new DdlParserSql2003();
DdlParser ddlParser = new DdlParserSql2003();
ddlParser.setCurrentSchema("db1"); // recover does this, so we need to as well
Tables tables1 = new Tables();
Tables tables2 = new Tables();
Tables tables3 = new Tables();
// Recover from the very beginning ...
setLogPosition(0);
history.recover(source, position, tables1, recoveryParser);
// There should have been nothing to recover ...
assertThat(tables1.size()).isEqualTo(0);
// Now record schema changes, which writes out to kafka but doesn't actually change the Tables ...
setLogPosition(10);
ddl = "CREATE TABLE foo ( name VARCHAR(255) NOT NULL PRIMARY KEY); \n" +
"CREATE TABLE customers ( id INTEGER NOT NULL PRIMARY KEY, name VARCHAR(100) NOT NULL ); \n" +
"CREATE TABLE products ( productId INTEGER NOT NULL PRIMARY KEY, desc VARCHAR(255) NOT NULL); \n";
history.record(source, position, "db1", tables1, ddl);
ddlParser.parse(ddl, tables1);
assertThat(tables1.size()).isEqualTo(3);
ddlParser.parse(ddl, tables2);
assertThat(tables2.size()).isEqualTo(3);
ddlParser.parse(ddl, tables3);
assertThat(tables3.size()).isEqualTo(3);
setLogPosition(39);
ddl = "DROP TABLE foo;";
history.record(source, position, "db1", tables2, ddl);
ddlParser.parse(ddl, tables2);
assertThat(tables2.size()).isEqualTo(2);
ddlParser.parse(ddl, tables3);
assertThat(tables3.size()).isEqualTo(2);
setLogPosition(10003);
ddl = "CREATE TABLE suppliers ( supplierId INTEGER NOT NULL PRIMARY KEY, name VARCHAR(255) NOT NULL);";
history.record(source, position, "db1", tables3, ddl);
ddlParser.parse(ddl, tables3);
assertThat(tables3.size()).isEqualTo(3);
// Stop the history (which should stop the producer) ...
history.stop();
history = new KafkaDatabaseHistory();
history.configure(config, null);
// no need to start
// Recover from the very beginning to just past the first change ...
Tables recoveredTables = new Tables();
setLogPosition(15);
history.recover(source, position, recoveredTables, recoveryParser);
assertThat(recoveredTables).isEqualTo(tables1);
// Recover from the very beginning to just past the second change ...
recoveredTables = new Tables();
setLogPosition(50);
history.recover(source, position, recoveredTables, recoveryParser);
assertThat(recoveredTables).isEqualTo(tables2);
// Recover from the very beginning to just past the third change ...
recoveredTables = new Tables();
setLogPosition(10010);
history.recover(source, position, recoveredTables, recoveryParser);
assertThat(recoveredTables).isEqualTo(tables3);
// Recover from the very beginning to way past the third change ...
recoveredTables = new Tables();
setLogPosition(100000010);
history.recover(source, position, recoveredTables, recoveryParser);
assertThat(recoveredTables).isEqualTo(tables3);
}
protected void setLogPosition(int index) {
this.position = Collect.hashMapOf("filename", "my-txn-file.log",
"position", index);
}
}
| 37.1625 | 114 | 0.628994 |
22aca6680936eb4ea031b431ae29a5d9fb2ef51f | 2,046 | // This file was generated by Mendix Studio Pro.
//
// WARNING: Only the following code will be retained when actions are regenerated:
// - the import list
// - the code between BEGIN USER CODE and END USER CODE
// - the code between BEGIN EXTRA CODE and END EXTRA CODE
// Other code you write will be lost the next time you deploy the project.
// Special characters, e.g., é, ö, à, etc. are supported in comments.
package communitycommons.actions;
import com.mendix.systemwideinterfaces.core.IContext;
import com.mendix.webui.CustomJavaAction;
import com.mendix.systemwideinterfaces.core.IMendixObject;
import communitycommons.Misc;
/**
* Overlay a generated PDF document with another PDF (containing the company stationary for example)
*/
public class OverlayPdfDocument extends CustomJavaAction<java.lang.Boolean>
{
private IMendixObject __generatedDocument;
private system.proxies.FileDocument generatedDocument;
private IMendixObject __overlay;
private system.proxies.FileDocument overlay;
private java.lang.Boolean onTopOfContent;
public OverlayPdfDocument(IContext context, IMendixObject generatedDocument, IMendixObject overlay, java.lang.Boolean onTopOfContent)
{
super(context);
this.__generatedDocument = generatedDocument;
this.__overlay = overlay;
this.onTopOfContent = onTopOfContent;
}
@java.lang.Override
public java.lang.Boolean executeAction() throws Exception
{
this.generatedDocument = __generatedDocument == null ? null : system.proxies.FileDocument.initialize(getContext(), __generatedDocument);
this.overlay = __overlay == null ? null : system.proxies.FileDocument.initialize(getContext(), __overlay);
// BEGIN USER CODE
return Misc.overlayPdf(getContext(), __generatedDocument, __overlay, onTopOfContent);
// END USER CODE
}
/**
* Returns a string representation of this action
*/
@java.lang.Override
public java.lang.String toString()
{
return "OverlayPdfDocument";
}
// BEGIN EXTRA CODE
// END EXTRA CODE
}
| 34.1 | 139 | 0.756109 |
d40f1e84db6bd8601a1586962ce8d23fb94777bd | 382 | package com.kisin.product.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.kisin.product.entity.Product;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 产品 服务类
* </p>
*
* @author kisin
* @since 2019-11-21
*/
public interface ProductService extends IService<Product> {
IPage<Product> findAllInfo(IPage<Product> page);
}
| 19.1 | 59 | 0.735602 |
cfca69fa6dba5fc895a134acb0a99b761550c632 | 956 | /**
*
*/
package com.strandls.species.pojo;
import java.util.List;
import com.strandls.traits.pojo.TraitsValuePair;
/**
* @author Abhishek Rudra
*
*
*/
public class SpeciesTrait {
private String CategoryName;
private List<TraitsValuePair> traitsValuePairList;
/**
*
*/
public SpeciesTrait() {
super();
}
/**
* @param categoryName
* @param traitsValuePairList
*/
public SpeciesTrait(String categoryName, List<TraitsValuePair> traitsValuePairList) {
super();
CategoryName = categoryName;
this.traitsValuePairList = traitsValuePairList;
}
public String getCategoryName() {
return CategoryName;
}
public void setCategoryName(String categoryName) {
CategoryName = categoryName;
}
public List<TraitsValuePair> getTraitsValuePairList() {
return traitsValuePairList;
}
public void setTraitsValuePairList(List<TraitsValuePair> traitsValuePairList) {
this.traitsValuePairList = traitsValuePairList;
};
}
| 17.703704 | 86 | 0.738494 |
75e36336eabbf67b48f5f31e8e435707a25dadbb | 3,943 | /*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.binder;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.PostConstruct;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.event.EventListRequest;
import com.ecwid.consul.v1.event.model.Event;
import com.ecwid.consul.v1.event.model.EventParams;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cloud.consul.binder.config.ConsulBinderProperties;
/**
* @author Spencer Gibb
*/
public class EventService {
protected ConsulBinderProperties properties;
protected ConsulClient consul;
protected ObjectMapper objectMapper = new ObjectMapper();
private AtomicReference<Long> lastIndex = new AtomicReference<>();
public EventService(ConsulBinderProperties properties, ConsulClient consul,
ObjectMapper objectMapper) {
this.properties = properties;
this.consul = consul;
this.objectMapper = objectMapper;
}
public ConsulClient getConsulClient() {
return this.consul;
}
@PostConstruct
public void init() {
setLastIndex(getEventsResponse());
}
public Long getLastIndex() {
return this.lastIndex.get();
}
private void setLastIndex(Response<?> response) {
Long consulIndex = response.getConsulIndex();
if (consulIndex != null) {
this.lastIndex.set(response.getConsulIndex());
}
}
public Event fire(String name, String payload) {
Response<Event> response = this.consul.eventFire(name, payload, new EventParams(),
QueryParams.DEFAULT);
return response.getValue();
}
public Response<List<Event>> getEventsResponse() {
return this.consul.eventList(EventListRequest.newBuilder()
.setQueryParams(QueryParams.DEFAULT).build());
}
public List<Event> getEvents() {
return getEventsResponse().getValue();
}
public List<Event> getEvents(Long lastIndex) {
return filterEvents(readEvents(getEventsResponse()), lastIndex);
}
public List<Event> watch() {
return watch(this.lastIndex.get());
}
public List<Event> watch(Long lastIndex) {
// TODO: parameterized or configurable watch time
long index = -1;
if (lastIndex != null) {
index = lastIndex;
}
int eventTimeout = 5;
if (this.properties != null) {
eventTimeout = this.properties.getEventTimeout();
}
Response<List<Event>> watch = this.consul.eventList(EventListRequest.newBuilder()
.setQueryParams(new QueryParams(eventTimeout, index)).build());
return filterEvents(readEvents(watch), lastIndex);
}
protected List<Event> readEvents(Response<List<Event>> response) {
setLastIndex(response);
return response.getValue();
}
/**
* from https://github.com/hashicorp/consul/blob/master/watch/funcs.go#L169-L194 .
* @param toFilter events to filter
* @param lastIndex last index to pick from the list of events
* @return filtered list of events
*/
protected List<Event> filterEvents(List<Event> toFilter, Long lastIndex) {
List<Event> events = toFilter;
if (lastIndex != null) {
for (int i = 0; i < events.size(); i++) {
Event event = events.get(i);
Long eventIndex = event.getWaitIndex();
if (lastIndex.equals(eventIndex)) {
events = events.subList(i + 1, events.size());
break;
}
}
}
return events;
}
}
| 28.366906 | 84 | 0.73472 |
5b038920f9e9a54484cdab5edbb6abe1de5974a4 | 2,593 | package com.xiangzhurui.demo.drools.domain;
import java.io.Serializable;
import java.text.MessageFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.kie.api.io.ResourceType;
/**
* @author xiangzhurui
* @version 2018/8/15 10:55
*/
@AllArgsConstructor
@NoArgsConstructor
@Data
public class DrlDataDO implements Serializable {
private static final long serialVersionUID = -255345757032720985L;
private static final String KIE_FILESYSTEM_SEPARATOR = "/";
private static final String KIE_PACKAGE_REGEX = "\\.";
private static final String KIE_PACKAGE_SEPARATOR = ".";
private String pkgName;
private String path;
private String content;
private String kBaseName;
private String statefulSessionName;
private String statelessSessionName;
public DrlDataDO(String pkgName, String content) {
this.pkgName = pkgName;
this.content = content;
this.path = newKieFileSystemPath();
this.kBaseName = this.newBaseName();
this.statefulSessionName = this.newStatefulSessionName();
this.statelessSessionName = this.newStatelessSessionName();
}
private static int getLength(String pkgName) {
return pkgName.length();
}
private static int getBeginIndex(String pkgName) {
return pkgName.lastIndexOf(KIE_PACKAGE_SEPARATOR) + 1;
}
/**
* 获取约定路径
*
* @return
*/
private String newKieFileSystemPath() {
String[] tmpStrArr = this.pkgName.split(KIE_PACKAGE_REGEX);
String pkgPath = StringUtils.join(tmpStrArr, KIE_FILESYSTEM_SEPARATOR);
String drlFilePath = MessageFormat.format("{0}{1}{2}/script.drl", ResourceType.DRL.getDefaultPath(), KIE_FILESYSTEM_SEPARATOR, pkgPath);
return drlFilePath;
}
private String newStatefulSessionName() {
String prefix = this.pkgName.substring(getBeginIndex(pkgName), getLength(pkgName));
String format = MessageFormat.format("session-{0}-stateful", prefix);
return format;
}
private String newStatelessSessionName() {
String prefix = this.pkgName.substring(getBeginIndex(pkgName), getLength(this.pkgName));
String format = MessageFormat.format("session-{0}-stateless", prefix);
return format;
}
private String newBaseName() {
String prefix = this.pkgName.substring(getBeginIndex(pkgName), getLength(this.pkgName));
String format = MessageFormat.format("base-{0}", prefix);
return format;
}
}
| 33.675325 | 144 | 0.705746 |
06c2a7b63dcc6cab04cc3eeff95ba52501a417fc | 752 | package cn.com.allunion.common.validation.bean.string;
import cn.com.allunion.common.validation.bean.AbstractValidation;
/**
* 字符串最小长度验证
* @author yang.jie
* @email yang.jie@all-union.com.cn
* @date 2016/5/26.
* @copyright <url>http://www.all-union.com.cn/</url>
*/
public class StringMinLength extends AbstractValidation<String> {
/**
* 长度
*/
private int minLength ;
public StringMinLength(String property, int minLength, String errorTip) {
this.object = property ;
this.minLength = minLength ;
this.errorTip = errorTip ;
}
@Override
public boolean validate() {
if (null != object) {
return object.length() >= minLength ;
}
return false;
}
}
| 22.787879 | 77 | 0.630319 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.